var Orbit=function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module.default}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=160)}([function(module,exports,__webpack_require__){"use strict";(function(Buffer,global){function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)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=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=String(encoding).toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128===(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128===(192&secondByte)&&128===(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128===(192&secondByte)&&128===(192&thirdByte)&&128===(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}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")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}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){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!==0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],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);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=__webpack_require__(117),ieee754=__webpack_require__(141),isArray=__webpack_require__(44);exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),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;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)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=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len,start<0&&(start=0)):start>len&&(start=len),end<0?(end+=len,end<0&&(end=0)):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?(255-this[offset]+1)*-1:this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),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=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i1)for(var i=1;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],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;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),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)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},function(module,exports,__webpack_require__){(function(module){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:(this.negative=0,this.words=null,this.length=0,this.red=null,void(null!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))))}function parseHex(str,start,end){for(var r=0,len=Math.min(str.length,end),i=start;i=49&&c<=54?c-49+10:c>=17&&c<=22?c-17+10:15&c}return r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=r/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0,hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}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()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){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}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),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)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer=__webpack_require__(0).Buffer}catch(e){}BN.isBN=function(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function(left,right){return left.cmp(right)>0?left:right},BN.min=function(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&start++,16===base?this._parseHex(number,start):this._parseBase(number,base,start),"-"===number[0]&&(this.negative=1),this.strip(),"le"===endian&&this._initArray(this.toArray(),base,endian)},BN.prototype._initNumber=function(number,base,endian){number<0&&(this.negative=1,number=-number),number<67108864?(this.words=[67108863&number],this.length=1):number<4503599627370496?(this.words=[67108863&number,number/67108864&67108863],this.length=2):(assert(number<9007199254740992),this.words=[67108863&number,number/67108864&67108863,1],this.length=3),"le"===endian&&this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function(number,base,endian){if(assert("number"==typeof number.length),number.length<=0)return this.words=[0],this.length=1,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,off>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function(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,off>=26&&(off-=26,j++);i+6!==start&&(w=parseHex(number,start,i+6),this.words[j]|=w<>>26-off&4194303),this.strip()},BN.prototype._parseBase=function(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;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function(){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"],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],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(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,off>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function(){return this.toString(16)},BN.prototype.toBuffer=function(endian,length){return assert("undefined"!=typeof Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function(ArrayType,endian,length){var byteLength=this.byteLength(),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 b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(0===w)return 26;var t=w,r=0;return 0===(8191&t)&&(r+=13,t>>>=13),0===(127&t)&&(r+=7,t>>>=7),0===(15&t)&&(r+=4,t>>>=4),0===(3&t)&&(r+=2,t>>>=2),0===(1&t)&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),val?this.words[off]=this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<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)+((8191&mid)<<13)|0;return 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,0!==c&&(o[19]=c,out.length++),out};Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?bigMulTo(this,num,out):jumboMulTo(this,num,out)},FFTM.prototype.makeRBT=function(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&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]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(carry===-1),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!==shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0!==(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode)},BN.prototype.div=function(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0===(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0===(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0===(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0===(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,res.cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return 0===(1&this.words[0])},BN.prototype.isOdd=function(){return 1===(1&this.words[0])},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function(num){var negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this.strip();var res;if(this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function(num){return 1===this.cmpn(num)},BN.prototype.gt=function(num){return 1===this.cmp(num)},BN.prototype.gten=function(num){return this.cmpn(num)>=0},BN.prototype.gte=function(num){return this.cmp(num)>=0},BN.prototype.ltn=function(num){return this.cmpn(num)===-1},BN.prototype.lt=function(num){return this.cmp(num)===-1},BN.prototype.lten=function(num){return this.cmpn(num)<=0},BN.prototype.lte=function(num){return this.cmp(num)<=0},BN.prototype.eqn=function(num){return 0===this.cmpn(num)},BN.prototype.eq=function(num){return 0===this.cmp(num)},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var rlen,r=num;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):r.strip(),r},MPrime.prototype.split=function(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function(input,output){for(var mask=4194303,outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function(a,b){assert(0===(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2===1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,currentLen++,(currentLen===windowSize||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}}("undefined"==typeof module||module,this)}).call(exports,__webpack_require__(50)(module))},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Post=function Post(type){_classCallCheck(this,Post),this.type=type};module.exports=Post},function(module,exports,__webpack_require__){var hash=exports;hash.utils=__webpack_require__(140),hash.common=__webpack_require__(136),hash.sha=__webpack_require__(139),hash.ripemd=__webpack_require__(138),hash.hmac=__webpack_require__(137),hash.sha1=hash.sha.sha1,hash.sha256=hash.sha.sha256,hash.sha224=hash.sha.sha224,hash.sha384=hash.sha.sha384,hash.sha512=hash.sha.sha512,hash.ripemd160=hash.ripemd.ripemd160},function(module,exports,__webpack_require__){"use strict";function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=__webpack_require__(26),util=__webpack_require__(13);util.inherits=__webpack_require__(3);var Readable=__webpack_require__(47),Writable=__webpack_require__(28);util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v=0&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(exports,__webpack_require__(10).setImmediate,__webpack_require__(10).clearImmediate)},function(module,exports){"use strict";module.exports=function(op,done){function sink(_read){return read=_read,abort?sink.abort():void function next(){for(var loop=!0,cbed=!1;loop;)if(cbed=!1,read(null,function(end,data){if(cbed=!0,end=end||abort){if(loop=!1,done)done(end===!0?null:end);else if(end&&end!==!0)throw end}else op&&!1===op(data)||abort?(loop=!1,read(abort||!0,done||function(){})):loop||next()}),!cbed)return void(loop=!1)}()}var read,abort;return sink.abort=function(err,cb){if("function"==typeof err&&(cb=err,err=!0),abort=err||!0,read)return read(abort,cb||function(){})},sink}},function(module,exports){"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};module.exports=function(key){return key&&("string"==typeof key?function(data){return data[key]}:"object"===("undefined"==typeof key?"undefined":_typeof(key))&&"function"==typeof key.exec?function(data){var v=key.exec(data);return v&&v[0]}:key)}},function(module,exports,__webpack_require__){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)} function isError(e){return"[object Error]"===objectToString(e)||e instanceof Error}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(global,process){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i0&&void 0!==arguments[0]?arguments[0]:"./";if("undefined"==typeof localStorage||null===localStorage){var _LocalStorage=__webpack_require__(45).LocalStorage;keystore=new _LocalStorage(directory)}else keystore=localStorage}},{key:"importKeyFromIpfs",value:function(ipfs,hash){var cached=cache.get(hash);return cached?Promise.resolve(cached):ipfs.object.get(hash,{enc:"base58"}).then(function(obj){return JSON.parse(obj.toJSON().data)}).then(function(key){return cache.set(hash,ec.keyFromPublic(key,"hex")),OrbitCrypto.importPublicKey(key)})}},{key:"exportKeyToIpfs",value:function(ipfs,key){var k=key.getPublic("hex"),cached=cache.get(k);return cached?Promise.resolve(cached):OrbitCrypto.exportPublicKey(key).then(function(k){return JSON.stringify(k,null,2)}).then(function(s){return new Buffer(s)}).then(function(buffer){return ipfs.object.put(buffer)}).then(function(res){return cache.set(k,res.toJSON().multihash),res.toJSON().multihash})}},{key:"getKey",value:function(){var id=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"default",savedKeys=JSON.parse(keystore.getItem(id)),key=void 0,publicKey=void 0,privateKey=void 0;return savedKeys?OrbitCrypto.importPrivateKey(savedKeys.privateKey).then(function(privKey){return privateKey=privKey}).then(function(){return OrbitCrypto.importPublicKey(savedKeys.publicKey)}).then(function(pubKey){return publicKey=pubKey}).then(function(){return{publicKey:publicKey,privateKey:privateKey}}):OrbitCrypto.generateKey().then(function(keyPair){return key=keyPair}).then(function(){return OrbitCrypto.exportPrivateKey(key)}).then(function(privKey){return privateKey=privKey}).then(function(){return OrbitCrypto.exportPublicKey(key)}).then(function(pubKey){return publicKey=pubKey}).then(function(){return keystore.setItem(id,JSON.stringify({publicKey:publicKey,privateKey:privateKey})),{publicKey:key,privateKey:key}})}},{key:"generateKey",value:function(){return Promise.resolve(ec.genKeyPair())}},{key:"exportPublicKey",value:function(key){return Promise.resolve(key.getPublic("hex"))}},{key:"exportPrivateKey",value:function(key){return Promise.resolve(key.getPrivate("hex"))}},{key:"importPublicKey",value:function(key){return Promise.resolve(ec.keyFromPublic(key,"hex"))}},{key:"importPrivateKey",value:function(key){return Promise.resolve(ec.keyFromPrivate(key,"hex"))}},{key:"sign",value:function(key,data){var sig=ec.sign(data,key);return Promise.resolve(sig.toDER("hex"))}},{key:"verify",value:function(signature,key,data){return Promise.resolve(ec.verify(data,signature,key))}}]),OrbitCrypto}();module.exports=OrbitCrypto}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(process){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=levelIdx}}]),Logger}();module.exports={Colors:Colors,LogLevels:LogLevels,setLogLevel:function(level){GlobalLogLevel=level},setLogfile:function(filename){GlobalLogfile=filename},create:function(category,options){var logger=new Logger(category,options);return logger},forceBrowserMode:function(force){return isNodejs=!force}}}).call(exports,__webpack_require__(1))},function(module,exports){"use strict";function baseSlice(array,start,end){var index=-1,length=array.length;start<0&&(start=-start>length?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index3&&void 0!==arguments[3]?arguments[3]:{};_classCallCheck(this,Store),this.id=id,this.dbname=dbname,this.events=new EventEmitter;var opts=Object.assign({},DefaultOptions);Object.assign(opts,options),this.options=opts,this._ipfs=ipfs,this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options),this._lastWrite=[]}return _createClass(Store,[{key:"loadHistory",value:function(hash){var _this=this;return this._lastWrite.includes(hash)?Promise.resolve([]):(hash&&this._lastWrite.push(hash),this.events.emit("load",this.dbname,hash),hash&&this.options.maxHistory>0?Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this._oplog.join(log)}).then(function(merged){_this._index.updateIndex(_this._oplog,merged),_this.events.emit("history",_this.dbname,merged)}).then(function(){return _this.events.emit("ready",_this.dbname)}).then(function(){return _this}):(this.events.emit("ready",this.dbname),Promise.resolve(this)))}},{key:"sync",value:function(hash){var _this2=this;if(!hash||this._lastWrite.includes(hash))return Promise.resolve([]);var newItems=[];hash&&this._lastWrite.push(hash),this.events.emit("sync",this.dbname);(new Date).getTime();return Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this2._oplog.join(log)}).then(function(merged){return newItems=merged}).then(function(){return _this2._index.updateIndex(_this2._oplog,newItems)}).then(function(){newItems.reverse().forEach(function(e){return _this2.events.emit("data",_this2.dbname,e)})}).then(function(){return newItems})}},{key:"close",value:function(){this.delete(),this.events.emit("close",this.dbname)}},{key:"delete",value:function(){this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options)}},{key:"_addOperation",value:function(data){var _this3=this,result=void 0,logHash=void 0;if(this._oplog)return this._oplog.add(data).then(function(res){return result=res}).then(function(){return Log.getIpfsHash(_this3._ipfs,_this3._oplog)}).then(function(hash){return logHash=hash}).then(function(){return _this3._lastWrite.push(logHash)}).then(function(){return _this3._index.updateIndex(_this3._oplog,[result])}).then(function(){return _this3.events.emit("write",_this3.dbname,logHash)}).then(function(){return _this3.events.emit("data",_this3.dbname,result)}).then(function(){return result.hash})}}]),Store}();module.exports=Store},function(module,exports,__webpack_require__){"use strict";var drain=__webpack_require__(11);module.exports=function(reducer,acc,cb){cb||(cb=acc,acc=null);var sink=drain(function(data){acc=reducer(acc,data)},function(err){cb(err,acc)});return 2===arguments.length?function(source){source(null,function(end,data){return end?cb(end===!0?null:end):(acc=data,void sink(source))})}:sink}},function(module,exports,__webpack_require__){"use strict";var abortCb=__webpack_require__(41);module.exports=function(array,onAbort){if(!array)return function(abort,cb){return abort?abortCb(cb,abort,onAbort):cb(!0)};Array.isArray(array)||(array=Object.keys(array).map(function(k){return array[k]}));var i=0;return function(abort,cb){return abort?abortCb(cb,abort,onAbort):void(i>=array.length?cb(!0):cb(null,array[i++]))}}},function(module,exports,__webpack_require__){"use strict";var tester=__webpack_require__(42);module.exports=function(test){return test=tester(test),function(read){return function next(end,cb){for(var sync,loop=!0;loop;)loop=!1,sync=!0,read(end,function(end,data){return end||test(data)?void cb(end,data):sync?loop=!0:next(end,cb)}),sync=!1}}}},function(module,exports,__webpack_require__){"use strict";(function(global){var buffer=__webpack_require__(0),Buffer=buffer.Buffer,SlowBuffer=buffer.SlowBuffer,MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function(size,fill,encoding){if("function"==typeof Buffer.alloc)return Buffer.alloc(size,fill,encoding);if("number"==typeof encoding)throw new TypeError("encoding must not be number");if("number"!=typeof size)throw new TypeError("size must be a number");if(size>MAX_LEN)throw new RangeError("size is too large");var enc=encoding,_fill=fill;void 0===_fill&&(enc=void 0,_fill=0);var buf=new Buffer(size);if("string"==typeof _fill)for(var fillBuf=new Buffer(_fill,enc),flen=fillBuf.length,i=-1;++iMAX_LEN)throw new RangeError("size is too large");return new Buffer(size)},exports.from=function(value,encodingOrOffset,length){if("function"==typeof Buffer.from&&(!global.Uint8Array||Uint8Array.from!==Buffer.from))return Buffer.from(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('"value" argument must not be a number');if("string"==typeof value)return new Buffer(value,encodingOrOffset);if("undefined"!=typeof ArrayBuffer&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(1===arguments.length)return new Buffer(value);"undefined"==typeof offset&&(offset=0);var len=length;if("undefined"==typeof len&&(len=value.byteLength-offset),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);return value.copy(out,0,0,value.length),out}if(value){if(Array.isArray(value)||"undefined"!=typeof ArrayBuffer&&value.buffer instanceof ArrayBuffer||"length"in value)return new Buffer(value);if("Buffer"===value.type&&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(size){if("function"==typeof Buffer.allocUnsafeSlow)return Buffer.allocUnsafeSlow(size);if("number"!=typeof size)throw new TypeError("size must be a number");if(size>=MAX_LEN)throw new RangeError("size is too large");return new SlowBuffer(size)}}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";(function(process){function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=__webpack_require__(13);util.inherits=__webpack_require__(3);var Stream,internalUtil={deprecate:__webpack_require__(154)};!function(){try{Stream=__webpack_require__(17)}catch(_){}finally{Stream||(Stream=__webpack_require__(5).EventEmitter)}}();var Buffer=__webpack_require__(0).Buffer,bufferShim=__webpack_require__(25);util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];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;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(exports,__webpack_require__(1),__webpack_require__(10).setImmediate)},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var OrbitUser=function OrbitUser(keys,profileData){_classCallCheck(this,OrbitUser),this._keys=keys,this.profile=profileData};module.exports=OrbitUser},function(module,exports,__webpack_require__){function LRU(opts){return this instanceof LRU?("number"==typeof opts&&(opts={max:opts}),opts||(opts={}),events.EventEmitter.call(this),this.cache={},this.head=this.tail=null,this.length=0,this.max=opts.max||1e3,void(this.maxAge=opts.maxAge||0)):new LRU(opts)}var events=__webpack_require__(5),inherits=__webpack_require__(3);module.exports=LRU,inherits(LRU,events.EventEmitter),Object.defineProperty(LRU.prototype,"keys",{get:function(){return Object.keys(this.cache)}}),LRU.prototype.clear=function(){this.cache={},this.head=this.tail=null,this.length=0},LRU.prototype.remove=function(key){if("string"!=typeof key&&(key=""+key),this.cache.hasOwnProperty(key)){var element=this.cache[key];return delete this.cache[key],this._unlink(key,element.prev,element.next),element.value}},LRU.prototype._unlink=function(key,prev,next){this.length--,0===this.length?this.head=this.tail=null:this.head===key?(this.head=prev,this.cache[this.head].next=null):this.tail===key?(this.tail=next,this.cache[this.tail].prev=null):(this.cache[prev].next=next,this.cache[next].prev=prev)},LRU.prototype.peek=function(key){if(this.cache.hasOwnProperty(key)){var element=this.cache[key];if(this._checkAge(key,element))return element.value}},LRU.prototype.set=function(key,value){"string"!=typeof key&&(key=""+key);var element;if(this.cache.hasOwnProperty(key)){if(element=this.cache[key],element.value=value,this.maxAge&&(element.modified=Date.now()),key===this.head)return value;this._unlink(key,element.prev,element.next)}else element={value:value,modified:0,next:null,prev:null},this.maxAge&&(element.modified=Date.now()),this.cache[key]=element,this.length===this.max&&this.evict();return this.length++,element.next=null,element.prev=this.head,this.head&&(this.cache[this.head].next=key),this.head=key,this.tail||(this.tail=key),value},LRU.prototype._checkAge=function(key,element){return!(this.maxAge&&Date.now()-element.modified>this.maxAge)||(this.remove(key),this.emit("evict",{key:key,value:element.value}),!1)},LRU.prototype.get=function(key){if("string"!=typeof key&&(key=""+key),this.cache.hasOwnProperty(key)){var element=this.cache[key];if(this._checkAge(key,element))return this.head!==key&&(key===this.tail?(this.tail=element.next,this.cache[this.tail].prev=null):this.cache[element.prev].next=element.next,this.cache[element.next].prev=element.prev,this.cache[this.head].next=key,element.prev=this.head,element.next=null,this.head=key),element.value}},LRU.prototype.evict=function(){if(this.tail){var key=this.tail,value=this.remove(this.tail);this.emit("evict",{key:key,value:value})}}},function(module,exports,__webpack_require__){(function(process){function normalizeArray(parts,allowAboveRoot){for(var up=0,i=parts.length-1;i>=0;i--){var last=parts[i];"."===last?parts.splice(i,1):".."===last?(parts.splice(i,1),up++):up&&(parts.splice(i,1),up--)}if(allowAboveRoot)for(;up--;up)parts.unshift("..");return parts}function filter(xs,f){if(xs.filter)return xs.filter(f);for(var res=[],i=0;i=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if("string"!=typeof path)throw new TypeError("Arguments to path.resolve must be strings");path&&(resolvedPath=path+"/"+resolvedPath,resolvedAbsolute="/"===path.charAt(0))}return resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/"),(resolvedAbsolute?"/":"")+resolvedPath||"."},exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash="/"===substr(path,-1);return path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/"),path||isAbsolute||(path="."),path&&trailingSlash&&(path+="/"),(isAbsolute?"/":"")+path},exports.isAbsolute=function(path){return"/"===path.charAt(0)},exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if("string"!=typeof p)throw new TypeError("Arguments to path.join must be strings");return p}).join("/"))},exports.relative=function(from,to){function trim(arr){for(var start=0;start=0&&""===arr[end];end--);return start>end?[]:arr.slice(start,end-start+1)}from=exports.resolve(from).substr(1),to=exports.resolve(to).substr(1);for(var fromParts=trim(from.split("/")),toParts=trim(to.split("/")),length=Math.min(fromParts.length,toParts.length),samePartsLength=length,i=0;i0;){var fn=queue.shift();if("function"==typeof fn){var receiver=queue.shift(),arg=queue.shift();fn.call(receiver,arg)}else fn._settlePromises()}},Async.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},Async.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},Async.prototype._reset=function(){this._isTickUsed=!1},module.exports=Async,module.exports.firstLineError=firstLineError},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL,tryConvertToPromise,debug){var calledBind=!1,rejectThis=function(_,e){this._reject(e)},targetRejected=function(e,context){context.promiseRejectionQueued=!0,context.bindingPromise._then(rejectThis,rejectThis,null,this,e)},bindingResolved=function(thisArg,context){0===(50397184&this._bitField)&&this._resolveCallback(context.target)},bindingRejected=function(e,context){context.promiseRejectionQueued||this._reject(e)};Promise.prototype.bind=function(thisArg){calledBind||(calledBind=!0,Promise.prototype._propagateFrom=debug.propagateFromFunction(),Promise.prototype._boundValue=debug.boundValueFunction());var maybePromise=tryConvertToPromise(thisArg),ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();if(ret._setBoundTo(maybePromise),maybePromise instanceof Promise){var context={promiseRejectionQueued:!1,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,void 0,ret,context),maybePromise._then(bindingResolved,bindingRejected,void 0,ret,context),ret._setOnCancel(maybePromise)}else ret._resolveCallback(target);return ret},Promise.prototype._setBoundTo=function(obj){void 0!==obj?(this._bitField=2097152|this._bitField,this._boundTo=obj):this._bitField=this._bitField&-2097153},Promise.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},Promise.bind=function(thisArg,value){return Promise.resolve(value).bind(thisArg)}}},{}],4:[function(_dereq_,module,exports){function noConflict(){try{Promise===bluebird&&(Promise=old)}catch(e){}return bluebird}var old;"undefined"!=typeof Promise&&(old=Promise);var bluebird=_dereq_("./promise")();bluebird.noConflict=noConflict,module.exports=bluebird},{"./promise":22}],5:[function(_dereq_,module,exports){var cr=Object.create;if(cr){var callerCache=cr(null),getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0}module.exports=function(Promise){function ensureMethod(obj,methodName){var fn;if(null!=obj&&(fn=obj[methodName]),"function"!=typeof fn){var message="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'";throw new Promise.TypeError(message)}return fn}function caller(obj){var methodName=this.pop(),fn=ensureMethod(obj,methodName);return fn.apply(obj,this)}function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;return index<0&&(index=Math.max(0,index+obj.length)),obj[index]}var getGetter,util=_dereq_("./util"),canEvaluate=util.canEvaluate;util.isIdentifier;Promise.prototype.call=function(methodName){var args=[].slice.call(arguments,1);return args.push(methodName),this._then(caller,void 0,void 0,args,void 0)},Promise.prototype.get=function(propertyName){var getter,isIndex="number"==typeof propertyName;if(isIndex)getter=indexedGetter;else if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=null!==maybeGetter?maybeGetter:namedGetter}else getter=namedGetter;return this._then(getter,void 0,void 0,propertyName,void 0)}}},{"./util":36}],6:[function(_dereq_,module,exports){module.exports=function(Promise,PromiseArray,apiRejection,debug){var util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;Promise.prototype.break=Promise.prototype.cancel=function(){if(!debug.cancellation())return this._warn("cancellation is disabled");for(var promise=this,child=promise;promise._isCancellable();){if(!promise._cancelBy(child)){child._isFollowing()?child._followee().cancel():child._cancelBranched();break}var parent=promise._cancellationParent;if(null==parent||!parent._isCancellable()){promise._isFollowing()?promise._followee().cancel():promise._cancelBranched();break}promise._isFollowing()&&promise._followee().cancel(),promise._setWillBeCancelled(),child=promise,promise=parent}},Promise.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},Promise.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},Promise.prototype._cancelBy=function(canceller){return canceller===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},Promise.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},Promise.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),async.invoke(this._cancelPromises,this,void 0))},Promise.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},Promise.prototype._unsetOnCancel=function(){this._onCancelField=void 0},Promise.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},Promise.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},Promise.prototype._doInvokeOnCancel=function(onCancelCallback,internalOnly){if(util.isArray(onCancelCallback))for(var i=0;i=0)return contextStack[lastIndex]}var longStackTraces=!1,contextStack=[];return Promise.prototype._promiseCreated=function(){},Promise.prototype._pushContext=function(){},Promise.prototype._popContext=function(){return null},Promise._peekContext=Promise.prototype._peekContext=function(){},Context.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,contextStack.push(this._trace))},Context.prototype._popContext=function(){if(void 0!==this._trace){var trace=contextStack.pop(),ret=trace._promiseCreated;return trace._promiseCreated=null,ret}return null},Context.CapturedTrace=null,Context.create=createContext,Context.deactivateLongStackTraces=function(){},Context.activateLongStackTraces=function(){var Promise_pushContext=Promise.prototype._pushContext,Promise_popContext=Promise.prototype._popContext,Promise_PeekContext=Promise._peekContext,Promise_peekContext=Promise.prototype._peekContext,Promise_promiseCreated=Promise.prototype._promiseCreated;Context.deactivateLongStackTraces=function(){Promise.prototype._pushContext=Promise_pushContext,Promise.prototype._popContext=Promise_popContext,Promise._peekContext=Promise_PeekContext,Promise.prototype._peekContext=Promise_peekContext,Promise.prototype._promiseCreated=Promise_promiseCreated,longStackTraces=!1},longStackTraces=!0,Promise.prototype._pushContext=Context.prototype._pushContext,Promise.prototype._popContext=Context.prototype._popContext,Promise._peekContext=Promise.prototype._peekContext=peekContext,Promise.prototype._promiseCreated=function(){var ctx=this._peekContext();ctx&&null==ctx._promiseCreated&&(ctx._promiseCreated=this)}},Context}},{}],9:[function(_dereq_,module,exports){module.exports=function(Promise,Context){function generatePromiseLifecycleEventObject(name,promise){return{promise:promise}}function defaultFireEvent(){return!1}function cancellationExecute(executor,resolve,reject){var promise=this;try{executor(resolve,reject,function(onCancel){if("function"!=typeof onCancel)throw new TypeError("onCancel must be a function, got: "+util.toString(onCancel));promise._attachCancellationCallback(onCancel)})}catch(e){return e}}function cancellationAttachCancellationCallback(onCancel){if(!this._isCancellable())return this;var previousOnCancel=this._onCancel();void 0!==previousOnCancel?util.isArray(previousOnCancel)?previousOnCancel.push(onCancel):this._setOnCancel([previousOnCancel,onCancel]):this._setOnCancel(onCancel)}function cancellationOnCancel(){return this._onCancelField}function cancellationSetOnCancel(onCancel){this._onCancelField=onCancel}function cancellationClearCancellationData(){this._cancellationParent=void 0,this._onCancelField=void 0}function cancellationPropagateFrom(parent,flags){if(0!==(1&flags)){this._cancellationParent=parent;var branchesRemainingToCancel=parent._branchesRemainingToCancel;void 0===branchesRemainingToCancel&&(branchesRemainingToCancel=0),parent._branchesRemainingToCancel=branchesRemainingToCancel+1}0!==(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)}function bindingPropagateFrom(parent,flags){0!==(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)}function _boundValueFunction(){var ret=this._boundTo;return void 0!==ret&&ret instanceof Promise?ret.isFulfilled()?ret.value():void 0:ret}function longStackTracesCaptureStackTrace(){this._trace=new CapturedTrace(this._peekContext())}function longStackTracesAttachExtraTrace(error,ignoreSelf){if(canAttachTrace(error)){var trace=this._trace;if(void 0!==trace&&ignoreSelf&&(trace=trace._parent),void 0!==trace)trace.attachExtraTrace(error);else if(!error.__stackCleaned__){var parsed=parseStackAndMessage(error);util.notEnumerableProp(error,"stack",parsed.message+"\n"+parsed.stack.join("\n")),util.notEnumerableProp(error,"__stackCleaned__",!0)}}}function checkForgottenReturns(returnValue,promiseCreated,name,promise,parent){if(void 0===returnValue&&null!==promiseCreated&&wForgottenReturn){if(void 0!==parent&&parent._returnedNonUndefined())return;if(0===(65535&promise._bitField))return;name&&(name+=" ");var handlerLine="",creatorLine="";if(promiseCreated._trace){for(var traceLines=promiseCreated._trace.stack.split("\n"),stack=cleanStack(traceLines),i=stack.length-1;i>=0;--i){var line=stack[i];if(!nodeFramePattern.test(line)){var lineMatches=line.match(parseLinePattern);lineMatches&&(handlerLine="at "+lineMatches[1]+":"+lineMatches[2]+":"+lineMatches[3]+" ");break}}if(stack.length>0)for(var firstUserLine=stack[0],i=0;i0&&(creatorLine="\n"+traceLines[i-1]);break}}var msg="a promise was created in a "+name+"handler "+handlerLine+"but was not returned from it, see http://goo.gl/rRqMUw"+creatorLine;promise._warn(msg,!0,promiseCreated)}}function deprecated(name,replacement){var message=name+" is deprecated and will be removed in a future version.";return replacement&&(message+=" Use "+replacement+" instead."),warn(message)}function warn(message,shouldUseOwnTrace,promise){if(config.warnings){var ctx,warning=new Warning(message);if(shouldUseOwnTrace)promise._attachExtraTrace(warning);else if(config.longStackTraces&&(ctx=Promise._peekContext()))ctx.attachExtraTrace(warning);else{var parsed=parseStackAndMessage(warning);warning.stack=parsed.message+"\n"+parsed.stack.join("\n")}activeFireEvent("warning",warning)||formatAndLogError(warning,"",!0)}}function reconstructStack(message,stacks){for(var i=0;i=0;--j)if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]!==line)break;current.pop(),currentLastIndex--}current=prev}}function cleanStack(stack){for(var ret=[],i=0;i0&&(stack=stack.slice(i)),stack}function parseStackAndMessage(error){var stack=error.stack,message=error.toString();return stack="string"==typeof stack&&stack.length>0?stackFramesAsArray(error):[" (No stack trace)"],{message:message,stack:cleanStack(stack)}}function formatAndLogError(error,title,isSoft){if("undefined"!=typeof console){var message;if(util.isObject(error)){var stack=error.stack;message=title+formatStack(stack,error)}else message=title+String(error);"function"==typeof printWarning?printWarning(message,isSoft):"function"!=typeof console.log&&"object"!==_typeof(console.log)||console.log(message)}}function fireRejectionEvent(name,localHandler,reason,promise){var localEventFired=!1;try{"function"==typeof localHandler&&(localEventFired=!0,"rejectionHandled"===name?localHandler(promise):localHandler(reason,promise))}catch(e){async.throwLater(e)}"unhandledRejection"===name?activeFireEvent(name,reason,promise)||localEventFired||formatAndLogError(reason,"Unhandled rejection "):activeFireEvent(name,promise)}function formatNonError(obj){var str;if("function"==typeof obj)str="[function "+(obj.name||"anonymous")+"]";else{str=obj&&"function"==typeof obj.toString?obj.toString():util.toString(obj);var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str))try{var newStr=JSON.stringify(obj);str=newStr}catch(e){}0===str.length&&(str="(empty array)")}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;return str.length=lastIndex||(shouldIgnore=function(line){if(bluebirdFramePattern.test(line))return!0;var info=parseLineInfo(line);return!!(info&&info.fileName===firstFileName&&firstIndex<=info.line&&info.line<=lastIndex)})}}function CapturedTrace(parent){this._parent=parent,this._promisesCreated=0;var length=this._length=1+(void 0===parent?0:parent._length);captureStackTrace(this,CapturedTrace),length>32&&this.uncycle()}var unhandledRejectionHandled,possiblyUnhandledRejection,printWarning,getDomain=Promise._getDomain,async=Promise._async,Warning=_dereq_("./errors").Warning,util=_dereq_("./util"),canAttachTrace=util.canAttachTrace,bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,nodeFramePattern=/\((?:timers\.js):\d+:\d+\)/,parseLinePattern=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,stackFramePattern=null,formatStack=null,indentStackFrames=!1,debugging=!(0==util.env("BLUEBIRD_DEBUG")),warnings=!(0==util.env("BLUEBIRD_WARNINGS")||!debugging&&!util.env("BLUEBIRD_WARNINGS")),longStackTraces=!(0==util.env("BLUEBIRD_LONG_STACK_TRACES")||!debugging&&!util.env("BLUEBIRD_LONG_STACK_TRACES")),wForgottenReturn=0!=util.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(warnings||!!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));Promise.prototype.suppressUnhandledRejections=function(){var target=this._target();target._bitField=target._bitField&-1048577|524288},Promise.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),async.invokeLater(this._notifyUnhandledRejection,this,void 0))},Promise.prototype._notifyUnhandledRejectionIsHandled=function(){fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,void 0,this)},Promise.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},Promise.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._settledValue();this._setUnhandledRejectionIsNotified(),fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this)}},Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&-262145},Promise.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&-1048577,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},Promise.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},Promise.prototype._warn=function(message,shouldUseOwnTrace,promise){return warn(message,shouldUseOwnTrace,promise||this)},Promise.onPossiblyUnhandledRejection=function(fn){var domain=getDomain();possiblyUnhandledRejection="function"==typeof fn?null===domain?fn:util.domainBind(domain,fn):void 0},Promise.onUnhandledRejectionHandled=function(fn){var domain=getDomain();unhandledRejectionHandled="function"==typeof fn?null===domain?fn:util.domainBind(domain,fn):void 0};var disableLongStackTraces=function(){};Promise.longStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!config.longStackTraces&&longStackTracesIsSupported()){var Promise_captureStackTrace=Promise.prototype._captureStackTrace,Promise_attachExtraTrace=Promise.prototype._attachExtraTrace;config.longStackTraces=!0,disableLongStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");Promise.prototype._captureStackTrace=Promise_captureStackTrace,Promise.prototype._attachExtraTrace=Promise_attachExtraTrace,Context.deactivateLongStackTraces(),async.enableTrampoline(),config.longStackTraces=!1},Promise.prototype._captureStackTrace=longStackTracesCaptureStackTrace,Promise.prototype._attachExtraTrace=longStackTracesAttachExtraTrace,Context.activateLongStackTraces(),async.disableTrampolineIfNecessary()}},Promise.hasLongStackTraces=function(){return config.longStackTraces&&longStackTracesIsSupported()};var fireDomEvent=function(){try{if("function"==typeof CustomEvent){var event=new CustomEvent("CustomEvent");return util.global.dispatchEvent(event),function(name,event){var domEvent=new CustomEvent(name.toLowerCase(),{detail:event,cancelable:!0});return!util.global.dispatchEvent(domEvent)}}if("function"==typeof Event){var event=new Event("CustomEvent");return util.global.dispatchEvent(event),function(name,event){var domEvent=new Event(name.toLowerCase(),{cancelable:!0});return domEvent.detail=event,!util.global.dispatchEvent(domEvent)}}var event=document.createEvent("CustomEvent");return event.initCustomEvent("testingtheevent",!1,!0,{}),util.global.dispatchEvent(event),function(name,event){var domEvent=document.createEvent("CustomEvent");return domEvent.initCustomEvent(name.toLowerCase(),!1,!0,event),!util.global.dispatchEvent(domEvent)}}catch(e){}return function(){return!1}}(),fireGlobalEvent=function(){return util.isNode?function(){return process.emit.apply(process,arguments)}:util.global?function(name){var methodName="on"+name.toLowerCase(),method=util.global[methodName];return!!method&&(method.apply(util.global,[].slice.call(arguments,1)),!0)}:function(){return!1}}(),eventToObjectGenerator={promiseCreated:generatePromiseLifecycleEventObject,promiseFulfilled:generatePromiseLifecycleEventObject,promiseRejected:generatePromiseLifecycleEventObject,promiseResolved:generatePromiseLifecycleEventObject,promiseCancelled:generatePromiseLifecycleEventObject,promiseChained:function(name,promise,child){return{promise:promise,child:child}},warning:function(name,_warning){return{warning:_warning}},unhandledRejection:function(name,reason,promise){return{reason:reason,promise:promise}},rejectionHandled:generatePromiseLifecycleEventObject},activeFireEvent=function(name){var globalEventFired=!1;try{globalEventFired=fireGlobalEvent.apply(null,arguments)}catch(e){async.throwLater(e),globalEventFired=!0}var domEventFired=!1;try{domEventFired=fireDomEvent(name,eventToObjectGenerator[name].apply(null,arguments))}catch(e){async.throwLater(e),domEventFired=!0}return domEventFired||globalEventFired};Promise.config=function(opts){if(opts=Object(opts),"longStackTraces"in opts&&(opts.longStackTraces?Promise.longStackTraces():!opts.longStackTraces&&Promise.hasLongStackTraces()&&disableLongStackTraces()),"warnings"in opts){var warningsOption=opts.warnings;config.warnings=!!warningsOption,wForgottenReturn=config.warnings,util.isObject(warningsOption)&&"wForgottenReturn"in warningsOption&&(wForgottenReturn=!!warningsOption.wForgottenReturn)}if("cancellation"in opts&&opts.cancellation&&!config.cancellation){if(async.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");Promise.prototype._clearCancellationData=cancellationClearCancellationData,Promise.prototype._propagateFrom=cancellationPropagateFrom,Promise.prototype._onCancel=cancellationOnCancel,Promise.prototype._setOnCancel=cancellationSetOnCancel,Promise.prototype._attachCancellationCallback=cancellationAttachCancellationCallback,Promise.prototype._execute=cancellationExecute,_propagateFromFunction=cancellationPropagateFrom,config.cancellation=!0}"monitoring"in opts&&(opts.monitoring&&!config.monitoring?(config.monitoring=!0,Promise.prototype._fireEvent=activeFireEvent):!opts.monitoring&&config.monitoring&&(config.monitoring=!1,Promise.prototype._fireEvent=defaultFireEvent))},Promise.prototype._fireEvent=defaultFireEvent,Promise.prototype._execute=function(executor,resolve,reject){try{executor(resolve,reject)}catch(e){return e}},Promise.prototype._onCancel=function(){},Promise.prototype._setOnCancel=function(handler){},Promise.prototype._attachCancellationCallback=function(onCancel){},Promise.prototype._captureStackTrace=function(){},Promise.prototype._attachExtraTrace=function(){},Promise.prototype._clearCancellationData=function(){},Promise.prototype._propagateFrom=function(parent,flags){};var _propagateFromFunction=bindingPropagateFrom,shouldIgnore=function(){return!1},parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;util.inherits(CapturedTrace,Error),Context.CapturedTrace=CapturedTrace,CapturedTrace.prototype.uncycle=function(){var length=this._length;if(!(length<2)){for(var nodes=[],stackToIndex={},i=0,node=this;void 0!==node;++i)nodes.push(node),node=node._parent;length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;void 0===stackToIndex[stack]&&(stackToIndex[stack]=i)}for(var i=0;i0&&(nodes[index-1]._parent=void 0,nodes[index-1]._length=1),nodes[i]._parent=void 0,nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;index=0;--j)nodes[j]._length=currentChildLength,currentChildLength++;return}}}},CapturedTrace.prototype.attachExtraTrace=function(error){if(!error.__stackCleaned__){this.uncycle();for(var parsed=parseStackAndMessage(error),message=parsed.message,stacks=[parsed.stack],trace=this;void 0!==trace;)stacks.push(cleanStack(trace.stack.split("\n"))),trace=trace._parent;removeCommonRoots(stacks),removeDuplicateOrEmptyJumps(stacks),util.notEnumerableProp(error,"stack",reconstructStack(message,stacks)),util.notEnumerableProp(error,"__stackCleaned__",!0)}};var captureStackTrace=function(){var v8stackFramePattern=/^\s*at\s*/,v8stackFormatter=function(stack,error){return"string"==typeof stack?stack:void 0!==error.name&&void 0!==error.message?error.toString():formatNonError(error)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;return shouldIgnore=function(line){return bluebirdFramePattern.test(line)},function(receiver,ignoreUntil){Error.stackTraceLimit+=6,captureStackTrace(receiver,ignoreUntil),Error.stackTraceLimit-=6}}var err=new Error;if("string"==typeof err.stack&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0)return stackFramePattern=/@/,formatStack=v8stackFormatter,indentStackFrames=!0,function(o){o.stack=(new Error).stack};var hasStackAfterThrow;try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}return"stack"in err||!hasStackAfterThrow||"number"!=typeof Error.stackTraceLimit?(formatStack=function(stack,error){return"string"==typeof stack?stack:"object"!==("undefined"==typeof error?"undefined":_typeof(error))&&"function"!=typeof error||void 0===error.name||void 0===error.message?formatNonError(error):error.toString()},null):(stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter,function(o){Error.stackTraceLimit+=6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(printWarning=function(message){console.warn(message)},util.isNode&&process.stderr.isTTY?printWarning=function(message,isSoft){ var color=isSoft?"":"";console.warn(color+message+"\n")}:util.isNode||"string"!=typeof(new Error).stack||(printWarning=function(message,isSoft){console.warn("%c"+message,isSoft?"color: darkorange":"color: red")}));var config={warnings:warnings,longStackTraces:!1,cancellation:!1,monitoring:!1};return longStackTraces&&Promise.longStackTraces(),{longStackTraces:function(){return config.longStackTraces},warnings:function(){return config.warnings},cancellation:function(){return config.cancellation},monitoring:function(){return config.monitoring},propagateFromFunction:function(){return _propagateFromFunction},boundValueFunction:function(){return _boundValueFunction},checkForgottenReturns:checkForgottenReturns,setBounds:setBounds,warn:warn,deprecated:deprecated,CapturedTrace:CapturedTrace,fireDomEvent:fireDomEvent,fireGlobalEvent:fireGlobalEvent}}},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){module.exports=function(Promise){function returner(){return this.value}function thrower(){throw this.reason}Promise.prototype.return=Promise.prototype.thenReturn=function(value){return value instanceof Promise&&value.suppressUnhandledRejections(),this._then(returner,void 0,void 0,{value:value},void 0)},Promise.prototype.throw=Promise.prototype.thenThrow=function(reason){return this._then(thrower,void 0,void 0,{reason:reason},void 0)},Promise.prototype.catchThrow=function(reason){if(arguments.length<=1)return this._then(void 0,thrower,void 0,{reason:reason},void 0);var _reason=arguments[1],handler=function(){throw _reason};return this.caught(reason,handler)},Promise.prototype.catchReturn=function(value){if(arguments.length<=1)return value instanceof Promise&&value.suppressUnhandledRejections(),this._then(void 0,returner,void 0,{value:value},void 0);var _value=arguments[1];_value instanceof Promise&&_value.suppressUnhandledRejections();var handler=function(){return _value};return this.caught(value,handler)}}},{}],11:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL){function promiseAllThis(){return PromiseAll(this)}function PromiseMapSeries(promises,fn){return PromiseReduce(promises,fn,INTERNAL,INTERNAL)}var PromiseReduce=Promise.reduce,PromiseAll=Promise.all;Promise.prototype.each=function(fn){return PromiseReduce(this,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,this,void 0)},Promise.prototype.mapSeries=function(fn){return PromiseReduce(this,fn,INTERNAL,INTERNAL)},Promise.each=function(promises,fn){return PromiseReduce(promises,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,promises,void 0)},Promise.mapSeries=PromiseMapSeries}},{}],12:[function(_dereq_,module,exports){function subError(nameProperty,defaultMessage){function SubError(message){return this instanceof SubError?(notEnumerableProp(this,"message","string"==typeof message?message:defaultMessage),notEnumerableProp(this,"name",nameProperty),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new SubError(message)}return inherits(SubError,Error),SubError}function OperationalError(message){return this instanceof OperationalError?(notEnumerableProp(this,"name","OperationalError"),notEnumerableProp(this,"message",message),this.cause=message,this.isOperational=!0,void(message instanceof Error?(notEnumerableProp(this,"message",message.message),notEnumerableProp(this,"stack",message.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new OperationalError(message)}var _TypeError,_RangeError,es5=_dereq_("./es5"),Objectfreeze=es5.freeze,util=_dereq_("./util"),inherits=util.inherits,notEnumerableProp=util.notEnumerableProp,Warning=subError("Warning","warning"),CancellationError=subError("CancellationError","cancellation error"),TimeoutError=subError("TimeoutError","timeout error"),AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError,_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error"),_RangeError=subError("RangeError","range error")}for(var methods="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),i=0;i1?ctx.cancelPromise._reject(reason):ctx.cancelPromise._cancel(),ctx.cancelPromise=null,!0)}function succeed(){return finallyHandler.call(this,this.promise._target()._settledValue())}function fail(reason){if(!checkCancel(this,reason))return errorObj.e=reason,errorObj}function finallyHandler(reasonOrValue){var promise=this.promise,handler=this.handler;if(!this.called){this.called=!0;var ret=this.isFinallyHandler()?handler.call(promise._boundValue()):handler.call(promise._boundValue(),reasonOrValue);if(void 0!==ret){promise._setReturnedNonUndefined();var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){if(null!=this.cancelPromise){if(maybePromise._isCancelled()){var reason=new CancellationError("late cancellation observer");return promise._attachExtraTrace(reason),errorObj.e=reason,errorObj}maybePromise.isPending()&&maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this))}return maybePromise._then(succeed,fail,void 0,this,void 0)}}}return promise.isRejected()?(checkCancel(this),errorObj.e=reasonOrValue,errorObj):(checkCancel(this),reasonOrValue)}var util=_dereq_("./util"),CancellationError=Promise.CancellationError,errorObj=util.errorObj;return PassThroughHandlerContext.prototype.isFinallyHandler=function(){return 0===this.type},FinallyHandlerCancelReaction.prototype._resultCancelled=function(){checkCancel(this.finallyHandler)},Promise.prototype._passThrough=function(handler,type,success,fail){return"function"!=typeof handler?this.then():this._then(success,fail,void 0,new PassThroughHandlerContext(this,type,handler),void 0)},Promise.prototype.lastly=Promise.prototype.finally=function(handler){return this._passThrough(handler,0,finallyHandler,finallyHandler)},Promise.prototype.tap=function(handler){return this._passThrough(handler,1,finallyHandler)},PassThroughHandlerContext}},{"./util":36}],16:[function(_dereq_,module,exports){module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug){function promiseFromYieldHandler(value,yieldHandlers,traceParent){for(var i=0;i0&&"function"==typeof arguments[last]){fn=arguments[last];var ret}var args=[].slice.call(arguments);fn&&args.pop();var ret=new PromiseArray(args).promise();return void 0!==fn?ret.spread(fn):ret}}},{"./util":36}],18:[function(_dereq_,module,exports){module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises),this._promise._captureStackTrace();var domain=getDomain();this._callback=null===domain?fn:util.domainBind(domain,fn),this._preservedValues=_filter===INTERNAL?new Array(this.length()):null,this._limit=limit,this._inFlight=0,this._queue=[],async.invoke(this._asyncInit,this,void 0)}function map(promises,fn,options,_filter){if("function"!=typeof fn)return apiRejection("expecting a function but got "+util.classString(fn));var limit=0;if(void 0!==options){if("object"!==("undefined"==typeof options?"undefined":_typeof(options))||null===options)return Promise.reject(new TypeError("options argument must be an object but it is "+util.classString(options)));if("number"!=typeof options.concurrency)return Promise.reject(new TypeError("'concurrency' must be a number but it is "+util.classString(options.concurrency)));limit=options.concurrency}return limit="number"==typeof limit&&isFinite(limit)&&limit>=1?limit:0,new MappingPromiseArray(promises,fn,limit,_filter).promise()}var getDomain=Promise._getDomain,util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;util.inherits(MappingPromiseArray,PromiseArray),MappingPromiseArray.prototype._asyncInit=function(){this._init$(void 0,-2)},MappingPromiseArray.prototype._init=function(){},MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values,length=this.length(),preservedValues=this._preservedValues,limit=this._limit;if(index<0){if(index=index*-1-1,values[index]=value,limit>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(limit>=1&&this._inFlight>=limit)return values[index]=value,this._queue.push(index),!1;null!==preservedValues&&(preservedValues[index]=value);var promise=this._promise,callback=this._callback,receiver=promise._boundValue();promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length),promiseCreated=promise._popContext();if(debug.checkForgottenReturns(ret,promiseCreated,null!==preservedValues?"Promise.filter":"Promise.map",promise),ret===errorObj)return this._reject(ret.e),!0;var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if(0===(50397184&bitField))return limit>=1&&this._inFlight++,values[index]=maybePromise,maybePromise._proxy(this,(index+1)*-1),!1;if(0===(33554432&bitField))return 0!==(16777216&bitField)?(this._reject(maybePromise._reason()),!0):(this._cancel(),!0);ret=maybePromise._value()}values[index]=ret}var totalResolved=++this._totalResolved;return totalResolved>=length&&(null!==preservedValues?this._filter(values,preservedValues):this._resolve(values),!0)},MappingPromiseArray.prototype._drainQueue=function(){for(var queue=this._queue,limit=this._limit,values=this._values;queue.length>0&&this._inFlight1){debug.deprecated("calling Promise.try with more than 1 argument");var arg=arguments[1],ctx=arguments[2];value=util.isArray(arg)?tryCatch(fn).apply(ctx,arg):tryCatch(fn).call(ctx,arg)}else value=tryCatch(fn)();var promiseCreated=ret._popContext();return debug.checkForgottenReturns(value,promiseCreated,"Promise.try",ret),ret._resolveFromSyncValue(value),ret},Promise.prototype._resolveFromSyncValue=function(value){value===util.errorObj?this._rejectCallback(value.e,!1):this._resolveCallback(value,!0)}}},{"./util":36}],20:[function(_dereq_,module,exports){function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj),ret.name=obj.name,ret.message=obj.message,ret.stack=obj.stack;for(var keys=es5.keys(obj),i=0;i1){var i,catchInstances=new Array(len-1),j=0;for(i=0;i0&&"function"!=typeof didFulfill&&"function"!=typeof didReject){var msg=".then() only accepts functions but was passed: "+util.classString(didFulfill);arguments.length>1&&(msg+=", "+util.classString(didReject)),this._warn(msg)}return this._then(didFulfill,didReject,void 0,void 0,void 0)},Promise.prototype.done=function(didFulfill,didReject){var promise=this._then(didFulfill,didReject,void 0,void 0,void 0);promise._setIsFinal()},Promise.prototype.spread=function(fn){return"function"!=typeof fn?apiRejection("expecting a function but got "+util.classString(fn)):this.all()._then(fn,void 0,void 0,APPLY,void 0)},Promise.prototype.toJSON=function(){var ret={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(ret.fulfillmentValue=this.value(),ret.isFulfilled=!0):this.isRejected()&&(ret.rejectionReason=this.reason(),ret.isRejected=!0),ret},Promise.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new PromiseArray(this).promise()},Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn)},Promise.getNewLibraryCopy=module.exports,Promise.is=function(val){return val instanceof Promise},Promise.fromNode=Promise.fromCallback=function(fn){var ret=new Promise(INTERNAL);ret._captureStackTrace();var multiArgs=arguments.length>1&&!!Object(arguments[1]).multiArgs,result=tryCatch(fn)(nodebackForPromise(ret,multiArgs));return result===errorObj&&ret._rejectCallback(result.e,!0),ret._isFateSealed()||ret._setAsyncGuaranteed(),ret},Promise.all=function(promises){return new PromiseArray(promises).promise()},Promise.cast=function(obj){var ret=tryConvertToPromise(obj);return ret instanceof Promise||(ret=new Promise(INTERNAL),ret._captureStackTrace(),ret._setFulfilled(),ret._rejectionHandler0=obj),ret},Promise.resolve=Promise.fulfilled=Promise.cast,Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);return ret._captureStackTrace(),ret._rejectCallback(reason,!0),ret},Promise.setScheduler=function(fn){if("function"!=typeof fn)throw new TypeError("expecting a function but got "+util.classString(fn));return async.setScheduler(fn)},Promise.prototype._then=function(didFulfill,didReject,_,receiver,internalData){var haveInternalData=void 0!==internalData,promise=haveInternalData?internalData:new Promise(INTERNAL),target=this._target(),bitField=target._bitField;haveInternalData||(promise._propagateFrom(this,3),promise._captureStackTrace(),void 0===receiver&&0!==(2097152&this._bitField)&&(receiver=0!==(50397184&bitField)?this._boundValue():target===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,promise));var domain=getDomain();if(0!==(50397184&bitField)){var handler,value,settler=target._settlePromiseCtx;0!==(33554432&bitField)?(value=target._rejectionHandler0,handler=didFulfill):0!==(16777216&bitField)?(value=target._fulfillmentHandler0,handler=didReject,target._unsetRejectionIsUnhandled()):(settler=target._settlePromiseLateCancellationObserver,value=new CancellationError("late cancellation observer"),target._attachExtraTrace(value),handler=didReject),async.invoke(settler,target,{handler:null===domain?handler:"function"==typeof handler&&util.domainBind(domain,handler),promise:promise,receiver:receiver,value:value})}else target._addCallbacks(didFulfill,didReject,promise,receiver,domain);return promise},Promise.prototype._length=function(){return 65535&this._bitField},Promise.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},Promise.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},Promise.prototype._setLength=function(len){this._bitField=this._bitField&-65536|65535&len},Promise.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},Promise.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},Promise.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},Promise.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},Promise.prototype._isFinal=function(){return(4194304&this._bitField)>0},Promise.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},Promise.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},Promise.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},Promise.prototype._setAsyncGuaranteed=function(){async.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},Promise.prototype._receiverAt=function(index){var ret=0===index?this._receiver0:this[4*index-4+3];if(ret!==UNDEFINED_BINDING)return void 0===ret&&this._isBound()?this._boundValue():ret},Promise.prototype._promiseAt=function(index){return this[4*index-4+2]},Promise.prototype._fulfillmentHandlerAt=function(index){return this[4*index-4+0]},Promise.prototype._rejectionHandlerAt=function(index){return this[4*index-4+1]},Promise.prototype._boundValue=function(){},Promise.prototype._migrateCallback0=function(follower){var fulfill=(follower._bitField,follower._fulfillmentHandler0),reject=follower._rejectionHandler0,promise=follower._promise0,receiver=follower._receiverAt(0);void 0===receiver&&(receiver=UNDEFINED_BINDING),this._addCallbacks(fulfill,reject,promise,receiver,null)},Promise.prototype._migrateCallbackAt=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index),reject=follower._rejectionHandlerAt(index),promise=follower._promiseAt(index),receiver=follower._receiverAt(index);void 0===receiver&&(receiver=UNDEFINED_BINDING),this._addCallbacks(fulfill,reject,promise,receiver,null)},Promise.prototype._addCallbacks=function(fulfill,reject,promise,receiver,domain){var index=this._length();if(index>=65531&&(index=0,this._setLength(0)),0===index)this._promise0=promise,this._receiver0=receiver,"function"==typeof fulfill&&(this._fulfillmentHandler0=null===domain?fulfill:util.domainBind(domain,fulfill)),"function"==typeof reject&&(this._rejectionHandler0=null===domain?reject:util.domainBind(domain,reject));else{ var base=4*index-4;this[base+2]=promise,this[base+3]=receiver,"function"==typeof fulfill&&(this[base+0]=null===domain?fulfill:util.domainBind(domain,fulfill)),"function"==typeof reject&&(this[base+1]=null===domain?reject:util.domainBind(domain,reject))}return this._setLength(index+1),index},Promise.prototype._proxy=function(proxyable,arg){this._addCallbacks(void 0,void 0,arg,proxyable,null)},Promise.prototype._resolveCallback=function(value,shouldBind){if(0===(117506048&this._bitField)){if(value===this)return this._rejectCallback(makeSelfResolutionError(),!1);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);shouldBind&&this._propagateFrom(maybePromise,2);var promise=maybePromise._target();if(promise===this)return void this._reject(makeSelfResolutionError());var bitField=promise._bitField;if(0===(50397184&bitField)){var len=this._length();len>0&&promise._migrateCallback0(this);for(var i=1;i>>16)){if(value===this){var err=makeSelfResolutionError();return this._attachExtraTrace(err),this._reject(err)}this._setFulfilled(),this._rejectionHandler0=value,(65535&bitField)>0&&(0!==(134217728&bitField)?this._settlePromises():async.settlePromises(this))}},Promise.prototype._reject=function(reason){var bitField=this._bitField;if(!((117506048&bitField)>>>16))return this._setRejected(),this._fulfillmentHandler0=reason,this._isFinal()?async.fatalError(reason,util.isNode):void((65535&bitField)>0?async.settlePromises(this):this._ensurePossibleRejectionHandled())},Promise.prototype._fulfillPromises=function(len,value){for(var i=1;i0){if(0!==(16842752&bitField)){var reason=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,reason,bitField),this._rejectPromises(len,reason)}else{var value=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,value,bitField),this._fulfillPromises(len,value)}this._setLength(0)}this._clearCancellationData()},Promise.prototype._settledValue=function(){var bitField=this._bitField;return 0!==(33554432&bitField)?this._rejectionHandler0:0!==(16777216&bitField)?this._fulfillmentHandler0:void 0},Promise.defer=Promise.pending=function(){debug.deprecated("Promise.defer","new Promise");var promise=new Promise(INTERNAL);return{promise:promise,resolve:deferResolve,reject:deferReject}},util.notEnumerableProp(Promise,"_makeSelfResolutionError",makeSelfResolutionError),_dereq_("./method")(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug),_dereq_("./bind")(Promise,INTERNAL,tryConvertToPromise,debug),_dereq_("./cancel")(Promise,PromiseArray,apiRejection,debug),_dereq_("./direct_resolve")(Promise),_dereq_("./synchronous_inspection")(Promise),_dereq_("./join")(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async,getDomain),Promise.Promise=Promise,Promise.version="3.4.6",_dereq_("./map.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug),_dereq_("./call_get.js")(Promise),_dereq_("./using.js")(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug),_dereq_("./timers.js")(Promise,INTERNAL,debug),_dereq_("./generators.js")(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug),_dereq_("./nodeify.js")(Promise),_dereq_("./promisify.js")(Promise,INTERNAL),_dereq_("./props.js")(Promise,PromiseArray,tryConvertToPromise,apiRejection),_dereq_("./race.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection),_dereq_("./reduce.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug),_dereq_("./settle.js")(Promise,PromiseArray,debug),_dereq_("./some.js")(Promise,PromiseArray,apiRejection),_dereq_("./filter.js")(Promise,INTERNAL),_dereq_("./each.js")(Promise,INTERNAL),_dereq_("./any.js")(Promise),util.toFastProperties(Promise),util.toFastProperties(Promise.prototype),fillTypes({a:1}),fillTypes({b:2}),fillTypes({c:3}),fillTypes(1),fillTypes(function(){}),fillTypes(void 0),fillTypes(!1),fillTypes(new Promise(INTERNAL)),debug.setBounds(Async.firstLineError,util.lastLineError),Promise}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable){function toResolutionValue(val){switch(val){case-2:return[];case-3:return{}}}function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);values instanceof Promise&&promise._propagateFrom(values,3),promise._setOnCancel(this),this._values=values,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var util=_dereq_("./util");util.isArray;return util.inherits(PromiseArray,Proxyable),PromiseArray.prototype.length=function(){return this._length},PromiseArray.prototype.promise=function(){return this._promise},PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){var values=tryConvertToPromise(this._values,this._promise);if(values instanceof Promise){values=values._target();var bitField=values._bitField;if(this._values=values,0===(50397184&bitField))return this._promise._setAsyncGuaranteed(),values._then(init,this._reject,void 0,this,resolveValueIfEmpty);if(0===(33554432&bitField))return 0!==(16777216&bitField)?this._reject(values._reason()):this._cancel();values=values._value()}if(values=util.asArray(values),null===values){var err=apiRejection("expecting an array or an iterable object but got "+util.classString(values)).reason();return void this._promise._rejectCallback(err,!1)}return 0===values.length?void(resolveValueIfEmpty===-5?this._resolveEmptyArray():this._resolve(toResolutionValue(resolveValueIfEmpty))):void this._iterate(values)},PromiseArray.prototype._iterate=function(values){var len=this.getActualLength(values.length);this._length=len,this._values=this.shouldCopyValues()?new Array(len):this._values;for(var result=this._promise,isResolved=!1,bitField=null,i=0;i=this._length&&(this._resolve(this._values),!0)},PromiseArray.prototype._promiseCancelled=function(){return this._cancel(),!0},PromiseArray.prototype._promiseRejected=function(reason){return this._totalResolved++,this._reject(reason),!0},PromiseArray.prototype._resultCancelled=function(){if(!this._isResolved()){var values=this._values;if(this._cancel(),values instanceof Promise)values.cancel();else for(var i=0;i=this._length){var val;if(this._isMap)val=entriesToMap(this._values);else{val={};for(var keyOffset=this.length(),i=0,len=this.length();i>1},Promise.prototype.props=function(){return props(this)},Promise.props=function(promises){return props(promises)}}},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j=this._length&&(this._resolve(this._values),!0)},SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;return ret._bitField=33554432,ret._settledValueField=value,this._promiseResolved(index,ret)},SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;return ret._bitField=16777216,ret._settledValueField=reason,this._promiseResolved(index,ret)},Promise.settle=function(promises){return debug.deprecated(".settle()",".reflect()"),new SettledPromiseArray(promises).promise()},Promise.prototype.settle=function(){return Promise.settle(this)}}},{"./util":36}],31:[function(_dereq_,module,exports){module.exports=function(Promise,PromiseArray,apiRejection){function SomePromiseArray(values){this.constructor$(values),this._howMany=0,this._unwrap=!1,this._initialized=!1}function some(promises,howMany){if((0|howMany)!==howMany||howMany<0)return apiRejection("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var ret=new SomePromiseArray(promises),promise=ret.promise();return ret.setHowMany(howMany),ret.init(),promise}var util=_dereq_("./util"),RangeError=_dereq_("./errors").RangeError,AggregateError=_dereq_("./errors").AggregateError,isArray=util.isArray,CANCELLATION={};util.inherits(SomePromiseArray,PromiseArray),SomePromiseArray.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var isArrayResolved=isArray(this._values);!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},SomePromiseArray.prototype.init=function(){this._initialized=!0,this._init()},SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=!0},SomePromiseArray.prototype.howMany=function(){return this._howMany},SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count},SomePromiseArray.prototype._promiseFulfilled=function(value){return this._addFulfilled(value),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},SomePromiseArray.prototype._promiseRejected=function(reason){return this._addRejected(reason),this._checkOutcome()},SomePromiseArray.prototype._promiseCancelled=function(){return this._values instanceof Promise||null==this._values?this._cancel():(this._addRejected(CANCELLATION),this._checkOutcome())},SomePromiseArray.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new AggregateError,i=this.length();i0?this._reject(e):this._cancel(),!0}return!1},SomePromiseArray.prototype._fulfilled=function(){return this._totalResolved},SomePromiseArray.prototype._rejected=function(){return this._values.length-this.length()},SomePromiseArray.prototype._addRejected=function(reason){this._values.push(reason)},SomePromiseArray.prototype._addFulfilled=function(value){this._values[this._totalResolved++]=value},SomePromiseArray.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},SomePromiseArray.prototype._getRangeError=function(count){var message="Input array must contain at least "+this._howMany+" items but contains only "+count+" items";return new RangeError(message)},SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},Promise.some=function(promises,howMany){return some(promises,howMany)},Promise.prototype.some=function(howMany){return some(this,howMany)},Promise._SomePromiseArray=SomePromiseArray}},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){module.exports=function(Promise){function PromiseInspection(promise){void 0!==promise?(promise=promise._target(),this._bitField=promise._bitField,this._settledValueField=promise._isFateSealed()?promise._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0); }PromiseInspection.prototype._settledValue=function(){return this._settledValueField};var value=PromiseInspection.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},reason=PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},isFulfilled=PromiseInspection.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},isRejected=PromiseInspection.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},isPending=PromiseInspection.prototype.isPending=function(){return 0===(50397184&this._bitField)},isResolved=PromiseInspection.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};PromiseInspection.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},Promise.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},Promise.prototype._isCancelled=function(){return this._target().__isCancelled()},Promise.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},Promise.prototype.isPending=function(){return isPending.call(this._target())},Promise.prototype.isRejected=function(){return isRejected.call(this._target())},Promise.prototype.isFulfilled=function(){return isFulfilled.call(this._target())},Promise.prototype.isResolved=function(){return isResolved.call(this._target())},Promise.prototype.value=function(){return value.call(this._target())},Promise.prototype.reason=function(){var target=this._target();return target._unsetRejectionIsUnhandled(),reason.call(target)},Promise.prototype._value=function(){return this._settledValue()},Promise.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},Promise.PromiseInspection=PromiseInspection}},{}],33:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL){function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;var then=getThen(obj);if(then===errorObj){context&&context._pushContext();var ret=Promise.reject(then.e);return context&&context._popContext(),ret}if("function"==typeof then){if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);return obj._then(ret._fulfill,ret._reject,void 0,ret,null),ret}return doThenable(obj,then,context)}}return obj}function doGetThen(obj){return obj.then}function getThen(obj){try{return doGetThen(obj)}catch(e){return errorObj.e=e,errorObj}}function isAnyBluebirdPromise(obj){try{return hasProp.call(obj,"_promise0")}catch(e){return!1}}function doThenable(x,then,context){function resolve(value){promise&&(promise._resolveCallback(value),promise=null)}function reject(reason){promise&&(promise._rejectCallback(reason,synchronous,!0),promise=null)}var promise=new Promise(INTERNAL),ret=promise;context&&context._pushContext(),promise._captureStackTrace(),context&&context._popContext();var synchronous=!0,result=util.tryCatch(then).call(x,resolve,reject);return synchronous=!1,promise&&result===errorObj&&(promise._rejectCallback(result.e,!0,!0),promise=null),ret}var util=_dereq_("./util"),errorObj=util.errorObj,isObject=util.isObject,hasProp={}.hasOwnProperty;return tryConvertToPromise}},{"./util":36}],34:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL,debug){function HandleWrapper(handle){this.handle=handle}function successClear(value){return clearTimeout(this.handle),value}function failureClear(reason){throw clearTimeout(this.handle),reason}var util=_dereq_("./util"),TimeoutError=Promise.TimeoutError;HandleWrapper.prototype._resultCancelled=function(){clearTimeout(this.handle)};var afterValue=function(value){return delay(+this).thenReturn(value)},delay=Promise.delay=function(ms,value){var ret,handle;return void 0!==value?(ret=Promise.resolve(value)._then(afterValue,null,null,ms,void 0),debug.cancellation()&&value instanceof Promise&&ret._setOnCancel(value)):(ret=new Promise(INTERNAL),handle=setTimeout(function(){ret._fulfill()},+ms),debug.cancellation()&&ret._setOnCancel(new HandleWrapper(handle)),ret._captureStackTrace()),ret._setAsyncGuaranteed(),ret};Promise.prototype.delay=function(ms){return delay(ms,this)};var afterTimeout=function(promise,message,parent){var err;err="string"!=typeof message?message instanceof Error?message:new TimeoutError("operation timed out"):new TimeoutError(message),util.markAsOriginatingFromRejection(err),promise._attachExtraTrace(err),promise._reject(err),null!=parent&&parent.cancel()};Promise.prototype.timeout=function(ms,message){ms=+ms;var ret,parent,handleWrapper=new HandleWrapper(setTimeout(function(){ret.isPending()&&afterTimeout(ret,message,parent)},ms));return debug.cancellation()?(parent=this.then(),ret=parent._then(successClear,failureClear,void 0,handleWrapper,void 0),ret._setOnCancel(handleWrapper)):ret=this._then(successClear,failureClear,void 0,handleWrapper,void 0),ret}}},{"./util":36}],35:[function(_dereq_,module,exports){module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug){function thrower(e){setTimeout(function(){throw e},0)}function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);return maybePromise!==thenable&&"function"==typeof thenable._isDisposable&&"function"==typeof thenable._getDisposer&&thenable._isDisposable()&&maybePromise._setDisposable(thenable._getDisposer()),maybePromise}function dispose(resources,inspection){function iterator(){if(i>=len)return ret._fulfill();var maybePromise=castPreservingDisposable(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise)}catch(e){return thrower(e)}if(maybePromise instanceof Promise)return maybePromise._then(iterator,thrower,null,null,null)}iterator()}var i=0,len=resources.length,ret=new Promise(INTERNAL);return iterator(),ret}function Disposer(data,promise,context){this._data=data,this._promise=promise,this._context=context}function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}function maybeUnwrapDisposer(value){return Disposer.isDisposer(value)?(this.resources[this.index]._setDisposable(value),value.promise()):value}function ResourceList(length){this.length=length,this.promise=null,this[length-1]=null}var util=_dereq_("./util"),TypeError=_dereq_("./errors").TypeError,inherits=_dereq_("./util").inherits,errorObj=util.errorObj,tryCatch=util.tryCatch,NULL={};Disposer.prototype.data=function(){return this._data},Disposer.prototype.promise=function(){return this._promise},Disposer.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():NULL},Disposer.prototype.tryDispose=function(inspection){var resource=this.resource(),context=this._context;void 0!==context&&context._pushContext();var ret=resource!==NULL?this.doDispose(resource,inspection):null;return void 0!==context&&context._popContext(),this._promise._unsetDisposable(),this._data=null,ret},Disposer.isDisposer=function(d){return null!=d&&"function"==typeof d.resource&&"function"==typeof d.tryDispose},inherits(FunctionDisposer,Disposer),FunctionDisposer.prototype.doDispose=function(resource,inspection){var fn=this.data();return fn.call(resource,resource,inspection)},ResourceList.prototype._resultCancelled=function(){for(var len=this.length,i=0;i0},Promise.prototype._getDisposer=function(){return this._disposer},Promise.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},Promise.prototype.disposer=function(fn){if("function"==typeof fn)return new FunctionDisposer(fn,this,createContext());throw new TypeError}}},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){function tryCatcher(){try{var target=tryCatchTarget;return tryCatchTarget=null,target.apply(this,arguments)}catch(e){return errorObj.e=e,errorObj}}function tryCatch(fn){return tryCatchTarget=fn,tryCatcher}function isPrimitive(val){return null==val||val===!0||val===!1||"string"==typeof val||"number"==typeof val}function isObject(value){return"function"==typeof value||"object"===("undefined"==typeof value?"undefined":_typeof(value))&&null!==value}function maybeWrapAsError(maybeError){return isPrimitive(maybeError)?new Error(safeToString(maybeError)):maybeError}function withAppended(target,appendee){var i,len=target.length,ret=new Array(len+1);for(i=0;i1,hasMethodsOtherThanConstructor=keys.length>0&&!(1===keys.length&&"constructor"===keys[0]),hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&es5.names(fn).length>0;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods)return!0}return!1}catch(e){return!1}}function toFastProperties(obj){function FakeConstructor(){}FakeConstructor.prototype=obj;for(var l=8;l--;)new FakeConstructor;return obj}function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){for(var ret=new Array(count),i=0;i10||version[0]>0}(),ret.isNode&&ret.toFastProperties(process);try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(exports,__webpack_require__(1),__webpack_require__(4),__webpack_require__(10).setImmediate)},function(module,exports,__webpack_require__){"use strict";(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}function baseRest(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=_Symbol?_Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var differenceWith=baseRest(function(array,values){var comparator=last(values);return isArrayLikeObject(comparator)&&(comparator=void 0),isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0),void 0,comparator):[]}),isArray=Array.isArray;module.exports=differenceWith}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";(function(global){function arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,_Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,spreadableSymbol=_Symbol?_Symbol.isConcatSpreadable:void 0,isArray=Array.isArray;module.exports=flatten}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}function baseRest(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}function noop(){}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=_Symbol?_Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),Set=getNative(root,"Set"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var createSet=Set&&1/setToArray(new Set([,-0]))[1]==INFINITY?function(values){return new Set(values)}:noop,unionWith=baseRest(function(arrays){var comparator=last(arrays);return isArrayLikeObject(comparator)&&(comparator=void 0),baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0),void 0,comparator)}),isArray=Array.isArray;module.exports=unionWith}).call(exports,__webpack_require__(4))},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i3&&void 0!==arguments[3]?arguments[3]:{};return _classCallCheck(this,EventStore),void 0===options.Index&&Object.assign(options,{Index:EventIndex}),_possibleConstructorReturn(this,(EventStore.__proto__||Object.getPrototypeOf(EventStore)).call(this,ipfs,id,dbname,options))}return _inherits(EventStore,_Store),_createClass(EventStore,[{key:"add",value:function(data){return this._addOperation({op:"ADD",key:null,value:data,meta:{ts:(new Date).getTime()}})}},{key:"get",value:function(hash){return this.iterator({gte:hash,limit:1}).collect()[0]}},{key:"iterator",value:function iterator(options){var _iterator,messages=this._query(options),currentIndex=0,iterator=(_iterator={},_defineProperty(_iterator,Symbol.iterator,function(){return this}),_defineProperty(_iterator,"next",function(){var item={value:null,done:!0};return currentIndex-1?opts.limit:this._index.get().length:1,events=this._index.get(),result=[];return result=opts.gt||opts.gte?this._read(events,opts.gt?opts.gt:opts.gte,amount,!!opts.gte):this._read(events.reverse(),opts.lt?opts.lt:opts.lte,amount,opts.lte||!opts.lt).reverse()}},{key:"_read",value:function(ops,hash,amount,inclusive){var startIndex=Math.max(findIndex(ops,function(e){return e.hash===hash}),0);return startIndex+=inclusive?0:1,take(ops.slice(startIndex),amount)}}]),EventStore}(Store);module.exports=EventStore},function(module,exports,__webpack_require__){"use strict";var sources=__webpack_require__(101),sinks=__webpack_require__(95),throughs=__webpack_require__(107);exports=module.exports=__webpack_require__(91);for(var k in sources)exports[k]=sources[k];for(var k in throughs)exports[k]=throughs[k];for(var k in sinks)exports[k]=sinks[k]},function(module,exports,__webpack_require__){"use strict";var abortCb=__webpack_require__(41);module.exports=function(value,onAbort){return function(abort,cb){if(abort)return abortCb(cb,abort,onAbort);if(null!=value){var _value=value;value=null,cb(null,_value)}else cb(!0)}}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(12),filter=__webpack_require__(24);module.exports=function(field,invert){field=prop(field)||id;var seen={};return filter(function(data){var key=field(data);return seen[key]?!!invert:(seen[key]=!0,!invert)})}},function(module,exports){"use strict";module.exports=function(cb,abort,onAbort){cb(abort),onAbort&&onAbort(abort===!0?null:abort)}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},prop=__webpack_require__(12);module.exports=function(test){return"object"===("undefined"==typeof test?"undefined":_typeof(test))&&"function"==typeof test.test?function(data){return test.test(data)}:prop(test)||id}},function(module,exports,__webpack_require__){"use strict";function clone(obj){if(null===obj||"object"!=typeof obj)return obj;if(obj instanceof Object)var copy={__proto__:obj.__proto__};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}var fs=__webpack_require__(15);module.exports=clone(fs)},function(module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},function(module,exports,__webpack_require__){(function(process){(function(){var JSONStorage,KEY_FOR_EMPTY_STRING,LocalStorage,MetaKey,QUOTA_EXCEEDED_ERR,StorageEvent,_emptyDirectory,_escapeKey,_rm,createMap,events,fs,path,writeSync,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;path=__webpack_require__(31),fs=__webpack_require__(15),events=__webpack_require__(5),writeSync=__webpack_require__(157).sync,KEY_FOR_EMPTY_STRING="---.EMPTY_STRING.---",_emptyDirectory=function(target){var i,len,p,ref,results;for(ref=fs.readdirSync(target),results=[],i=0,len=ref.length;ithis.quota)throw new QUOTA_EXCEEDED_ERR;if(writeSync(filename,valueString,"utf8"),existsBeforeSet||(metaKey=new MetaKey(encodedKey,this._keys.push(key)-1),metaKey.size=valueStringLength,this._metaKeyMap[key]=metaKey,this.length+=1,this._bytesInUse+=valueStringLength),hasListeners)return evnt=new StorageEvent(key,oldValue,value,this._eventUrl),this.emit("storage",evnt)},LocalStorage.prototype.getItem=function(key){var filename,metaKey;return key=_escapeKey(key),metaKey=this._metaKeyMap[key],metaKey?(filename=path.join(this._location,metaKey.key),fs.readFileSync(filename,"utf8")):null},LocalStorage.prototype._getStat=function(key){var filename;key=_escapeKey(key),filename=path.join(this._location,encodeURIComponent(key));try{return fs.statSync(filename)}catch(error){return null}},LocalStorage.prototype.removeItem=function(key){var evnt,filename,hasListeners,k,meta,metaKey,oldValue,ref,v;if(key=_escapeKey(key),metaKey=this._metaKeyMap[key]){hasListeners=events.EventEmitter.listenerCount(this,"storage"),oldValue=null,hasListeners&&(oldValue=this.getItem(key)),delete this._metaKeyMap[key],this.length-=1,this._bytesInUse-=metaKey.size,filename=path.join(this._location,metaKey.key),this._keys.splice(metaKey.index,1),ref=this._metaKeyMap;for(k in ref)v=ref[k],meta=this._metaKeyMap[k],meta.index>metaKey.index&&(meta.index-=1);if(_rm(filename),hasListeners)return evnt=new StorageEvent(key,oldValue,null,this._eventUrl),this.emit("storage",evnt)}},LocalStorage.prototype.key=function(n){return this._keys[n]},LocalStorage.prototype.clear=function(){var evnt;if(_emptyDirectory(this._location),this._metaKeyMap=createMap(),this._keys=[],this.length=0,this._bytesInUse=0,events.EventEmitter.listenerCount(this,"storage"))return evnt=new StorageEvent(null,null,null,this._eventUrl),this.emit("storage",evnt)},LocalStorage.prototype._getBytesInUse=function(){return this._bytesInUse},LocalStorage.prototype._deleteLocation=function(){return delete instanceMap[this._location],_rm(this._location),this._metaKeyMap={},this._keys=[],this.length=0,this._bytesInUse=0},LocalStorage}(events.EventEmitter),JSONStorage=function(superClass){function JSONStorage(){return JSONStorage.__super__.constructor.apply(this,arguments)}return extend(JSONStorage,superClass),JSONStorage.prototype.setItem=function(key,value){var newValue;return newValue=JSON.stringify(value),JSONStorage.__super__.setItem.call(this,key,newValue)},JSONStorage.prototype.getItem=function(key){return JSON.parse(JSONStorage.__super__.getItem.call(this,key))},JSONStorage}(LocalStorage),exports.LocalStorage=LocalStorage,exports.JSONStorage=JSONStorage,exports.QUOTA_EXCEEDED_ERR=QUOTA_EXCEEDED_ERR}).call(this)}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=__webpack_require__(27),util=__webpack_require__(13);util.inherits=__webpack_require__(3),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},function(module,exports,__webpack_require__){"use strict";(function(process){function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(9),options=options||{},this.objectMode=!!options.objectMode,stream instanceof Duplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode);var hwm=options.highWaterMark,defaultHwm=this.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:defaultHwm,this.highWaterMark=~~this.highWaterMark,this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=__webpack_require__(49).StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){return Duplex=Duplex||__webpack_require__(9),this instanceof Readable?(this._readableState=new ReadableState(options,this),this.readable=!0,options&&"function"==typeof options.read&&(this._read=options.read),void Stream.call(this)):new Readable(options)}function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er)stream.emit("error",er);else if(null===chunk)state.reading=!1,onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)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;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe(); }function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;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,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&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)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},function(module,exports){module.exports=function(module){return module.webpackPolyfill||(module.deprecate=function(){},module.paths=[],module.children||(module.children=[]),Object.defineProperty(module,"loaded",{enumerable:!0,configurable:!1,get:function(){return module.l}}),Object.defineProperty(module,"id",{enumerable:!0,configurable:!1,get:function(){return module.i}}),module.webpackPolyfill=1),module}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:"default",options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};_classCallCheck(this,OrbitDB),this._ipfs=ipfs,this._pubsub=options&&options.broker?new options.broker(ipfs):new Pubsub(ipfs),this.user={id:id},this.network={name:defaultNetworkName},this.events=new EventEmitter,this.stores={}}return _createClass(OrbitDB,[{key:"feed",value:function(dbname,options){return this._createStore(FeedStore,dbname,options)}},{key:"eventlog",value:function(dbname,options){return this._createStore(EventStore,dbname,options)}},{key:"kvstore",value:function(dbname,options){return this._createStore(KeyValueStore,dbname,options)}},{key:"counter",value:function(dbname,options){return this._createStore(CounterStore,dbname,options)}},{key:"docstore",value:function(dbname,options){return this._createStore(DocumentStore,dbname,options)}},{key:"disconnect",value:function(){var _this=this;this._pubsub&&this._pubsub.disconnect(),this.events.removeAllListeners("data"),Object.keys(this.stores).map(function(e){return _this.stores[e]}).forEach(function(store){store.events.removeAllListeners("data"),store.events.removeAllListeners("write"),store.events.removeAllListeners("close")}),this.stores={},this.user=null,this.network=null}},{key:"_createStore",value:function(Store,dbname){var options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{subscribe:!0},store=new Store(this._ipfs,this.user.id,dbname,options);return this.stores[dbname]=store,this._subscribe(store,dbname,options.subscribe,options.cachePath)}},{key:"_subscribe",value:function(store,dbname){var subscribe=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],cachePath=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"./orbit-db";return store.events.on("data",this._onData.bind(this)),store.events.on("write",this._onWrite.bind(this)),store.events.on("close",this._onClose.bind(this)),subscribe&&this._pubsub?this._pubsub.subscribe(dbname,this._onMessage.bind(this),this._onConnected.bind(this),store.options.maxHistory>0):store.loadHistory().catch(function(e){return console.error(e.stack)}),Cache.loadCache(cachePath).then(function(){var hash=Cache.get(dbname);store.loadHistory(hash).catch(function(e){return console.error(e.stack)})}),store}},{key:"_onConnected",value:function(dbname,hash){var store=this.stores[dbname];store.loadHistory(hash).catch(function(e){return console.error(e.stack)})}},{key:"_onMessage",value:function(dbname,hash){var store=this.stores[dbname];store.sync(hash).then(function(res){return Cache.set(dbname,hash)}).catch(function(e){return console.error(e.stack)})}},{key:"_onWrite",value:function(dbname,hash){if(!hash)throw new Error("Hash can't be null!");this._pubsub&&this._pubsub.publish(dbname,hash),Cache.set(dbname,hash)}},{key:"_onData",value:function(dbname,item){this.events.emit("data",dbname,item)}},{key:"_onClose",value:function(dbname){this._pubsub&&this._pubsub.unsubscribe(dbname),delete this.stores[dbname]}}]),OrbitDB}();module.exports=OrbitDB},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{};if(!credentials.provider)throw new Error("'provider' not specified");var provider=identityProviders[credentials.provider];if(!provider)throw new Error("Provider '"+credentials.provider+"' not found");return provider.authorize(ipfs,credentials)}},{key:"loadProfile",value:function(ipfs){var profile=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!profile.identityProvider)throw new Error("'identityProvider' not specified");if(!profile.identityProvider.provider)throw new Error("'provider' not specified");var provider=identityProviders[profile.identityProvider.provider];if(!provider)throw new Error("Provider '"+profile.identityProvider.provider+"' not found");return provider.load(ipfs,profile)}}]),IdentityProviders}();module.exports=IdentityProviders},function(module,exports,__webpack_require__){"use strict";(function(global){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&expected.call({},actual)===!0}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=__webpack_require__(14),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),DirectoryPost=function(_Post){function DirectoryPost(name,hash,size){_classCallCheck(this,DirectoryPost);var _this=_possibleConstructorReturn(this,(DirectoryPost.__proto__||Object.getPrototypeOf(DirectoryPost)).call(this,"directory"));return _this.name=name,_this.hash=hash,_this.size=size,_this}return _inherits(DirectoryPost,_Post),DirectoryPost}(Post);module.exports=DirectoryPost},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),FilePost=function(_Post){function FilePost(name,hash,size,meta){_classCallCheck(this,FilePost);var _this=_possibleConstructorReturn(this,(FilePost.__proto__||Object.getPrototypeOf(FilePost)).call(this,"file"));return _this.name=name,_this.hash=hash,_this.size=size||-1,_this.meta=meta||{},_this}return _inherits(FilePost,_Post),FilePost}(Post);module.exports=FilePost},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var MetaInfo=function MetaInfo(type,size,ts,from){_classCallCheck(this,MetaInfo),this.type=type,this.size=size,this.ts=ts,this.from=from||""};module.exports=MetaInfo},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),OrbitDBItem=function(_Post){function OrbitDBItem(operation,key,value){_classCallCheck(this,OrbitDBItem);var _this=_possibleConstructorReturn(this,(OrbitDBItem.__proto__||Object.getPrototypeOf(OrbitDBItem)).call(this,"orbit-db-op"));return _this.op=operation,_this.key=key,_this.value=value,_this}return _inherits(OrbitDBItem,_Post),OrbitDBItem}(Post);module.exports=OrbitDBItem},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),PinnedPost=function(_Post){function PinnedPost(pinned){_classCallCheck(this,PinnedPost);var _this=_possibleConstructorReturn(this,(PinnedPost.__proto__||Object.getPrototypeOf(PinnedPost)).call(this,"pin"));return _this.pinned=pinned,_this}return _inherits(PinnedPost,_Post),PinnedPost}(Post);module.exports=PinnedPost},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),Poll=function(_Post){function Poll(question,options){_classCallCheck(this,Poll);var _this=_possibleConstructorReturn(this,(Poll.__proto__||Object.getPrototypeOf(Poll)).call(this,"poll"));return _this.question=question,_this.options=options,_this}return _inherits(Poll,_Post),Poll}(Post);module.exports=Poll},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),TextPost=function(_Post){function TextPost(content,replyto){_classCallCheck(this,TextPost);var _this=_possibleConstructorReturn(this,(TextPost.__proto__||Object.getPrototypeOf(TextPost)).call(this,"text"));return _this.content=content,_this.replyto=replyto,_this}return _inherits(TextPost,_Post),TextPost}(Post);module.exports=TextPost},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i0;)for(callbacks=microtickQueue,microtickQueue=[],l=callbacks.length,i=0;i0);isOutsideMicroTick=!0,needsNewPhysicalTick=!0}function finalizePhysicalTick(){var unhandledErrs=unhandledErrors; unhandledErrors=[],unhandledErrs.forEach(function(p){p._PSD.onunhandled.call(null,p._value,p)});for(var finalizers=tickFinalizers.slice(0),i=finalizers.length;i;)finalizers[--i]()}function run_at_end_of_this_or_next_physical_tick(fn){function finalizer(){fn(),tickFinalizers.splice(tickFinalizers.indexOf(finalizer),1)}tickFinalizers.push(finalizer),++numScheduledCalls,asap$1(function(){0===--numScheduledCalls&&finalizePhysicalTick()},[])}function addPossiblyUnhandledError(promise){unhandledErrors.some(function(p){return p._value===promise._value})||unhandledErrors.push(promise)}function markErrorAsHandled(promise){for(var i=unhandledErrors.length;i;)if(unhandledErrors[--i]._value===promise._value)return void unhandledErrors.splice(i,1)}function defaultErrorHandler(e){console.warn("Unhandled rejection: "+(e.stack||e))}function PromiseReject(reason){return new Promise(INTERNAL,!1,reason)}function wrap(fn,errorCatcher){var psd=PSD;return function(){var wasRootExec=beginMicroTickScope(),outerScope=PSD;try{return outerScope!==psd&&(PSD=psd),fn.apply(this,arguments)}catch(e){errorCatcher&&errorCatcher(e)}finally{outerScope!==psd&&(PSD=outerScope),wasRootExec&&endMicroTickScope()}}}function newScope(fn,a1,a2,a3){var parent=PSD,psd=Object.create(parent);psd.parent=parent,psd.ref=0,psd.global=!1,++parent.ref,psd.finalize=function(){--this.parent.ref||this.parent.finalize()};var rv=usePSD(psd,fn,a1,a2,a3);return 0===psd.ref&&psd.finalize(),rv}function usePSD(psd,fn,a1,a2,a3){var outerScope=PSD;try{return psd!==outerScope&&(PSD=psd),fn(a1,a2,a3)}finally{psd!==outerScope&&(PSD=outerScope)}}function globalError(err,promise){var rv;try{rv=promise.onuncatched(err)}catch(e){}if(rv!==!1)try{var event,eventData={promise:promise,reason:err};if(_global.document&&document.createEvent?(event=document.createEvent("Event"),event.initEvent(UNHANDLEDREJECTION,!0,!0),extend(event,eventData)):_global.CustomEvent&&(event=new CustomEvent(UNHANDLEDREJECTION,{detail:eventData}),extend(event,eventData)),event&&_global.dispatchEvent&&(dispatchEvent(event),!_global.PromiseRejectionEvent&&_global.onunhandledrejection))try{_global.onunhandledrejection(event)}catch(_){}event.defaultPrevented||Promise.on.error.fire(err,promise)}catch(e){}}function rejection(err,uncaughtHandler){var rv=Promise.reject(err);return uncaughtHandler?rv.uncaught(uncaughtHandler):rv}function Dexie(dbName,options){function init(){db.on("versionchange",function(ev){ev.newVersion>0?console.warn("Another connection wants to upgrade database '"+db.name+"'. Closing db now to resume the upgrade."):console.warn("Another connection wants to delete database '"+db.name+"'. Closing db now to resume the delete request."),db.close()}),db.on("blocked",function(ev){!ev.newVersion||ev.newVersionoldVersion});return versToRun.forEach(function(version){queue.push(function(){var oldSchema=globalSchema,newSchema=version._cfg.dbschema;adjustToExistingIndexNames(oldSchema,idbtrans),adjustToExistingIndexNames(newSchema,idbtrans),globalSchema=db._dbSchema=newSchema;var diff=getSchemaDiff(oldSchema,newSchema);if(diff.add.forEach(function(tuple){createTable(idbtrans,tuple[0],tuple[1].primKey,tuple[1].indexes)}),diff.change.forEach(function(change){if(change.recreate)throw new exceptions.Upgrade("Not yet support for changing primary key");var store=idbtrans.objectStore(change.name);change.add.forEach(function(idx){addIndex(store,idx)}),change.change.forEach(function(idx){store.deleteIndex(idx.name),addIndex(store,idx)}),change.del.forEach(function(idxName){store.deleteIndex(idxName)})}),version._cfg.contentUpgrade)return anyContentUpgraderHasRun=!0,Promise.follow(function(){version._cfg.contentUpgrade(trans)})}),queue.push(function(idbtrans){if(!anyContentUpgraderHasRun||!hasIEDeleteObjectStoreBug){var newSchema=version._cfg.dbschema;deleteRemovedTables(newSchema,idbtrans)}})}),runQueue().then(function(){createMissingTables(globalSchema,idbtrans)})}function getSchemaDiff(oldSchema,newSchema){var diff={del:[],add:[],change:[]};for(var table in oldSchema)newSchema[table]||diff.del.push(table);for(table in newSchema){var oldDef=oldSchema[table],newDef=newSchema[table];if(oldDef){var change={name:table,def:newDef,recreate:!1,del:[],add:[],change:[]};if(oldDef.primKey.src!==newDef.primKey.src)change.recreate=!0,diff.change.push(change);else{var oldIndexes=oldDef.idxByName,newIndexes=newDef.idxByName;for(var idxName in oldIndexes)newIndexes[idxName]||change.del.push(idxName);for(idxName in newIndexes){var oldIdx=oldIndexes[idxName],newIdx=newIndexes[idxName];oldIdx?oldIdx.src!==newIdx.src&&change.change.push(newIdx):change.add.push(newIdx)}(change.del.length>0||change.add.length>0||change.change.length>0)&&diff.change.push(change)}}else diff.add.push([table,newDef])}return diff}function createTable(idbtrans,tableName,primKey,indexes){var store=idbtrans.db.createObjectStore(tableName,primKey.keyPath?{keyPath:primKey.keyPath,autoIncrement:primKey.auto}:{autoIncrement:primKey.auto});return indexes.forEach(function(idx){addIndex(store,idx)}),store}function createMissingTables(newSchema,idbtrans){keys(newSchema).forEach(function(tableName){idbtrans.db.objectStoreNames.contains(tableName)||createTable(idbtrans,tableName,newSchema[tableName].primKey,newSchema[tableName].indexes)})}function deleteRemovedTables(newSchema,idbtrans){for(var i=0;i0?a:b}function ascending(a,b){return indexedDB.cmp(a,b)}function descending(a,b){return indexedDB.cmp(b,a)}function simpleCompare(a,b){return ab?-1:a===b?0:1}function combine(filter1,filter2){return filter1?filter2?function(){return filter1.apply(this,arguments)&&filter2.apply(this,arguments)}:filter1:filter2}function readGlobalSchema(){if(db.verno=idbdb.version/10,db._dbSchema=globalSchema={},dbStoreNames=slice(idbdb.objectStoreNames,0),0!==dbStoreNames.length){var trans=idbdb.transaction(safariMultiStoreFix(dbStoreNames),"readonly");dbStoreNames.forEach(function(storeName){for(var store=trans.objectStore(storeName),keyPath=store.keyPath,dotted=keyPath&&"string"==typeof keyPath&&keyPath.indexOf(".")!==-1,primKey=new IndexSpec(keyPath,keyPath||"",!1,!1,!!store.autoIncrement,keyPath&&"string"!=typeof keyPath,dotted),indexes=[],j=0;j0&&(autoSchema=!1),!indexedDB)throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL (not locally). If using old Safari versions, make sure to include indexedDB polyfill.");var req=autoSchema?indexedDB.open(dbName):indexedDB.open(dbName,Math.round(10*db.verno));if(!req)throw new exceptions.MissingAPI("IndexedDB API not available");req.onerror=wrap(eventRejectHandler(reject)),req.onblocked=wrap(fireOnBlocked),req.onupgradeneeded=wrap(function(e){if(upgradeTransaction=req.transaction,autoSchema&&!db._allowEmptyDB){req.onerror=preventDefault,upgradeTransaction.abort(),req.result.close();var delreq=indexedDB.deleteDatabase(dbName);delreq.onsuccess=delreq.onerror=wrap(function(){reject(new exceptions.NoSuchDatabase("Database "+dbName+" doesnt exist"))})}else{upgradeTransaction.onerror=wrap(eventRejectHandler(reject));var oldVer=e.oldVersion>Math.pow(2,62)?0:e.oldVersion;runUpgraders(oldVer/10,upgradeTransaction,reject,req)}},reject),req.onsuccess=wrap(function(){if(upgradeTransaction=null,idbdb=req.result,connections.push(db),autoSchema)readGlobalSchema();else if(idbdb.objectStoreNames.length>0)try{adjustToExistingIndexNames(globalSchema,idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames),READONLY))}catch(e){}idbdb.onversionchange=wrap(function(ev){db._vcFired=!0,db.on("versionchange").fire(ev)}),hasNativeGetDatabaseNames||globalDatabaseList(function(databaseNames){if(databaseNames.indexOf(dbName)===-1)return databaseNames.push(dbName)}),resolve()},reject)})]).then(function(){return Dexie.vip(db.on.ready.fire)}).then(function(){return isBeingOpened=!1,db}).catch(function(err){try{upgradeTransaction&&upgradeTransaction.abort()}catch(e){}return isBeingOpened=!1,db.close(),dbOpenError=err,rejection(dbOpenError,dbUncaught)}).finally(function(){openComplete=!0,resolveDbReady()})},this.close=function(){var idx=connections.indexOf(db);if(idx>=0&&connections.splice(idx,1),idbdb){try{idbdb.close()}catch(e){}idbdb=null}autoOpen=!1,dbOpenError=new exceptions.DatabaseClosed,isBeingOpened&&cancelOpen(dbOpenError),dbReadyPromise=new Promise(function(resolve){dbReadyResolve=resolve}),openCanceller=new Promise(function(_,reject){cancelOpen=reject})},this.delete=function(){var hasArguments=arguments.length>0;return new Promise(function(resolve,reject){function doDelete(){db.close();var req=indexedDB.deleteDatabase(dbName);req.onsuccess=wrap(function(){hasNativeGetDatabaseNames||globalDatabaseList(function(databaseNames){var pos=databaseNames.indexOf(dbName);if(pos>=0)return databaseNames.splice(pos,1)}),resolve()}),req.onerror=wrap(eventRejectHandler(reject)),req.onblocked=fireOnBlocked}if(hasArguments)throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()");isBeingOpened?dbReadyPromise.then(doDelete):doDelete()}).uncaught(dbUncaught)},this.backendDB=function(){return idbdb},this.isOpen=function(){return null!==idbdb},this.hasFailed=function(){return null!==dbOpenError},this.dynamicallyOpened=function(){return autoSchema},this.name=dbName,setProp(this,"tables",{get:function(){return keys(allTables).map(function(name){return allTables[name]})}}),this.on=Events(this,"error","populate","blocked","versionchange",{ready:[promisableChain,nop]}),this.on.error.subscribe=deprecated("Dexie.on.error",this.on.error.subscribe),this.on.error.unsubscribe=deprecated("Dexie.on.error.unsubscribe",this.on.error.unsubscribe),this.on.ready.subscribe=override(this.on.ready.subscribe,function(subscribe){return function(subscriber,bSticky){Dexie.vip(function(){openComplete?(dbOpenError||Promise.resolve().then(subscriber),bSticky&&subscribe(subscriber)):(subscribe(subscriber),bSticky||subscribe(function unsubscribe(){db.on.ready.unsubscribe(subscriber),db.on.ready.unsubscribe(unsubscribe)}))})}}),fakeAutoComplete(function(){db.on("populate").fire(db._createTransaction(READWRITE,dbStoreNames,globalSchema)),db.on("error").fire(new Error)}),this.transaction=function(mode,tableInstances,scopeFunc){function enterTransactionScope(resolve){var parentPSD=PSD;resolve(Promise.resolve().then(function(){return newScope(function(){PSD.transless=PSD.transless||parentPSD;var trans=db._createTransaction(mode,storeNames,globalSchema,parentTransaction);PSD.trans=trans,parentTransaction?trans.idbtrans=parentTransaction.idbtrans:trans.create();var tableArgs=storeNames.map(function(name){return allTables[name]});tableArgs.push(trans);var returnValue;return Promise.follow(function(){if(returnValue=scopeFunc.apply(trans,tableArgs))if("function"==typeof returnValue.next&&"function"==typeof returnValue.throw)returnValue=awaitIterator(returnValue);else if("function"==typeof returnValue.then&&!hasOwn(returnValue,"_PSD"))throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: "+scopeFunc.toString())}).uncaught(dbUncaught).then(function(){return parentTransaction&&trans._resolve(),trans._completion}).then(function(){return returnValue}).catch(function(e){return trans._reject(e),rejection(e)})})}))}var i=arguments.length;if(i<2)throw new exceptions.InvalidArgument("Too few arguments");for(var args=new Array(i-1);--i;)args[i-1]=arguments[i];scopeFunc=args.pop();var tables=flatten(args),parentTransaction=PSD.trans;parentTransaction&&parentTransaction.db===db&&mode.indexOf("!")===-1||(parentTransaction=null);var onlyIfCompatible=mode.indexOf("?")!==-1;mode=mode.replace("!","").replace("?","");try{var storeNames=tables.map(function(table){var storeName=table instanceof Table?table.name:table;if("string"!=typeof storeName)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return storeName});if("r"==mode||mode==READONLY)mode=READONLY;else{if("rw"!=mode&&mode!=READWRITE)throw new exceptions.InvalidArgument("Invalid transaction mode: "+mode);mode=READWRITE}if(parentTransaction){if(parentTransaction.mode===READONLY&&mode===READWRITE){if(!onlyIfCompatible)throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");parentTransaction=null}parentTransaction&&storeNames.forEach(function(storeName){if(parentTransaction&&parentTransaction.storeNames.indexOf(storeName)===-1){if(!onlyIfCompatible)throw new exceptions.SubTransaction("Table "+storeName+" not included in parent transaction.");parentTransaction=null}})}}catch(e){return parentTransaction?parentTransaction._promise(null,function(_,reject){reject(e)}):rejection(e,dbUncaught)}return parentTransaction?parentTransaction._promise(mode,enterTransactionScope,"lock"):db._whenReady(enterTransactionScope)},this.table=function(tableName){if(fake&&autoSchema)return new WriteableTable(tableName);if(!hasOwn(allTables,tableName))throw new exceptions.InvalidTable("Table "+tableName+" does not exist");return allTables[tableName]},props(Table.prototype,{_trans:function(mode,fn,writeLocked){var trans=PSD.trans;return trans&&trans.db===db?trans._promise(mode,fn,writeLocked):tempTransaction(mode,[this.name],fn)},_idbstore:function(mode,fn,writeLocked){function supplyIdbStore(resolve,reject,trans){fn(resolve,reject,trans.idbtrans.objectStore(tableName),trans)}if(fake)return new Promise(fn);var trans=PSD.trans,tableName=this.name;return trans&&trans.db===db?trans._promise(mode,supplyIdbStore,writeLocked):tempTransaction(mode,[this.name],supplyIdbStore)},get:function(key,cb){var self=this;return this._idbstore(READONLY,function(resolve,reject,idbstore){fake&&resolve(self.schema.instanceTemplate);var req=idbstore.get(key);req.onerror=eventRejectHandler(reject),req.onsuccess=wrap(function(){resolve(self.hook.reading.fire(req.result))},reject)}).then(cb)},where:function(indexName){return new WhereClause(this,indexName)},count:function(cb){return this.toCollection().count(cb)},offset:function(_offset){return this.toCollection().offset(_offset)},limit:function(numRows){return this.toCollection().limit(numRows)},reverse:function(){return this.toCollection().reverse()},filter:function(filterFunction){return this.toCollection().and(filterFunction)},each:function(fn){return this.toCollection().each(fn)},toArray:function(cb){return this.toCollection().toArray(cb)},orderBy:function(index){return new this._collClass(new WhereClause(this,index))},toCollection:function(){return new this._collClass(new WhereClause(this))},mapToClass:function(constructor,structure){this.schema.mappedClass=constructor;var instanceTemplate=Object.create(constructor.prototype);structure&&applyStructure(instanceTemplate,structure),this.schema.instanceTemplate=instanceTemplate;var readHook=function(obj){if(!obj)return obj;var res=Object.create(constructor.prototype);for(var m in obj)if(hasOwn(obj,m))try{res[m]=obj[m]}catch(_){}return res};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=readHook,this.hook("reading",readHook),constructor},defineClass:function(structure){return this.mapToClass(Dexie.defineClass(structure),structure)}}),derive(WriteableTable).from(Table).extend({bulkDelete:function(keys$$1){return this.hook.deleting.fire===nop?this._idbstore(READWRITE,function(resolve,reject,idbstore,trans){resolve(_bulkDelete(idbstore,trans,keys$$1,!1,nop))}):this.where(":id").anyOf(keys$$1).delete().then(function(){})},bulkPut:function(objects,keys$$1){var _this=this;return this._idbstore(READWRITE,function(resolve,reject,idbstore){if(!idbstore.keyPath&&!_this.schema.primKey.auto&&!keys$$1)throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument");if(idbstore.keyPath&&keys$$1)throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(keys$$1&&keys$$1.length!==objects.length)throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");if(0===objects.length)return resolve();var req,errorHandler,done=function(result){0===errorList.length?resolve(result):reject(new BulkError(_this.name+".bulkPut(): "+errorList.length+" of "+numObjs+" operations failed",errorList))},errorList=[],numObjs=objects.length,table=_this;if(_this.hook.creating.fire===nop&&_this.hook.updating.fire===nop){errorHandler=BulkErrorHandlerCatchAll(errorList);for(var i=0,l=objects.length;i=0;--i){var key=effectiveKeys[i];(null==key||objectLookup[key])&&(objsToAdd.push(objects[i]),keys$$1&&keysToAdd.push(key),null!=key&&(objectLookup[key]=null))}return objsToAdd.reverse(),keys$$1&&keysToAdd.reverse(),table.bulkAdd(objsToAdd,keysToAdd)}).then(function(lastAddedKey){var lastEffectiveKey=effectiveKeys[effectiveKeys.length-1];return null!=lastEffectiveKey?lastEffectiveKey:lastAddedKey}):table.bulkAdd(objects);promise.then(done).catch(BulkError,function(e){errorList=errorList.concat(e.failures),done()}).catch(reject)}},"locked")},bulkAdd:function(objects,keys$$1){var self=this,creatingHook=this.hook.creating.fire;return this._idbstore(READWRITE,function(resolve,reject,idbstore,trans){function done(result){0===errorList.length?resolve(result):reject(new BulkError(self.name+".bulkAdd(): "+errorList.length+" of "+numObjs+" operations failed",errorList))}if(!idbstore.keyPath&&!self.schema.primKey.auto&&!keys$$1)throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument");if(idbstore.keyPath&&keys$$1)throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(keys$$1&&keys$$1.length!==objects.length)throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");if(0===objects.length)return resolve();var req,errorHandler,successHandler,errorList=[],numObjs=objects.length;if(creatingHook!==nop){var hookCtx,keyPath=idbstore.keyPath;errorHandler=BulkErrorHandlerCatchAll(errorList,null,!0),successHandler=hookedEventSuccessHandler(null),tryCatch(function(){for(var i=0,l=objects.length;i0&&!this._locked();){var fnAndPSD=this._blockedFuncs.shift();try{usePSD(fnAndPSD[1],fnAndPSD[0])}catch(e){}}return this},_locked:function(){return this._reculock&&PSD.lockOwnerFor!==this},create:function(idbtrans){var _this3=this;if(assert(!this.idbtrans),!idbtrans&&!idbdb)switch(dbOpenError&&dbOpenError.name){case"DatabaseClosedError":throw new exceptions.DatabaseClosed(dbOpenError);case"MissingAPIError":throw new exceptions.MissingAPI(dbOpenError.message,dbOpenError);default:throw new exceptions.OpenFailed(dbOpenError)}if(!this.active)throw new exceptions.TransactionInactive;return assert(null===this._completion._state),idbtrans=this.idbtrans=idbtrans||idbdb.transaction(safariMultiStoreFix(this.storeNames),this.mode),idbtrans.onerror=wrap(function(ev){preventDefault(ev),_this3._reject(idbtrans.error)}),idbtrans.onabort=wrap(function(ev){preventDefault(ev),_this3.active&&_this3._reject(new exceptions.Abort),_this3.active=!1,_this3.on("abort").fire(ev)}),idbtrans.oncomplete=wrap(function(){_this3.active=!1,_this3._resolve()}),this},_promise:function(mode,fn,bWriteLock){var self=this,p=self._locked()?new Promise(function(resolve,reject){self._blockedFuncs.push([function(){self._promise(mode,fn,bWriteLock).then(resolve,reject)},PSD])}):newScope(function(){var p_=self.active?new Promise(function(resolve,reject){if(mode===READWRITE&&self.mode!==READWRITE)throw new exceptions.ReadOnly("Transaction is readonly");!self.idbtrans&&mode&&self.create(),bWriteLock&&self._lock(),fn(resolve,reject,self)}):rejection(new exceptions.TransactionInactive);return self.active&&bWriteLock&&p_.finally(function(){self._unlock()}),p_});return p._lib=!0,p.uncaught(dbUncaught)},abort:function(){this.active&&this._reject(new exceptions.Abort),this.active=!1},tables:{get:deprecated("Transaction.tables",function(){return arrayToObject(this.storeNames,function(name){return[name,allTables[name]]})},"Use db.tables()")},complete:deprecated("Transaction.complete()",function(cb){return this.on("complete",cb)}),error:deprecated("Transaction.error()",function(cb){return this.on("error",cb)}),table:deprecated("Transaction.table()",function(name){if(this.storeNames.indexOf(name)===-1)throw new exceptions.InvalidTable("Table "+name+" not in transaction");return allTables[name]})}),props(WhereClause.prototype,function(){function fail(collectionOrWhereClause,err,T){var collection=collectionOrWhereClause instanceof WhereClause?new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause):collectionOrWhereClause;return collection._ctx.error=T?new T(err):new TypeError(err),collection}function emptyCollection(whereClause){return new whereClause._ctx.collClass(whereClause,function(){return IDBKeyRange.only("")}).limit(0)}function upperFactory(dir){return"next"===dir?function(s){return s.toUpperCase()}:function(s){return s.toLowerCase()}}function lowerFactory(dir){return"next"===dir?function(s){return s.toLowerCase()}:function(s){return s.toUpperCase()}}function nextCasing(key,lowerKey,upperNeedle,lowerNeedle,cmp,dir){for(var length=Math.min(key.length,lowerNeedle.length),llp=-1,i=0;i=0?key.substr(0,llp)+lowerKey[llp]+upperNeedle.substr(llp+1):null;cmp(key[i],lwrKeyChar)<0&&(llp=i)}return length0)&&(lowestPossibleCasing=casing)}return advance(null!==lowestPossibleCasing?function(){cursor.continue(lowestPossibleCasing+nextKeySuffix)}:resolve),!1}),c}return{between:function(lower,upper,includeLower,includeUpper){includeLower=includeLower!==!1,includeUpper=includeUpper===!0;try{return cmp(lower,upper)>0||0===cmp(lower,upper)&&(includeLower||includeUpper)&&(!includeLower||!includeUpper)?emptyCollection(this):new this._ctx.collClass(this,function(){return IDBKeyRange.bound(lower,upper,!includeLower,!includeUpper)})}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}},equals:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.only(value)})},above:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.lowerBound(value,!0)})},aboveOrEqual:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.lowerBound(value)})},below:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.upperBound(value,!0)})},belowOrEqual:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.upperBound(value)})},startsWith:function(str){return"string"!=typeof str?fail(this,STRING_EXPECTED):this.between(str,str+maxString,!0,!0)},startsWithIgnoreCase:function(str){return""===str?this.startsWith(str):addIgnoreCaseAlgorithm(this,function(x,a){return 0===x.indexOf(a[0])},[str],maxString)},equalsIgnoreCase:function(str){return addIgnoreCaseAlgorithm(this,function(x,a){return x===a[0]},[str],"")},anyOfIgnoreCase:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return 0===set.length?emptyCollection(this):addIgnoreCaseAlgorithm(this,function(x,a){return a.indexOf(x)!==-1},set,"")},startsWithAnyOfIgnoreCase:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return 0===set.length?emptyCollection(this):addIgnoreCaseAlgorithm(this,function(x,a){return a.some(function(n){return 0===x.indexOf(n)})},set,maxString)},anyOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments),compare=ascending;try{set.sort(compare)}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}if(0===set.length)return emptyCollection(this);var c=new this._ctx.collClass(this,function(){return IDBKeyRange.bound(set[0],set[set.length-1])});c._ondirectionchange=function(direction){compare="next"===direction?ascending:descending,set.sort(compare)};var i=0;return c._addAlgorithm(function(cursor,advance,resolve){for(var key=cursor.key;compare(key,set[i])>0;)if(++i,i===set.length)return advance(resolve),!1;return 0===compare(key,set[i])||(advance(function(){cursor.continue(set[i])}),!1)}),c},notEqual:function(value){return this.inAnyRange([[-(1/0),value],[value,maxKey]],{includeLowers:!1,includeUppers:!1})},noneOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);if(0===set.length)return new this._ctx.collClass(this);try{set.sort(ascending)}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}var ranges=set.reduce(function(res,val){return res?res.concat([[res[res.length-1][1],val]]):[[-(1/0),val]]},null);return ranges.push([set[set.length-1],maxKey]),this.inAnyRange(ranges,{includeLowers:!1,includeUppers:!1})},inAnyRange:function(ranges,options){function addRange(ranges,newRange){for(var i=0,l=ranges.length;i0){range[0]=min(range[0],newRange[0]),range[1]=max(range[1],newRange[1]);break}}return i===l&&ranges.push(newRange),ranges}function rangeSorter(a,b){return sortDirection(a[0],b[0])}function keyWithinCurrentRange(key){return!keyIsBeyondCurrentEntry(key)&&!keyIsBeforeCurrentEntry(key)}var ctx=this._ctx;if(0===ranges.length)return emptyCollection(this);if(!ranges.every(function(range){return void 0!==range[0]&&void 0!==range[1]&&ascending(range[0],range[1])<=0}))return fail(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",exceptions.InvalidArgument);var set,includeLowers=!options||options.includeLowers!==!1,includeUppers=options&&options.includeUppers===!0,sortDirection=ascending;try{set=ranges.reduce(addRange,[]),set.sort(rangeSorter)}catch(ex){return fail(this,INVALID_KEY_ARGUMENT)}var i=0,keyIsBeyondCurrentEntry=includeUppers?function(key){return ascending(key,set[i][1])>0}:function(key){return ascending(key,set[i][1])>=0},keyIsBeforeCurrentEntry=includeLowers?function(key){return descending(key,set[i][0])>0}:function(key){return descending(key,set[i][0])>=0},checkKey=keyIsBeyondCurrentEntry,c=new ctx.collClass(this,function(){return IDBKeyRange.bound(set[0][0],set[set.length-1][1],!includeLowers,!includeUppers)});return c._ondirectionchange=function(direction){"next"===direction?(checkKey=keyIsBeyondCurrentEntry,sortDirection=ascending):(checkKey=keyIsBeforeCurrentEntry,sortDirection=descending),set.sort(rangeSorter)},c._addAlgorithm(function(cursor,advance,resolve){for(var key=cursor.key;checkKey(key);)if(++i,i===set.length)return advance(resolve),!1;return!!keyWithinCurrentRange(key)||0!==cmp(key,set[i][1])&&0!==cmp(key,set[i][0])&&(advance(function(){sortDirection===ascending?cursor.continue(set[i][0]):cursor.continue(set[i][1])}),!1)}),c},startsWithAnyOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return set.every(function(s){return"string"==typeof s})?0===set.length?emptyCollection(this):this.inAnyRange(set.map(function(str){return[str,str+maxString]})):fail(this,"startsWithAnyOf() only works with strings")}}}),props(Collection.prototype,function(){function addFilter(ctx,fn){ctx.filter=combine(ctx.filter,fn)}function addReplayFilter(ctx,factory,isLimitFilter){var curr=ctx.replayFilter;ctx.replayFilter=curr?function(){return combine(curr(),factory())}:factory,ctx.justLimit=isLimitFilter&&!curr}function addMatchFilter(ctx,fn){ctx.isMatch=combine(ctx.isMatch,fn)}function getIndexOrStore(ctx,store){if(ctx.isPrimKey)return store;var indexSpec=ctx.table.schema.idxByName[ctx.index];if(!indexSpec)throw new exceptions.Schema("KeyPath "+ctx.index+" on object store "+store.name+" is not indexed");return store.index(indexSpec.name)}function openCursor(ctx,store){var idxOrStore=getIndexOrStore(ctx,store);return ctx.keysOnly&&"openKeyCursor"in idxOrStore?idxOrStore.openKeyCursor(ctx.range||null,ctx.dir+ctx.unique):idxOrStore.openCursor(ctx.range||null,ctx.dir+ctx.unique)}function iter(ctx,fn,resolve,reject,idbstore){var filter=ctx.replayFilter?combine(ctx.filter,ctx.replayFilter()):ctx.filter;ctx.or?function(){function resolveboth(){2===++resolved&&resolve()}function union(item,cursor,advance){if(!filter||filter(cursor,advance,resolveboth,reject)){var key=cursor.primaryKey.toString();hasOwn(set,key)||(set[key]=!0,fn(item,cursor,advance))}}var set={},resolved=0;ctx.or._iterate(union,resolveboth,reject,idbstore),iterate(openCursor(ctx,idbstore),ctx.algorithm,union,resolveboth,reject,!ctx.keysOnly&&ctx.valueMapper)}():iterate(openCursor(ctx,idbstore),combine(ctx.algorithm,filter),fn,resolve,reject,!ctx.keysOnly&&ctx.valueMapper)}function getInstanceTemplate(ctx){return ctx.table.schema.instanceTemplate}return{_read:function(fn,cb){var ctx=this._ctx;return ctx.error?ctx.table._trans(null,function(resolve,reject){reject(ctx.error)}):ctx.table._idbstore(READONLY,fn).then(cb)},_write:function(fn){var ctx=this._ctx;return ctx.error?ctx.table._trans(null,function(resolve,reject){reject(ctx.error)}):ctx.table._idbstore(READWRITE,fn,"locked")},_addAlgorithm:function(fn){var ctx=this._ctx;ctx.algorithm=combine(ctx.algorithm,fn)},_iterate:function(fn,resolve,reject,idbstore){return iter(this._ctx,fn,resolve,reject,idbstore)},clone:function(props$$1){var rv=Object.create(this.constructor.prototype),ctx=Object.create(this._ctx);return props$$1&&extend(ctx,props$$1),rv._ctx=ctx,rv},raw:function(){return this._ctx.valueMapper=null,this},each:function(fn){var ctx=this._ctx;if(fake){var item=getInstanceTemplate(ctx),primKeyPath=ctx.table.schema.primKey.keyPath,key=getByKeyPath(item,ctx.index?ctx.table.schema.idxByName[ctx.index].keyPath:primKeyPath),primaryKey=getByKeyPath(item,primKeyPath);fn(item,{key:key,primaryKey:primaryKey})}return this._read(function(resolve,reject,idbstore){iter(ctx,fn,resolve,reject,idbstore)})},count:function count(cb){if(fake)return Promise.resolve(0).then(cb);var ctx=this._ctx;if(isPlainKeyRange(ctx,!0))return this._read(function(resolve,reject,idbstore){var idx=getIndexOrStore(ctx,idbstore),req=ctx.range?idx.count(ctx.range):idx.count();req.onerror=eventRejectHandler(reject),req.onsuccess=function(e){resolve(Math.min(e.target.result,ctx.limit))}},cb);var count=0;return this._read(function(resolve,reject,idbstore){iter(ctx,function(){return++count,!1},function(){resolve(count)},reject,idbstore)},cb)},sortBy:function(keyPath,cb){function getval(obj,i){return i?getval(obj[parts[i]],i-1):obj[lastPart]}function sorter(a,b){var aVal=getval(a,lastIndex),bVal=getval(b,lastIndex);return aValbVal?order:0}var parts=keyPath.split(".").reverse(),lastPart=parts[0],lastIndex=parts.length-1,order="next"===this._ctx.dir?1:-1;return this.toArray(function(a){return a.sort(sorter)}).then(cb)},toArray:function(cb){var ctx=this._ctx;return this._read(function(resolve,reject,idbstore){if(fake&&resolve([getInstanceTemplate(ctx)]),hasGetAll&&"next"===ctx.dir&&isPlainKeyRange(ctx,!0)&&ctx.limit>0){var readingHook=ctx.table.hook.reading.fire,idxOrStore=getIndexOrStore(ctx,idbstore),req=ctx.limit<1/0?idxOrStore.getAll(ctx.range,ctx.limit):idxOrStore.getAll(ctx.range);req.onerror=eventRejectHandler(reject),req.onsuccess=readingHook===mirror?eventSuccessHandler(resolve):wrap(eventSuccessHandler(function(res){try{resolve(res.map(readingHook))}catch(e){reject(e)}}))}else{var a=[];iter(ctx,function(item){a.push(item)},function(){resolve(a)},reject,idbstore)}},cb)},offset:function(_offset2){var ctx=this._ctx;return _offset2<=0?this:(ctx.offset+=_offset2,isPlainKeyRange(ctx)?addReplayFilter(ctx,function(){var offsetLeft=_offset2;return function(cursor,advance){return 0===offsetLeft||(1===offsetLeft?(--offsetLeft,!1):(advance(function(){cursor.advance(offsetLeft),offsetLeft=0}),!1))}}):addReplayFilter(ctx,function(){var offsetLeft=_offset2;return function(){return--offsetLeft<0}}),this)},limit:function(numRows){return this._ctx.limit=Math.min(this._ctx.limit,numRows),addReplayFilter(this._ctx,function(){var rowsLeft=numRows;return function(cursor,advance,resolve){return--rowsLeft<=0&&advance(resolve),rowsLeft>=0}},!0),this},until:function(filterFunction,bIncludeStopEntry){var ctx=this._ctx;return fake&&filterFunction(getInstanceTemplate(ctx)),addFilter(this._ctx,function(cursor,advance,resolve){return!filterFunction(cursor.value)||(advance(resolve),bIncludeStopEntry)}),this},first:function(cb){return this.limit(1).toArray(function(a){return a[0]}).then(cb)},last:function(cb){return this.reverse().first(cb)},filter:function(filterFunction){return fake&&filterFunction(getInstanceTemplate(this._ctx)),addFilter(this._ctx,function(cursor){return filterFunction(cursor.value)}),addMatchFilter(this._ctx,filterFunction),this},and:function(filterFunction){return this.filter(filterFunction)},or:function(indexName){return new WhereClause(this._ctx.table,indexName,this)},reverse:function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},desc:function(){return this.reverse()},eachKey:function(cb){var ctx=this._ctx;return ctx.keysOnly=!ctx.isMatch,this.each(function(val,cursor){cb(cursor.key,cursor)})},eachUniqueKey:function(cb){return this._ctx.unique="unique",this.eachKey(cb)},eachPrimaryKey:function(cb){var ctx=this._ctx;return ctx.keysOnly=!ctx.isMatch,this.each(function(val,cursor){cb(cursor.primaryKey,cursor)})},keys:function(cb){var ctx=this._ctx;ctx.keysOnly=!ctx.isMatch;var a=[];return this.each(function(item,cursor){a.push(cursor.key)}).then(function(){return a}).then(cb)},primaryKeys:function(cb){var ctx=this._ctx;if(hasGetAll&&"next"===ctx.dir&&isPlainKeyRange(ctx,!0)&&ctx.limit>0)return this._read(function(resolve,reject,idbstore){var idxOrStore=getIndexOrStore(ctx,idbstore),req=ctx.limit<1/0?idxOrStore.getAllKeys(ctx.range,ctx.limit):idxOrStore.getAllKeys(ctx.range);req.onerror=eventRejectHandler(reject),req.onsuccess=eventSuccessHandler(resolve)}).then(cb);ctx.keysOnly=!ctx.isMatch;var a=[];return this.each(function(item,cursor){a.push(cursor.primaryKey)}).then(function(){return a}).then(cb)},uniqueKeys:function(cb){return this._ctx.unique="unique",this.keys(cb)},firstKey:function(cb){return this.limit(1).keys(function(a){return a[0]}).then(cb)},lastKey:function(cb){return this.reverse().firstKey(cb)},distinct:function(){var ctx=this._ctx,idx=ctx.index&&ctx.table.schema.idxByName[ctx.index];if(!idx||!idx.multi)return this;var set={};return addFilter(this._ctx,function(cursor){var strKey=cursor.primaryKey.toString(),found=hasOwn(set,strKey);return set[strKey]=!0,!found}),this}}}),derive(WriteableCollection).from(Collection).extend({modify:function(changes){var self=this,ctx=this._ctx,hook=ctx.table.hook,updatingHook=hook.updating.fire,deletingHook=hook.deleting.fire;return fake&&"function"==typeof changes&&changes.call({value:ctx.table.schema.instanceTemplate},ctx.table.schema.instanceTemplate),this._write(function(resolve,reject,idbstore,trans){function modifyItem(item,cursor){function onerror(e){return failures.push(e),failKeys.push(thisContext.primKey),checkFinished(),!0}currentKey=cursor.primaryKey;var thisContext={primKey:cursor.primaryKey,value:item,onsuccess:null,onerror:null};if(modifyer.call(thisContext,item,thisContext)!==!1){var bDelete=!hasOwn(thisContext,"value");++count,tryCatch(function(){var req=bDelete?cursor.delete():cursor.update(thisContext.value);req._hookCtx=thisContext,req.onerror=hookedEventRejectHandler(onerror),req.onsuccess=hookedEventSuccessHandler(function(){++successCount,checkFinished()})},onerror)}else thisContext.onsuccess&&thisContext.onsuccess(thisContext.value)}function doReject(e){return e&&(failures.push(e),failKeys.push(currentKey)),reject(new ModifyError("Error modifying one or more objects",failures,successCount,failKeys))}function checkFinished(){iterationComplete&&successCount+failures.length===count&&(failures.length>0?doReject():resolve(successCount))}var modifyer;if("function"==typeof changes)modifyer=updatingHook===nop&&deletingHook===nop?changes:function(item){var origItem=deepClone(item);if(changes.call(this,item,this)===!1)return!1;if(hasOwn(this,"value")){var objectDiff=getObjectDiff(origItem,this.value),additionalChanges=updatingHook.call(this,objectDiff,this.primKey,origItem,trans);additionalChanges&&(item=this.value,keys(additionalChanges).forEach(function(keyPath){setByKeyPath(item,keyPath,additionalChanges[keyPath])}))}else deletingHook.call(this,this.primKey,item,trans)};else if(updatingHook===nop){var keyPaths=keys(changes),numKeys=keyPaths.length;modifyer=function(item){for(var anythingModified=!1,i=0;i99?queue.push(Buffer.concat(data)):queue[lastIndex(queue)]=Buffer.concat(last(queue).concat(data)),queue}if(err)return cb(err);var table=_this.table;d.resolve(pull(toWindow(100,10),_write(writer,reduce,100,cb)))}),d):(cb(new Error("Missing key")),d)}},{key:"read",value:function(key){var _this2=this,p=pushable();return key?(this.exists(key,function(err,exists){return err?p.end(err):exists?void _this2.table.where("key").equals(key).each(function(val){return p.push(toBuffer(val.blob))}).catch(function(err){return p.end(err)}).then(function(){return p.end()}):p.end(new Error("Not found"))}),p):(p.end(new Error("Missing key")),p)}},{key:"exists",value:function(key,cb){return cb=cb||function(){},key?void this.table.where("key").equals(key).count().then(function(val){return cb(null,Boolean(val))}).catch(cb):cb(new Error("Missing key"))}},{key:"remove",value:function(key,cb){if(cb=cb||function(){},!key)return cb(new Error("Missing key"));var coll=this.table.where("key").equals(key);coll.count(function(count){return count>0?coll.delete():null}).then(function(){return cb()}).catch(cb)}},{key:"table",get:function(){return this.db[this.path]}}]),IdbBlobStore}()}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function isTypedArray(arr){return isStrictTypedArray(arr)||isLooseTypedArray(arr)}function isStrictTypedArray(arr){return arr instanceof Int8Array||arr instanceof Int16Array||arr instanceof Int32Array||arr instanceof Uint8Array||arr instanceof Uint8ClampedArray||arr instanceof Uint16Array||arr instanceof Uint32Array||arr instanceof Float32Array||arr instanceof Float64Array}function isLooseTypedArray(arr){return names[toString.call(arr)]}module.exports=isTypedArray,isTypedArray.strict=isStrictTypedArray,isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString,names={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}},function(module,exports,__webpack_require__){"use strict";(function(setImmediate){var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};module.exports=function(){function _releaser(key,exec){return function(done){return function(){_release(key,exec),done&&done.apply(null,arguments)}}}function _release(key,exec){var i=locked[key].indexOf(exec);~i&&(locked[key].splice(i,1),isLocked(key)?next(function(){locked[key][0](_releaser(key,locked[key][0]))}):delete locked[key])}function _lock(key,exec){return isLocked(key)?(locked[key].push(exec),!1):(locked[key]=[exec],!0)}function lock(key,exec){if(Array.isArray(key)){var keys,locks,l,_ret=function(){var releaser=function(done){return function(){var args=[].slice.call(arguments);for(var key in l)_release(key,l[key]);done.apply(this,args)}};return keys=key.length,locks=[],l={},key.forEach(function(key){function ready(){n++||--keys||exec(releaser)}var n=0;l[key]=ready,_lock(key,ready)&&ready()}),{v:void 0}}();if("object"===("undefined"==typeof _ret?"undefined":_typeof(_ret)))return _ret.v}_lock(key,exec)&&exec(_releaser(key,exec))}function isLocked(key){return!!Array.isArray(locked[key])&&!!locked[key].length}var next="undefined"==typeof setImmediate?setTimeout:setImmediate,locked={};return lock.isLocked=isLocked,lock}}).call(exports,__webpack_require__(10).setImmediate)},function(module,exports,__webpack_require__){"use strict";(function(global,module){function arraySome(array,predicate){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}function isSymbol(value){return"symbol"==("undefined"==typeof value?"undefined":_typeof(value))||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toString(value){return null==value?"":baseToString(value)}function get(object,path,defaultValue){var result=null==object?void 0:baseGet(object,path);return void 0===result?defaultValue:result}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function identity(value){return value}function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reTrim=/^\s+|\s+$/g,reEscapeChar=/\\(\\)?/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1; var freeParseInt=parseInt,freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==_typeof(exports)&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==_typeof(module)&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=_Symbol?_Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0,symbolToString=symbolProto?symbolProto.toString:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&getTag(Promise.resolve())!=promiseTag||Set&&getTag(new Set)!=setTag||WeakMap&&getTag(new WeakMap)!=weakMapTag)&&(getTag=function(value){var result=objectToString.call(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):void 0;if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});var stringToPath=memoize(function(string){string=toString(string);var result=[];return reLeadingDot.test(string)&&result.push(""),string.replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)}),result});memoize.Cache=MapCache;var isArray=Array.isArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=findIndex}).call(exports,__webpack_require__(4),__webpack_require__(50)(module))},function(module,exports){"use strict";function baseSlice(array,start,end){var index=-1,length=array.length;start<0&&(start=-start>length?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}function isSymbol(value){return"symbol"==("undefined"==typeof value?"undefined":_typeof(value))||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,funcTag="[object Function]",genTag="[object GeneratorFunction]",symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString;module.exports=slice},function(module,exports,__webpack_require__){"use strict";(function(process){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=levelIdx}}]),Logger}();module.exports={Colors:Colors,LogLevels:LogLevels,setLogLevel:function(level){GlobalLogLevel=level},setLogfile:function(filename){GlobalLogfile=filename},create:function(category,options){var logger=new Logger(category,options);return logger},forceBrowserMode:function(force){return isNodejs=!force}}}).call(exports,__webpack_require__(1))},function(module,exports){"use strict";module.exports=function(fun){return function next(a,b,c){var loop=!0,sync=!1;do sync=!0,loop=!1,fun.call(function(x,y,z){sync?(a=x,b=y,c=z,loop=!0):next(x,y,z)},a,b,c),sync=!1;while(loop)}}},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i3&&void 0!==arguments[3]?arguments[3]:{};return _classCallCheck(this,CounterStore),options.Index||Object.assign(options,{Index:CounterIndex}),_possibleConstructorReturn(this,(CounterStore.__proto__||Object.getPrototypeOf(CounterStore)).call(this,ipfs,id,dbname,options))}return _inherits(CounterStore,_Store),_createClass(CounterStore,[{key:"inc",value:function(amount){var counter=this._index.get();if(counter)return counter.increment(amount),this._addOperation({op:"COUNTER",key:null,value:counter.payload,meta:{ts:(new Date).getTime()}})}},{key:"value",get:function(){return this._index.get().value}}]),CounterStore}(Store);module.exports=CounterStore},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i2&&void 0!==arguments[2]?arguments[2]:[];if(!ipfs)throw new Error("Entry requires ipfs instance");var nexts=null!==next&&next instanceof Array?next.map(function(e){return e.hash?e.hash:e}):[null!==next&&next.hash?next.hash:next],entry={hash:null,payload:data,next:nexts};return Entry.toIpfsHash(ipfs,entry).then(function(hash){return entry.hash=hash,entry})}},{key:"toIpfsHash",value:function(ipfs,entry){if(!ipfs)throw new Error("Entry requires ipfs instance");var data=new Buffer(JSON.stringify(entry));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash){if(!ipfs)throw new Error("Entry requires ipfs instance");if(!hash)throw new Error("Invalid hash: "+hash);return ipfs.object.get(hash,{enc:"base58"}).then(function(obj){var data=JSON.parse(obj.toJSON().data),entry={hash:hash,payload:data.payload,next:data.next};return entry})}},{key:"hasChild",value:function(entry1,entry2){return entry1.next.includes(entry2.hash)}},{key:"compare",value:function(a,b){return a.hash===b.hash}}]),Entry}()}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=MaxBatchSize&&this._commit(),Entry.create(this._ipfs,data,this._heads).then(function(entry){return _this._heads=[entry.hash],_this._currentBatch.push(entry),entry})}},{key:"join",value:function(other){var _this2=this;if(!other.items)throw new Error("The log to join must be an instance of Log");var newItems=other.items.slice(-Math.max(this.options.maxHistory,1)),diff=differenceWith(newItems,this.items,Entry.compare),final=unionWith(this._currentBatch,diff,Entry.compare);this._items=this._items.concat(final),this._currentBatch=[];var nexts=take(flatten(diff.map(function(f){return f.next})),this.options.maxHistory);return Promise.map(nexts,function(f){var all=_this2.items.map(function(a){return a.hash});return _this2._fetchRecursive(_this2._ipfs,f,all,_this2.options.maxHistory-nexts.length,0).then(function(history){return history.forEach(function(b){return _this2._insert(b)}),history})},{concurrency:1}).then(function(res){return _this2._heads=Log.findHeads(_this2),flatten(res).concat(diff)})}},{key:"_insert",value:function(entry){var _this3=this,indices=entry.next.map(function(next){return _this3._items.map(function(f){return f.hash}).indexOf(next)}),index=indices.length>0?Math.max(Math.max.apply(null,indices)+1,0):0;return this._items.splice(index,0,entry),entry}},{key:"_commit",value:function(){this._items=this._items.concat(this._currentBatch),this._currentBatch=[]}},{key:"_fetchRecursive",value:function(ipfs,hash,all,amount,depth){var _this4=this,isReferenced=function(list,item){return void 0!==list.reverse().find(function(f){return f===item})},result=[];return isReferenced(all,hash)||depth>=amount?Promise.resolve(result):Entry.fromIpfsHash(ipfs,hash).then(function(entry){return result.push(entry),all.push(hash),depth++,Promise.map(entry.next,function(f){return _this4._fetchRecursive(ipfs,f,all,amount,depth)},{concurrency:1}).then(function(res){return flatten(res.concat(result))})})}},{key:"items",get:function(){return this._items.concat(this._currentBatch)}},{key:"snapshot",get:function(){return{id:this.id,items:this._currentBatch.map(function(f){return f.hash})}}}],[{key:"getIpfsHash",value:function(ipfs,log){if(!ipfs)throw new Error("Ipfs instance not defined");var data=new Buffer(JSON.stringify(log.snapshot));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash,options){if(!ipfs)throw new Error("Ipfs instance not defined");if(!hash)throw new Error("Invalid hash: "+hash);options||(options={});var logData=void 0;return ipfs.object.get(hash,{enc:"base58"}).then(function(res){return logData=JSON.parse(res.toJSON().data)}).then(function(res){if(!logData.items)throw new Error("Not a Log instance");return Promise.all(logData.items.map(function(f){return Entry.fromIpfsHash(ipfs,f)}))}).then(function(items){return Object.assign(options,{items:items})}).then(function(items){return new Log(ipfs,logData.id,options)})}},{key:"findHeads",value:function(log){return log.items.reverse().filter(function(f){return!Log.isReferencedInChain(log,f)}).map(function(f){return f.hash})}},{key:"isReferencedInChain",value:function(log,item){return void 0!==log.items.reverse().find(function(e){return Entry.hasChild(e,item)})}},{key:"batchSize",get:function(){return MaxBatchSize}}]),Log}();module.exports=Log}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i3&&void 0!==arguments[3]?arguments[3]:{};_classCallCheck(this,Store),this.id=id,this.dbname=dbname,this.events=new EventEmitter;var opts=Object.assign({},DefaultOptions);Object.assign(opts,options),this.options=opts,this._ipfs=ipfs,this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options),this._lastWrite=[]}return _createClass(Store,[{key:"loadHistory",value:function(hash){var _this=this;return this._lastWrite.includes(hash)?Promise.resolve([]):(hash&&this._lastWrite.push(hash),this.events.emit("load",this.dbname,hash),hash&&this.options.maxHistory>0?Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this._oplog.join(log)}).then(function(merged){_this._index.updateIndex(_this._oplog,merged),_this.events.emit("history",_this.dbname,merged)}).then(function(){return _this.events.emit("ready",_this.dbname)}).then(function(){return _this}):(this.events.emit("ready",this.dbname),Promise.resolve(this)))}},{key:"sync",value:function(hash){var _this2=this;if(!hash||this._lastWrite.includes(hash))return Promise.resolve([]);var newItems=[];hash&&this._lastWrite.push(hash),this.events.emit("sync",this.dbname);(new Date).getTime();return Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this2._oplog.join(log)}).then(function(merged){return newItems=merged}).then(function(){return _this2._index.updateIndex(_this2._oplog,newItems)}).then(function(){newItems.reverse().forEach(function(e){return _this2.events.emit("data",_this2.dbname,e)})}).then(function(){return newItems})}},{key:"close",value:function(){this.delete(),this.events.emit("close",this.dbname)}},{key:"delete",value:function(){this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options)}},{key:"_addOperation",value:function(data){var _this3=this,result=void 0,logHash=void 0;if(this._oplog)return this._oplog.add(data).then(function(res){return result=res}).then(function(){return Log.getIpfsHash(_this3._ipfs,_this3._oplog)}).then(function(hash){return logHash=hash}).then(function(){return _this3._lastWrite.push(logHash)}).then(function(){return _this3._index.updateIndex(_this3._oplog,[result])}).then(function(){return _this3.events.emit("write",_this3.dbname,logHash)}).then(function(){return _this3.events.emit("data",_this3.dbname,result)}).then(function(){return result.hash})}}]),Store}();module.exports=Store},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i2&&void 0!==arguments[2]?arguments[2]:[];if(!ipfs)throw new Error("Entry requires ipfs instance");var nexts=null!==next&&next instanceof Array?next.map(function(e){return e.hash?e.hash:e}):[null!==next&&next.hash?next.hash:next],entry={hash:null,payload:data,next:nexts};return Entry.toIpfsHash(ipfs,entry).then(function(hash){return entry.hash=hash,entry})}},{key:"toIpfsHash",value:function(ipfs,entry){if(!ipfs)throw new Error("Entry requires ipfs instance");var data=new Buffer(JSON.stringify(entry));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash){if(!ipfs)throw new Error("Entry requires ipfs instance");if(!hash)throw new Error("Invalid hash: "+hash);return ipfs.object.get(hash,{enc:"base58"}).then(function(obj){var data=JSON.parse(obj.toJSON().data),entry={hash:hash,payload:data.payload,next:data.next};return entry})}},{key:"hasChild",value:function(entry1,entry2){return entry1.next.includes(entry2.hash)}},{key:"compare",value:function(a,b){return a.hash===b.hash}}]),Entry}()}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=MaxBatchSize&&this._commit(),Entry.create(this._ipfs,data,this._heads).then(function(entry){return _this._heads=[entry.hash],_this._currentBatch.push(entry),entry})}},{key:"join",value:function(other){var _this2=this;if(!other.items)throw new Error("The log to join must be an instance of Log");var newItems=other.items.slice(-Math.max(this.options.maxHistory,1)),diff=differenceWith(newItems,this.items,Entry.compare),final=unionWith(this._currentBatch,diff,Entry.compare);this._items=this._items.concat(final),this._currentBatch=[];var nexts=take(flatten(diff.map(function(f){return f.next})),this.options.maxHistory);return Promise.map(nexts,function(f){var all=_this2.items.map(function(a){return a.hash});return _this2._fetchRecursive(_this2._ipfs,f,all,_this2.options.maxHistory-nexts.length,0).then(function(history){return history.forEach(function(b){return _this2._insert(b)}),history})},{concurrency:1}).then(function(res){return _this2._heads=Log.findHeads(_this2),flatten(res).concat(diff)})}},{key:"_insert",value:function(entry){var _this3=this,indices=entry.next.map(function(next){return _this3._items.map(function(f){return f.hash}).indexOf(next)}),index=indices.length>0?Math.max(Math.max.apply(null,indices)+1,0):0;return this._items.splice(index,0,entry),entry}},{key:"_commit",value:function(){this._items=this._items.concat(this._currentBatch),this._currentBatch=[]}},{key:"_fetchRecursive",value:function(ipfs,hash,all,amount,depth){var _this4=this,isReferenced=function(list,item){return void 0!==list.reverse().find(function(f){return f===item})},result=[];return isReferenced(all,hash)||depth>=amount?Promise.resolve(result):Entry.fromIpfsHash(ipfs,hash).then(function(entry){return result.push(entry),all.push(hash),depth++,Promise.map(entry.next,function(f){return _this4._fetchRecursive(ipfs,f,all,amount,depth)},{concurrency:1}).then(function(res){return flatten(res.concat(result))})})}},{key:"items",get:function(){return this._items.concat(this._currentBatch)}},{key:"snapshot",get:function(){return{id:this.id,items:this._currentBatch.map(function(f){return f.hash})}}}],[{key:"getIpfsHash",value:function(ipfs,log){if(!ipfs)throw new Error("Ipfs instance not defined");var data=new Buffer(JSON.stringify(log.snapshot));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash,options){if(!ipfs)throw new Error("Ipfs instance not defined");if(!hash)throw new Error("Invalid hash: "+hash);options||(options={});var logData=void 0;return ipfs.object.get(hash,{enc:"base58"}).then(function(res){return logData=JSON.parse(res.toJSON().data)}).then(function(res){if(!logData.items)throw new Error("Not a Log instance");return Promise.all(logData.items.map(function(f){return Entry.fromIpfsHash(ipfs,f)}))}).then(function(items){return Object.assign(options,{items:items})}).then(function(items){return new Log(ipfs,logData.id,options)})}},{key:"findHeads",value:function(log){return log.items.reverse().filter(function(f){return!Log.isReferencedInChain(log,f)}).map(function(f){return f.hash})}},{key:"isReferencedInChain",value:function(log,item){return void 0!==log.items.reverse().find(function(e){return Entry.hasChild(e,item)})}},{key:"batchSize",get:function(){return MaxBatchSize}}]),Log}();module.exports=Log}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;imax?cb(!0):void cb(null,i++)}}},function(module,exports){"use strict";module.exports=function(){return function(abort,cb){cb(!0)}}},function(module,exports){"use strict";module.exports=function(err){return function(abort,cb){cb(err)}}},function(module,exports,__webpack_require__){"use strict";module.exports={keys:__webpack_require__(103),once:__webpack_require__(39),values:__webpack_require__(23),count:__webpack_require__(98),infinite:__webpack_require__(102),empty:__webpack_require__(99),error:__webpack_require__(100)}},function(module,exports){"use strict";module.exports=function(generate){return generate=generate||Math.random,function(end,cb){return end?cb&&cb(end):cb(null,generate())}}},function(module,exports,__webpack_require__){"use strict";var values=__webpack_require__(23);module.exports=function(object){return values(Object.keys(object))}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(12);module.exports=function(map){if(!map)return id;map=prop(map);var abortCb,aborted,busy=!1;return function(read){return function next(abort,cb){return aborted?cb(aborted):void(abort?(aborted=abort,busy?read(abort,function(){busy?abortCb=cb:cb(abort)}):read(abort,cb)):read(null,function(end,data){end?cb(end):aborted?cb(aborted):(busy=!0,map(data,function(err,data){busy=!1,aborted?(cb(aborted),abortCb(aborted)):err?next(err,cb):cb(null,data)}))}))}}}},function(module,exports,__webpack_require__){"use strict";var tester=__webpack_require__(42),filter=__webpack_require__(24);module.exports=function(test){return test=tester(test),filter(function(data){return!test(data)})}},function(module,exports,__webpack_require__){"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},values=__webpack_require__(23),once=__webpack_require__(39);module.exports=function(){return function(read){var _read;return function(abort,cb){function nextChunk(){_read(null,function(err,data){err===!0?nextStream():err?read(!0,function(abortErr){cb(err)}):cb(null,data)})}function nextStream(){_read=null,read(null,function(end,stream){return end?cb(end):(Array.isArray(stream)||stream&&"object"===("undefined"==typeof stream?"undefined":_typeof(stream))?stream=values(stream):"function"!=typeof stream&&(stream=once(stream)),_read=stream,void nextChunk())})}abort?_read?_read(abort,function(err){read(err||abort,cb)}):read(abort,cb):_read?nextChunk():nextStream()}}}},function(module,exports,__webpack_require__){"use strict";module.exports={map:__webpack_require__(108),asyncMap:__webpack_require__(104),filter:__webpack_require__(24),filterNot:__webpack_require__(105),through:__webpack_require__(111),take:__webpack_require__(110),unique:__webpack_require__(40),nonUnique:__webpack_require__(109),flatten:__webpack_require__(106)}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(12);module.exports=function(mapper){return mapper?(mapper=prop(mapper),function(read){return function(abort,cb){read(abort,function(end,data){try{data=end?null:mapper(data)}catch(err){return read(err,function(){return cb(err)})}cb(end,data)})}}):id}},function(module,exports,__webpack_require__){"use strict";var unique=__webpack_require__(40);module.exports=function(field){return unique(field,!0)}},function(module,exports){"use strict";module.exports=function(test,opts){opts=opts||{};var last=opts.last||!1,ended=!1;if("number"==typeof test){last=!0;var n=test;test=function(){return--n}}return function(read){function terminate(cb){read(!0,function(err){last=!1,cb(err||!0)})}return function(end,cb){ended?last?terminate(cb):cb(ended):(ended=end)?read(ended,cb):read(null,function(end,data){(ended=ended||end)?cb(ended):test(data)?cb(null,data):(ended=!0,last?cb(null,data):terminate(cb))})}}}},function(module,exports){"use strict";module.exports=function(op,onEnd){function once(abort){!a&&onEnd&&(a=!0,onEnd(abort===!0?null:abort))}var a=!1;return function(read){return function(end,cb){return end&&once(end),read(end,function(end,data){end?once(end):op&&op(data),cb(end,data)})}}}},function(module,exports,__webpack_require__){"use strict";var looper=__webpack_require__(71),window=module.exports=function(init,start){return function(read){start=start||function(start,data){return{start:start,data:data}};var windows=[],output=[],ended=null,j=0;return function(abort,cb){if(output.length)return cb(null,output.shift());if(ended)return cb(ended);j++;read(abort,looper(function(end,data){function _update(end,_data){once||(once=!0,delete windows[windows.indexOf(update)],output.push(start(data,_data)))}var update,next=this,once=!1;return end&&(ended=end),ended||(update=init(data,_update)),update?windows.push(update):once=!0,windows.forEach(function(update,i){update(end,data)}),output.length?cb(null,output.shift()):ended?cb(ended):void read(null,next)}))}}};window.recent=function(size,time){var current=null;return window(function(data,cb){function done(){var _current=current;current=null,clearTimeout(timer),cb(null,_current)}if(!current){current=[];var timer;return time&&(timer=setTimeout(done,time)),function(end,data){return end?done():(current.push(data),void(null!=size&¤t.length>=size&&done()))}}},function(_,data){return data})},window.sliding=function(reduce,width){width=width||10;var k=0;return window(function(data,cb){var acc,i=0;k++;return function(end,data){end||(acc=reduce(acc,data),width<=++i&&cb(null,acc))}})}},function(module,exports){"use strict";function append(array,item){return(array=array||[]).push(item),array}module.exports=function(write,reduce,max,cb){function reader(read){function more(){reading||ended||(reading=!0,read(null,function(err,data){reading=!1,next(err,data)}))}function flush(){if(!writing){var _queue=queue;queue=null,writing=!0,length=0,write(_queue,function(err){writing=!1,ended!==!0||length?ended&&ended!==!0?(cb(ended),_cb&&_cb()):err?read(ended=err,cb):length?flush():more():cb(err)})}}function next(end,data){ended||(ended=end,ended?writing||cb(ended===!0?null:ended):(queue=reduce(queue,data),length=queue&&queue.length||0,null!=queue&&flush(),length1&&void 0!==arguments[1]?arguments[1]:"orbit-db.cache";return cache={},cachePath?(store=new BlobStore(cachePath),filePath=cacheFile,new Promise(function(resolve,reject){store.exists(cacheFile,function(err,exists){return err||!exists?resolve():void lock(cacheFile,function(release){pull(store.read(cacheFile),pull.collect(release(function(err,res){return err?reject(err):(cache=JSON.parse(Buffer.concat(res).toString()||"{}"),void resolve())})))})})})):Promise.resolve()}},{key:"reset",value:function(){cache={},store=null}}]),Cache}();module.exports=Cache}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{};if(credentials.provider!==OrbitIdentityProvider.id)throw new Error("OrbitIdentityProvider can't handle provider type '"+credentials.provider+"'");if(!credentials.username)throw new Error("'username' not specified");var keys=void 0,profileData=void 0;return Crypto.getKey(credentials.username).then(function(keyPair){return keys=keyPair,Crypto.exportKeyToIpfs(ipfs,keys.publicKey)}).then(function(pubKeyHash){return profileData={name:credentials.username,location:"Earth",image:null,signKey:pubKeyHash,updated:null,identityProvider:{provider:OrbitIdentityProvider.id,id:null}},ipfs.object.put(new Buffer(JSON.stringify(profileData))).then(function(res){return res.toJSON().multihash})}).then(function(hash){return profileData.id=hash,new OrbitUser(keys,profileData)})}},{key:"load",value:function(ipfs){var profile=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(profile.identityProvider.provider!==OrbitIdentityProvider.id)throw new Error("OrbitIdentityProvider can't handle provider type '"+profile.identityProvider.provider+"'");return Promise.resolve(profile)}},{key:"id",get:function(){return"orbit"}}]),OrbitIdentityProvider}();module.exports=OrbitIdentityProvider}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function placeHoldersCount(b64){var len=b64.length;if(len%4>0)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 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/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++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4, arr[L++]=255&tmp):1===placeHolders&&(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++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(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),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function BasePoint(curve,type){this.curve=curve,this.type=type,this.precomputed=null}var BN=__webpack_require__(6),elliptic=__webpack_require__(2),utils=elliptic.utils,getNAF=utils.getNAF,getJSF=utils.getJSF,assert=utils.assert;module.exports=BaseCurve,BaseCurve.prototype.point=function(){throw new Error("Not implemented")},BaseCurve.prototype.validate=function(){throw new Error("Not implemented")},BaseCurve.prototype._fixedNafMul=function(p,k){assert(p.precomputed);var doubles=p._getDoubles(),naf=getNAF(k,1),I=(1<=j;k--)nafW=(nafW<<1)+naf[k];repr.push(nafW)}for(var a=this.jpoint(null,null,null),b=this.jpoint(null,null,null),i=I;i>0;i--){for(var j=0;j=0;i--){for(var k=0;i>=0&&0===naf[i];i--)k++;if(i>=0&&k++,acc=acc.dblp(k),i<0)break;var z=naf[i];assert(0!==z),acc="affine"===p.type?z>0?acc.mixedAdd(wnd[z-1>>1]):acc.mixedAdd(wnd[-z-1>>1].neg()):z>0?acc.add(wnd[z-1>>1]):acc.add(wnd[-z-1>>1].neg())}return"affine"===p.type?acc.toP():acc},BaseCurve.prototype._wnafMulAdd=function(defW,points,coeffs,len,jacobianResult){for(var wndWidth=this._wnafT1,wnd=this._wnafT2,naf=this._wnafT3,max=0,i=0;i=1;i-=2){var a=i-1,b=i;if(1===wndWidth[a]&&1===wndWidth[b]){var comb=[points[a],null,null,points[b]];0===points[a].y.cmp(points[b].y)?(comb[1]=points[a].add(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg())):0===points[a].y.cmp(points[b].y.redNeg())?(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].add(points[b].neg())):(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],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--){for(var k=0;i>=0;){for(var zero=!0,j=0;j=0&&k++,acc=acc.dblp(k),i<0)break;for(var j=0;j0?p=wnd[j][z-1>>1]:z<0&&(p=wnd[j][-z-1>>1].neg()),acc="affine"===p.type?acc.mixedAdd(p):acc.add(p))}}for(var i=0;i=Math.ceil((k.bitLength()+1)/doubles.step)},BasePoint.prototype._getDoubles=function(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var doubles=[this],acc=this,i=0;i":""},Point.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&0===this.y.cmp(this.z)},Point.prototype._extDbl=function(){var a=this.x.redSqr(),b=this.y.redSqr(),c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a),e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b),g=d.redAdd(b),f=g.redSub(c),h=d.redSub(b),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projDbl=function(){var nx,ny,nz,b=this.x.redAdd(this.y).redSqr(),c=this.x.redSqr(),d=this.y.redSqr();if(this.curve.twisted){var e=this.curve._mulA(c),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(),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),h=this.curve._mulC(this.c.redMul(this.z)).redSqr(),j=e.redSub(h).redSub(h);nx=this.curve._mulC(b.redISub(e)).redMul(j),ny=this.curve._mulC(e).redMul(c.redISub(d)),nz=e.redMul(j)}return this.curve.point(nx,ny,nz)},Point.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Point.prototype._extAdd=function(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x)),b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)),c=this.t.redMul(this.curve.dd).redMul(p.t),d=this.z.redMul(p.z.redAdd(p.z)),e=b.redSub(a),f=d.redSub(c),g=d.redAdd(c),h=b.redAdd(a),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projAdd=function(p){var ny,nz,a=this.z.redMul(p.z),b=a.redSqr(),c=this.x.redMul(p.x),d=this.y.redMul(p.y),e=this.curve.d.redMul(c).redMul(d),f=b.redSub(e),g=b.redAdd(e),tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d),nx=a.redMul(f).redMul(tmp);return this.curve.twisted?(ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c))),nz=f.redMul(g)):(ny=a.redMul(g).redMul(d.redSub(c)),nz=this.curve._mulC(f).redMul(g)),this.curve.point(nx,ny,nz)},Point.prototype.add=function(p){return this.isInfinity()?p:p.isInfinity()?this:this.curve.extended?this._extAdd(p):this._projAdd(p)},Point.prototype.mul=function(k){return this._hasDoubles(k)?this.curve._fixedNafMul(this,k):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!1)},Point.prototype.jmulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!0)},Point.prototype.normalize=function(){if(this.zOne)return this;var zi=this.z.redInvm();return this.x=this.x.redMul(zi),this.y=this.y.redMul(zi),this.t&&(this.t=this.t.redMul(zi)),this.z=this.curve.one,this.zOne=!0,this},Point.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Point.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Point.prototype.eq=function(other){return this===other||0===this.getX().cmp(other.getX())&&0===this.getY().cmp(other.getY())},Point.prototype.eqXToP=function(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(rx))return!0;for(var xc=x.clone(),t=this.curve.redN.redMul(this.z);;){if(xc.iadd(this.curve.n),xc.cmp(this.curve.p)>=0)return!1;if(rx.redIAdd(t),0===this.x.cmp(rx))return!0}return!1},Point.prototype.toP=Point.prototype.normalize,Point.prototype.mixedAdd=Point.prototype.add},function(module,exports,__webpack_require__){"use strict";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))}function Point(curve,x,z){Base.BasePoint.call(this,curve,"projective"),null===x&&null===z?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new BN(x,16),this.z=new BN(z,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}var curve=__webpack_require__(16),BN=__webpack_require__(6),inherits=__webpack_require__(3),Base=curve.base,elliptic=__webpack_require__(2),utils=elliptic.utils;inherits(MontCurve,Base),module.exports=MontCurve,MontCurve.prototype.validate=function(point){var x=point.normalize().x,x2=x.redSqr(),rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x),y=rhs.redSqrt();return 0===y.redSqr().cmp(rhs)},inherits(Point,Base.BasePoint),MontCurve.prototype.decodePoint=function(bytes,enc){return this.point(utils.toArray(bytes,enc),1)},MontCurve.prototype.point=function(x,z){return new Point(this,x,z)},MontCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},Point.prototype.precompute=function(){},Point.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)},Point.prototype.inspect=function(){return this.isInfinity()?"":""},Point.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Point.prototype.dbl=function(){var a=this.x.redAdd(this.z),aa=a.redSqr(),b=this.x.redSub(this.z),bb=b.redSqr(),c=aa.redSub(bb),nx=aa.redMul(bb),nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)},Point.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.diffAdd=function(p,diff){var a=this.x.redAdd(this.z),b=this.x.redSub(this.z),c=p.x.redAdd(p.z),d=p.x.redSub(p.z),da=d.redMul(a),cb=c.redMul(b),nx=diff.z.redMul(da.redAdd(cb).redSqr()),nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)},Point.prototype.mul=function(k){for(var t=k.clone(),a=this,b=this.curve.point(null,null),c=this,bits=[];0!==t.cmpn(0);t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--)0===bits[i]?(a=a.diffAdd(b,c),b=b.dbl()):(b=a.diffAdd(b,c),a=a.dbl());return b},Point.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.eq=function(other){return 0===this.getX().cmp(other.getX())},Point.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},function(module,exports,__webpack_require__){"use strict";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=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(conf),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function Point(curve,x,y,isRed){Base.BasePoint.call(this,curve,"affine"),null===x&&null===y?(this.x=null,this.y=null,this.inf=!0):(this.x=new BN(x,16),this.y=new BN(y,16),isRed&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,"jacobian"),null===x&&null===y&&null===z?(this.x=this.curve.one,this.y=this.curve.one,this.z=new BN(0)):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=new BN(z,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}var curve=__webpack_require__(16),elliptic=__webpack_require__(2),BN=__webpack_require__(6),inherits=__webpack_require__(3),Base=curve.base,assert=elliptic.utils.assert;inherits(ShortCurve,Base),module.exports=ShortCurve,ShortCurve.prototype._getEndomorphism=function(conf){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var beta,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);0===this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))?lambda=lambdas[0]:(lambda=lambdas[1],assert(0===this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))))}var basis;return basis=conf.basis?conf.basis.map(function(vec){return{a:new BN(vec.a,16),b:new BN(vec.b,16)}}):this._getEndoBasis(lambda),{beta:beta,lambda:lambda,basis:basis}}},ShortCurve.prototype._getEndoRoots=function(num){var red=num===this.p?this.red:BN.mont(num),tinv=new BN(2).toRed(red).redInvm(),ntinv=tinv.redNeg(),s=new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv),l1=ntinv.redAdd(s).fromRed(),l2=ntinv.redSub(s).fromRed();return[l1,l2]},ShortCurve.prototype._getEndoBasis=function(lambda){for(var a0,b0,a1,b1,a2,b2,prevR,r,x,aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2)),u=lambda,v=this.n.clone(),x1=new BN(1),y1=new BN(0),x2=new BN(0),y2=new BN(1),i=0;0!==u.cmpn(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&&2===++i)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()),len2=a2.sqr().add(b2.sqr());return len2.cmp(len1)>=0&&(a2=a0,b2=b0),a1.negative&&(a1=a1.neg(),b1=b1.neg()),a2.negative&&(a2=a2.neg(),b2=b2.neg()),[{a:a1,b:b1},{a:a2,b:b2}]},ShortCurve.prototype._endoSplit=function(k){var basis=this.endo.basis,v1=basis[0],v2=basis[1],c1=v2.b.mul(k).divRound(this.n),c2=v1.b.neg().mul(k).divRound(this.n),p1=c1.mul(v1.a),p2=c2.mul(v2.a),q1=c1.mul(v1.b),q2=c2.mul(v2.b),k1=k.sub(p1).sub(p2),k2=q1.add(q2).neg();return{k1:k1,k2:k2}},ShortCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b),y=y2.redSqrt();if(0!==y.redSqr().redSub(y2).cmp(this.zero))throw new Error("invalid point");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},ShortCurve.prototype.validate=function(point){if(point.inf)return!0;var x=point.x,y=point.y,ax=this.a.redMul(x),rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return 0===y.redSqr().redISub(rhs).cmpn(0)},ShortCurve.prototype._endoWnafMulAdd=function(points,coeffs,jacobianResult){for(var npoints=this._endoWnafT1,ncoeffs=this._endoWnafT2,i=0;i":""},Point.prototype.isInfinity=function(){return this.inf},Point.prototype.add=function(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(0===this.x.cmp(p.x))return this.curve.point(null,null);var c=this.y.redSub(p.y);0!==c.cmpn(0)&&(c=c.redMul(this.x.redSub(p.x).redInvm()));var nx=c.redSqr().redISub(this.x).redISub(p.x),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.dbl=function(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(0===ys1.cmpn(0))return this.curve.point(null,null);var a=this.curve.a,x2=this.x.redSqr(),dyinv=ys1.redInvm(),c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv),nx=c.redSqr().redISub(this.x.redAdd(this.x)),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.getX=function(){return this.x.fromRed()},Point.prototype.getY=function(){return this.y.fromRed()},Point.prototype.mul=function(k){return k=new BN(k,16),this._hasDoubles(k)?this.curve._fixedNafMul(this,k):this.curve.endo?this.curve._endoWnafMulAdd([this],[k]):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs):this.curve._wnafMulAdd(1,points,coeffs,2)},Point.prototype.jmulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs,!0):this.curve._wnafMulAdd(1,points,coeffs,2,!0)},Point.prototype.eq=function(p){return this===p||this.inf===p.inf&&(this.inf||0===this.x.cmp(p.x)&&0===this.y.cmp(p.y))},Point.prototype.neg=function(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed,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(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res},inherits(JPoint,Base.BasePoint),ShortCurve.prototype.jpoint=function(x,y,z){return new JPoint(this,x,y,z)},JPoint.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm(),zinv2=zinv.redSqr(),ax=this.x.redMul(zinv2),ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)},JPoint.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},JPoint.prototype.add=function(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr(),z2=this.z.redSqr(),u1=this.x.redMul(pz2),u2=p.x.redMul(z2),s1=this.y.redMul(pz2.redMul(p.z)),s2=p.y.redMul(z2.redMul(this.z)),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.mixedAdd=function(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr(),u1=this.x,u2=p.x.redMul(z2),s1=this.y,s2=p.y.redMul(z2).redMul(this.z),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.dblp=function(pow){if(0===pow)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var r=this,i=0;i=0)return!1;if(rx.redIAdd(t),0===this.x.cmp(rx))return!0}return!1},JPoint.prototype.inspect=function(){return this.isInfinity()?"":""},JPoint.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},function(module,exports,__webpack_require__){"use strict";function PresetCurve(options){"short"===options.type?this.curve=new elliptic.curve.short(options):"edwards"===options.type?this.curve=new elliptic.curve.edwards(options):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")}function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,get:function(){var curve=new PresetCurve(options);return Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,value:curve}),curve}})}var curves=exports,hash=__webpack_require__(8),elliptic=__webpack_require__(2),assert=elliptic.utils.assert;curves.PresetCurve=PresetCurve,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:!1,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:!1,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:!1,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:!1,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:!1,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:"0",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:!1,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:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var pre;try{pre=__webpack_require__(131)}catch(e){pre=void 0}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:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})},function(module,exports,__webpack_require__){"use strict";function EC(options){return this instanceof EC?("string"==typeof options&&(assert(elliptic.curves.hasOwnProperty(options),"Unknown curve "+options),options=elliptic.curves[options]),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),void(this.hash=options.hash||options.curve.hash)):new EC(options)}var BN=__webpack_require__(6),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert,KeyPair=__webpack_require__(125),Signature=__webpack_require__(126);module.exports=EC,EC.prototype.keyPair=function(options){return new KeyPair(this,options)},EC.prototype.keyFromPrivate=function(priv,enc){return KeyPair.fromPrivate(this,priv,enc)},EC.prototype.keyFromPublic=function(pub,enc){return KeyPair.fromPublic(this,pub,enc)},EC.prototype.genKeyPair=function(options){options||(options={});for(var drbg=new elliptic.hmacDRBG({hash:this.hash,pers:options.pers,entropy:options.entropy||elliptic.rand(this.hash.hmacStrength),nonce:this.n.toArray()}),bytes=this.n.byteLength(),ns2=this.n.sub(new BN(2));;){var priv=new BN(drbg.generate(bytes));if(!(priv.cmp(ns2)>0))return priv.iaddn(1),this.keyFromPrivate(priv)}},EC.prototype._truncateToN=function(msg,truncOnly){var delta=8*msg.byteLength()-this.n.bitLength();return delta>0&&(msg=msg.ushrn(delta)),!truncOnly&&msg.cmp(this.n)>=0?msg.sub(this.n):msg},EC.prototype.sign=function(msg,key,enc,options){"object"==typeof enc&&(options=enc,enc=null),options||(options={}),key=this.keyFromPrivate(key,enc),msg=this._truncateToN(new BN(msg,16));for(var bytes=this.n.byteLength(),bkey=key.getPrivate().toArray("be",bytes),nonce=msg.toArray("be",bytes),drbg=new elliptic.hmacDRBG({hash:this.hash,entropy:bkey,nonce:nonce,pers:options.pers,persEnc:options.persEnc}),ns1=this.n.sub(new BN(1)),iter=0;!0;iter++){var k=options.k?options.k(iter):new BN(drbg.generate(this.n.byteLength()));if(k=this._truncateToN(k,!0),!(k.cmpn(1)<=0||k.cmp(ns1)>=0)){var kp=this.g.mul(k);if(!kp.isInfinity()){var kpX=kp.getX(),r=kpX.umod(this.n);if(0!==r.cmpn(0)){var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));if(s=s.umod(this.n),0!==s.cmpn(0)){var recoveryParam=(kp.getY().isOdd()?1:0)|(0!==kpX.cmp(r)?2:0);return options.canonical&&s.cmp(this.nh)>0&&(s=this.n.sub(s),recoveryParam^=1),new Signature({r:r,s:s,recoveryParam:recoveryParam})}}}}}},EC.prototype.verify=function(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,s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var sinv=s.invm(this.n),u1=sinv.mul(msg).umod(this.n),u2=sinv.mul(r).umod(this.n);if(!this.curve._maxwellTrick){var p=this.g.mulAdd(u1,key.getPublic(),u2);return!p.isInfinity()&&0===p.getX().umod(this.n).cmp(r)}var p=this.g.jmulAdd(u1,key.getPublic(),u2);return!p.isInfinity()&&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,e=new BN(msg),r=signature.r,s=signature.s,isYOdd=1&j,isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");r=isSecondKey?this.curve.pointFromX(r.add(this.curve.n),isYOdd):this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n),s1=n.sub(e).mul(rInv).umod(n),s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)},EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){if(signature=new Signature(signature,enc),null!==signature.recoveryParam)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")}},function(module,exports,__webpack_require__){"use strict";function KeyPair(ec,options){this.ec=ec,this.priv=null,this.pub=null,options.priv&&this._importPrivate(options.priv,options.privEnc),options.pub&&this._importPublic(options.pub,options.pubEnc)}var BN=__webpack_require__(6);module.exports=KeyPair,KeyPair.fromPublic=function(ec,pub,enc){return pub instanceof KeyPair?pub:new KeyPair(ec,{pub:pub,pubEnc:enc})},KeyPair.fromPrivate=function(ec,priv,enc){return priv instanceof KeyPair?priv:new KeyPair(ec,{priv:priv,privEnc:enc})},KeyPair.prototype.validate=function(){var pub=this.getPublic();return pub.isInfinity()?{result:!1,reason:"Invalid public key"}:pub.validate()?pub.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},KeyPair.prototype.getPublic=function(compact,enc){return"string"==typeof compact&&(enc=compact,compact=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),enc?this.pub.encode(enc,compact):this.pub},KeyPair.prototype.getPrivate=function(enc){return"hex"===enc?this.priv.toString(16,2):this.priv},KeyPair.prototype._importPrivate=function(key,enc){this.priv=new BN(key,enc||16),this.priv=this.priv.umod(this.ec.curve.n)},KeyPair.prototype._importPublic=function(key,enc){return key.x||key.y?void(this.pub=this.ec.curve.point(key.x,key.y)):void(this.pub=this.ec.curve.decodePoint(key,enc))},KeyPair.prototype.derive=function(pub){return pub.mul(this.priv).getX()},KeyPair.prototype.sign=function(msg,enc,options){return this.ec.sign(msg,this,enc,options)},KeyPair.prototype.verify=function(msg,signature){return this.ec.verify(msg,signature,this)},KeyPair.prototype.inspect=function(){return""}},function(module,exports,__webpack_require__){"use strict";function Signature(options,enc){return options instanceof Signature?options:void(this._importDER(options,enc)||(assert(options.r&&options.s,"Signature without r or s"),this.r=new BN(options.r,16),this.s=new BN(options.s,16),void 0===options.recoveryParam?this.recoveryParam=null:this.recoveryParam=options.recoveryParam))}function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(128&initial))return initial;for(var octetLen=15&initial,val=0,i=0,off=p.place;i>>3);for(arr.push(128|octets);--octets;)arr.push(len>>>(octets<<3)&255);arr.push(len)}var BN=__webpack_require__(6),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert;module.exports=Signature,Signature.prototype._importDER=function(data,enc){data=utils.toArray(data,enc);var p=new Position;if(48!==data[p.place++])return!1;var len=getLength(data,p);if(len+p.place!==data.length)return!1;if(2!==data[p.place++])return!1;var rlen=getLength(data,p),r=data.slice(p.place,rlen+p.place);if(p.place+=rlen,2!==data[p.place++])return!1;var slen=getLength(data,p);if(data.length!==slen+p.place)return!1;var s=data.slice(p.place,slen+p.place);return 0===r[0]&&128&r[1]&&(r=r.slice(1)),0===s[0]&&128&s[1]&&(s=s.slice(1)),this.r=new BN(r),this.s=new BN(s),this.recoveryParam=null,!0},Signature.prototype.toDER=function(enc){var r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=rmPadding(r),s=rmPadding(s);!(s[0]||128&s[1]);)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),res=[48];return constructLength(res,backHalf.length),res=res.concat(backHalf),utils.encode(res,enc)}},function(module,exports,__webpack_require__){"use strict";function EDDSA(curve){if(assert("ed25519"===curve,"only tested with ed25519 so far"),!(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}var hash=__webpack_require__(8),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert,parseBytes=utils.parseBytes,KeyPair=__webpack_require__(128),Signature=__webpack_require__(129);module.exports=EDDSA,EDDSA.prototype.sign=function(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret),r=this.hashInt(key.messagePrefix(),message),R=this.g.mul(r),Rencoded=this.encodePoint(R),s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv()),S=r.add(s_).umod(this.curve.n);return this.makeSignature({R:R,S:S,Rencoded:Rencoded})},EDDSA.prototype.verify=function(message,sig,pub){message=parseBytes(message),sig=this.makeSignature(sig);var key=this.keyFromPublic(pub),h=this.hashInt(sig.Rencoded(),key.pubBytes(),message),SG=this.g.mul(sig.S()),RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)},EDDSA.prototype.hashInt=function(){for(var hash=this.hash(),i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(entropy,nonce,pers)}var hash=__webpack_require__(8),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert;module.exports=HmacDRBG,HmacDRBG.prototype._init=function(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(len,enc,add,addEnc){if(this.reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof enc&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc),this._update(add));for(var temp=[];temp.length>8,lo=255&c;hi?res.push(hi,lo):res.push(lo)}return res}function zero2(word){return 1===word.length?"0"+word:word}function toHex(msg){for(var res="",i=0;i=0;){var z;if(k.isOdd()){var mod=k.andln(ws-1);z=mod>(ws>>1)-1?(ws>>1)-mod:mod,k.isubn(z)}else z=0;naf.push(z);for(var shift=0!==k.cmpn(0)&&0===k.andln(ws-1)?w+1:1,i=1;i0||k2.cmpn(-d2)>0;){var m14=k1.andln(3)+d1&3,m24=k2.andln(3)+d2&3;3===m14&&(m14=-1),3===m24&&(m24=-1);var u1;if(0===(1&m14))u1=0;else{var m8=k1.andln(7)+d1&7;u1=3!==m8&&5!==m8||2!==m24?m14:-m14}jsf[0].push(u1);var u2;if(0===(1&m24))u2=0;else{var m8=k2.andln(7)+d2&7;u2=3!==m8&&5!==m8||2!==m14?m24:-m24}jsf[1].push(u2),2*d1===u1+1&&(d1=1-d1),2*d2===u2+1&&(d2=1-d2),k1.iushrn(1),k2.iushrn(1)}return jsf}function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function(){return void 0!==this[key]?this[key]:this[key]=computer.call(this)}}function parseBytes(bytes){return"string"==typeof bytes?utils.toArray(bytes,"hex"):bytes}function intFromLE(bytes){return new BN(bytes,"hex","le")}var utils=exports,BN=__webpack_require__(6);utils.assert=function(val,msg){if(!val)throw new Error(msg||"Assertion failed")},utils.toArray=toArray,utils.zero2=zero2,utils.toHex=toHex,utils.encode=function(arr,enc){return"hex"===enc?toHex(arr):arr},utils.getNAF=getNAF,utils.getJSF=getJSF,utils.cachedProperty=cachedProperty,utils.parseBytes=parseBytes,utils.intFromLE=intFromLE},function(module,exports,__webpack_require__){(function(process){function noop(){}function patch(fs){function readFile(path,options,cb){function go$readFile(path,options,cb){return fs$readFile(path,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$readFile,[path,options,cb]])})}return"function"==typeof options&&(cb=options,options=null),go$readFile(path,options,cb)}function writeFile(path,data,options,cb){function go$writeFile(path,data,options,cb){return fs$writeFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$writeFile,[path,data,options,cb]])})}return"function"==typeof options&&(cb=options,options=null),go$writeFile(path,data,options,cb)}function appendFile(path,data,options,cb){function go$appendFile(path,data,options,cb){return fs$appendFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$appendFile,[path,data,options,cb]])})}return"function"==typeof options&&(cb=options,options=null),go$appendFile(path,data,options,cb)}function readdir(path,options,cb){function go$readdir$cb(err,files){files&&files.sort&&files.sort(),!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$readdir,[args]])}var args=[path];return"function"!=typeof options?args.push(options):cb=options,args.push(go$readdir$cb),go$readdir(args)}function go$readdir(args){return fs$readdir.apply(fs,args)}function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new ReadStream(path,options)}function createWriteStream(path,options){return new WriteStream(path,options)}function open(path,flags,mode,cb){function go$open(path,flags,mode,cb){return fs$open(path,flags,mode,function(err,fd){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$open,[path,flags,mode,cb]])})}return"function"==typeof mode&&(cb=mode,mode=null),go$open(path,flags,mode,cb)}polyfills(fs),fs.gracefulify=patch,fs.FileReadStream=ReadStream,fs.FileWriteStream=WriteStream,fs.createReadStream=createReadStream,fs.createWriteStream=createWriteStream;var fs$readFile=fs.readFile;fs.readFile=readFile;var fs$writeFile=fs.writeFile;fs.writeFile=writeFile;var fs$appendFile=fs.appendFile;fs$appendFile&&(fs.appendFile=appendFile);var fs$readdir=fs.readdir;if(fs.readdir=readdir,"v0.8"===process.version.substr(0,4)){var legStreams=legacy(fs);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs.ReadStream;ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs.WriteStream;WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open,fs.ReadStream=ReadStream,fs.WriteStream=WriteStream;var fs$open=fs.open;return fs.open=open,fs}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),queue.push(elem)}function retry(){var elem=queue.shift();elem&&(debug("RETRY",elem[0].name,elem[1]),elem[0].apply(null,elem[1]))}var fs=__webpack_require__(15),polyfills=__webpack_require__(135),legacy=__webpack_require__(134),queue=[],util=__webpack_require__(14),debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join("\nGFS4: "),console.error(m)}),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(queue),__webpack_require__(54).equal(queue.length,0)}),module.exports=patch(__webpack_require__(43)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&(module.exports=patch(fs)),module.exports.close=fs.close=function(fs$close){return function(fd,cb){return fs$close.call(fs,fd,function(err){err||retry(),"function"==typeof cb&&cb.apply(this,arguments)})}}(fs.close),module.exports.closeSync=fs.closeSync=function(fs$closeSync){return function(fd){var rval=fs$closeSync.apply(fs,arguments);return retry(),rval}}(fs.closeSync)}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){(function(process){function legacy(fs){function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;indexthis.end)throw new Error("start must be <= end");this.pos=this.start}return null!==this.fd?void process.nextTick(function(){self._read()}):void fs.open(this.path,this.flags,this.mode,function(err,fd){return err?(self.emit("error",err),void(self.readable=!1)):(self.fd=fd,self.emit("open",fd),void self._read())})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index= zero");this.pos=this.start}this.busy=!1,this._queue=[],null===this.fd&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}return{ReadStream:ReadStream,WriteStream:WriteStream}}var Stream=__webpack_require__(17).Stream;module.exports=legacy}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){(function(process){function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.lchmod||(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.lchown||(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),"win32"===platform&&(fs.rename=function(fs$rename){return function(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){return er&&("EACCES"===er.code||"EPERM"===er.code)&&Date.now()-start<6e4?(setTimeout(function(){fs.stat(to,function(stater,st){stater&&"ENOENT"===stater.code?fs$rename(from,to,CB):cb(er)})},backoff),void(backoff<100&&(backoff+=10))):void(cb&&cb(er))})}}(fs.rename)),fs.read=function(fs$read){return function(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&"function"==typeof callback_){var eagCounter=0;callback=function(er,_,__){return er&&"EAGAIN"===er.code&&eagCounter<10?(eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback)):void callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}}(fs.read),fs.readSync=function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if("EAGAIN"===er.code&&eagCounter<10){eagCounter++;continue}throw er}}}(fs.readSync)}function patchLchmod(fs){fs.lchmod=function(path,mode,callback){fs.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){return err?void(callback&&callback(err)):void fs.fchmod(fd,mode,function(err){fs.close(fd,function(err2){callback&&callback(err||err2)})})})},fs.lchmodSync=function(path,mode){var ret,fd=fs.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0;try{ret=fs.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}}function patchLutimes(fs){constants.hasOwnProperty("O_SYMLINK")?(fs.lutimes=function(path,at,mt,cb){fs.open(path,constants.O_SYMLINK,function(er,fd){return er?void(cb&&cb(er)):void fs.futimes(fd,at,mt,function(er){fs.close(fd,function(er2){cb&&cb(er||er2)})})})},fs.lutimesSync=function(path,at,mt){var ret,fd=fs.openSync(path,constants.O_SYMLINK),threw=!0;try{ret=fs.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}):(fs.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs.lutimesSync=function(){})}function chmodFix(orig){return orig?function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chmodFixSync(orig){return orig?function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}:orig}function chownFix(orig){return orig?function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chownFixSync(orig){return orig?function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}:orig}function statFix(orig){return orig?function(target,cb){return orig.call(fs,target,function(er,stats){return stats?(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296),void(cb&&cb.apply(this,arguments))):cb.apply(this,arguments)})}:orig}function statFixSync(orig){return orig?function(target){var stats=orig.call(fs,target);return stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296),stats}:orig}function chownErOk(er){if(!er)return!0;if("ENOSYS"===er.code)return!0;var nonroot=!process.getuid||0!==process.getuid();return!(!nonroot||"EINVAL"!==er.code&&"EPERM"!==er.code)}var fs=__webpack_require__(43),constants=__webpack_require__(143),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch(er){}var chdir=process.chdir;process.chdir=function(d){cwd=null,chdir.call(process,d)},module.exports=patch}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){function BlockHash(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var hash=__webpack_require__(8),utils=hash.utils,assert=utils.assert;exports.BlockHash=BlockHash,BlockHash.prototype.update=function(msg,enc){if(msg=utils.toArray(msg,enc),this.pending?this.pending=this.pending.concat(msg):this.pending=msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),0===this.pending.length&&(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++]=255&len}else{res[i++]=255&len,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){return 0===s?ch32(x,y,z):1===s||3===s?p32(x,y,z):2===s?maj32(x,y,z):void 0}function ch64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^~xh&zh;return r<0&&(r+=4294967296),r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;return r<0&&(r+=4294967296),r}function maj64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^xh&zh^yh&zh;return r<0&&(r+=4294967296),r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;return r<0&&(r+=4294967296),r}function s0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,28),c1_hi=rotr64_hi(xl,xh,2),c2_hi=rotr64_hi(xl,xh,7),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function s0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,28),c1_lo=rotr64_lo(xl,xh,2),c2_lo=rotr64_lo(xl,xh,7),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}function s1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,14),c1_hi=rotr64_hi(xh,xl,18),c2_hi=rotr64_hi(xl,xh,9),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function s1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,14),c1_lo=rotr64_lo(xh,xl,18),c2_lo=rotr64_lo(xl,xh,9),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}function g0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,1),c1_hi=rotr64_hi(xh,xl,8),c2_hi=shr64_hi(xh,xl,7),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function g0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,1),c1_lo=rotr64_lo(xh,xl,8),c2_lo=shr64_lo(xh,xl,7),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}function g1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,19),c1_hi=rotr64_hi(xl,xh,29),c2_hi=shr64_hi(xh,xl,6),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function g1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,19),c1_lo=rotr64_lo(xl,xh,29),c2_lo=shr64_lo(xh,xl,6),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}var hash=__webpack_require__(8),utils=hash.utils,assert=utils.assert,rotr32=utils.rotr32,rotl32=utils.rotl32,sum32=utils.sum32,sum32_4=utils.sum32_4,sum32_5=utils.sum32_5,rotr64_hi=utils.rotr64_hi,rotr64_lo=utils.rotr64_lo,shr64_hi=utils.shr64_hi,shr64_lo=utils.shr64_lo,sum64=utils.sum64,sum64_hi=utils.sum64_hi,sum64_lo=utils.sum64_lo,sum64_4_hi=utils.sum64_4_hi,sum64_4_lo=utils.sum64_4_lo,sum64_5_hi=utils.sum64_5_hi,sum64_5_lo=utils.sum64_5_lo,BlockHash=hash.common.BlockHash,sha256_K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],sha512_K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],sha1_K=[1518500249,1859775393,2400959708,3395469782];utils.inherits(SHA256,BlockHash),exports.sha256=SHA256,SHA256.blockSize=512,SHA256.outSize=256,SHA256.hmacStrength=192,SHA256.padLength=64,SHA256.prototype._update=function(msg,start){for(var W=this.W,i=0;i<16;i++)W[i]=msg[start+i];for(;i>8,lo=255&c;hi?res.push(hi,lo):res.push(lo)}else for(var i=0;i>>24|w>>>8&65280|w<<8&16711680|(255&w)<<24;return res>>>0}function toHex32(msg,endian){for(var res="",i=0;i>>0}return res}function split32(msg,endian){for(var res=new Array(4*msg.length),i=0,k=0;i>>24,res[k+1]=m>>>16&255,res[k+2]=m>>>8&255,res[k+3]=255&m):(res[k+3]=m>>>24,res[k+2]=m>>>16&255,res[k+1]=m>>>8&255,res[k]=255&m)}return res}function rotr32(w,b){return w>>>b|w<<32-b}function rotl32(w,b){return w<>>32-b}function sum32(a,b){return a+b>>>0}function sum32_3(a,b,c){return a+b+c>>>0}function sum32_4(a,b,c,d){return a+b+c+d>>>0}function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}function assert(cond,msg){if(!cond)throw new Error(msg||"Assertion failed")}function sum64(buf,pos,ah,al){var bh=buf[pos],bl=buf[pos+1],lo=al+bl>>>0,hi=(lo>>0,buf[pos+1]=lo}function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0,hi=(lo>>0}function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el; return lo>>>0}function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}function shr64_hi(ah,al,num){return ah>>>num}function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}var utils=exports,inherits=__webpack_require__(3);utils.toArray=toArray,utils.toHex=toHex,utils.htonl=htonl,utils.toHex32=toHex32,utils.zero2=zero2,utils.zero8=zero8,utils.join32=join32,utils.split32=split32,utils.rotr32=rotr32,utils.rotl32=rotl32,utils.sum32=sum32,utils.sum32_3=sum32_3,utils.sum32_4=sum32_4,utils.sum32_5=sum32_5,utils.assert=assert,utils.inherits=inherits,exports.sum64=sum64,exports.sum64_hi=sum64_hi,exports.sum64_lo=sum64_lo,exports.sum64_4_hi=sum64_4_hi,exports.sum64_4_lo=sum64_4_lo,exports.sum64_5_hi=sum64_5_hi,exports.sum64_5_lo=sum64_5_lo,exports.rotr64_hi=rotr64_hi,exports.rotr64_lo=rotr64_lo,exports.shr64_hi=shr64_hi,exports.shr64_lo=shr64_lo},function(module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),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,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},function(module,exports,__webpack_require__){/** * @preserve * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) * * @author Jens Taylor * @see http://github.com/homebrewing/brauhaus-diff * @author Gary Court * @see http://github.com/garycourt/murmurhash-js * @author Austin Appleby * @see http://sites.google.com/site/murmurhash/ */ !function(){function MurmurHash3(key,seed){var m=this instanceof MurmurHash3?this:cache;if(m.reset(seed),"string"==typeof key&&key.length>0&&m.hash(key),m!==this)return m}var cache;MurmurHash3.prototype.hash=function(key){var h1,k1,i,top,len;switch(len=key.length,this.len+=len,k1=this.k1,i=0,this.rem){case 0:k1^=len>i?65535&key.charCodeAt(i++):0;case 1:k1^=len>i?(65535&key.charCodeAt(i++))<<8:0;case 2:k1^=len>i?(65535&key.charCodeAt(i++))<<16:0;case 3:k1^=len>i?(255&key.charCodeAt(i))<<24:0,k1^=len>i?(65280&key.charCodeAt(i++))>>8:0}if(this.rem=len+this.rem&3,len-=this.rem,len>0){for(h1=this.h1;;){if(k1=11601*k1+3432906752*(65535&k1)&4294967295,k1=k1<<15|k1>>>17,k1=13715*k1+461832192*(65535&k1)&4294967295,h1^=k1,h1=h1<<13|h1>>>19,h1=5*h1+3864292196&4294967295,i>=len)break;k1=65535&key.charCodeAt(i++)^(65535&key.charCodeAt(i++))<<8^(65535&key.charCodeAt(i++))<<16,top=key.charCodeAt(i++),k1^=(255&top)<<24^(65280&top)>>8}switch(k1=0,this.rem){case 3:k1^=(65535&key.charCodeAt(i+2))<<16;case 2:k1^=(65535&key.charCodeAt(i+1))<<8;case 1:k1^=65535&key.charCodeAt(i)}this.h1=h1}return this.k1=k1,this},MurmurHash3.prototype.result=function(){var k1,h1;return k1=this.k1,h1=this.h1,k1>0&&(k1=11601*k1+3432906752*(65535&k1)&4294967295,k1=k1<<15|k1>>>17,k1=13715*k1+461832192*(65535&k1)&4294967295,h1^=k1),h1^=this.len,h1^=h1>>>16,h1=51819*h1+2246770688*(65535&h1)&4294967295,h1^=h1>>>13,h1=44597*h1+3266445312*(65535&h1)&4294967295,h1^=h1>>>16,h1>>>0},MurmurHash3.prototype.reset=function(seed){return this.h1="number"==typeof seed?seed:0,this.rem=this.k1=this.len=0,this},cache=new MurmurHash3,module.exports=MurmurHash3}()},function(module,exports){module.exports={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:512,O_EXCL:2048,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_DIRECTORY:1048576,O_NOFOLLOW:256,O_SYNC:128,O_SYMLINK:2097152,O_NONBLOCK:4,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,E2BIG:7,EACCES:13,EADDRINUSE:48,EADDRNOTAVAIL:49,EAFNOSUPPORT:47,EAGAIN:35,EALREADY:37,EBADF:9,EBADMSG:94,EBUSY:16,ECANCELED:89,ECHILD:10,ECONNABORTED:53,ECONNREFUSED:61,ECONNRESET:54,EDEADLK:11,EDESTADDRREQ:39,EDOM:33,EDQUOT:69,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:65,EIDRM:90,EILSEQ:92,EINPROGRESS:36,EINTR:4,EINVAL:22,EIO:5,EISCONN:56,EISDIR:21,ELOOP:62,EMFILE:24,EMLINK:31,EMSGSIZE:40,EMULTIHOP:95,ENAMETOOLONG:63,ENETDOWN:50,ENETRESET:52,ENETUNREACH:51,ENFILE:23,ENOBUFS:55,ENODATA:96,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:77,ENOLINK:97,ENOMEM:12,ENOMSG:91,ENOPROTOOPT:42,ENOSPC:28,ENOSR:98,ENOSTR:99,ENOSYS:78,ENOTCONN:57,ENOTDIR:20,ENOTEMPTY:66,ENOTSOCK:38,ENOTSUP:45,ENOTTY:25,ENXIO:6,EOPNOTSUPP:102,EOVERFLOW:84,EPERM:1,EPIPE:32,EPROTO:100,EPROTONOSUPPORT:43,EPROTOTYPE:41,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:70,ETIME:101,ETIMEDOUT:60,ETXTBSY:26,EWOULDBLOCK:35,EXDEV:18,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:10,SIGFPE:8,SIGKILL:9,SIGUSR1:30,SIGSEGV:11,SIGUSR2:31,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:20,SIGCONT:19,SIGSTOP:17,SIGTSTP:18,SIGTTIN:21,SIGTTOU:22,SIGURG:16,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:23,SIGSYS:12,SSL_OP_ALL:2147486719,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_EPHEMERAL_RSA:0,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER:32,SSL_OP_MICROSOFT_SESS_ID_BUG:1,SSL_OP_MSIE_SSLV2_RSA_PADDING:0,SSL_OP_NETSCAPE_CA_DN_BUG:536870912,SSL_OP_NETSCAPE_CHALLENGE_BUG:2,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG:1073741824,SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG:8,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:16777216,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_PKCS1_CHECK_1:0,SSL_OP_PKCS1_CHECK_2:0,SSL_OP_SINGLE_DH_USE:1048576,SSL_OP_SINGLE_ECDH_USE:524288,SSL_OP_SSLEAY_080_CLIENT_DH_BUG:128,SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG:0,SSL_OP_TLS_BLOCK_PADDING_BUG:512,SSL_OP_TLS_D5_BUG:256,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_ECDH:16,ENGINE_METHOD_ECDSA:32,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_STORE:256,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_UDP_REUSEADDR:4}},function(module,exports){module.exports={_args:[[{raw:"elliptic@^6.3.1",scope:null,escapedName:"elliptic",name:"elliptic",rawSpec:"^6.3.1",spec:">=6.3.1 <7.0.0",type:"range"},"/Users/samuli/code/orbit-core/node_modules/orbit-crypto"]],_from:"elliptic@>=6.3.1 <7.0.0",_id:"elliptic@6.3.2",_inCache:!0,_location:"/elliptic",_nodeVersion:"6.3.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/elliptic-6.3.2.tgz_1473938837205_0.3108903462998569"},_npmUser:{name:"indutny",email:"fedor@indutny.com"},_npmVersion:"3.10.3",_phantomChildren:{},_requested:{raw:"elliptic@^6.3.1",scope:null,escapedName:"elliptic",name:"elliptic",rawSpec:"^6.3.1",spec:">=6.3.1 <7.0.0",type:"range"},_requiredBy:["/browserify-sign","/create-ecdh","/orbit-crypto"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz",_shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",_shrinkwrap:null,_spec:"elliptic@^6.3.1",_where:"/Users/samuli/code/orbit-core/node_modules/orbit-crypto",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0",inherits:"^2.0.1"},description:"EC cryptography",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},directories:{},dist:{shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",tarball:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"},files:["lib"],gitHead:"cbace4683a4a548dc0306ef36756151a20299cd5",homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",maintainers:[{name:"indutny",email:"fedor@indutny.com"}],name:"elliptic",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.3.2"}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(9)},function(module,exports,__webpack_require__){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var bufferShim=(__webpack_require__(0).Buffer,__webpack_require__(25));module.exports=BufferList,BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(46)},function(module,exports,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(17)}catch(_){}}();exports=module.exports=__webpack_require__(47),exports.Stream=Stream||exports,exports.Readable=exports,exports.Writable=__webpack_require__(28),exports.Duplex=__webpack_require__(9),exports.Transform=__webpack_require__(27),exports.PassThrough=__webpack_require__(46),!process.browser&&"disable"===process.env.READABLE_STREAM&&Stream&&(module.exports=Stream)}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){module.exports=__webpack_require__(27)},function(module,exports,__webpack_require__){module.exports=__webpack_require__(28)},function(module,exports,__webpack_require__){(function(process){function asyncMap(){function cb(er){er&&!errState&&(errState=er);for(var argLen=arguments.length,i=1;il){var newList=list.slice(l);a+=(list.length-l)*n,l=list.length,process.nextTick(function(){newList.forEach(function(ar){steps.forEach(function(fn){fn(ar,cb)})})})}0===--a&&cb_.apply(null,[errState].concat(data))}var steps=Array.prototype.slice.call(arguments),list=steps.shift()||[],cb_=steps.pop();if("function"!=typeof cb_)throw new Error("No callback provided to asyncMap");if(!list)return cb_(null,[]);Array.isArray(list)||(list=[list]);var n=steps.length,data=[],errState=null,l=list.length,a=l*n;return a?void list.forEach(function(ar){steps.forEach(function(fn){fn(ar,cb)})}):cb_(null,[])}module.exports=asyncMap}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){function chain(things,cb){var res=[];!function LOOP(i,len){return i>=len?cb(null,res):(Array.isArray(things[i])&&(things[i]=bindActor.apply(null,things[i].map(function(i){return i===chain.first?res[0]:i===chain.last?res[res.length-1]:i}))),things[i]?void things[i](function(er,data){return er?cb(er,res):(void 0!==data&&(res=res.concat(data)),void LOOP(i+1,len))}):LOOP(i+1,len))}(0,things.length)}module.exports=chain;var bindActor=__webpack_require__(48);chain.first={},chain.last={}},function(module,exports,__webpack_require__){exports.asyncMap=__webpack_require__(151),exports.bindActor=__webpack_require__(48),exports.chain=__webpack_require__(152)},function(module,exports,__webpack_require__){(function(global){function deprecate(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(exports,__webpack_require__(4))},function(module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},function(module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},function(module,exports,__webpack_require__){"use strict";(function(__filename,process){function murmurhex(){for(var hash=new MurmurHash3,ii=0;ii1&&void 0!==arguments[1]?arguments[1]:{};_classCallCheck(this,Orbit),this.events=new EventEmitter,this._ipfs=ipfs,this._orbitdb=null,this._user=null,this._channels={},this._peers=[],this._pollPeersTimer=null,this._options=Object.assign({},defaultOptions),this._cache=new LRU(1e3),Object.assign(this._options,options),Crypto.useKeyStore(this._options.keystorePath)}return _createClass(Orbit,[{key:"connect",value:function(){var _this=this,credentials=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return logger.debug("Load cache from:",this._options.cachePath),logger.info("Connecting to Orbit as '"+JSON.stringify(credentials)),"string"==typeof credentials&&(credentials={provider:"orbit",username:credentials}),this._ipfs.object.put(new Buffer(JSON.stringify({app:"orbit.chat"}))).then(function(res){return _this._ipfs.object.get(res.toJSON().multihash,{enc:"base58"})}).catch(function(err){return logger.error(err)}),IdentityProviders.authorizeUser(this._ipfs,credentials).then(function(user){return _this._user=user}).then(function(){return new OrbitDB(_this._ipfs,_this._user.id)}).then(function(orbitdb){_this._orbitdb=orbitdb,_this._orbitdb.events.on("data",_this._handleMessage.bind(_this)),_this._startPollingForPeers()}).then(function(){return logger.info("Connected to '"+_this._orbitdb.network.name+"' as '"+_this.user.name),_this.events.emit("connected",_this.network,_this.user),_this}).catch(function(e){return console.error(e)})}},{key:"disconnect",value:function(){this._orbitdb&&(logger.warn("Disconnected from '"+this.network.name+"'"),this._orbitdb.disconnect(),this._orbitdb=null,this._user=null,this._channels={},this._pollPeersTimer&&clearInterval(this._pollPeersTimer),this.events.emit("disconnected"))}},{key:"join",value:function(channel){if(logger.debug("Join #"+channel),!channel||""===channel)return Promise.reject("Channel not specified");if(this._channels[channel])return Promise.resolve(!1);var dbOptions={cachePath:this._options.cachePath,maxHistory:this._options.maxHistory};return this._channels[channel]={name:channel,password:null,feed:this._orbitdb.eventlog(channel,dbOptions)},this.events.emit("joined",channel),Promise.resolve(!0)}},{key:"leave",value:function(channel){this._channels[channel]&&(this._channels[channel].feed.close(),delete this._channels[channel],logger.debug("Left channel #"+channel)),this.events.emit("left",channel)}},{key:"send",value:function(channel,message,replyToHash){var _this2=this;if(!message||""===message)return Promise.reject("Can't send an empty message");logger.debug("Send message to #"+channel+": "+message);var data={content:message,replyto:replyToHash||null,from:this.user.id};return this._getChannelFeed(channel).then(function(feed){return _this2._postMessage(feed,Post.Types.Message,data,_this2._user._keys)})}},{key:"get",value:function(channel){var lessThanHash=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,greaterThanHash=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,amount=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;logger.debug("Get messages from #"+channel+": "+lessThanHash+", "+greaterThanHash+", "+amount);var options={limit:amount,lt:lessThanHash,gte:greaterThanHash};return this._getChannelFeed(channel).then(function(feed){return feed.iterator(options).collect()})}},{key:"getPost",value:function(hash,withUserProfile){var _this3=this,post=this._cache.get(hash);if(post)return Promise.resolve(post);var _ret=function(){var post=void 0;return{v:_this3._ipfs.object.get(hash,{enc:"base58"}).then(function(res){return post=JSON.parse(res.toJSON().data)}).then(function(){return Crypto.importKeyFromIpfs(_this3._ipfs,post.signKey)}).then(function(signKey){return Crypto.verify(post.sig,signKey,new Buffer(JSON.stringify({content:post.content,meta:post.meta,replyto:post.replyto})))}).then(function(){return _this3._cache.set(hash,post),withUserProfile?_this3.getUser(post.meta.from).then(function(user){return post.meta.from=user,post}):post})}}();return"object"===("undefined"==typeof _ret?"undefined":_typeof(_ret))?_ret.v:void 0}},{key:"addFile",value:function(channel,source){var _this4=this;if(!source||!source.filename&&!source.directory)return Promise.reject("Filename or directory not specified");var addToIpfsJs=function(ipfs,data){return ipfs.files.add(new Buffer(data)).then(function(result){return{Hash:result[0].toJSON().multihash,isDirectory:!1}})},addToIpfsGo=function(ipfs,filename,filePath){return ipfs.util.addFromFs(filePath,{recursive:!0}).then(function(result){var isDirectory=result[0].path.split("/").pop()!==filename;return{Hash:isDirectory?result[result.length-1].hash:result[0].hash,isDirectory:isDirectory}})};logger.info("Adding file from path '"+source.filename+"'");var isBuffer=!(!source.buffer||!source.filename),name=source.directory?source.directory.split("/").pop():source.filename.split("/").pop(),size=source.meta&&source.meta.size?source.meta.size:0,feed=void 0,addToIpfs=void 0;return addToIpfs=isBuffer?function(){return addToIpfsJs(_this4._ipfs,source.buffer)}:source.directory?function(){return addToIpfsGo(_this4._ipfs,name,source.directory)}:function(){return addToIpfsGo(_this4._ipfs,name,source.filename)},this._getChannelFeed(channel).then(function(res){return feed=res}).then(function(){return addToIpfs()}).then(function(result){logger.info("Added file '"+source.filename+"' as ",result);var type=result.isDirectory?Post.Types.Directory:Post.Types.File,data={name:name,hash:result.Hash,size:size,from:_this4.user.id,meta:source.meta||{}};return _this4._postMessage(feed,type,data,_this4._user._keys)})}},{key:"getFile",value:function(hash){return this._ipfs.cat(hash)}},{key:"getDirectory",value:function(hash){return this._ipfs.ls(hash).then(function(res){return res.Objects[0].Links})}},{key:"getUser",value:function(hash){var _this5=this,user=this._cache.get(hash);return user?Promise.resolve(user):this._ipfs.object.get(hash,{enc:"base58"}).then(function(res){var profileData=Object.assign(JSON.parse(res.toJSON().data));return Object.assign(profileData,{id:hash}),IdentityProviders.loadProfile(_this5._ipfs,profileData).then(function(profile){return Object.assign(profile||profileData,{id:hash}),_this5._cache.set(hash,profile),profile}).catch(function(e){return logger.error(e),profileData})})}},{key:"_postMessage",value:function(feed,postType,data,signKey){var post=void 0;return Post.create(this._ipfs,postType,data,signKey).then(function(res){return post=res}).then(function(){return feed.add(post.Hash)}).then(function(){return post})}},{key:"_getChannelFeed",value:function(channel){var _this6=this;return channel&&""!==channel?new Promise(function(resolve,reject){var feed=_this6._channels[channel]&&_this6._channels[channel].feed?_this6._channels[channel].feed:null;feed||reject("Haven't joined #"+channel),resolve(feed)}):Promise.reject("Channel not specified")}},{key:"_handleMessage",value:function(channel,message){logger.debug("New message in #",channel,"\n"+JSON.stringify(message,null,2)),this._channels[channel]&&this.events.emit("message",channel,message)}},{key:"_startPollingForPeers",value:function(){var _this7=this;this._pollPeersTimer||(this._pollPeersTimer=setInterval(function(){_this7._updateSwarmPeers().then(function(peers){_this7._peers=peers||[],_this7.events.emit("peers",_this7._peers)})},3e3))}},{key:"_updateSwarmPeers",value:function(){var _this8=this;return this._ipfs.libp2p&&this._ipfs.libp2p.swarm.peers?new Promise(function(resolve,reject){_this8._ipfs.libp2p.swarm.peers(function(err,peers){err&&reject(err),resolve(peers)})}).then(function(peers){return Object.keys(peers).map(function(e){return peers[e].multiaddrs[0].toString()})}).catch(function(e){return logger.error(e)}):Promise.resolve([])}},{key:"user",get:function(){return this._user?this._user.profile:null}},{key:"network",get:function(){return this._orbitdb?this._orbitdb.network:null}},{key:"channels",get:function(){return this._channels}},{key:"peers",get:function(){return this._peers}}]),Orbit}();module.exports=Orbit}).call(exports,__webpack_require__(1),__webpack_require__(0).Buffer)}]);