nfewizard-io 0.5.46 → 0.5.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
7
7
|
* MIT Licensed
|
|
8
8
|
*/(),extname=path__default.default.extname,EXTRACT_TYPE_REGEXP=/^\s*([^;\s]*)(?:;|\s|$)/,TEXT_TYPE_REGEXP=/^text\//i;function charset(type){if(!type||"string"!=typeof type)return!1;var match=EXTRACT_TYPE_REGEXP.exec(type),mime=match&&db[match[1].toLowerCase()];return mime&&mime.charset?mime.charset:!(!match||!TEXT_TYPE_REGEXP.test(match[1]))&&"UTF-8"}exports.charset=charset,exports.charsets={lookup:charset},exports.contentType=function contentType(str){if(!str||"string"!=typeof str)return!1;var mime=-1===str.indexOf("/")?exports.lookup(str):str;if(!mime)return!1;if(-1===mime.indexOf("charset")){var charset=exports.charset(mime);charset&&(mime+="; charset="+charset.toLowerCase())}return mime},exports.extension=function extension(type){if(!type||"string"!=typeof type)return!1;var match=EXTRACT_TYPE_REGEXP.exec(type),exts=match&&exports.extensions[match[1].toLowerCase()];if(!exts||!exts.length)return!1;return exts[0]},exports.extensions=Object.create(null),exports.lookup=function lookup(path){if(!path||"string"!=typeof path)return!1;var extension=extname("x."+path).toLowerCase().substr(1);if(!extension)return!1;return exports.types[extension]||!1},exports.types=Object.create(null),function populateMaps(extensions,types){var preference=["nginx","apache",void 0,"iana"];Object.keys(db).forEach(function forEachMimeType(type){var mime=db[type],exts=mime.extensions;if(exts&&exts.length){extensions[type]=exts;for(var i=0;i<exts.length;i++){var extension=exts[i];if(types[extension]){var from=preference.indexOf(db[types[extension]].source),to=preference.indexOf(mime.source);if("application/octet-stream"!==types[extension]&&(from>to||from===to&&"application/"===types[extension].substr(0,12)))continue}types[extension]=type}}})}(exports.extensions,exports.types)}(mimeTypes)),mimeTypes}function requireAsync(){if(hasRequiredAsync)return async_1;hasRequiredAsync=1;var defer=function requireDefer(){return hasRequiredDefer?defer_1:(hasRequiredDefer=1,defer_1=function defer(fn){var nextTick="function"==typeof setImmediate?setImmediate:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:null;nextTick?nextTick(fn):setTimeout(fn,0)})}();return async_1=function async(callback){var isAsync=!1;return defer(function(){isAsync=!0}),function async_callback(err,result){isAsync?callback(err,result):defer(function nextTick_callback(){callback(err,result)})}},async_1}function requireAbort(){if(hasRequiredAbort)return abort_1;function clean(key){"function"==typeof this.jobs[key]&&this.jobs[key]()}return hasRequiredAbort=1,abort_1=function abort(state){Object.keys(state.jobs).forEach(clean.bind(state)),state.jobs={}},abort_1}function requireIterate(){if(hasRequiredIterate)return iterate_1;hasRequiredIterate=1;var async=requireAsync(),abort=requireAbort();return iterate_1=function iterate(list,iterator,state,callback){var key=state.keyedList?state.keyedList[state.index]:state.index;state.jobs[key]=function runJob(iterator,key,item,callback){var aborter;aborter=2==iterator.length?iterator(item,async(callback)):iterator(item,key,async(callback));return aborter}(iterator,key,list[key],function(error,output){key in state.jobs&&(delete state.jobs[key],error?abort(state):state.results[key]=output,callback(error,state.results))})},iterate_1}function requireState(){if(hasRequiredState)return state_1;return hasRequiredState=1,state_1=function state(list,sortMethod){var isNamedList=!Array.isArray(list),initState={index:0,keyedList:isNamedList||sortMethod?Object.keys(list):null,jobs:{},results:isNamedList?{}:[],size:isNamedList?Object.keys(list).length:list.length};sortMethod&&initState.keyedList.sort(isNamedList?sortMethod:function(a,b){return sortMethod(list[a],list[b])});return initState}}function requireTerminator(){if(hasRequiredTerminator)return terminator_1;hasRequiredTerminator=1;var abort=requireAbort(),async=requireAsync();return terminator_1=function terminator(callback){if(!Object.keys(this.jobs).length)return;this.index=this.size,abort(this),async(callback)(null,this.results)}}function requireParallel(){if(hasRequiredParallel)return parallel_1;hasRequiredParallel=1;var iterate=requireIterate(),initState=requireState(),terminator=requireTerminator();return parallel_1=function parallel(list,iterator,callback){var state=initState(list);for(;state.index<(state.keyedList||list).length;)iterate(list,iterator,state,function(error,result){error?callback(error,result):0!==Object.keys(state.jobs).length||callback(null,state.results)}),state.index++;return terminator.bind(state,callback)},parallel_1}var hasRequiredSerialOrdered,serial_1,hasRequiredSerial,asynckit,hasRequiredAsynckit,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,type,hasRequiredType,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign$1,hasRequiredSign$1,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,shams$1,hasRequiredShams$1,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,shams,hasRequiredShams,esSetTostringtag,hasRequiredEsSetTostringtag,populate,hasRequiredPopulate,form_data,hasRequiredForm_data,serialOrdered={exports:{}};function requireSerialOrdered(){if(hasRequiredSerialOrdered)return serialOrdered.exports;hasRequiredSerialOrdered=1;var iterate=requireIterate(),initState=requireState(),terminator=requireTerminator();function ascending(a,b){return a<b?-1:a>b?1:0}return serialOrdered.exports=function serialOrdered$1(list,iterator,sortMethod,callback){var state=initState(list,sortMethod);return iterate(list,iterator,state,function iteratorHandler(error,result){error?callback(error,result):(state.index++,state.index<(state.keyedList||list).length?iterate(list,iterator,state,iteratorHandler):callback(null,state.results))}),terminator.bind(state,callback)},serialOrdered.exports.ascending=ascending,serialOrdered.exports.descending=function descending(a,b){return-1*ascending(a,b)},serialOrdered.exports}function requireSerial(){if(hasRequiredSerial)return serial_1;hasRequiredSerial=1;var serialOrdered=requireSerialOrdered();return serial_1=function serial(list,iterator,callback){return serialOrdered(list,iterator,null,callback)},serial_1}function requireAsynckit(){return hasRequiredAsynckit?asynckit:(hasRequiredAsynckit=1,asynckit={parallel:requireParallel(),serial:requireSerial(),serialOrdered:requireSerialOrdered()})}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function require_isNaN(){return hasRequired_isNaN?_isNaN:(hasRequired_isNaN=1,_isNaN=Number.isNaN||function isNaN(a){return a!=a})}function requireSign$1(){if(hasRequiredSign$1)return sign$1;hasRequiredSign$1=1;var $isNaN=require_isNaN();return sign$1=function sign(number){return $isNaN(number)||0===number?number:number<0?-1:1}}function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var $gOPD=requireGOPD();if($gOPD)try{$gOPD([],"length")}catch(e){$gOPD=null}return gopd=$gOPD}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var $defineProperty=Object.defineProperty||!1;if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=!1}return esDefineProperty=$defineProperty}function requireShams$1(){return hasRequiredShams$1?shams$1:(hasRequiredShams$1=1,shams$1=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var obj={},sym=Symbol("test"),symObj=Object(sym);if("string"==typeof sym)return!1;if("[object Symbol]"!==Object.prototype.toString.call(sym))return!1;if("[object Symbol]"!==Object.prototype.toString.call(symObj))return!1;for(var _ in obj[sym]=42,obj)return!1;if("function"==typeof Object.keys&&0!==Object.keys(obj).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(obj).length)return!1;var syms=Object.getOwnPropertySymbols(obj);if(1!==syms.length||syms[0]!==sym)return!1;if(!Object.prototype.propertyIsEnumerable.call(obj,sym))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(42!==descriptor.value||!0!==descriptor.enumerable)return!1}return!0})}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=requireShams$1();return hasSymbols=function hasNativeSymbols(){return"function"==typeof origSymbol&&("function"==typeof Symbol&&("symbol"==typeof origSymbol("foo")&&("symbol"==typeof Symbol("bar")&&hasSymbolSham())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var toStr=Object.prototype.toString,max=Math.max,concatty=function concatty(a,b){for(var arr=[],i=0;i<a.length;i+=1)arr[i]=a[i];for(var j=0;j<b.length;j+=1)arr[j+a.length]=b[j];return arr};return implementation=function bind(that){var target=this;if("function"!=typeof target||"[object Function]"!==toStr.apply(target))throw new TypeError("Function.prototype.bind called on incompatible "+target);for(var bound,args=function slicy(arrLike,offset){for(var arr=[],i=offset||0,j=0;i<arrLike.length;i+=1,j+=1)arr[j]=arrLike[i];return arr}(arguments,1),boundLength=max(0,target.length-args.length),boundArgs=[],i=0;i<boundLength;i++)boundArgs[i]="$"+i;if(bound=Function("binder","return function ("+function(arr,joiner){for(var str="",i=0;i<arr.length;i+=1)str+=arr[i],i+1<arr.length&&(str+=joiner);return str}(boundArgs,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof bound){var result=target.apply(this,concatty(args,arguments));return Object(result)===result?result:this}return target.apply(that,concatty(args,arguments))}),target.prototype){var Empty=function Empty(){};Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null}return bound},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var implementation=requireImplementation();return functionBind=Function.prototype.bind||implementation}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var bind=requireFunctionBind(),$apply=requireFunctionApply(),$call=requireFunctionCall(),$reflectApply=function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}();return actualApply=$reflectApply||bind.call($call,$apply)}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var hasProtoAccessor,callBind=function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var bind=requireFunctionBind(),$TypeError=requireType(),$call=requireFunctionCall(),$actualApply=requireActualApply();return callBindApplyHelpers=function callBindBasic(args){if(args.length<1||"function"!=typeof args[0])throw new $TypeError("a function is required");return $actualApply(bind,$call,args)}}(),gOPD=requireGopd();try{hasProtoAccessor=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var desc=!!hasProtoAccessor&&gOPD&&gOPD(Object.prototype,"__proto__"),$Object=Object,$getPrototypeOf=$Object.getPrototypeOf;return get=desc&&"function"==typeof desc.get?callBind([desc.get]):"function"==typeof $getPrototypeOf&&function getDunder(value){return $getPrototypeOf(null==value?value:$Object(value))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var reflectGetProto=requireReflect_getPrototypeOf(),originalGetProto=requireObject_getPrototypeOf(),getDunderProto=requireGet();return getProto=reflectGetProto?function getProto(O){return reflectGetProto(O)}:originalGetProto?function getProto(O){if(!O||"object"!=typeof O&&"function"!=typeof O)throw new TypeError("getProto: not an object");return originalGetProto(O)}:getDunderProto?function getProto(O){return getDunderProto(O)}:null}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var call=Function.prototype.call,$hasOwn=Object.prototype.hasOwnProperty,bind=requireFunctionBind();return hasown=bind.call(call,$hasOwn)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;hasRequiredGetIntrinsic=1;var $Object=requireEsObjectAtoms(),$Error=requireEsErrors(),$EvalError=require_eval(),$RangeError=requireRange(),$ReferenceError=requireRef(),$SyntaxError=requireSyntax(),$TypeError=requireType(),$URIError=requireUri(),abs=requireAbs(),floor=requireFloor(),max=requireMax(),min=requireMin(),pow=requirePow(),round=requireRound(),sign=requireSign$1(),$Function=Function,getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+").constructor;")()}catch(e){}},$gOPD=requireGopd(),$defineProperty=requireEsDefineProperty(),throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError,hasSymbols=requireHasSymbols()(),getProto=requireGetProto(),$ObjectGPO=requireObject_getPrototypeOf(),$ReflectGPO=requireReflect_getPrototypeOf(),$apply=requireFunctionApply(),$call=requireFunctionCall(),needsEval={},TypedArray="undefined"!=typeof Uint8Array&&getProto?getProto(Uint8Array):undefined,INTRINSICS={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols&&getProto?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?undefined:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?undefined:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":$Error,"%eval%":eval,"%EvalError%":$EvalError,"%Float16Array%":"undefined"==typeof Float16Array?undefined:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols&&getProto?getProto((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":$Object,"%Object.getOwnPropertyDescriptor%":$gOPD,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":$RangeError,"%ReferenceError%":$ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols&&getProto?getProto((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols&&getProto?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":$URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet,"%Function.prototype.call%":$call,"%Function.prototype.apply%":$apply,"%Object.defineProperty%":$defineProperty,"%Object.getPrototypeOf%":$ObjectGPO,"%Math.abs%":abs,"%Math.floor%":floor,"%Math.max%":max,"%Math.min%":min,"%Math.pow%":pow,"%Math.round%":round,"%Math.sign%":sign,"%Reflect.getPrototypeOf%":$ReflectGPO};if(getProto)try{null.error}catch(e){var errorProto=getProto(getProto(e));INTRINSICS["%Error.prototype%"]=errorProto}var doEval=function doEval(name){var value;if("%AsyncFunction%"===name)value=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===name)value=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===name)value=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===name){var fn=doEval("%AsyncGeneratorFunction%");fn&&(value=fn.prototype)}else if("%AsyncIteratorPrototype%"===name){var gen=doEval("%AsyncGenerator%");gen&&getProto&&(value=getProto(gen.prototype))}return INTRINSICS[name]=value,value},LEGACY_ALIASES={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=requireFunctionBind(),hasOwn=requireHasown(),$concat=bind.call($call,Array.prototype.concat),$spliceApply=bind.call($apply,Array.prototype.splice),$replace=bind.call($call,String.prototype.replace),$strSlice=bind.call($call,String.prototype.slice),$exec=bind.call($call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var alias,intrinsicName=name;if(hasOwn(LEGACY_ALIASES,intrinsicName)&&(intrinsicName="%"+(alias=LEGACY_ALIASES[intrinsicName])[0]+"%"),hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval&&(value=doEval(intrinsicName)),void 0===value&&!allowMissing)throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!");return{alias:alias,name:intrinsicName,value:value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};return getIntrinsic=function GetIntrinsic(name,allowMissing){if("string"!=typeof name||0===name.length)throw new $TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof allowMissing)throw new $TypeError('"allowMissing" argument must be a boolean');if(null===$exec(/^%?[^%]*%?$/,name))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var parts=function stringToPath(string){var first=$strSlice(string,0,1),last=$strSlice(string,-1);if("%"===first&&"%"!==last)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===last&&"%"!==first)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var result=[];return $replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match}),result}(name),intrinsicBaseName=parts.length>0?parts[0]:"",intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing),intrinsicRealName=intrinsic.name,value=intrinsic.value,skipFurtherCaching=!1,alias=intrinsic.alias;alias&&(intrinsicBaseName=alias[0],$spliceApply(parts,$concat([0,1],alias)));for(var i=1,isOwn=!0;i<parts.length;i+=1){var part=parts[i],first=$strSlice(part,0,1),last=$strSlice(part,-1);if(('"'===first||"'"===first||"`"===first||'"'===last||"'"===last||"`"===last)&&first!==last)throw new $SyntaxError("property names with quotes must have matching quotes");if("constructor"!==part&&isOwn||(skipFurtherCaching=!0),hasOwn(INTRINSICS,intrinsicRealName="%"+(intrinsicBaseName+="."+part)+"%"))value=INTRINSICS[intrinsicRealName];else if(null!=value){if(!(part in value)){if(!allowMissing)throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.");return}if($gOPD&&i+1>=parts.length){var desc=$gOPD(value,part);value=(isOwn=!!desc)&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[part]}else isOwn=hasOwn(value,part),value=value[part];isOwn&&!skipFurtherCaching&&(INTRINSICS[intrinsicRealName]=value)}}return value},getIntrinsic}function requireEsSetTostringtag(){if(hasRequiredEsSetTostringtag)return esSetTostringtag;hasRequiredEsSetTostringtag=1;var $defineProperty=requireGetIntrinsic()("%Object.defineProperty%",!0),hasToStringTag=function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var hasSymbols=requireShams$1();return shams=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}}()(),hasOwn=requireHasown(),$TypeError=requireType(),toStringTag=hasToStringTag?Symbol.toStringTag:null;return esSetTostringtag=function setToStringTag(object,value){var overrideIfSet=arguments.length>2&&!!arguments[2]&&arguments[2].force,nonConfigurable=arguments.length>2&&!!arguments[2]&&arguments[2].nonConfigurable;if(void 0!==overrideIfSet&&"boolean"!=typeof overrideIfSet||void 0!==nonConfigurable&&"boolean"!=typeof nonConfigurable)throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");!toStringTag||!overrideIfSet&&hasOwn(object,toStringTag)||($defineProperty?$defineProperty(object,toStringTag,{configurable:!nonConfigurable,enumerable:!1,value:value,writable:!1}):object[toStringTag]=value)},esSetTostringtag}function requirePopulate(){return hasRequiredPopulate||(hasRequiredPopulate=1,populate=function(dst,src){return Object.keys(src).forEach(function(prop){dst[prop]=dst[prop]||src[prop]}),dst}),populate}var form_dataExports=function requireForm_data(){if(hasRequiredForm_data)return form_data;hasRequiredForm_data=1;var CombinedStream=requireCombined_stream(),util=require$$0__default$2.default,path=path__default.default,http=require$$0__default$5.default,https=https__default.default,parseUrl=require$$0__default$6.default.parse,fs=fs__default.default,Stream=require$$0__default$4.default.Stream,crypto=require$$0__default$1.default,mime=requireMimeTypes$1(),asynckit=requireAsynckit(),setToStringTag=requireEsSetTostringtag(),hasOwn=requireHasown(),populate=requirePopulate();function FormData(options){if(!(this instanceof FormData))return new FormData(options);for(var option in this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],CombinedStream.call(this),options=options||{})this[option]=options[option]}return util.inherits(FormData,CombinedStream),FormData.LINE_BREAK="\r\n",FormData.DEFAULT_CONTENT_TYPE="application/octet-stream",FormData.prototype.append=function(field,value,options){"string"==typeof(options=options||{})&&(options={filename:options});var append=CombinedStream.prototype.append.bind(this);if("number"!=typeof value&&null!=value||(value=String(value)),Array.isArray(value))this._error(new Error("Arrays are not supported."));else{var header=this._multiPartHeader(field,value,options),footer=this._multiPartFooter();append(header),append(value),append(footer),this._trackLength(header,value,options)}},FormData.prototype._trackLength=function(header,value,options){var valueLength=0;null!=options.knownLength?valueLength+=Number(options.knownLength):Buffer.isBuffer(value)?valueLength=value.length:"string"==typeof value&&(valueLength=Buffer.byteLength(value)),this._valueLength+=valueLength,this._overheadLength+=Buffer.byteLength(header)+FormData.LINE_BREAK.length,value&&(value.path||value.readable&&hasOwn(value,"httpVersion")||value instanceof Stream)&&(options.knownLength||this._valuesToMeasure.push(value))},FormData.prototype._lengthRetriever=function(value,callback){hasOwn(value,"fd")?null!=value.end&&value.end!=1/0&&null!=value.start?callback(null,value.end+1-(value.start?value.start:0)):fs.stat(value.path,function(err,stat){if(err)callback(err);else{var fileSize=stat.size-(value.start?value.start:0);callback(null,fileSize)}}):hasOwn(value,"httpVersion")?callback(null,Number(value.headers["content-length"])):hasOwn(value,"httpModule")?(value.on("response",function(response){value.pause(),callback(null,Number(response.headers["content-length"]))}),value.resume()):callback("Unknown stream")},FormData.prototype._multiPartHeader=function(field,value,options){if("string"==typeof options.header)return options.header;var header,contentDisposition=this._getContentDisposition(value,options),contentType=this._getContentType(value,options),contents="",headers={"Content-Disposition":["form-data",'name="'+field+'"'].concat(contentDisposition||[]),"Content-Type":[].concat(contentType||[])};for(var prop in"object"==typeof options.header&&populate(headers,options.header),headers)if(hasOwn(headers,prop)){if(null==(header=headers[prop]))continue;Array.isArray(header)||(header=[header]),header.length&&(contents+=prop+": "+header.join("; ")+FormData.LINE_BREAK)}return"--"+this.getBoundary()+FormData.LINE_BREAK+contents+FormData.LINE_BREAK},FormData.prototype._getContentDisposition=function(value,options){var filename;if("string"==typeof options.filepath?filename=path.normalize(options.filepath).replace(/\\/g,"/"):options.filename||value&&(value.name||value.path)?filename=path.basename(options.filename||value&&(value.name||value.path)):value&&value.readable&&hasOwn(value,"httpVersion")&&(filename=path.basename(value.client._httpMessage.path||"")),filename)return'filename="'+filename+'"'},FormData.prototype._getContentType=function(value,options){var contentType=options.contentType;return!contentType&&value&&value.name&&(contentType=mime.lookup(value.name)),!contentType&&value&&value.path&&(contentType=mime.lookup(value.path)),!contentType&&value&&value.readable&&hasOwn(value,"httpVersion")&&(contentType=value.headers["content-type"]),contentType||!options.filepath&&!options.filename||(contentType=mime.lookup(options.filepath||options.filename)),!contentType&&value&&"object"==typeof value&&(contentType=FormData.DEFAULT_CONTENT_TYPE),contentType},FormData.prototype._multiPartFooter=function(){return function(next){var footer=FormData.LINE_BREAK;0===this._streams.length&&(footer+=this._lastBoundary()),next(footer)}.bind(this)},FormData.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+FormData.LINE_BREAK},FormData.prototype.getHeaders=function(userHeaders){var header,formHeaders={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(header in userHeaders)hasOwn(userHeaders,header)&&(formHeaders[header.toLowerCase()]=userHeaders[header]);return formHeaders},FormData.prototype.setBoundary=function(boundary){if("string"!=typeof boundary)throw new TypeError("FormData boundary must be a string");this._boundary=boundary},FormData.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary},FormData.prototype.getBuffer=function(){for(var dataBuffer=new Buffer.alloc(0),boundary=this.getBoundary(),i=0,len=this._streams.length;i<len;i++)"function"!=typeof this._streams[i]&&(dataBuffer=Buffer.isBuffer(this._streams[i])?Buffer.concat([dataBuffer,this._streams[i]]):Buffer.concat([dataBuffer,Buffer.from(this._streams[i])]),"string"==typeof this._streams[i]&&this._streams[i].substring(2,boundary.length+2)===boundary||(dataBuffer=Buffer.concat([dataBuffer,Buffer.from(FormData.LINE_BREAK)])));return Buffer.concat([dataBuffer,Buffer.from(this._lastBoundary())])},FormData.prototype._generateBoundary=function(){this._boundary="--------------------------"+crypto.randomBytes(12).toString("hex")},FormData.prototype.getLengthSync=function(){var knownLength=this._overheadLength+this._valueLength;return this._streams.length&&(knownLength+=this._lastBoundary().length),this.hasKnownLength()||this._error(new Error("Cannot calculate proper length in synchronous way.")),knownLength},FormData.prototype.hasKnownLength=function(){var hasKnownLength=!0;return this._valuesToMeasure.length&&(hasKnownLength=!1),hasKnownLength},FormData.prototype.getLength=function(cb){var knownLength=this._overheadLength+this._valueLength;this._streams.length&&(knownLength+=this._lastBoundary().length),this._valuesToMeasure.length?asynckit.parallel(this._valuesToMeasure,this._lengthRetriever,function(err,values){err?cb(err):(values.forEach(function(length){knownLength+=length}),cb(null,knownLength))}):process.nextTick(cb.bind(this,null,knownLength))},FormData.prototype.submit=function(params,cb){var request,options,defaults={method:"post"};return"string"==typeof params?(params=parseUrl(params),options=populate({port:params.port,path:params.pathname,host:params.hostname,protocol:params.protocol},defaults)):(options=populate(params,defaults)).port||(options.port="https:"===options.protocol?443:80),options.headers=this.getHeaders(params.headers),request="https:"===options.protocol?https.request(options):http.request(options),this.getLength(function(err,length){if(err&&"Unknown stream"!==err)this._error(err);else if(length&&request.setHeader("Content-Length",length),this.pipe(request),cb){var onResponse,callback=function(error,responce){return request.removeListener("error",callback),request.removeListener("response",onResponse),cb.call(this,error,responce)};onResponse=callback.bind(this,null),request.on("error",callback),request.on("response",onResponse)}}.bind(this)),request},FormData.prototype._error=function(err){this.error||(this.error=err,this.pause(),this.emit("error",err))},FormData.prototype.toString=function(){return"[object FormData]"},setToStringTag(FormData,"FormData"),form_data=FormData}(),FormData$1=getDefaultExportFromCjs(form_dataExports);function isVisitable(thing){return utils$3.isPlainObject(thing)||utils$3.isArray(thing)}function removeBrackets(key){return utils$3.endsWith(key,"[]")?key.slice(0,-2):key}function renderKey(path,key,dots){return path?path.concat(key).map(function each(token,i){return token=removeBrackets(token),!dots&&i?"["+token+"]":token}).join(dots?".":""):key}const predicates=utils$3.toFlatObject(utils$3,{},null,function filter(prop){return/^is[A-Z]/.test(prop)});function toFormData(obj,formData,options){if(!utils$3.isObject(obj))throw new TypeError("target must be an object");formData=formData||new(FormData$1||FormData);const metaTokens=(options=utils$3.toFlatObject(options,{metaTokens:!0,dots:!1,indexes:!1},!1,function defined(option,source){return!utils$3.isUndefined(source[option])})).metaTokens,visitor=options.visitor||defaultVisitor,dots=options.dots,indexes=options.indexes,useBlob=(options.Blob||"undefined"!=typeof Blob&&Blob)&&utils$3.isSpecCompliantForm(formData);if(!utils$3.isFunction(visitor))throw new TypeError("visitor must be a function");function convertValue(value){if(null===value)return"";if(utils$3.isDate(value))return value.toISOString();if(utils$3.isBoolean(value))return value.toString();if(!useBlob&&utils$3.isBlob(value))throw new AxiosError("Blob is not supported. Use a Buffer instead.");return utils$3.isArrayBuffer(value)||utils$3.isTypedArray(value)?useBlob&&"function"==typeof Blob?new Blob([value]):Buffer.from(value):value}function defaultVisitor(value,key,path){let arr=value;if(value&&!path&&"object"==typeof value)if(utils$3.endsWith(key,"{}"))key=metaTokens?key:key.slice(0,-2),value=JSON.stringify(value);else if(utils$3.isArray(value)&&function isFlatArray(arr){return utils$3.isArray(arr)&&!arr.some(isVisitable)}(value)||(utils$3.isFileList(value)||utils$3.endsWith(key,"[]"))&&(arr=utils$3.toArray(value)))return key=removeBrackets(key),arr.forEach(function each(el,index){!utils$3.isUndefined(el)&&null!==el&&formData.append(!0===indexes?renderKey([key],index,dots):null===indexes?key:key+"[]",convertValue(el))}),!1;return!!isVisitable(value)||(formData.append(renderKey(path,key,dots),convertValue(value)),!1)}const stack=[],exposedHelpers=Object.assign(predicates,{defaultVisitor:defaultVisitor,convertValue:convertValue,isVisitable:isVisitable});if(!utils$3.isObject(obj))throw new TypeError("data must be an object");return function build(value,path){if(!utils$3.isUndefined(value)){if(-1!==stack.indexOf(value))throw Error("Circular reference detected in "+path.join("."));stack.push(value),utils$3.forEach(value,function each(el,key){!0===(!(utils$3.isUndefined(el)||null===el)&&visitor.call(formData,el,utils$3.isString(key)?key.trim():key,path,exposedHelpers))&&build(el,path?path.concat(key):[key])}),stack.pop()}}(obj),formData}function encode$1(str){const charMap={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g,function replacer(match){return charMap[match]})}function AxiosURLSearchParams(params,options){this._pairs=[],params&&toFormData(params,this,options)}const prototype=AxiosURLSearchParams.prototype;function encode(val){return encodeURIComponent(val).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function buildURL(url,params,options){if(!params)return url;const _encode=options&&options.encode||encode;utils$3.isFunction(options)&&(options={serialize:options});const serializeFn=options&&options.serialize;let serializedParams;if(serializedParams=serializeFn?serializeFn(params,options):utils$3.isURLSearchParams(params)?params.toString():new AxiosURLSearchParams(params,options).toString(_encode),serializedParams){const hashmarkIndex=url.indexOf("#");-1!==hashmarkIndex&&(url=url.slice(0,hashmarkIndex)),url+=(-1===url.indexOf("?")?"?":"&")+serializedParams}return url}prototype.append=function append(name,value){this._pairs.push([name,value])},prototype.toString=function toString(encoder){const _encode=encoder?function(value){return encoder.call(this,value,encode$1)}:encode$1;return this._pairs.map(function each(pair){return _encode(pair[0])+"="+_encode(pair[1])},"").join("&")};var InterceptorManager$1=class InterceptorManager{constructor(){this.handlers=[]}use(fulfilled,rejected,options){return this.handlers.push({fulfilled:fulfilled,rejected:rejected,synchronous:!!options&&options.synchronous,runWhen:options?options.runWhen:null}),this.handlers.length-1}eject(id){this.handlers[id]&&(this.handlers[id]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(fn){utils$3.forEach(this.handlers,function forEachHandler(h){null!==h&&fn(h)})}},transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams=require$$0__default$6.default.URLSearchParams;const ALPHA="abcdefghijklmnopqrstuvwxyz",ALPHABET={DIGIT:"0123456789",ALPHA:ALPHA,ALPHA_DIGIT:ALPHA+ALPHA.toUpperCase()+"0123456789"};var platform$1={isNode:!0,classes:{URLSearchParams:URLSearchParams,FormData:FormData$1,Blob:"undefined"!=typeof Blob&&Blob||null},ALPHABET:ALPHABET,generateString:(size=16,alphabet=ALPHABET.ALPHA_DIGIT)=>{let str="";const{length:length}=alphabet,randomValues=new Uint32Array(size);require$$0__default$1.default.randomFillSync(randomValues);for(let i=0;i<size;i++)str+=alphabet[randomValues[i]%length];return str},protocols:["http","https","file","data"]};const hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost";var platform={...Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,navigator:_navigator,origin:origin}),...platform$1};function formDataToJSON(formData){function buildPath(path,value,target,index){let name=path[index++];if("__proto__"===name)return!0;const isNumericKey=Number.isFinite(+name),isLast=index>=path.length;if(name=!name&&utils$3.isArray(target)?target.length:name,isLast)return utils$3.hasOwnProp(target,name)?target[name]=[target[name],value]:target[name]=value,!isNumericKey;target[name]&&utils$3.isObject(target[name])||(target[name]=[]);return buildPath(path,value,target[name],index)&&utils$3.isArray(target[name])&&(target[name]=function arrayToObject(arr){const obj={},keys=Object.keys(arr);let i;const len=keys.length;let key;for(i=0;i<len;i++)key=keys[i],obj[key]=arr[key];return obj}(target[name])),!isNumericKey}if(utils$3.isFormData(formData)&&utils$3.isFunction(formData.entries)){const obj={};return utils$3.forEachEntry(formData,(name,value)=>{buildPath(function parsePropPath(name){return utils$3.matchAll(/\w+|\[(\w*)]/g,name).map(match=>"[]"===match[0]?"":match[1]||match[0])}(name),value,obj,0)}),obj}return null}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function transformRequest(data,headers){const contentType=headers.getContentType()||"",hasJSONContentType=contentType.indexOf("application/json")>-1,isObjectPayload=utils$3.isObject(data);isObjectPayload&&utils$3.isHTMLForm(data)&&(data=new FormData(data));if(utils$3.isFormData(data))return hasJSONContentType?JSON.stringify(formDataToJSON(data)):data;if(utils$3.isArrayBuffer(data)||utils$3.isBuffer(data)||utils$3.isStream(data)||utils$3.isFile(data)||utils$3.isBlob(data)||utils$3.isReadableStream(data))return data;if(utils$3.isArrayBufferView(data))return data.buffer;if(utils$3.isURLSearchParams(data))return headers.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),data.toString();let isFileList;if(isObjectPayload){if(contentType.indexOf("application/x-www-form-urlencoded")>-1)return function toURLEncodedForm(data,options){return toFormData(data,new platform.classes.URLSearchParams,{visitor:function(value,key,path,helpers){return platform.isNode&&utils$3.isBuffer(value)?(this.append(key,value.toString("base64")),!1):helpers.defaultVisitor.apply(this,arguments)},...options})}(data,this.formSerializer).toString();if((isFileList=utils$3.isFileList(data))||contentType.indexOf("multipart/form-data")>-1){const _FormData=this.env&&this.env.FormData;return toFormData(isFileList?{"files[]":data}:data,_FormData&&new _FormData,this.formSerializer)}}return isObjectPayload||hasJSONContentType?(headers.setContentType("application/json",!1),function stringifySafely(rawValue,parser,encoder){if(utils$3.isString(rawValue))try{return(parser||JSON.parse)(rawValue),utils$3.trim(rawValue)}catch(e){if("SyntaxError"!==e.name)throw e}return(encoder||JSON.stringify)(rawValue)}(data)):data}],transformResponse:[function transformResponse(data){const transitional=this.transitional||defaults.transitional,forcedJSONParsing=transitional&&transitional.forcedJSONParsing,JSONRequested="json"===this.responseType;if(utils$3.isResponse(data)||utils$3.isReadableStream(data))return data;if(data&&utils$3.isString(data)&&(forcedJSONParsing&&!this.responseType||JSONRequested)){const strictJSONParsing=!(transitional&&transitional.silentJSONParsing)&&JSONRequested;try{return JSON.parse(data)}catch(e){if(strictJSONParsing){if("SyntaxError"===e.name)throw AxiosError.from(e,AxiosError.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function validateStatus(status){return status>=200&&status<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$3.forEach(["delete","get","head","post","put","patch"],method=>{defaults.headers[method]={}});var defaults$1=defaults;const ignoreDuplicateOf=utils$3.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const $internals=Symbol("internals");function normalizeHeader(header){return header&&String(header).trim().toLowerCase()}function normalizeValue(value){return!1===value||null==value?value:utils$3.isArray(value)?value.map(normalizeValue):String(value)}function matchHeaderValue(context,value,header,filter,isHeaderNameFilter){return utils$3.isFunction(filter)?filter.call(this,value,header):(isHeaderNameFilter&&(value=header),utils$3.isString(value)?utils$3.isString(filter)?-1!==value.indexOf(filter):utils$3.isRegExp(filter)?filter.test(value):void 0:void 0)}class AxiosHeaders{constructor(headers){headers&&this.set(headers)}set(header,valueOrRewrite,rewrite){const self=this;function setHeader(_value,_header,_rewrite){const lHeader=normalizeHeader(_header);if(!lHeader)throw new Error("header name must be a non-empty string");const key=utils$3.findKey(self,lHeader);(!key||void 0===self[key]||!0===_rewrite||void 0===_rewrite&&!1!==self[key])&&(self[key||_header]=normalizeValue(_value))}const setHeaders=(headers,_rewrite)=>utils$3.forEach(headers,(_value,_header)=>setHeader(_value,_header,_rewrite));if(utils$3.isPlainObject(header)||header instanceof this.constructor)setHeaders(header,valueOrRewrite);else if(utils$3.isString(header)&&(header=header.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(header.trim()))setHeaders((rawHeaders=>{const parsed={};let key,val,i;return rawHeaders&&rawHeaders.split("\n").forEach(function parser(line){i=line.indexOf(":"),key=line.substring(0,i).trim().toLowerCase(),val=line.substring(i+1).trim(),!key||parsed[key]&&ignoreDuplicateOf[key]||("set-cookie"===key?parsed[key]?parsed[key].push(val):parsed[key]=[val]:parsed[key]=parsed[key]?parsed[key]+", "+val:val)}),parsed})(header),valueOrRewrite);else if(utils$3.isObject(header)&&utils$3.isIterable(header)){let dest,key,obj={};for(const entry of header){if(!utils$3.isArray(entry))throw TypeError("Object iterator must return a key-value pair");obj[key=entry[0]]=(dest=obj[key])?utils$3.isArray(dest)?[...dest,entry[1]]:[dest,entry[1]]:entry[1]}setHeaders(obj,valueOrRewrite)}else null!=header&&setHeader(valueOrRewrite,header,rewrite);return this}get(header,parser){if(header=normalizeHeader(header)){const key=utils$3.findKey(this,header);if(key){const value=this[key];if(!parser)return value;if(!0===parser)return function parseTokens(str){const tokens=Object.create(null),tokensRE=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let match;for(;match=tokensRE.exec(str);)tokens[match[1]]=match[2];return tokens}(value);if(utils$3.isFunction(parser))return parser.call(this,value,key);if(utils$3.isRegExp(parser))return parser.exec(value);throw new TypeError("parser must be boolean|regexp|function")}}}has(header,matcher){if(header=normalizeHeader(header)){const key=utils$3.findKey(this,header);return!(!key||void 0===this[key]||matcher&&!matchHeaderValue(0,this[key],key,matcher))}return!1}delete(header,matcher){const self=this;let deleted=!1;function deleteHeader(_header){if(_header=normalizeHeader(_header)){const key=utils$3.findKey(self,_header);!key||matcher&&!matchHeaderValue(0,self[key],key,matcher)||(delete self[key],deleted=!0)}}return utils$3.isArray(header)?header.forEach(deleteHeader):deleteHeader(header),deleted}clear(matcher){const keys=Object.keys(this);let i=keys.length,deleted=!1;for(;i--;){const key=keys[i];matcher&&!matchHeaderValue(0,this[key],key,matcher,!0)||(delete this[key],deleted=!0)}return deleted}normalize(format){const self=this,headers={};return utils$3.forEach(this,(value,header)=>{const key=utils$3.findKey(headers,header);if(key)return self[key]=normalizeValue(value),void delete self[header];const normalized=format?function formatHeader(header){return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(w,char,str)=>char.toUpperCase()+str)}(header):String(header).trim();normalized!==header&&delete self[header],self[normalized]=normalizeValue(value),headers[normalized]=!0}),this}concat(...targets){return this.constructor.concat(this,...targets)}toJSON(asStrings){const obj=Object.create(null);return utils$3.forEach(this,(value,header)=>{null!=value&&!1!==value&&(obj[header]=asStrings&&utils$3.isArray(value)?value.join(", "):value)}),obj}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([header,value])=>header+": "+value).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(thing){return thing instanceof this?thing:new this(thing)}static concat(first,...targets){const computed=new this(first);return targets.forEach(target=>computed.set(target)),computed}static accessor(header){const accessors=(this[$internals]=this[$internals]={accessors:{}}).accessors,prototype=this.prototype;function defineAccessor(_header){const lHeader=normalizeHeader(_header);accessors[lHeader]||(!function buildAccessors(obj,header){const accessorName=utils$3.toCamelCase(" "+header);["get","set","has"].forEach(methodName=>{Object.defineProperty(obj,methodName+accessorName,{value:function(arg1,arg2,arg3){return this[methodName].call(this,header,arg1,arg2,arg3)},configurable:!0})})}(prototype,_header),accessors[lHeader]=!0)}return utils$3.isArray(header)?header.forEach(defineAccessor):defineAccessor(header),this}}AxiosHeaders.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$3.reduceDescriptors(AxiosHeaders.prototype,({value:value},key)=>{let mapped=key[0].toUpperCase()+key.slice(1);return{get:()=>value,set(headerValue){this[mapped]=headerValue}}}),utils$3.freezeMethods(AxiosHeaders);var AxiosHeaders$1=AxiosHeaders;function transformData(fns,response){const config=this||defaults$1,context=response||config,headers=AxiosHeaders$1.from(context.headers);let data=context.data;return utils$3.forEach(fns,function transform(fn){data=fn.call(config,data,headers.normalize(),response?response.status:void 0)}),headers.normalize(),data}function isCancel(value){return!(!value||!value.__CANCEL__)}function CanceledError(message,config,request){AxiosError.call(this,null==message?"canceled":message,AxiosError.ERR_CANCELED,config,request),this.name="CanceledError"}function settle(resolve,reject,response){const validateStatus=response.config.validateStatus;response.status&&validateStatus&&!validateStatus(response.status)?reject(new AxiosError("Request failed with status code "+response.status,[AxiosError.ERR_BAD_REQUEST,AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status/100)-4],response.config,response.request,response)):resolve(response)}function buildFullPath(baseURL,requestedURL,allowAbsoluteUrls){let isRelativeUrl=!function isAbsoluteURL(url){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)}(requestedURL);return baseURL&&(isRelativeUrl||0==allowAbsoluteUrls)?function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/?\/$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL}(baseURL,requestedURL):requestedURL}utils$3.inherits(CanceledError,AxiosError,{__CANCEL__:!0});var hasRequiredProxyFromEnv,proxyFromEnv$1={};var common$1,hasRequiredCommon,hasRequiredBrowser$1,proxyFromEnv=getDefaultExportFromCjs(function requireProxyFromEnv(){if(hasRequiredProxyFromEnv)return proxyFromEnv$1;hasRequiredProxyFromEnv=1;var parseUrl=require$$0__default$6.default.parse,DEFAULT_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443},stringEndsWith=String.prototype.endsWith||function(s){return s.length<=this.length&&-1!==this.indexOf(s,this.length-s.length)};function getEnv(key){return process.env[key.toLowerCase()]||process.env[key.toUpperCase()]||""}return proxyFromEnv$1.getProxyForUrl=function getProxyForUrl(url){var parsedUrl="string"==typeof url?parseUrl(url):url||{},proto=parsedUrl.protocol,hostname=parsedUrl.host,port=parsedUrl.port;if("string"!=typeof hostname||!hostname||"string"!=typeof proto)return"";if(proto=proto.split(":",1)[0],!function shouldProxy(hostname,port){var NO_PROXY=(getEnv("npm_config_no_proxy")||getEnv("no_proxy")).toLowerCase();if(!NO_PROXY)return!0;if("*"===NO_PROXY)return!1;return NO_PROXY.split(/[,\s]/).every(function(proxy){if(!proxy)return!0;var parsedProxy=proxy.match(/^(.+):(\d+)$/),parsedProxyHostname=parsedProxy?parsedProxy[1]:proxy,parsedProxyPort=parsedProxy?parseInt(parsedProxy[2]):0;return!(!parsedProxyPort||parsedProxyPort===port)||(/^[.*]/.test(parsedProxyHostname)?("*"===parsedProxyHostname.charAt(0)&&(parsedProxyHostname=parsedProxyHostname.slice(1)),!stringEndsWith.call(hostname,parsedProxyHostname)):hostname!==parsedProxyHostname)})}(hostname=hostname.replace(/:\d*$/,""),port=parseInt(port)||DEFAULT_PORTS[proto]||0))return"";var proxy=getEnv("npm_config_"+proto+"_proxy")||getEnv(proto+"_proxy")||getEnv("npm_config_proxy")||getEnv("all_proxy");return proxy&&-1===proxy.indexOf("://")&&(proxy=proto+"://"+proxy),proxy},proxyFromEnv$1}()),followRedirects$1={exports:{}},src={exports:{}},browser$1={exports:{}};function requireCommon(){if(hasRequiredCommon)return common$1;return hasRequiredCommon=1,common$1=function setup(env){function createDebug(namespace){let prevTime,namespacesCache,enabledCache,enableOverride=null;function debug(...args){if(!debug.enabled)return;const self=debug,curr=Number(new Date),ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return"%";index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);(self.log||createDebug.log).apply(self,args)}return debug.namespace=namespace,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(namespace),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==enableOverride?enableOverride:(namespacesCache!==createDebug.namespaces&&(namespacesCache=createDebug.namespaces,enabledCache=createDebug.enabled(namespace)),enabledCache),set:v=>{enableOverride=v}}),"function"==typeof createDebug.init&&createDebug.init(debug),debug}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+(void 0===delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function matchesTemplate(search,template){let searchIndex=0,templateIndex=0,starIndex=-1,matchIndex=0;for(;searchIndex<search.length;)if(templateIndex<template.length&&(template[templateIndex]===search[searchIndex]||"*"===template[templateIndex]))"*"===template[templateIndex]?(starIndex=templateIndex,matchIndex=searchIndex,templateIndex++):(searchIndex++,templateIndex++);else{if(-1===starIndex)return!1;templateIndex=starIndex+1,matchIndex++,searchIndex=matchIndex}for(;templateIndex<template.length&&"*"===template[templateIndex];)templateIndex++;return templateIndex===template.length}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function coerce(val){if(val instanceof Error)return val.stack||val.message;return val},createDebug.disable=function disable(){const namespaces=[...createDebug.names,...createDebug.skips.map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function enable(namespaces){createDebug.save(namespaces),createDebug.namespaces=namespaces,createDebug.names=[],createDebug.skips=[];const split=("string"==typeof namespaces?namespaces:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const ns of split)"-"===ns[0]?createDebug.skips.push(ns.slice(1)):createDebug.names.push(ns)},createDebug.enabled=function enabled(name){for(const skip of createDebug.skips)if(matchesTemplate(name,skip))return!1;for(const ns of createDebug.names)if(matchesTemplate(name,ns))return!0;return!1},createDebug.humanize=requireMs$1(),createDebug.destroy=function destroy(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(env).forEach(key=>{createDebug[key]=env[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function selectColor(namespace){let hash=0;for(let i=0;i<namespace.length;i++)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return createDebug.colors[Math.abs(hash)%createDebug.colors.length]},createDebug.enable(createDebug.load()),createDebug},common$1}var hasFlag,hasRequiredHasFlag,supportsColor_1,hasRequiredSupportsColor,hasRequiredNode,hasRequiredSrc,debug_1,hasRequiredDebug,hasRequiredFollowRedirects,node={exports:{}};function requireHasFlag(){return hasRequiredHasFlag?hasFlag:(hasRequiredHasFlag=1,hasFlag=(flag,argv=process.argv)=>{const prefix=flag.startsWith("-")?"":1===flag.length?"-":"--",position=argv.indexOf(prefix+flag),terminatorPosition=argv.indexOf("--");return-1!==position&&(-1===terminatorPosition||position<terminatorPosition)})}function requireNode(){return hasRequiredNode||(hasRequiredNode=1,function(module,exports){const tty=require$$1__default$1.default,util=require$$0__default$2.default;exports.init=function init(debug){debug.inspectOpts={};const keys=Object.keys(exports.inspectOpts);for(let i=0;i<keys.length;i++)debug.inspectOpts[keys[i]]=exports.inspectOpts[keys[i]]},exports.log=function log(...args){return process.stderr.write(util.formatWithOptions(exports.inspectOpts,...args)+"\n")},exports.formatArgs=function formatArgs(args){const{namespace:name,useColors:useColors}=this;if(useColors){const c=this.color,colorCode="[3"+(c<8?c:"8;5;"+c),prefix=` ${colorCode};1m${name} [0m`;args[0]=prefix+args[0].split("\n").join("\n"+prefix),args.push(colorCode+"m+"+module.exports.humanize(this.diff)+"[0m")}else args[0]=function getDate(){if(exports.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+name+" "+args[0]},exports.save=function save(namespaces){namespaces?process.env.DEBUG=namespaces:delete process.env.DEBUG},exports.load=function load(){return process.env.DEBUG},exports.useColors=function useColors(){return"colors"in exports.inspectOpts?Boolean(exports.inspectOpts.colors):tty.isatty(process.stderr.fd)},exports.destroy=util.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),exports.colors=[6,2,3,4,5,1];try{const supportsColor=function requireSupportsColor(){if(hasRequiredSupportsColor)return supportsColor_1;hasRequiredSupportsColor=1;const os=require$$0__default$3.default,tty=require$$1__default$1.default,hasFlag=requireHasFlag(),{env:env}=process;let forceColor;function translateLevel(level){return 0!==level&&{level:level,hasBasic:!0,has256:level>=2,has16m:level>=3}}function supportsColor(haveStream,streamIsTTY){if(0===forceColor)return 0;if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor"))return 3;if(hasFlag("color=256"))return 2;if(haveStream&&!streamIsTTY&&void 0===forceColor)return 0;const min=forceColor||0;if("dumb"===env.TERM)return min;if("win32"===process.platform){const osRelease=os.release().split(".");return Number(osRelease[0])>=10&&Number(osRelease[2])>=10586?Number(osRelease[2])>=14931?3:2:1}if("CI"in env)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(sign=>sign in env)||"codeship"===env.CI_NAME?1:min;if("TEAMCITY_VERSION"in env)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0;if("truecolor"===env.COLORTERM)return 3;if("TERM_PROGRAM"in env){const version=parseInt((env.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":return version>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(env.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)||"COLORTERM"in env?1:min}return hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never")?forceColor=0:(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always"))&&(forceColor=1),"FORCE_COLOR"in env&&(forceColor="true"===env.FORCE_COLOR?1:"false"===env.FORCE_COLOR?0:0===env.FORCE_COLOR.length?1:Math.min(parseInt(env.FORCE_COLOR,10),3)),supportsColor_1={supportsColor:function getSupportLevel(stream){return translateLevel(supportsColor(stream,stream&&stream.isTTY))},stdout:translateLevel(supportsColor(!0,tty.isatty(1))),stderr:translateLevel(supportsColor(!0,tty.isatty(2)))},supportsColor_1}();supportsColor&&(supportsColor.stderr||supportsColor).level>=2&&(exports.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(error){}exports.inspectOpts=Object.keys(process.env).filter(key=>/^debug_/i.test(key)).reduce((obj,key)=>{const prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,(_,k)=>k.toUpperCase());let val=process.env[key];return val=!!/^(yes|on|true|enabled)$/i.test(val)||!/^(no|off|false|disabled)$/i.test(val)&&("null"===val?null:Number(val)),obj[prop]=val,obj},{}),module.exports=requireCommon()(exports);const{formatters:formatters}=module.exports;formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split("\n").map(str=>str.trim()).join(" ")},formatters.O=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts)}}(node,node.exports)),node.exports}function requireSrc(){return hasRequiredSrc||(hasRequiredSrc=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?src.exports=function requireBrowser$1(){return hasRequiredBrowser$1||(hasRequiredBrowser$1=1,function(module,exports){exports.formatArgs=function formatArgs(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"!==match&&(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports.save=function save(namespaces){try{namespaces?exports.storage.setItem("debug",namespaces):exports.storage.removeItem("debug")}catch(error){}},exports.load=function load(){let r;try{r=exports.storage.getItem("debug")||exports.storage.getItem("DEBUG")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r},exports.useColors=function useColors(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let m;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(m=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(m[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},exports.storage=function localstorage(){try{return localStorage}catch(error){}}(),exports.destroy=(()=>{let warned=!1;return()=>{warned||(warned=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],exports.log=console.debug||console.log||(()=>{}),module.exports=requireCommon()(exports);const{formatters:formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}(browser$1,browser$1.exports)),browser$1.exports}():src.exports=requireNode()),src.exports}var followRedirectsExports=function requireFollowRedirects(){if(hasRequiredFollowRedirects)return followRedirects$1.exports;hasRequiredFollowRedirects=1;var url=require$$0__default$6.default,URL=url.URL,http=require$$0__default$5.default,https=https__default.default,Writable=require$$0__default$4.default.Writable,assert=require$$4__default$1.default,debug=function requireDebug(){return hasRequiredDebug||(hasRequiredDebug=1,debug_1=function(){if(!debug){try{debug=requireSrc()("follow-redirects")}catch(error){}"function"!=typeof debug&&(debug=function(){})}debug.apply(null,arguments)}),debug_1;var debug}();!function detectUnsupportedEnvironment(){var looksLikeNode="undefined"!=typeof process,looksLikeBrowser="undefined"!=typeof window&&"undefined"!=typeof document,looksLikeV8=isFunction(Error.captureStackTrace);looksLikeNode||!looksLikeBrowser&&looksLikeV8||console.warn("The follow-redirects package should be excluded from browser builds.")}();var useNativeURL=!1;try{assert(new URL(""))}catch(error){useNativeURL="ERR_INVALID_URL"===error.code}var preservedUrlFields=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],events=["abort","aborted","connect","error","socket","timeout"],eventHandlers=Object.create(null);events.forEach(function(event){eventHandlers[event]=function(arg1,arg2,arg3){this._redirectable.emit(event,arg1,arg2,arg3)}});var InvalidUrlError=createErrorType("ERR_INVALID_URL","Invalid URL",TypeError),RedirectionError=createErrorType("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),TooManyRedirectsError=createErrorType("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",RedirectionError),MaxBodyLengthExceededError=createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),WriteAfterEndError=createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),destroy=Writable.prototype.destroy||noop;function RedirectableRequest(options,responseCallback){Writable.call(this),this._sanitizeOptions(options),this._options=options,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],responseCallback&&this.on("response",responseCallback);var self=this;this._onNativeResponse=function(response){try{self._processResponse(response)}catch(cause){self.emit("error",cause instanceof RedirectionError?cause:new RedirectionError({cause:cause}))}},this._performRequest()}function wrap(protocols){var exports={maxRedirects:21,maxBodyLength:10485760},nativeProtocols={};return Object.keys(protocols).forEach(function(scheme){var protocol=scheme+":",nativeProtocol=nativeProtocols[protocol]=protocols[scheme],wrappedProtocol=exports[scheme]=Object.create(nativeProtocol);Object.defineProperties(wrappedProtocol,{request:{value:function request(input,options,callback){return!function isURL(value){return URL&&value instanceof URL}(input)?isString(input)?input=spreadUrlObject(parseUrl(input)):(callback=options,options=validateUrl(input),input={protocol:protocol}):input=spreadUrlObject(input),isFunction(options)&&(callback=options,options=null),(options=Object.assign({maxRedirects:exports.maxRedirects,maxBodyLength:exports.maxBodyLength},input,options)).nativeProtocols=nativeProtocols,isString(options.host)||isString(options.hostname)||(options.hostname="::1"),assert.equal(options.protocol,protocol,"protocol mismatch"),debug("options",options),new RedirectableRequest(options,callback)},configurable:!0,enumerable:!0,writable:!0},get:{value:function get(input,options,callback){var wrappedRequest=wrappedProtocol.request(input,options,callback);return wrappedRequest.end(),wrappedRequest},configurable:!0,enumerable:!0,writable:!0}})}),exports}function noop(){}function parseUrl(input){var parsed;if(useNativeURL)parsed=new URL(input);else if(!isString((parsed=validateUrl(url.parse(input))).protocol))throw new InvalidUrlError({input:input});return parsed}function validateUrl(input){if(/^\[/.test(input.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(input.hostname))throw new InvalidUrlError({input:input.href||input});if(/^\[/.test(input.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host))throw new InvalidUrlError({input:input.href||input});return input}function spreadUrlObject(urlObject,target){var spread=target||{};for(var key of preservedUrlFields)spread[key]=urlObject[key];return spread.hostname.startsWith("[")&&(spread.hostname=spread.hostname.slice(1,-1)),""!==spread.port&&(spread.port=Number(spread.port)),spread.path=spread.search?spread.pathname+spread.search:spread.pathname,spread}function removeMatchingHeaders(regex,headers){var lastValue;for(var header in headers)regex.test(header)&&(lastValue=headers[header],delete headers[header]);return null==lastValue?void 0:String(lastValue).trim()}function createErrorType(code,message,baseClass){function CustomError(properties){isFunction(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,properties||{}),this.code=code,this.message=this.cause?message+": "+this.cause.message:message}return CustomError.prototype=new(baseClass||Error),Object.defineProperties(CustomError.prototype,{constructor:{value:CustomError,enumerable:!1},name:{value:"Error ["+code+"]",enumerable:!1}}),CustomError}function destroyRequest(request,error){for(var event of events)request.removeListener(event,eventHandlers[event]);request.on("error",noop),request.destroy(error)}function isString(value){return"string"==typeof value||value instanceof String}function isFunction(value){return"function"==typeof value}return RedirectableRequest.prototype=Object.create(Writable.prototype),RedirectableRequest.prototype.abort=function(){destroyRequest(this._currentRequest),this._currentRequest.abort(),this.emit("abort")},RedirectableRequest.prototype.destroy=function(error){return destroyRequest(this._currentRequest,error),destroy.call(this,error),this},RedirectableRequest.prototype.write=function(data,encoding,callback){if(this._ending)throw new WriteAfterEndError;if(!isString(data)&&!function isBuffer(value){return"object"==typeof value&&"length"in value}(data))throw new TypeError("data should be a string, Buffer or Uint8Array");isFunction(encoding)&&(callback=encoding,encoding=null),0!==data.length?this._requestBodyLength+data.length<=this._options.maxBodyLength?(this._requestBodyLength+=data.length,this._requestBodyBuffers.push({data:data,encoding:encoding}),this._currentRequest.write(data,encoding,callback)):(this.emit("error",new MaxBodyLengthExceededError),this.abort()):callback&&callback()},RedirectableRequest.prototype.end=function(data,encoding,callback){if(isFunction(data)?(callback=data,data=encoding=null):isFunction(encoding)&&(callback=encoding,encoding=null),data){var self=this,currentRequest=this._currentRequest;this.write(data,encoding,function(){self._ended=!0,currentRequest.end(null,null,callback)}),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,callback)},RedirectableRequest.prototype.setHeader=function(name,value){this._options.headers[name]=value,this._currentRequest.setHeader(name,value)},RedirectableRequest.prototype.removeHeader=function(name){delete this._options.headers[name],this._currentRequest.removeHeader(name)},RedirectableRequest.prototype.setTimeout=function(msecs,callback){var self=this;function destroyOnTimeout(socket){socket.setTimeout(msecs),socket.removeListener("timeout",socket.destroy),socket.addListener("timeout",socket.destroy)}function startTimer(socket){self._timeout&&clearTimeout(self._timeout),self._timeout=setTimeout(function(){self.emit("timeout"),clearTimer()},msecs),destroyOnTimeout(socket)}function clearTimer(){self._timeout&&(clearTimeout(self._timeout),self._timeout=null),self.removeListener("abort",clearTimer),self.removeListener("error",clearTimer),self.removeListener("response",clearTimer),self.removeListener("close",clearTimer),callback&&self.removeListener("timeout",callback),self.socket||self._currentRequest.removeListener("socket",startTimer)}return callback&&this.on("timeout",callback),this.socket?startTimer(this.socket):this._currentRequest.once("socket",startTimer),this.on("socket",destroyOnTimeout),this.on("abort",clearTimer),this.on("error",clearTimer),this.on("response",clearTimer),this.on("close",clearTimer),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(method){RedirectableRequest.prototype[method]=function(a,b){return this._currentRequest[method](a,b)}}),["aborted","connection","socket"].forEach(function(property){Object.defineProperty(RedirectableRequest.prototype,property,{get:function(){return this._currentRequest[property]}})}),RedirectableRequest.prototype._sanitizeOptions=function(options){if(options.headers||(options.headers={}),options.host&&(options.hostname||(options.hostname=options.host),delete options.host),!options.pathname&&options.path){var searchPos=options.path.indexOf("?");searchPos<0?options.pathname=options.path:(options.pathname=options.path.substring(0,searchPos),options.search=options.path.substring(searchPos))}},RedirectableRequest.prototype._performRequest=function(){var protocol=this._options.protocol,nativeProtocol=this._options.nativeProtocols[protocol];if(!nativeProtocol)throw new TypeError("Unsupported protocol "+protocol);if(this._options.agents){var scheme=protocol.slice(0,-1);this._options.agent=this._options.agents[scheme]}var request=this._currentRequest=nativeProtocol.request(this._options,this._onNativeResponse);for(var event of(request._redirectable=this,events))request.on(event,eventHandlers[event]);if(this._currentUrl=/^\//.test(this._options.path)?url.format(this._options):this._options.path,this._isRedirect){var i=0,self=this,buffers=this._requestBodyBuffers;!function writeNext(error){if(request===self._currentRequest)if(error)self.emit("error",error);else if(i<buffers.length){var buffer=buffers[i++];request.finished||request.write(buffer.data,buffer.encoding,writeNext)}else self._ended&&request.end()}()}},RedirectableRequest.prototype._processResponse=function(response){var statusCode=response.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:response.headers,statusCode:statusCode});var requestHeaders,location=response.headers.location;if(!location||!1===this._options.followRedirects||statusCode<300||statusCode>=400)return response.responseUrl=this._currentUrl,response.redirects=this._redirects,this.emit("response",response),void(this._requestBodyBuffers=[]);if(destroyRequest(this._currentRequest),response.destroy(),++this._redirectCount>this._options.maxRedirects)throw new TooManyRedirectsError;var beforeRedirect=this._options.beforeRedirect;beforeRedirect&&(requestHeaders=Object.assign({Host:response.req.getHeader("host")},this._options.headers));var method=this._options.method;((301===statusCode||302===statusCode)&&"POST"===this._options.method||303===statusCode&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],removeMatchingHeaders(/^content-/i,this._options.headers));var currentHostHeader=removeMatchingHeaders(/^host$/i,this._options.headers),currentUrlParts=parseUrl(this._currentUrl),currentHost=currentHostHeader||currentUrlParts.host,currentUrl=/^\w+:/.test(location)?this._currentUrl:url.format(Object.assign(currentUrlParts,{host:currentHost})),redirectUrl=function resolveUrl(relative,base){return useNativeURL?new URL(relative,base):parseUrl(url.resolve(base,relative))}(location,currentUrl);if(debug("redirecting to",redirectUrl.href),this._isRedirect=!0,spreadUrlObject(redirectUrl,this._options),(redirectUrl.protocol!==currentUrlParts.protocol&&"https:"!==redirectUrl.protocol||redirectUrl.host!==currentHost&&!function isSubdomain(subdomain,domain){assert(isString(subdomain)&&isString(domain));var dot=subdomain.length-domain.length-1;return dot>0&&"."===subdomain[dot]&&subdomain.endsWith(domain)}(redirectUrl.host,currentHost))&&removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i,this._options.headers),isFunction(beforeRedirect)){var responseDetails={headers:response.headers,statusCode:statusCode},requestDetails={url:currentUrl,method:method,headers:requestHeaders};beforeRedirect(this._options,responseDetails,requestDetails),this._sanitizeOptions(this._options)}this._performRequest()},followRedirects$1.exports=wrap({http:http,https:https}),followRedirects$1.exports.wrap=wrap,followRedirects$1.exports}(),followRedirects=getDefaultExportFromCjs(followRedirectsExports);function parseProtocol(url){const match=/^([-+\w]{1,25})(:?\/\/|:)/.exec(url);return match&&match[1]||""}const DATA_URL_PATTERN=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;const kInternals=Symbol("internals");class AxiosTransformStream extends require$$0__default$4.default.Transform{constructor(options){super({readableHighWaterMark:(options=utils$3.toFlatObject(options,{maxRate:0,chunkSize:65536,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(prop,source)=>!utils$3.isUndefined(source[prop]))).chunkSize});const internals=this[kInternals]={timeWindow:options.timeWindow,chunkSize:options.chunkSize,maxRate:options.maxRate,minChunkSize:options.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",event=>{"progress"===event&&(internals.isCaptured||(internals.isCaptured=!0))})}_read(size){const internals=this[kInternals];return internals.onReadCallback&&internals.onReadCallback(),super._read(size)}_transform(chunk,encoding,callback){const internals=this[kInternals],maxRate=internals.maxRate,readableHighWaterMark=this.readableHighWaterMark,timeWindow=internals.timeWindow,bytesThreshold=maxRate/(1e3/timeWindow),minChunkSize=!1!==internals.minChunkSize?Math.max(internals.minChunkSize,.01*bytesThreshold):0,pushChunk=(_chunk,_callback)=>{const bytes=Buffer.byteLength(_chunk);internals.bytesSeen+=bytes,internals.bytes+=bytes,internals.isCaptured&&this.emit("progress",internals.bytesSeen),this.push(_chunk)?process.nextTick(_callback):internals.onReadCallback=()=>{internals.onReadCallback=null,process.nextTick(_callback)}},transformChunk=(_chunk,_callback)=>{const chunkSize=Buffer.byteLength(_chunk);let bytesLeft,chunkRemainder=null,maxChunkSize=readableHighWaterMark,passed=0;if(maxRate){const now=Date.now();(!internals.ts||(passed=now-internals.ts)>=timeWindow)&&(internals.ts=now,bytesLeft=bytesThreshold-internals.bytes,internals.bytes=bytesLeft<0?-bytesLeft:0,passed=0),bytesLeft=bytesThreshold-internals.bytes}if(maxRate){if(bytesLeft<=0)return setTimeout(()=>{_callback(null,_chunk)},timeWindow-passed);bytesLeft<maxChunkSize&&(maxChunkSize=bytesLeft)}maxChunkSize&&chunkSize>maxChunkSize&&chunkSize-maxChunkSize>minChunkSize&&(chunkRemainder=_chunk.subarray(maxChunkSize),_chunk=_chunk.subarray(0,maxChunkSize)),pushChunk(_chunk,chunkRemainder?()=>{process.nextTick(_callback,null,chunkRemainder)}:_callback)};transformChunk(chunk,function transformNextChunk(err,_chunk){if(err)return callback(err);_chunk?transformChunk(_chunk,transformNextChunk):callback(null)})}}var AxiosTransformStream$1=AxiosTransformStream;const{asyncIterator:asyncIterator}=Symbol;var readBlob$1=async function*(blob){blob.stream?yield*blob.stream():blob.arrayBuffer?yield await blob.arrayBuffer():blob[asyncIterator]?yield*blob[asyncIterator]():yield blob};const BOUNDARY_ALPHABET=platform.ALPHABET.ALPHA_DIGIT+"-_",textEncoder="function"==typeof TextEncoder?new TextEncoder:new require$$0__default$2.default.TextEncoder,CRLF_BYTES=textEncoder.encode("\r\n");class FormDataPart{constructor(name,value){const{escapeName:escapeName}=this.constructor,isStringValue=utils$3.isString(value);let headers=`Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue&&value.name?`; filename="${escapeName(value.name)}"`:""}\r\n`;isStringValue?value=textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g,"\r\n")):headers+=`Content-Type: ${value.type||"application/octet-stream"}\r\n`,this.headers=textEncoder.encode(headers+"\r\n"),this.contentLength=isStringValue?value.byteLength:value.size,this.size=this.headers.byteLength+this.contentLength+2,this.name=name,this.value=value}async*encode(){yield this.headers;const{value:value}=this;utils$3.isTypedArray(value)?yield value:yield*readBlob$1(value),yield CRLF_BYTES}static escapeName(name){return String(name).replace(/[\r\n"]/g,match=>({"\r":"%0D","\n":"%0A",'"':"%22"}[match]))}}var formDataToStream$1=(form,headersHandler,options)=>{const{tag:tag="form-data-boundary",size:size=25,boundary:boundary=tag+"-"+platform.generateString(size,BOUNDARY_ALPHABET)}=options||{};if(!utils$3.isFormData(form))throw TypeError("FormData instance required");if(boundary.length<1||boundary.length>70)throw Error("boundary must be 10-70 characters long");const boundaryBytes=textEncoder.encode("--"+boundary+"\r\n"),footerBytes=textEncoder.encode("--"+boundary+"--\r\n");let contentLength=footerBytes.byteLength;const parts=Array.from(form.entries()).map(([name,value])=>{const part=new FormDataPart(name,value);return contentLength+=part.size,part});contentLength+=boundaryBytes.byteLength*parts.length,contentLength=utils$3.toFiniteNumber(contentLength);const computedHeaders={"Content-Type":`multipart/form-data; boundary=${boundary}`};return Number.isFinite(contentLength)&&(computedHeaders["Content-Length"]=contentLength),headersHandler&&headersHandler(computedHeaders),require$$0$7.Readable.from(async function*(){for(const part of parts)yield boundaryBytes,yield*part.encode();yield footerBytes}())};class ZlibHeaderTransformStream extends require$$0__default$4.default.Transform{__transform(chunk,encoding,callback){this.push(chunk),callback()}_transform(chunk,encoding,callback){if(0!==chunk.length&&(this._transform=this.__transform,120!==chunk[0])){const header=Buffer.alloc(2);header[0]=120,header[1]=156,this.push(header,encoding)}this.__transform(chunk,encoding,callback)}}var ZlibHeaderTransformStream$1=ZlibHeaderTransformStream;var callbackify$1=(fn,reducer)=>utils$3.isAsyncFn(fn)?function(...args){const cb=args.pop();fn.apply(this,args).then(value=>{try{reducer?cb(null,...reducer(value)):cb(null,value)}catch(err){cb(err)}},cb)}:fn;const progressEventReducer=(listener,isDownloadStream,freq=3)=>{let bytesNotified=0;const _speedometer=function speedometer(samplesCount,min){samplesCount=samplesCount||10;const bytes=new Array(samplesCount),timestamps=new Array(samplesCount);let firstSampleTS,head=0,tail=0;return min=void 0!==min?min:1e3,function push(chunkLength){const now=Date.now(),startedAt=timestamps[tail];firstSampleTS||(firstSampleTS=now),bytes[head]=chunkLength,timestamps[head]=now;let i=tail,bytesCount=0;for(;i!==head;)bytesCount+=bytes[i++],i%=samplesCount;if(head=(head+1)%samplesCount,head===tail&&(tail=(tail+1)%samplesCount),now-firstSampleTS<min)return;const passed=startedAt&&now-startedAt;return passed?Math.round(1e3*bytesCount/passed):void 0}}(50,250);return function throttle(fn,freq){let lastArgs,timer,timestamp=0,threshold=1e3/freq;const invoke=(args,now=Date.now())=>{timestamp=now,lastArgs=null,timer&&(clearTimeout(timer),timer=null),fn(...args)};return[(...args)=>{const now=Date.now(),passed=now-timestamp;passed>=threshold?invoke(args,now):(lastArgs=args,timer||(timer=setTimeout(()=>{timer=null,invoke(lastArgs)},threshold-passed)))},()=>lastArgs&&invoke(lastArgs)]}(e=>{const loaded=e.loaded,total=e.lengthComputable?e.total:void 0,progressBytes=loaded-bytesNotified,rate=_speedometer(progressBytes);bytesNotified=loaded;listener({loaded:loaded,total:total,progress:total?loaded/total:void 0,bytes:progressBytes,rate:rate||void 0,estimated:rate&&total&&loaded<=total?(total-loaded)/rate:void 0,event:e,lengthComputable:null!=total,[isDownloadStream?"download":"upload"]:!0})},freq)},progressEventDecorator=(total,throttled)=>{const lengthComputable=null!=total;return[loaded=>throttled[0]({lengthComputable:lengthComputable,total:total,loaded:loaded}),throttled[1]]},asyncDecorator=fn=>(...args)=>utils$3.asap(()=>fn(...args)),zlibOptions={flush:zlib__default.default.constants.Z_SYNC_FLUSH,finishFlush:zlib__default.default.constants.Z_SYNC_FLUSH},brotliOptions={flush:zlib__default.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:zlib__default.default.constants.BROTLI_OPERATION_FLUSH},isBrotliSupported=utils$3.isFunction(zlib__default.default.createBrotliDecompress),{http:httpFollow,https:httpsFollow}=followRedirects,isHttps=/https:?/,supportedProtocols=platform.protocols.map(protocol=>protocol+":"),flushOnFinish=(stream,[throttled,flush])=>(stream.on("end",flush).on("error",flush),throttled);function dispatchBeforeRedirect(options,responseDetails){options.beforeRedirects.proxy&&options.beforeRedirects.proxy(options),options.beforeRedirects.config&&options.beforeRedirects.config(options,responseDetails)}function setProxy(options,configProxy,location){let proxy=configProxy;if(!proxy&&!1!==proxy){const proxyUrl=proxyFromEnv.getProxyForUrl(location);proxyUrl&&(proxy=new URL(proxyUrl))}if(proxy){if(proxy.username&&(proxy.auth=(proxy.username||"")+":"+(proxy.password||"")),proxy.auth){(proxy.auth.username||proxy.auth.password)&&(proxy.auth=(proxy.auth.username||"")+":"+(proxy.auth.password||""));const base64=Buffer.from(proxy.auth,"utf8").toString("base64");options.headers["Proxy-Authorization"]="Basic "+base64}options.headers.host=options.hostname+(options.port?":"+options.port:"");const proxyHost=proxy.hostname||proxy.host;options.hostname=proxyHost,options.host=proxyHost,options.port=proxy.port,options.path=location,proxy.protocol&&(options.protocol=proxy.protocol.includes(":")?proxy.protocol:`${proxy.protocol}:`)}options.beforeRedirects.proxy=function beforeRedirect(redirectOptions){setProxy(redirectOptions,configProxy,redirectOptions.href)}}const isHttpAdapterSupported="undefined"!=typeof process&&"process"===utils$3.kindOf(process),buildAddressEntry=(address,family)=>(({address:address,family:family})=>{if(!utils$3.isString(address))throw TypeError("address must be a string");return{address:address,family:family||(address.indexOf(".")<0?6:4)}})(utils$3.isObject(address)?address:{address:address,family:family});var httpAdapter=isHttpAdapterSupported&&function httpAdapter(config){return asyncExecutor=async function dispatchHttpRequest(resolve,reject,onDone){let{data:data,lookup:lookup,family:family}=config;const{responseType:responseType,responseEncoding:responseEncoding}=config,method=config.method.toUpperCase();let isDone,req,rejected=!1;if(lookup){const _lookup=callbackify$1(lookup,value=>utils$3.isArray(value)?value:[value]);lookup=(hostname,opt,cb)=>{_lookup(hostname,opt,(err,arg0,arg1)=>{if(err)return cb(err);const addresses=utils$3.isArray(arg0)?arg0.map(addr=>buildAddressEntry(addr)):[buildAddressEntry(arg0,arg1)];opt.all?cb(err,addresses):cb(err,addresses[0].address,addresses[0].family)})}}const emitter=new require$$0$3.EventEmitter,onFinished=()=>{config.cancelToken&&config.cancelToken.unsubscribe(abort),config.signal&&config.signal.removeEventListener("abort",abort),emitter.removeAllListeners()};function abort(reason){emitter.emit("abort",!reason||reason.type?new CanceledError(null,config,req):reason)}onDone((value,isRejected)=>{isDone=!0,isRejected&&(rejected=!0,onFinished())}),emitter.once("abort",reject),(config.cancelToken||config.signal)&&(config.cancelToken&&config.cancelToken.subscribe(abort),config.signal&&(config.signal.aborted?abort():config.signal.addEventListener("abort",abort)));const fullPath=buildFullPath(config.baseURL,config.url,config.allowAbsoluteUrls),parsed=new URL(fullPath,platform.hasBrowserEnv?platform.origin:void 0),protocol=parsed.protocol||supportedProtocols[0];if("data:"===protocol){let convertedData;if("GET"!==method)return settle(resolve,reject,{status:405,statusText:"method not allowed",headers:{},config:config});try{convertedData=function fromDataURI(uri,asBlob,options){const _Blob=options&&options.Blob||platform.classes.Blob,protocol=parseProtocol(uri);if(void 0===asBlob&&_Blob&&(asBlob=!0),"data"===protocol){uri=protocol.length?uri.slice(protocol.length+1):uri;const match=DATA_URL_PATTERN.exec(uri);if(!match)throw new AxiosError("Invalid URL",AxiosError.ERR_INVALID_URL);const mime=match[1],isBase64=match[2],body=match[3],buffer=Buffer.from(decodeURIComponent(body),isBase64?"base64":"utf8");if(asBlob){if(!_Blob)throw new AxiosError("Blob is not supported",AxiosError.ERR_NOT_SUPPORT);return new _Blob([buffer],{type:mime})}return buffer}throw new AxiosError("Unsupported protocol "+protocol,AxiosError.ERR_NOT_SUPPORT)}(config.url,"blob"===responseType,{Blob:config.env&&config.env.Blob})}catch(err){throw AxiosError.from(err,AxiosError.ERR_BAD_REQUEST,config)}return"text"===responseType?(convertedData=convertedData.toString(responseEncoding),responseEncoding&&"utf8"!==responseEncoding||(convertedData=utils$3.stripBOM(convertedData))):"stream"===responseType&&(convertedData=require$$0__default$4.default.Readable.from(convertedData)),settle(resolve,reject,{data:convertedData,status:200,statusText:"OK",headers:new AxiosHeaders$1,config:config})}if(-1===supportedProtocols.indexOf(protocol))return reject(new AxiosError("Unsupported protocol "+protocol,AxiosError.ERR_BAD_REQUEST,config));const headers=AxiosHeaders$1.from(config.headers).normalize();headers.set("User-Agent","axios/1.11.0",!1);const{onUploadProgress:onUploadProgress,onDownloadProgress:onDownloadProgress}=config,maxRate=config.maxRate;let maxUploadRate,maxDownloadRate;if(utils$3.isSpecCompliantForm(data)){const userBoundary=headers.getContentType(/boundary=([-_\w\d]{10,70})/i);data=formDataToStream$1(data,formHeaders=>{headers.set(formHeaders)},{tag:"axios-1.11.0-boundary",boundary:userBoundary&&userBoundary[1]||void 0})}else if(utils$3.isFormData(data)&&utils$3.isFunction(data.getHeaders)){if(headers.set(data.getHeaders()),!headers.hasContentLength())try{const knownLength=await require$$0__default$2.default.promisify(data.getLength).call(data);Number.isFinite(knownLength)&&knownLength>=0&&headers.setContentLength(knownLength)}catch(e){}}else if(utils$3.isBlob(data)||utils$3.isFile(data))data.size&&headers.setContentType(data.type||"application/octet-stream"),headers.setContentLength(data.size||0),data=require$$0__default$4.default.Readable.from(readBlob$1(data));else if(data&&!utils$3.isStream(data)){if(Buffer.isBuffer(data));else if(utils$3.isArrayBuffer(data))data=Buffer.from(new Uint8Array(data));else{if(!utils$3.isString(data))return reject(new AxiosError("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",AxiosError.ERR_BAD_REQUEST,config));data=Buffer.from(data,"utf-8")}if(headers.setContentLength(data.length,!1),config.maxBodyLength>-1&&data.length>config.maxBodyLength)return reject(new AxiosError("Request body larger than maxBodyLength limit",AxiosError.ERR_BAD_REQUEST,config))}const contentLength=utils$3.toFiniteNumber(headers.getContentLength());let auth,path;utils$3.isArray(maxRate)?(maxUploadRate=maxRate[0],maxDownloadRate=maxRate[1]):maxUploadRate=maxDownloadRate=maxRate,data&&(onUploadProgress||maxUploadRate)&&(utils$3.isStream(data)||(data=require$$0__default$4.default.Readable.from(data,{objectMode:!1})),data=require$$0__default$4.default.pipeline([data,new AxiosTransformStream$1({maxRate:utils$3.toFiniteNumber(maxUploadRate)})],utils$3.noop),onUploadProgress&&data.on("progress",flushOnFinish(data,progressEventDecorator(contentLength,progressEventReducer(asyncDecorator(onUploadProgress),!1,3))))),config.auth&&(auth=(config.auth.username||"")+":"+(config.auth.password||"")),!auth&&parsed.username&&(auth=parsed.username+":"+parsed.password),auth&&headers.delete("authorization");try{path=buildURL(parsed.pathname+parsed.search,config.params,config.paramsSerializer).replace(/^\?/,"")}catch(err){const customErr=new Error(err.message);return customErr.config=config,customErr.url=config.url,customErr.exists=!0,reject(customErr)}headers.set("Accept-Encoding","gzip, compress, deflate"+(isBrotliSupported?", br":""),!1);const options={path:path,method:method,headers:headers.toJSON(),agents:{http:config.httpAgent,https:config.httpsAgent},auth:auth,protocol:protocol,family:family,beforeRedirect:dispatchBeforeRedirect,beforeRedirects:{}};let transport;!utils$3.isUndefined(lookup)&&(options.lookup=lookup),config.socketPath?options.socketPath=config.socketPath:(options.hostname=parsed.hostname.startsWith("[")?parsed.hostname.slice(1,-1):parsed.hostname,options.port=parsed.port,setProxy(options,config.proxy,protocol+"//"+parsed.hostname+(parsed.port?":"+parsed.port:"")+options.path));const isHttpsRequest=isHttps.test(options.protocol);if(options.agent=isHttpsRequest?config.httpsAgent:config.httpAgent,config.transport?transport=config.transport:0===config.maxRedirects?transport=isHttpsRequest?https__default.default:require$$0__default$5.default:(config.maxRedirects&&(options.maxRedirects=config.maxRedirects),config.beforeRedirect&&(options.beforeRedirects.config=config.beforeRedirect),transport=isHttpsRequest?httpsFollow:httpFollow),config.maxBodyLength>-1?options.maxBodyLength=config.maxBodyLength:options.maxBodyLength=1/0,config.insecureHTTPParser&&(options.insecureHTTPParser=config.insecureHTTPParser),req=transport.request(options,function handleResponse(res){if(req.destroyed)return;const streams=[res],responseLength=+res.headers["content-length"];if(onDownloadProgress||maxDownloadRate){const transformStream=new AxiosTransformStream$1({maxRate:utils$3.toFiniteNumber(maxDownloadRate)});onDownloadProgress&&transformStream.on("progress",flushOnFinish(transformStream,progressEventDecorator(responseLength,progressEventReducer(asyncDecorator(onDownloadProgress),!0,3)))),streams.push(transformStream)}let responseStream=res;const lastRequest=res.req||req;if(!1!==config.decompress&&res.headers["content-encoding"])switch("HEAD"!==method&&204!==res.statusCode||delete res.headers["content-encoding"],(res.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":streams.push(zlib__default.default.createUnzip(zlibOptions)),delete res.headers["content-encoding"];break;case"deflate":streams.push(new ZlibHeaderTransformStream$1),streams.push(zlib__default.default.createUnzip(zlibOptions)),delete res.headers["content-encoding"];break;case"br":isBrotliSupported&&(streams.push(zlib__default.default.createBrotliDecompress(brotliOptions)),delete res.headers["content-encoding"])}responseStream=streams.length>1?require$$0__default$4.default.pipeline(streams,utils$3.noop):streams[0];const offListeners=require$$0__default$4.default.finished(responseStream,()=>{offListeners(),onFinished()}),response={status:res.statusCode,statusText:res.statusMessage,headers:new AxiosHeaders$1(res.headers),config:config,request:lastRequest};if("stream"===responseType)response.data=responseStream,settle(resolve,reject,response);else{const responseBuffer=[];let totalResponseBytes=0;responseStream.on("data",function handleStreamData(chunk){responseBuffer.push(chunk),totalResponseBytes+=chunk.length,config.maxContentLength>-1&&totalResponseBytes>config.maxContentLength&&(rejected=!0,responseStream.destroy(),reject(new AxiosError("maxContentLength size of "+config.maxContentLength+" exceeded",AxiosError.ERR_BAD_RESPONSE,config,lastRequest)))}),responseStream.on("aborted",function handlerStreamAborted(){if(rejected)return;const err=new AxiosError("stream has been aborted",AxiosError.ERR_BAD_RESPONSE,config,lastRequest);responseStream.destroy(err),reject(err)}),responseStream.on("error",function handleStreamError(err){req.destroyed||reject(AxiosError.from(err,null,config,lastRequest))}),responseStream.on("end",function handleStreamEnd(){try{let responseData=1===responseBuffer.length?responseBuffer[0]:Buffer.concat(responseBuffer);"arraybuffer"!==responseType&&(responseData=responseData.toString(responseEncoding),responseEncoding&&"utf8"!==responseEncoding||(responseData=utils$3.stripBOM(responseData))),response.data=responseData}catch(err){return reject(AxiosError.from(err,null,config,response.request,response))}settle(resolve,reject,response)})}emitter.once("abort",err=>{responseStream.destroyed||(responseStream.emit("error",err),responseStream.destroy())})}),emitter.once("abort",err=>{reject(err),req.destroy(err)}),req.on("error",function handleRequestError(err){reject(AxiosError.from(err,null,config,req))}),req.on("socket",function handleRequestSocket(socket){socket.setKeepAlive(!0,6e4)}),config.timeout){const timeout=parseInt(config.timeout,10);if(Number.isNaN(timeout))return void reject(new AxiosError("error trying to parse `config.timeout` to int",AxiosError.ERR_BAD_OPTION_VALUE,config,req));req.setTimeout(timeout,function handleRequestTimeout(){if(isDone)return;let timeoutErrorMessage=config.timeout?"timeout of "+config.timeout+"ms exceeded":"timeout exceeded";const transitional=config.transitional||transitionalDefaults;config.timeoutErrorMessage&&(timeoutErrorMessage=config.timeoutErrorMessage),reject(new AxiosError(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,config,req)),abort()})}if(utils$3.isStream(data)){let ended=!1,errored=!1;data.on("end",()=>{ended=!0}),data.once("error",err=>{errored=!0,req.destroy(err)}),data.on("close",()=>{ended||errored||abort(new CanceledError("Request stream has been aborted",config,req))}),data.pipe(req)}else req.end(data)},new Promise((resolve,reject)=>{let onDone,isDone;const done=(value,isRejected)=>{isDone||(isDone=!0,onDone&&onDone(value,isRejected))},_reject=reason=>{done(reason,!0),reject(reason)};asyncExecutor(value=>{done(value),resolve(value)},_reject,onDoneHandler=>onDone=onDoneHandler).catch(_reject)});var asyncExecutor},isURLSameOrigin=platform.hasStandardBrowserEnv?((origin,isMSIE)=>url=>(url=new URL(url,platform.origin),origin.protocol===url.protocol&&origin.host===url.host&&(isMSIE||origin.port===url.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies$1=platform.hasStandardBrowserEnv?{write(name,value,expires,path,domain,secure){const cookie=[name+"="+encodeURIComponent(value)];utils$3.isNumber(expires)&&cookie.push("expires="+new Date(expires).toGMTString()),utils$3.isString(path)&&cookie.push("path="+path),utils$3.isString(domain)&&cookie.push("domain="+domain),!0===secure&&cookie.push("secure"),document.cookie=cookie.join("; ")},read(name){const match=document.cookie.match(new RegExp("(^|;\\s*)("+name+")=([^;]*)"));return match?decodeURIComponent(match[3]):null},remove(name){this.write(name,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};const headersToObject=thing=>thing instanceof AxiosHeaders$1?{...thing}:thing;function mergeConfig(config1,config2){config2=config2||{};const config={};function getMergedValue(target,source,prop,caseless){return utils$3.isPlainObject(target)&&utils$3.isPlainObject(source)?utils$3.merge.call({caseless:caseless},target,source):utils$3.isPlainObject(source)?utils$3.merge({},source):utils$3.isArray(source)?source.slice():source}function mergeDeepProperties(a,b,prop,caseless){return utils$3.isUndefined(b)?utils$3.isUndefined(a)?void 0:getMergedValue(void 0,a,0,caseless):getMergedValue(a,b,0,caseless)}function valueFromConfig2(a,b){if(!utils$3.isUndefined(b))return getMergedValue(void 0,b)}function defaultToConfig2(a,b){return utils$3.isUndefined(b)?utils$3.isUndefined(a)?void 0:getMergedValue(void 0,a):getMergedValue(void 0,b)}function mergeDirectKeys(a,b,prop){return prop in config2?getMergedValue(a,b):prop in config1?getMergedValue(void 0,a):void 0}const mergeMap={url:valueFromConfig2,method:valueFromConfig2,data:valueFromConfig2,baseURL:defaultToConfig2,transformRequest:defaultToConfig2,transformResponse:defaultToConfig2,paramsSerializer:defaultToConfig2,timeout:defaultToConfig2,timeoutMessage:defaultToConfig2,withCredentials:defaultToConfig2,withXSRFToken:defaultToConfig2,adapter:defaultToConfig2,responseType:defaultToConfig2,xsrfCookieName:defaultToConfig2,xsrfHeaderName:defaultToConfig2,onUploadProgress:defaultToConfig2,onDownloadProgress:defaultToConfig2,decompress:defaultToConfig2,maxContentLength:defaultToConfig2,maxBodyLength:defaultToConfig2,beforeRedirect:defaultToConfig2,transport:defaultToConfig2,httpAgent:defaultToConfig2,httpsAgent:defaultToConfig2,cancelToken:defaultToConfig2,socketPath:defaultToConfig2,responseEncoding:defaultToConfig2,validateStatus:mergeDirectKeys,headers:(a,b,prop)=>mergeDeepProperties(headersToObject(a),headersToObject(b),0,!0)};return utils$3.forEach(Object.keys({...config1,...config2}),function computeConfigValue(prop){const merge=mergeMap[prop]||mergeDeepProperties,configValue=merge(config1[prop],config2[prop],prop);utils$3.isUndefined(configValue)&&merge!==mergeDirectKeys||(config[prop]=configValue)}),config}var resolveConfig=config=>{const newConfig=mergeConfig({},config);let contentType,{data:data,withXSRFToken:withXSRFToken,xsrfHeaderName:xsrfHeaderName,xsrfCookieName:xsrfCookieName,headers:headers,auth:auth}=newConfig;if(newConfig.headers=headers=AxiosHeaders$1.from(headers),newConfig.url=buildURL(buildFullPath(newConfig.baseURL,newConfig.url,newConfig.allowAbsoluteUrls),config.params,config.paramsSerializer),auth&&headers.set("Authorization","Basic "+btoa((auth.username||"")+":"+(auth.password?unescape(encodeURIComponent(auth.password)):""))),utils$3.isFormData(data))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)headers.setContentType(void 0);else if(!1!==(contentType=headers.getContentType())){const[type,...tokens]=contentType?contentType.split(";").map(token=>token.trim()).filter(Boolean):[];headers.setContentType([type||"multipart/form-data",...tokens].join("; "))}if(platform.hasStandardBrowserEnv&&(withXSRFToken&&utils$3.isFunction(withXSRFToken)&&(withXSRFToken=withXSRFToken(newConfig)),withXSRFToken||!1!==withXSRFToken&&isURLSameOrigin(newConfig.url))){const xsrfValue=xsrfHeaderName&&xsrfCookieName&&cookies$1.read(xsrfCookieName);xsrfValue&&headers.set(xsrfHeaderName,xsrfValue)}return newConfig};var xhrAdapter="undefined"!=typeof XMLHttpRequest&&function(config){return new Promise(function dispatchXhrRequest(resolve,reject){const _config=resolveConfig(config);let requestData=_config.data;const requestHeaders=AxiosHeaders$1.from(_config.headers).normalize();let onCanceled,uploadThrottled,downloadThrottled,flushUpload,flushDownload,{responseType:responseType,onUploadProgress:onUploadProgress,onDownloadProgress:onDownloadProgress}=_config;function done(){flushUpload&&flushUpload(),flushDownload&&flushDownload(),_config.cancelToken&&_config.cancelToken.unsubscribe(onCanceled),_config.signal&&_config.signal.removeEventListener("abort",onCanceled)}let request=new XMLHttpRequest;function onloadend(){if(!request)return;const responseHeaders=AxiosHeaders$1.from("getAllResponseHeaders"in request&&request.getAllResponseHeaders());settle(function _resolve(value){resolve(value),done()},function _reject(err){reject(err),done()},{data:responseType&&"text"!==responseType&&"json"!==responseType?request.response:request.responseText,status:request.status,statusText:request.statusText,headers:responseHeaders,config:config,request:request}),request=null}request.open(_config.method.toUpperCase(),_config.url,!0),request.timeout=_config.timeout,"onloadend"in request?request.onloadend=onloadend:request.onreadystatechange=function handleLoad(){request&&4===request.readyState&&(0!==request.status||request.responseURL&&0===request.responseURL.indexOf("file:"))&&setTimeout(onloadend)},request.onabort=function handleAbort(){request&&(reject(new AxiosError("Request aborted",AxiosError.ECONNABORTED,config,request)),request=null)},request.onerror=function handleError(){reject(new AxiosError("Network Error",AxiosError.ERR_NETWORK,config,request)),request=null},request.ontimeout=function handleTimeout(){let timeoutErrorMessage=_config.timeout?"timeout of "+_config.timeout+"ms exceeded":"timeout exceeded";const transitional=_config.transitional||transitionalDefaults;_config.timeoutErrorMessage&&(timeoutErrorMessage=_config.timeoutErrorMessage),reject(new AxiosError(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,config,request)),request=null},void 0===requestData&&requestHeaders.setContentType(null),"setRequestHeader"in request&&utils$3.forEach(requestHeaders.toJSON(),function setRequestHeader(val,key){request.setRequestHeader(key,val)}),utils$3.isUndefined(_config.withCredentials)||(request.withCredentials=!!_config.withCredentials),responseType&&"json"!==responseType&&(request.responseType=_config.responseType),onDownloadProgress&&([downloadThrottled,flushDownload]=progressEventReducer(onDownloadProgress,!0),request.addEventListener("progress",downloadThrottled)),onUploadProgress&&request.upload&&([uploadThrottled,flushUpload]=progressEventReducer(onUploadProgress),request.upload.addEventListener("progress",uploadThrottled),request.upload.addEventListener("loadend",flushUpload)),(_config.cancelToken||_config.signal)&&(onCanceled=cancel=>{request&&(reject(!cancel||cancel.type?new CanceledError(null,config,request):cancel),request.abort(),request=null)},_config.cancelToken&&_config.cancelToken.subscribe(onCanceled),_config.signal&&(_config.signal.aborted?onCanceled():_config.signal.addEventListener("abort",onCanceled)));const protocol=parseProtocol(_config.url);protocol&&-1===platform.protocols.indexOf(protocol)?reject(new AxiosError("Unsupported protocol "+protocol+":",AxiosError.ERR_BAD_REQUEST,config)):request.send(requestData||null)})};var composeSignals$1=(signals,timeout)=>{const{length:length}=signals=signals?signals.filter(Boolean):[];if(timeout||length){let aborted,controller=new AbortController;const onabort=function(reason){if(!aborted){aborted=!0,unsubscribe();const err=reason instanceof Error?reason:this.reason;controller.abort(err instanceof AxiosError?err:new CanceledError(err instanceof Error?err.message:err))}};let timer=timeout&&setTimeout(()=>{timer=null,onabort(new AxiosError(`timeout ${timeout} of ms exceeded`,AxiosError.ETIMEDOUT))},timeout);const unsubscribe=()=>{signals&&(timer&&clearTimeout(timer),timer=null,signals.forEach(signal=>{signal.unsubscribe?signal.unsubscribe(onabort):signal.removeEventListener("abort",onabort)}),signals=null)};signals.forEach(signal=>signal.addEventListener("abort",onabort));const{signal:signal}=controller;return signal.unsubscribe=()=>utils$3.asap(unsubscribe),signal}};const streamChunk=function*(chunk,chunkSize){let len=chunk.byteLength;if(!chunkSize||len<chunkSize)return void(yield chunk);let end,pos=0;for(;pos<len;)end=pos+chunkSize,yield chunk.slice(pos,end),pos=end},readStream=async function*(stream){if(stream[Symbol.asyncIterator])return void(yield*stream);const reader=stream.getReader();try{for(;;){const{done:done,value:value}=await reader.read();if(done)break;yield value}}finally{await reader.cancel()}},trackStream=(stream,chunkSize,onProgress,onFinish)=>{const iterator=async function*(iterable,chunkSize){for await(const chunk of readStream(iterable))yield*streamChunk(chunk,chunkSize)}(stream,chunkSize);let done,bytes=0,_onFinish=e=>{done||(done=!0,onFinish&&onFinish(e))};return new ReadableStream({async pull(controller){try{const{done:done,value:value}=await iterator.next();if(done)return _onFinish(),void controller.close();let len=value.byteLength;if(onProgress){let loadedBytes=bytes+=len;onProgress(loadedBytes)}controller.enqueue(new Uint8Array(value))}catch(err){throw _onFinish(err),err}},cancel:reason=>(_onFinish(reason),iterator.return())},{highWaterMark:2})},isFetchSupported="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,isReadableStreamSupported=isFetchSupported&&"function"==typeof ReadableStream,encodeText=isFetchSupported&&("function"==typeof TextEncoder?(encoder=new TextEncoder,str=>encoder.encode(str)):async str=>new Uint8Array(await new Response(str).arrayBuffer()));var encoder;const test=(fn,...args)=>{try{return!!fn(...args)}catch(e){return!1}},supportsRequestStream=isReadableStreamSupported&&test(()=>{let duplexAccessed=!1;const hasContentType=new Request(platform.origin,{body:new ReadableStream,method:"POST",get duplex(){return duplexAccessed=!0,"half"}}).headers.has("Content-Type");return duplexAccessed&&!hasContentType}),supportsResponseStream=isReadableStreamSupported&&test(()=>utils$3.isReadableStream(new Response("").body)),resolvers={stream:supportsResponseStream&&(res=>res.body)};var res;isFetchSupported&&(res=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(type=>{!resolvers[type]&&(resolvers[type]=utils$3.isFunction(res[type])?res=>res[type]():(_,config)=>{throw new AxiosError(`Response type '${type}' is not supported`,AxiosError.ERR_NOT_SUPPORT,config)})}));const resolveBodyLength=async(headers,body)=>{const length=utils$3.toFiniteNumber(headers.getContentLength());return null==length?(async body=>{if(null==body)return 0;if(utils$3.isBlob(body))return body.size;if(utils$3.isSpecCompliantForm(body)){const _request=new Request(platform.origin,{method:"POST",body:body});return(await _request.arrayBuffer()).byteLength}return utils$3.isArrayBufferView(body)||utils$3.isArrayBuffer(body)?body.byteLength:(utils$3.isURLSearchParams(body)&&(body+=""),utils$3.isString(body)?(await encodeText(body)).byteLength:void 0)})(body):length};var fetchAdapter=isFetchSupported&&(async config=>{let{url:url,method:method,data:data,signal:signal,cancelToken:cancelToken,timeout:timeout,onDownloadProgress:onDownloadProgress,onUploadProgress:onUploadProgress,responseType:responseType,headers:headers,withCredentials:withCredentials="same-origin",fetchOptions:fetchOptions}=resolveConfig(config);responseType=responseType?(responseType+"").toLowerCase():"text";let request,composedSignal=composeSignals$1([signal,cancelToken&&cancelToken.toAbortSignal()],timeout);const unsubscribe=composedSignal&&composedSignal.unsubscribe&&(()=>{composedSignal.unsubscribe()});let requestContentLength;try{if(onUploadProgress&&supportsRequestStream&&"get"!==method&&"head"!==method&&0!==(requestContentLength=await resolveBodyLength(headers,data))){let contentTypeHeader,_request=new Request(url,{method:"POST",body:data,duplex:"half"});if(utils$3.isFormData(data)&&(contentTypeHeader=_request.headers.get("content-type"))&&headers.setContentType(contentTypeHeader),_request.body){const[onProgress,flush]=progressEventDecorator(requestContentLength,progressEventReducer(asyncDecorator(onUploadProgress)));data=trackStream(_request.body,65536,onProgress,flush)}}utils$3.isString(withCredentials)||(withCredentials=withCredentials?"include":"omit");const isCredentialsSupported="credentials"in Request.prototype;request=new Request(url,{...fetchOptions,signal:composedSignal,method:method.toUpperCase(),headers:headers.normalize().toJSON(),body:data,duplex:"half",credentials:isCredentialsSupported?withCredentials:void 0});let response=await fetch(request,fetchOptions);const isStreamResponse=supportsResponseStream&&("stream"===responseType||"response"===responseType);if(supportsResponseStream&&(onDownloadProgress||isStreamResponse&&unsubscribe)){const options={};["status","statusText","headers"].forEach(prop=>{options[prop]=response[prop]});const responseContentLength=utils$3.toFiniteNumber(response.headers.get("content-length")),[onProgress,flush]=onDownloadProgress&&progressEventDecorator(responseContentLength,progressEventReducer(asyncDecorator(onDownloadProgress),!0))||[];response=new Response(trackStream(response.body,65536,onProgress,()=>{flush&&flush(),unsubscribe&&unsubscribe()}),options)}responseType=responseType||"text";let responseData=await resolvers[utils$3.findKey(resolvers,responseType)||"text"](response,config);return!isStreamResponse&&unsubscribe&&unsubscribe(),await new Promise((resolve,reject)=>{settle(resolve,reject,{data:responseData,headers:AxiosHeaders$1.from(response.headers),status:response.status,statusText:response.statusText,config:config,request:request})})}catch(err){if(unsubscribe&&unsubscribe(),err&&"TypeError"===err.name&&/Load failed|fetch/i.test(err.message))throw Object.assign(new AxiosError("Network Error",AxiosError.ERR_NETWORK,config,request),{cause:err.cause||err});throw AxiosError.from(err,err&&err.code,config,request)}});const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:fetchAdapter};utils$3.forEach(knownAdapters,(fn,value)=>{if(fn){try{Object.defineProperty(fn,"name",{value:value})}catch(e){}Object.defineProperty(fn,"adapterName",{value:value})}});const renderReason=reason=>`- ${reason}`,isResolvedHandle=adapter=>utils$3.isFunction(adapter)||null===adapter||!1===adapter;var adapters_getAdapter=adapters=>{adapters=utils$3.isArray(adapters)?adapters:[adapters];const{length:length}=adapters;let nameOrAdapter,adapter;const rejectedReasons={};for(let i=0;i<length;i++){let id;if(nameOrAdapter=adapters[i],adapter=nameOrAdapter,!isResolvedHandle(nameOrAdapter)&&(adapter=knownAdapters[(id=String(nameOrAdapter)).toLowerCase()],void 0===adapter))throw new AxiosError(`Unknown adapter '${id}'`);if(adapter)break;rejectedReasons[id||"#"+i]=adapter}if(!adapter){const reasons=Object.entries(rejectedReasons).map(([id,state])=>`adapter ${id} `+(!1===state?"is not supported by the environment":"is not available in the build"));throw new AxiosError("There is no suitable adapter to dispatch the request "+(length?reasons.length>1?"since :\n"+reasons.map(renderReason).join("\n"):" "+renderReason(reasons[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return adapter};function throwIfCancellationRequested(config){if(config.cancelToken&&config.cancelToken.throwIfRequested(),config.signal&&config.signal.aborted)throw new CanceledError(null,config)}function dispatchRequest(config){throwIfCancellationRequested(config),config.headers=AxiosHeaders$1.from(config.headers),config.data=transformData.call(config,config.transformRequest),-1!==["post","put","patch"].indexOf(config.method)&&config.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters_getAdapter(config.adapter||defaults$1.adapter)(config).then(function onAdapterResolution(response){return throwIfCancellationRequested(config),response.data=transformData.call(config,config.transformResponse,response),response.headers=AxiosHeaders$1.from(response.headers),response},function onAdapterRejection(reason){return isCancel(reason)||(throwIfCancellationRequested(config),reason&&reason.response&&(reason.response.data=transformData.call(config,config.transformResponse,reason.response),reason.response.headers=AxiosHeaders$1.from(reason.response.headers))),Promise.reject(reason)})}const validators$1={};["object","boolean","number","function","string","symbol"].forEach((type,i)=>{validators$1[type]=function validator(thing){return typeof thing===type||"a"+(i<1?"n ":" ")+type}});const deprecatedWarnings={};validators$1.transitional=function transitional(validator,version,message){function formatMessage(opt,desc){return"[Axios v1.11.0] Transitional option '"+opt+"'"+desc+(message?". "+message:"")}return(value,opt,opts)=>{if(!1===validator)throw new AxiosError(formatMessage(opt," has been removed"+(version?" in "+version:"")),AxiosError.ERR_DEPRECATED);return version&&!deprecatedWarnings[opt]&&(deprecatedWarnings[opt]=!0,console.warn(formatMessage(opt," has been deprecated since v"+version+" and will be removed in the near future"))),!validator||validator(value,opt,opts)}},validators$1.spelling=function spelling(correctSpelling){return(value,opt)=>(console.warn(`${opt} is likely a misspelling of ${correctSpelling}`),!0)};var validator={assertOptions:function assertOptions(options,schema,allowUnknown){if("object"!=typeof options)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);const keys=Object.keys(options);let i=keys.length;for(;i-- >0;){const opt=keys[i],validator=schema[opt];if(validator){const value=options[opt],result=void 0===value||validator(value,opt,options);if(!0!==result)throw new AxiosError("option "+opt+" must be "+result,AxiosError.ERR_BAD_OPTION_VALUE);continue}if(!0!==allowUnknown)throw new AxiosError("Unknown option "+opt,AxiosError.ERR_BAD_OPTION)}},validators:validators$1};const validators=validator.validators;class Axios{constructor(instanceConfig){this.defaults=instanceConfig||{},this.interceptors={request:new InterceptorManager$1,response:new InterceptorManager$1}}async request(configOrUrl,config){try{return await this._request(configOrUrl,config)}catch(err){if(err instanceof Error){let dummy={};Error.captureStackTrace?Error.captureStackTrace(dummy):dummy=new Error;const stack=dummy.stack?dummy.stack.replace(/^.+\n/,""):"";try{err.stack?stack&&!String(err.stack).endsWith(stack.replace(/^.+\n.+\n/,""))&&(err.stack+="\n"+stack):err.stack=stack}catch(e){}}throw err}}_request(configOrUrl,config){"string"==typeof configOrUrl?(config=config||{}).url=configOrUrl:config=configOrUrl||{},config=mergeConfig(this.defaults,config);const{transitional:transitional,paramsSerializer:paramsSerializer,headers:headers}=config;void 0!==transitional&&validator.assertOptions(transitional,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),null!=paramsSerializer&&(utils$3.isFunction(paramsSerializer)?config.paramsSerializer={serialize:paramsSerializer}:validator.assertOptions(paramsSerializer,{encode:validators.function,serialize:validators.function},!0)),void 0!==config.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?config.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:config.allowAbsoluteUrls=!0),validator.assertOptions(config,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),config.method=(config.method||this.defaults.method||"get").toLowerCase();let contextHeaders=headers&&utils$3.merge(headers.common,headers[config.method]);headers&&utils$3.forEach(["delete","get","head","post","put","patch","common"],method=>{delete headers[method]}),config.headers=AxiosHeaders$1.concat(contextHeaders,headers);const requestInterceptorChain=[];let synchronousRequestInterceptors=!0;this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor){"function"==typeof interceptor.runWhen&&!1===interceptor.runWhen(config)||(synchronousRequestInterceptors=synchronousRequestInterceptors&&interceptor.synchronous,requestInterceptorChain.unshift(interceptor.fulfilled,interceptor.rejected))});const responseInterceptorChain=[];let promise;this.interceptors.response.forEach(function pushResponseInterceptors(interceptor){responseInterceptorChain.push(interceptor.fulfilled,interceptor.rejected)});let len,i=0;if(!synchronousRequestInterceptors){const chain=[dispatchRequest.bind(this),void 0];for(chain.unshift(...requestInterceptorChain),chain.push(...responseInterceptorChain),len=chain.length,promise=Promise.resolve(config);i<len;)promise=promise.then(chain[i++],chain[i++]);return promise}len=requestInterceptorChain.length;let newConfig=config;for(i=0;i<len;){const onFulfilled=requestInterceptorChain[i++],onRejected=requestInterceptorChain[i++];try{newConfig=onFulfilled(newConfig)}catch(error){onRejected.call(this,error);break}}try{promise=dispatchRequest.call(this,newConfig)}catch(error){return Promise.reject(error)}for(i=0,len=responseInterceptorChain.length;i<len;)promise=promise.then(responseInterceptorChain[i++],responseInterceptorChain[i++]);return promise}getUri(config){return buildURL(buildFullPath((config=mergeConfig(this.defaults,config)).baseURL,config.url,config.allowAbsoluteUrls),config.params,config.paramsSerializer)}}utils$3.forEach(["delete","get","head","options"],function forEachMethodNoData(method){Axios.prototype[method]=function(url,config){return this.request(mergeConfig(config||{},{method:method,url:url,data:(config||{}).data}))}}),utils$3.forEach(["post","put","patch"],function forEachMethodWithData(method){function generateHTTPMethod(isForm){return function httpMethod(url,data,config){return this.request(mergeConfig(config||{},{method:method,headers:isForm?{"Content-Type":"multipart/form-data"}:{},url:url,data:data}))}}Axios.prototype[method]=generateHTTPMethod(),Axios.prototype[method+"Form"]=generateHTTPMethod(!0)});var Axios$1=Axios;class CancelToken{constructor(executor){if("function"!=typeof executor)throw new TypeError("executor must be a function.");let resolvePromise;this.promise=new Promise(function promiseExecutor(resolve){resolvePromise=resolve});const token=this;this.promise.then(cancel=>{if(!token._listeners)return;let i=token._listeners.length;for(;i-- >0;)token._listeners[i](cancel);token._listeners=null}),this.promise.then=onfulfilled=>{let _resolve;const promise=new Promise(resolve=>{token.subscribe(resolve),_resolve=resolve}).then(onfulfilled);return promise.cancel=function reject(){token.unsubscribe(_resolve)},promise},executor(function cancel(message,config,request){token.reason||(token.reason=new CanceledError(message,config,request),resolvePromise(token.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(listener){this.reason?listener(this.reason):this._listeners?this._listeners.push(listener):this._listeners=[listener]}unsubscribe(listener){if(!this._listeners)return;const index=this._listeners.indexOf(listener);-1!==index&&this._listeners.splice(index,1)}toAbortSignal(){const controller=new AbortController,abort=err=>{controller.abort(err)};return this.subscribe(abort),controller.signal.unsubscribe=()=>this.unsubscribe(abort),controller.signal}static source(){let cancel;return{token:new CancelToken(function executor(c){cancel=c}),cancel:cancel}}}var CancelToken$1=CancelToken;const HttpStatusCode={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode).forEach(([key,value])=>{HttpStatusCode[value]=key});var HttpStatusCode$1=HttpStatusCode;const axios=function createInstance(defaultConfig){const context=new Axios$1(defaultConfig),instance=bind(Axios$1.prototype.request,context);return utils$3.extend(instance,Axios$1.prototype,context,{allOwnKeys:!0}),utils$3.extend(instance,context,null,{allOwnKeys:!0}),instance.create=function create(instanceConfig){return createInstance(mergeConfig(defaultConfig,instanceConfig))},instance}(defaults$1);axios.Axios=Axios$1,axios.CanceledError=CanceledError,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel,axios.VERSION="1.11.0",axios.toFormData=toFormData,axios.AxiosError=AxiosError,axios.Cancel=axios.CanceledError,axios.all=function all(promises){return Promise.all(promises)},axios.spread=function spread(callback){return function wrap(arr){return callback.apply(null,arr)}},axios.isAxiosError=function isAxiosError(payload){return utils$3.isObject(payload)&&!0===payload.isAxiosError},axios.mergeConfig=mergeConfig,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=thing=>formDataToJSON(utils$3.isHTMLForm(thing)?new FormData(thing):thing),axios.getAdapter=adapters_getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;var forge$1,hasRequiredForge,axios$1=axios;class AxiosHttpClient{create(config){return axios$1.create({headers:config.headers,httpsAgent:config.agent,timeout:config.timeout})}}class HttpClientBuilder{config;agent;httpClient;constructor(config,agent,httpClient){this.config=config,this.agent=agent,this.httpClient=httpClient}createHttpClient(){logger.info("Criando client HTTP",{context:"createHttpClient"});try{const axiosConfig={headers:{"Content-Type":"text/xml; charset=utf-8"},httpsAgent:this.agent,timeout:this.config.lib?.connection?.timeout||6e4};return this.httpClient.create(axiosConfig)}catch(error){throw logger.error("Erro ao criar client HTTP",error,{context:"createHttpClient"}),new Error(error.message)}}}class ValidateEnvironment{checkRequiredSettings(config){logger.info("Verificando parâmetros de inicialização",{context:"ValidateEnvironment",config:{pathCertificado:config.dfe.pathCertificado,senhaCertificado:config.dfe.senhaCertificado,ambiente:config.nfe.ambiente}});try{const requiredConfigFields={dfe:["pathCertificado","senhaCertificado"],nfe:["ambiente"]};let missingConfigurations={dfe:[],nfe:[]},errors=[],tableData=[];if(Object.keys(requiredConfigFields).forEach(categoryKey=>{const category=config[categoryKey];if(category){const fields=requiredConfigFields[categoryKey];if(fields){fields.forEach(fieldKey=>{missingConfigurations[categoryKey]||(missingConfigurations[categoryKey]=[]),void 0===category[fieldKey]&&(missingConfigurations[categoryKey]||(missingConfigurations[categoryKey]=[]),missingConfigurations[categoryKey].push(fieldKey))});const missingConfig=missingConfigurations[categoryKey];missingConfig&&missingConfig.length>0&&(errors.push(`Configurações faltando em '${categoryKey}': [${missingConfig.join(", ")}].`),tableData.push({Categoria:categoryKey,Faltando:missingConfig.join(", ")}))}}else errors.push(`Chave principal faltando: '${categoryKey}'.`),tableData.push({Categoria:categoryKey,Faltando:"Chave principal faltando"})}),errors.length>0)throw console.log("Configurações necessárias faltando:"),console.table(tableData),new Error(`Erro ao validar configurações: ${errors.join(" ")}`);return{missingConfigurations:missingConfigurations,message:"Todas as configurações necessárias estão presentes.",success:!0}}catch(error){throw logger.error("Erro ao inicializar ambiente",error,{context:"ValidateEnvironment",method:"checkRequiredSettings"}),new Error(`Erro ao inicializar ambiente: ${error.message}`)}}}function requireForge(){return hasRequiredForge?forge$1:(hasRequiredForge=1,forge$1={options:{usePureJavaScript:!1}})}var baseN,hasRequiredBaseN,hasRequiredUtil,cipher,hasRequiredCipher,util={exports:{}};function requireBaseN(){if(hasRequiredBaseN)return baseN;hasRequiredBaseN=1;var api={};baseN=api;var _reverseAlphabets={};return api.encode=function(input,alphabet,maxline){if("string"!=typeof alphabet)throw new TypeError('"alphabet" must be a string.');if(void 0!==maxline&&"number"!=typeof maxline)throw new TypeError('"maxline" must be a number.');var output="";if(input instanceof Uint8Array){var i=0,base=alphabet.length,first=alphabet.charAt(0),digits=[0];for(i=0;i<input.length;++i){for(var j=0,carry=input[i];j<digits.length;++j)carry+=digits[j]<<8,digits[j]=carry%base,carry=carry/base|0;for(;carry>0;)digits.push(carry%base),carry=carry/base|0}for(i=0;0===input[i]&&i<input.length-1;++i)output+=first;for(i=digits.length-1;i>=0;--i)output+=alphabet[digits[i]]}else output=function _encodeWithByteBuffer(input,alphabet){var i=0,base=alphabet.length,first=alphabet.charAt(0),digits=[0];for(i=0;i<input.length();++i){for(var j=0,carry=input.at(i);j<digits.length;++j)carry+=digits[j]<<8,digits[j]=carry%base,carry=carry/base|0;for(;carry>0;)digits.push(carry%base),carry=carry/base|0}var output="";for(i=0;0===input.at(i)&&i<input.length()-1;++i)output+=first;for(i=digits.length-1;i>=0;--i)output+=alphabet[digits[i]];return output}(input,alphabet);if(maxline){var regex=new RegExp(".{1,"+maxline+"}","g");output=output.match(regex).join("\r\n")}return output},api.decode=function(input,alphabet){if("string"!=typeof input)throw new TypeError('"input" must be a string.');if("string"!=typeof alphabet)throw new TypeError('"alphabet" must be a string.');var table=_reverseAlphabets[alphabet];if(!table){table=_reverseAlphabets[alphabet]=[];for(var i=0;i<alphabet.length;++i)table[alphabet.charCodeAt(i)]=i}input=input.replace(/\s/g,"");var base=alphabet.length,first=alphabet.charAt(0),bytes=[0];for(i=0;i<input.length;i++){var value=table[input.charCodeAt(i)];if(void 0===value)return;for(var j=0,carry=value;j<bytes.length;++j)carry+=bytes[j]*base,bytes[j]=255&carry,carry>>=8;for(;carry>0;)bytes.push(255&carry),carry>>=8}for(var k=0;input[k]===first&&k<input.length-1;++k)bytes.push(0);return"undefined"!=typeof Buffer?Buffer.from(bytes.reverse()):new Uint8Array(bytes.reverse())},baseN}function requireUtil(){if(hasRequiredUtil)return util.exports;hasRequiredUtil=1;var forge=requireForge(),baseN=requireBaseN(),util$1=util.exports=forge.util=forge.util||{};function _checkBitsParam(n){if(8!==n&&16!==n&&24!==n&&32!==n)throw new Error("Only 8, 16, 24, or 32 bits supported: "+n)}function ByteStringBuffer(b){if(this.data="",this.read=0,"string"==typeof b)this.data=b;else if(util$1.isArrayBuffer(b)||util$1.isArrayBufferView(b))if("undefined"!=typeof Buffer&&b instanceof Buffer)this.data=b.toString("binary");else{var arr=new Uint8Array(b);try{this.data=String.fromCharCode.apply(null,arr)}catch(e){for(var i=0;i<arr.length;++i)this.putByte(arr[i])}}else(b instanceof ByteStringBuffer||"object"==typeof b&&"string"==typeof b.data&&"number"==typeof b.read)&&(this.data=b.data,this.read=b.read);this._constructedStringLength=0}!function(){if("undefined"!=typeof process&&process.nextTick&&!process.browser)return util$1.nextTick=process.nextTick,void("function"==typeof setImmediate?util$1.setImmediate=setImmediate:util$1.setImmediate=util$1.nextTick);if("function"==typeof setImmediate)return util$1.setImmediate=function(){return setImmediate.apply(void 0,arguments)},void(util$1.nextTick=function(callback){return setImmediate(callback)});if(util$1.setImmediate=function(callback){setTimeout(callback,0)},"undefined"!=typeof window&&"function"==typeof window.postMessage){var msg="forge.setImmediate",callbacks=[];function handler(event){if(event.source===window&&event.data===msg){event.stopPropagation();var copy=callbacks.slice();callbacks.length=0,copy.forEach(function(callback){callback()})}}util$1.setImmediate=function(callback){callbacks.push(callback),1===callbacks.length&&window.postMessage(msg,"*")},window.addEventListener("message",handler,!0)}if("undefined"!=typeof MutationObserver){var now=Date.now(),attr=!0,div=document.createElement("div");callbacks=[];new MutationObserver(function(){var copy=callbacks.slice();callbacks.length=0,copy.forEach(function(callback){callback()})}).observe(div,{attributes:!0});var oldSetImmediate=util$1.setImmediate;util$1.setImmediate=function(callback){Date.now()-now>15?(now=Date.now(),oldSetImmediate(callback)):(callbacks.push(callback),1===callbacks.length&&div.setAttribute("a",attr=!attr))}}util$1.nextTick=util$1.setImmediate}(),util$1.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,util$1.globalScope=util$1.isNodejs?commonjsGlobal:"undefined"==typeof self?window:self,util$1.isArray=Array.isArray||function(x){return"[object Array]"===Object.prototype.toString.call(x)},util$1.isArrayBuffer=function(x){return"undefined"!=typeof ArrayBuffer&&x instanceof ArrayBuffer},util$1.isArrayBufferView=function(x){return x&&util$1.isArrayBuffer(x.buffer)&&void 0!==x.byteLength},util$1.ByteBuffer=ByteStringBuffer,util$1.ByteStringBuffer=ByteStringBuffer;util$1.ByteStringBuffer.prototype._optimizeConstructedString=function(x){this._constructedStringLength+=x,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},util$1.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},util$1.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},util$1.ByteStringBuffer.prototype.putByte=function(b){return this.putBytes(String.fromCharCode(b))},util$1.ByteStringBuffer.prototype.fillWithByte=function(b,n){b=String.fromCharCode(b);for(var d=this.data;n>0;)1&n&&(d+=b),(n>>>=1)>0&&(b+=b);return this.data=d,this._optimizeConstructedString(n),this},util$1.ByteStringBuffer.prototype.putBytes=function(bytes){return this.data+=bytes,this._optimizeConstructedString(bytes.length),this},util$1.ByteStringBuffer.prototype.putString=function(str){return this.putBytes(util$1.encodeUtf8(str))},util$1.ByteStringBuffer.prototype.putInt16=function(i){return this.putBytes(String.fromCharCode(i>>8&255)+String.fromCharCode(255&i))},util$1.ByteStringBuffer.prototype.putInt24=function(i){return this.putBytes(String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(255&i))},util$1.ByteStringBuffer.prototype.putInt32=function(i){return this.putBytes(String.fromCharCode(i>>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(255&i))},util$1.ByteStringBuffer.prototype.putInt16Le=function(i){return this.putBytes(String.fromCharCode(255&i)+String.fromCharCode(i>>8&255))},util$1.ByteStringBuffer.prototype.putInt24Le=function(i){return this.putBytes(String.fromCharCode(255&i)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255))},util$1.ByteStringBuffer.prototype.putInt32Le=function(i){return this.putBytes(String.fromCharCode(255&i)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>24&255))},util$1.ByteStringBuffer.prototype.putInt=function(i,n){_checkBitsParam(n);var bytes="";do{n-=8,bytes+=String.fromCharCode(i>>n&255)}while(n>0);return this.putBytes(bytes)},util$1.ByteStringBuffer.prototype.putSignedInt=function(i,n){return i<0&&(i+=2<<n-1),this.putInt(i,n)},util$1.ByteStringBuffer.prototype.putBuffer=function(buffer){return this.putBytes(buffer.getBytes())},util$1.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},util$1.ByteStringBuffer.prototype.getInt16=function(){var rval=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,rval},util$1.ByteStringBuffer.prototype.getInt24=function(){var rval=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,rval},util$1.ByteStringBuffer.prototype.getInt32=function(){var rval=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,rval},util$1.ByteStringBuffer.prototype.getInt16Le=function(){var rval=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,rval},util$1.ByteStringBuffer.prototype.getInt24Le=function(){var rval=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,rval},util$1.ByteStringBuffer.prototype.getInt32Le=function(){var rval=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,rval},util$1.ByteStringBuffer.prototype.getInt=function(n){_checkBitsParam(n);var rval=0;do{rval=(rval<<8)+this.data.charCodeAt(this.read++),n-=8}while(n>0);return rval},util$1.ByteStringBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n),max=2<<n-2;return x>=max&&(x-=max<<1),x},util$1.ByteStringBuffer.prototype.getBytes=function(count){var rval;return count?(count=Math.min(this.length(),count),rval=this.data.slice(this.read,this.read+count),this.read+=count):0===count?rval="":(rval=0===this.read?this.data:this.data.slice(this.read),this.clear()),rval},util$1.ByteStringBuffer.prototype.bytes=function(count){return void 0===count?this.data.slice(this.read):this.data.slice(this.read,this.read+count)},util$1.ByteStringBuffer.prototype.at=function(i){return this.data.charCodeAt(this.read+i)},util$1.ByteStringBuffer.prototype.setAt=function(i,b){return this.data=this.data.substr(0,this.read+i)+String.fromCharCode(b)+this.data.substr(this.read+i+1),this},util$1.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},util$1.ByteStringBuffer.prototype.copy=function(){var c=util$1.createBuffer(this.data);return c.read=this.read,c},util$1.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},util$1.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},util$1.ByteStringBuffer.prototype.truncate=function(count){var len=Math.max(0,this.length()-count);return this.data=this.data.substr(this.read,len),this.read=0,this},util$1.ByteStringBuffer.prototype.toHex=function(){for(var rval="",i=this.read;i<this.data.length;++i){var b=this.data.charCodeAt(i);b<16&&(rval+="0"),rval+=b.toString(16)}return rval},util$1.ByteStringBuffer.prototype.toString=function(){return util$1.decodeUtf8(this.bytes())},util$1.DataBuffer=function DataBuffer(b,options){options=options||{},this.read=options.readOffset||0,this.growSize=options.growSize||1024;var isArrayBuffer=util$1.isArrayBuffer(b),isArrayBufferView=util$1.isArrayBufferView(b);if(isArrayBuffer||isArrayBufferView)return this.data=isArrayBuffer?new DataView(b):new DataView(b.buffer,b.byteOffset,b.byteLength),void(this.write="writeOffset"in options?options.writeOffset:this.data.byteLength);this.data=new DataView(new ArrayBuffer(0)),this.write=0,null!=b&&this.putBytes(b),"writeOffset"in options&&(this.write=options.writeOffset)},util$1.DataBuffer.prototype.length=function(){return this.write-this.read},util$1.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},util$1.DataBuffer.prototype.accommodate=function(amount,growSize){if(this.length()>=amount)return this;growSize=Math.max(growSize||this.growSize,amount);var src=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),dst=new Uint8Array(this.length()+growSize);return dst.set(src),this.data=new DataView(dst.buffer),this},util$1.DataBuffer.prototype.putByte=function(b){return this.accommodate(1),this.data.setUint8(this.write++,b),this},util$1.DataBuffer.prototype.fillWithByte=function(b,n){this.accommodate(n);for(var i=0;i<n;++i)this.data.setUint8(b);return this},util$1.DataBuffer.prototype.putBytes=function(bytes,encoding){if(util$1.isArrayBufferView(bytes)){var len=(src=new Uint8Array(bytes.buffer,bytes.byteOffset,bytes.byteLength)).byteLength-src.byteOffset;return this.accommodate(len),new Uint8Array(this.data.buffer,this.write).set(src),this.write+=len,this}if(util$1.isArrayBuffer(bytes)){var src=new Uint8Array(bytes);return this.accommodate(src.byteLength),new Uint8Array(this.data.buffer).set(src,this.write),this.write+=src.byteLength,this}if(bytes instanceof util$1.DataBuffer||"object"==typeof bytes&&"number"==typeof bytes.read&&"number"==typeof bytes.write&&util$1.isArrayBufferView(bytes.data)){src=new Uint8Array(bytes.data.byteLength,bytes.read,bytes.length());return this.accommodate(src.byteLength),new Uint8Array(bytes.data.byteLength,this.write).set(src),this.write+=src.byteLength,this}if(bytes instanceof util$1.ByteStringBuffer&&(bytes=bytes.data,encoding="binary"),encoding=encoding||"binary","string"==typeof bytes){var view;if("hex"===encoding)return this.accommodate(Math.ceil(bytes.length/2)),view=new Uint8Array(this.data.buffer,this.write),this.write+=util$1.binary.hex.decode(bytes,view,this.write),this;if("base64"===encoding)return this.accommodate(3*Math.ceil(bytes.length/4)),view=new Uint8Array(this.data.buffer,this.write),this.write+=util$1.binary.base64.decode(bytes,view,this.write),this;if("utf8"===encoding&&(bytes=util$1.encodeUtf8(bytes),encoding="binary"),"binary"===encoding||"raw"===encoding)return this.accommodate(bytes.length),view=new Uint8Array(this.data.buffer,this.write),this.write+=util$1.binary.raw.decode(view),this;if("utf16"===encoding)return this.accommodate(2*bytes.length),view=new Uint16Array(this.data.buffer,this.write),this.write+=util$1.text.utf16.encode(view),this;throw new Error("Invalid encoding: "+encoding)}throw Error("Invalid parameter: "+bytes)},util$1.DataBuffer.prototype.putBuffer=function(buffer){return this.putBytes(buffer),buffer.clear(),this},util$1.DataBuffer.prototype.putString=function(str){return this.putBytes(str,"utf16")},util$1.DataBuffer.prototype.putInt16=function(i){return this.accommodate(2),this.data.setInt16(this.write,i),this.write+=2,this},util$1.DataBuffer.prototype.putInt24=function(i){return this.accommodate(3),this.data.setInt16(this.write,i>>8&65535),this.data.setInt8(this.write,i>>16&255),this.write+=3,this},util$1.DataBuffer.prototype.putInt32=function(i){return this.accommodate(4),this.data.setInt32(this.write,i),this.write+=4,this},util$1.DataBuffer.prototype.putInt16Le=function(i){return this.accommodate(2),this.data.setInt16(this.write,i,!0),this.write+=2,this},util$1.DataBuffer.prototype.putInt24Le=function(i){return this.accommodate(3),this.data.setInt8(this.write,i>>16&255),this.data.setInt16(this.write,i>>8&65535,!0),this.write+=3,this},util$1.DataBuffer.prototype.putInt32Le=function(i){return this.accommodate(4),this.data.setInt32(this.write,i,!0),this.write+=4,this},util$1.DataBuffer.prototype.putInt=function(i,n){_checkBitsParam(n),this.accommodate(n/8);do{n-=8,this.data.setInt8(this.write++,i>>n&255)}while(n>0);return this},util$1.DataBuffer.prototype.putSignedInt=function(i,n){return _checkBitsParam(n),this.accommodate(n/8),i<0&&(i+=2<<n-1),this.putInt(i,n)},util$1.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},util$1.DataBuffer.prototype.getInt16=function(){var rval=this.data.getInt16(this.read);return this.read+=2,rval},util$1.DataBuffer.prototype.getInt24=function(){var rval=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,rval},util$1.DataBuffer.prototype.getInt32=function(){var rval=this.data.getInt32(this.read);return this.read+=4,rval},util$1.DataBuffer.prototype.getInt16Le=function(){var rval=this.data.getInt16(this.read,!0);return this.read+=2,rval},util$1.DataBuffer.prototype.getInt24Le=function(){var rval=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,rval},util$1.DataBuffer.prototype.getInt32Le=function(){var rval=this.data.getInt32(this.read,!0);return this.read+=4,rval},util$1.DataBuffer.prototype.getInt=function(n){_checkBitsParam(n);var rval=0;do{rval=(rval<<8)+this.data.getInt8(this.read++),n-=8}while(n>0);return rval},util$1.DataBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n),max=2<<n-2;return x>=max&&(x-=max<<1),x},util$1.DataBuffer.prototype.getBytes=function(count){var rval;return count?(count=Math.min(this.length(),count),rval=this.data.slice(this.read,this.read+count),this.read+=count):0===count?rval="":(rval=0===this.read?this.data:this.data.slice(this.read),this.clear()),rval},util$1.DataBuffer.prototype.bytes=function(count){return void 0===count?this.data.slice(this.read):this.data.slice(this.read,this.read+count)},util$1.DataBuffer.prototype.at=function(i){return this.data.getUint8(this.read+i)},util$1.DataBuffer.prototype.setAt=function(i,b){return this.data.setUint8(i,b),this},util$1.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},util$1.DataBuffer.prototype.copy=function(){return new util$1.DataBuffer(this)},util$1.DataBuffer.prototype.compact=function(){if(this.read>0){var src=new Uint8Array(this.data.buffer,this.read),dst=new Uint8Array(src.byteLength);dst.set(src),this.data=new DataView(dst),this.write-=this.read,this.read=0}return this},util$1.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},util$1.DataBuffer.prototype.truncate=function(count){return this.write=Math.max(0,this.length()-count),this.read=Math.min(this.read,this.write),this},util$1.DataBuffer.prototype.toHex=function(){for(var rval="",i=this.read;i<this.data.byteLength;++i){var b=this.data.getUint8(i);b<16&&(rval+="0"),rval+=b.toString(16)}return rval},util$1.DataBuffer.prototype.toString=function(encoding){var view=new Uint8Array(this.data,this.read,this.length());if("binary"===(encoding=encoding||"utf8")||"raw"===encoding)return util$1.binary.raw.encode(view);if("hex"===encoding)return util$1.binary.hex.encode(view);if("base64"===encoding)return util$1.binary.base64.encode(view);if("utf8"===encoding)return util$1.text.utf8.decode(view);if("utf16"===encoding)return util$1.text.utf16.decode(view);throw new Error("Invalid encoding: "+encoding)},util$1.createBuffer=function(input,encoding){return encoding=encoding||"raw",void 0!==input&&"utf8"===encoding&&(input=util$1.encodeUtf8(input)),new util$1.ByteBuffer(input)},util$1.fillString=function(c,n){for(var s="";n>0;)1&n&&(s+=c),(n>>>=1)>0&&(c+=c);return s},util$1.xorBytes=function(s1,s2,n){for(var s3="",b="",t="",i=0,c=0;n>0;--n,++i)b=s1.charCodeAt(i)^s2.charCodeAt(i),c>=10&&(s3+=t,t="",c=0),t+=String.fromCharCode(b),++c;return s3+=t},util$1.hexToBytes=function(hex){var rval="",i=0;for(!0&hex.length&&(i=1,rval+=String.fromCharCode(parseInt(hex[0],16)));i<hex.length;i+=2)rval+=String.fromCharCode(parseInt(hex.substr(i,2),16));return rval},util$1.bytesToHex=function(bytes){return util$1.createBuffer(bytes).toHex()},util$1.int32ToBytes=function(i){return String.fromCharCode(i>>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(255&i)};var _base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_base64Idx=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],_base58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";util$1.encode64=function(input,maxline){for(var chr1,chr2,chr3,line="",output="",i=0;i<input.length;)chr1=input.charCodeAt(i++),chr2=input.charCodeAt(i++),chr3=input.charCodeAt(i++),line+=_base64.charAt(chr1>>2),line+=_base64.charAt((3&chr1)<<4|chr2>>4),isNaN(chr2)?line+="==":(line+=_base64.charAt((15&chr2)<<2|chr3>>6),line+=isNaN(chr3)?"=":_base64.charAt(63&chr3)),maxline&&line.length>maxline&&(output+=line.substr(0,maxline)+"\r\n",line=line.substr(maxline));return output+=line},util$1.decode64=function(input){input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var enc1,enc2,enc3,enc4,output="",i=0;i<input.length;)enc1=_base64Idx[input.charCodeAt(i++)-43],enc2=_base64Idx[input.charCodeAt(i++)-43],enc3=_base64Idx[input.charCodeAt(i++)-43],enc4=_base64Idx[input.charCodeAt(i++)-43],output+=String.fromCharCode(enc1<<2|enc2>>4),64!==enc3&&(output+=String.fromCharCode((15&enc2)<<4|enc3>>2),64!==enc4&&(output+=String.fromCharCode((3&enc3)<<6|enc4)));return output},util$1.encodeUtf8=function(str){return unescape(encodeURIComponent(str))},util$1.decodeUtf8=function(str){return decodeURIComponent(escape(str))},util$1.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:baseN.encode,decode:baseN.decode}},util$1.binary.raw.encode=function(bytes){return String.fromCharCode.apply(null,bytes)},util$1.binary.raw.decode=function(str,output,offset){var out=output;out||(out=new Uint8Array(str.length));for(var j=offset=offset||0,i=0;i<str.length;++i)out[j++]=str.charCodeAt(i);return output?j-offset:out},util$1.binary.hex.encode=util$1.bytesToHex,util$1.binary.hex.decode=function(hex,output,offset){var out=output;out||(out=new Uint8Array(Math.ceil(hex.length/2)));var i=0,j=offset=offset||0;for(1&hex.length&&(i=1,out[j++]=parseInt(hex[0],16));i<hex.length;i+=2)out[j++]=parseInt(hex.substr(i,2),16);return output?j-offset:out},util$1.binary.base64.encode=function(input,maxline){for(var chr1,chr2,chr3,line="",output="",i=0;i<input.byteLength;)chr1=input[i++],chr2=input[i++],chr3=input[i++],line+=_base64.charAt(chr1>>2),line+=_base64.charAt((3&chr1)<<4|chr2>>4),isNaN(chr2)?line+="==":(line+=_base64.charAt((15&chr2)<<2|chr3>>6),line+=isNaN(chr3)?"=":_base64.charAt(63&chr3)),maxline&&line.length>maxline&&(output+=line.substr(0,maxline)+"\r\n",line=line.substr(maxline));return output+=line},util$1.binary.base64.decode=function(input,output,offset){var enc1,enc2,enc3,enc4,out=output;out||(out=new Uint8Array(3*Math.ceil(input.length/4))),input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var i=0,j=offset=offset||0;i<input.length;)enc1=_base64Idx[input.charCodeAt(i++)-43],enc2=_base64Idx[input.charCodeAt(i++)-43],enc3=_base64Idx[input.charCodeAt(i++)-43],enc4=_base64Idx[input.charCodeAt(i++)-43],out[j++]=enc1<<2|enc2>>4,64!==enc3&&(out[j++]=(15&enc2)<<4|enc3>>2,64!==enc4&&(out[j++]=(3&enc3)<<6|enc4));return output?j-offset:out.subarray(0,j)},util$1.binary.base58.encode=function(input,maxline){return util$1.binary.baseN.encode(input,_base58,maxline)},util$1.binary.base58.decode=function(input,maxline){return util$1.binary.baseN.decode(input,_base58,maxline)},util$1.text={utf8:{},utf16:{}},util$1.text.utf8.encode=function(str,output,offset){str=util$1.encodeUtf8(str);var out=output;out||(out=new Uint8Array(str.length));for(var j=offset=offset||0,i=0;i<str.length;++i)out[j++]=str.charCodeAt(i);return output?j-offset:out},util$1.text.utf8.decode=function(bytes){return util$1.decodeUtf8(String.fromCharCode.apply(null,bytes))},util$1.text.utf16.encode=function(str,output,offset){var out=output;out||(out=new Uint8Array(2*str.length));for(var view=new Uint16Array(out.buffer),j=offset=offset||0,k=offset,i=0;i<str.length;++i)view[k++]=str.charCodeAt(i),j+=2;return output?j-offset:out},util$1.text.utf16.decode=function(bytes){return String.fromCharCode.apply(null,new Uint16Array(bytes.buffer))},util$1.deflate=function(api,bytes,raw){if(bytes=util$1.decode64(api.deflate(util$1.encode64(bytes)).rval),raw){var start=2;32&bytes.charCodeAt(1)&&(start=6),bytes=bytes.substring(start,bytes.length-4)}return bytes},util$1.inflate=function(api,bytes,raw){var rval=api.inflate(util$1.encode64(bytes)).rval;return null===rval?null:util$1.decode64(rval)};var _setStorageObject=function(api,id,obj){if(!api)throw new Error("WebStorage not available.");var rval;if(null===obj?rval=api.removeItem(id):(obj=util$1.encode64(JSON.stringify(obj)),rval=api.setItem(id,obj)),void 0!==rval&&!0!==rval.rval){var error=new Error(rval.error.message);throw error.id=rval.error.id,error.name=rval.error.name,error}},_getStorageObject=function(api,id){if(!api)throw new Error("WebStorage not available.");var rval=api.getItem(id);if(api.init)if(null===rval.rval){if(rval.error){var error=new Error(rval.error.message);throw error.id=rval.error.id,error.name=rval.error.name,error}rval=null}else rval=rval.rval;return null!==rval&&(rval=JSON.parse(util$1.decode64(rval))),rval},_setItem=function(api,id,key,data){var obj=_getStorageObject(api,id);null===obj&&(obj={}),obj[key]=data,_setStorageObject(api,id,obj)},_getItem=function(api,id,key){var rval=_getStorageObject(api,id);return null!==rval&&(rval=key in rval?rval[key]:null),rval},_removeItem=function(api,id,key){var obj=_getStorageObject(api,id);if(null!==obj&&key in obj){delete obj[key];var empty=!0;for(var prop in obj){empty=!1;break}empty&&(obj=null),_setStorageObject(api,id,obj)}},_clearItems=function(api,id){_setStorageObject(api,id,null)},_callStorageFunction=function(func,args,location){var type,rval=null;void 0===location&&(location=["web","flash"]);var done=!1,exception=null;for(var idx in location){type=location[idx];try{if("flash"===type||"both"===type){if(null===args[0])throw new Error("Flash local storage not available.");rval=func.apply(this,args),done="flash"===type}"web"!==type&&"both"!==type||(args[0]=localStorage,rval=func.apply(this,args),done=!0)}catch(ex){exception=ex}if(done)break}if(!done)throw exception;return rval};return util$1.setItem=function(api,id,key,data,location){_callStorageFunction(_setItem,arguments,location)},util$1.getItem=function(api,id,key,location){return _callStorageFunction(_getItem,arguments,location)},util$1.removeItem=function(api,id,key,location){_callStorageFunction(_removeItem,arguments,location)},util$1.clearItems=function(api,id,location){_callStorageFunction(_clearItems,arguments,location)},util$1.isEmpty=function(obj){for(var prop in obj)if(obj.hasOwnProperty(prop))return!1;return!0},util$1.format=function(format){for(var match,part,re=/%./g,argi=0,parts=[],last=0;match=re.exec(format);){(part=format.substring(last,re.lastIndex-2)).length>0&&parts.push(part),last=re.lastIndex;var code=match[0][1];switch(code){case"s":case"o":argi<arguments.length?parts.push(arguments[1+argi++]):parts.push("<?>");break;case"%":parts.push("%");break;default:parts.push("<%"+code+"?>")}}return parts.push(format.substring(last)),parts.join("")},util$1.formatNumber=function(number,decimals,dec_point,thousands_sep){var n=number,c=isNaN(decimals=Math.abs(decimals))?2:decimals,d=void 0===dec_point?",":dec_point,t=void 0===thousands_sep?".":thousands_sep,s=n<0?"-":"",i=parseInt(n=Math.abs(+n||0).toFixed(c),10)+"",j=i.length>3?i.length%3:0;return s+(j?i.substr(0,j)+t:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+t)+(c?d+Math.abs(n-i).toFixed(c).slice(2):"")},util$1.formatSize=function(size){return size=size>=1073741824?util$1.formatNumber(size/1073741824,2,".","")+" GiB":size>=1048576?util$1.formatNumber(size/1048576,2,".","")+" MiB":size>=1024?util$1.formatNumber(size/1024,0)+" KiB":util$1.formatNumber(size,0)+" bytes"},util$1.bytesFromIP=function(ip){return-1!==ip.indexOf(".")?util$1.bytesFromIPv4(ip):-1!==ip.indexOf(":")?util$1.bytesFromIPv6(ip):null},util$1.bytesFromIPv4=function(ip){if(4!==(ip=ip.split(".")).length)return null;for(var b=util$1.createBuffer(),i=0;i<ip.length;++i){var num=parseInt(ip[i],10);if(isNaN(num))return null;b.putByte(num)}return b.getBytes()},util$1.bytesFromIPv6=function(ip){for(var blanks=0,zeros=2*(8-(ip=ip.split(":").filter(function(e){return 0===e.length&&++blanks,!0})).length+blanks),b=util$1.createBuffer(),i=0;i<8;++i)if(ip[i]&&0!==ip[i].length){var bytes=util$1.hexToBytes(ip[i]);bytes.length<2&&b.putByte(0),b.putBytes(bytes)}else b.fillWithByte(0,zeros),zeros=0;return b.getBytes()},util$1.bytesToIP=function(bytes){return 4===bytes.length?util$1.bytesToIPv4(bytes):16===bytes.length?util$1.bytesToIPv6(bytes):null},util$1.bytesToIPv4=function(bytes){if(4!==bytes.length)return null;for(var ip=[],i=0;i<bytes.length;++i)ip.push(bytes.charCodeAt(i));return ip.join(".")},util$1.bytesToIPv6=function(bytes){if(16!==bytes.length)return null;for(var ip=[],zeroGroups=[],zeroMaxGroup=0,i=0;i<bytes.length;i+=2){for(var hex=util$1.bytesToHex(bytes[i]+bytes[i+1]);"0"===hex[0]&&"0"!==hex;)hex=hex.substr(1);if("0"===hex){var last=zeroGroups[zeroGroups.length-1],idx=ip.length;last&&idx===last.end+1?(last.end=idx,last.end-last.start>zeroGroups[zeroMaxGroup].end-zeroGroups[zeroMaxGroup].start&&(zeroMaxGroup=zeroGroups.length-1)):zeroGroups.push({start:idx,end:idx})}ip.push(hex)}if(zeroGroups.length>0){var group=zeroGroups[zeroMaxGroup];group.end-group.start>0&&(ip.splice(group.start,group.end-group.start+1,""),0===group.start&&ip.unshift(""),7===group.end&&ip.push(""))}return ip.join(":")},util$1.estimateCores=function(options,callback){if("function"==typeof options&&(callback=options,options={}),options=options||{},"cores"in util$1&&!options.update)return callback(null,util$1.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return util$1.cores=navigator.hardwareConcurrency,callback(null,util$1.cores);if("undefined"==typeof Worker)return util$1.cores=1,callback(null,util$1.cores);if("undefined"==typeof Blob)return util$1.cores=2,callback(null,util$1.cores);var blobUrl=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){var st=Date.now(),et=st+4;self.postMessage({st:st,et:et})})}.toString(),")()"],{type:"application/javascript"}));!function sample(max,samples,numWorkers){if(0===samples){var avg=Math.floor(max.reduce(function(avg,x){return avg+x},0)/max.length);return util$1.cores=Math.max(1,avg),URL.revokeObjectURL(blobUrl),callback(null,util$1.cores)}!function map(numWorkers,callback){for(var workers=[],results=[],i=0;i<numWorkers;++i){var worker=new Worker(blobUrl);worker.addEventListener("message",function(e){if(results.push(e.data),results.length===numWorkers){for(var i=0;i<numWorkers;++i)workers[i].terminate();callback(null,results)}}),workers.push(worker)}for(i=0;i<numWorkers;++i)workers[i].postMessage(i)}(numWorkers,function(err,results){max.push(function reduce(numWorkers,results){for(var overlaps=[],n=0;n<numWorkers;++n)for(var r1=results[n],overlap=overlaps[n]=[],i=0;i<numWorkers;++i)if(n!==i){var r2=results[i];(r1.st>r2.st&&r1.st<r2.et||r2.st>r1.st&&r2.st<r1.et)&&overlap.push(i)}return overlaps.reduce(function(max,overlap){return Math.max(max,overlap.length)},0)}(numWorkers,results)),sample(max,samples-1,numWorkers)})}([],5,16)},util.exports}function requireCipher(){if(hasRequiredCipher)return cipher;hasRequiredCipher=1;var forge=requireForge();requireUtil(),cipher=forge.cipher=forge.cipher||{},forge.cipher.algorithms=forge.cipher.algorithms||{},forge.cipher.createCipher=function(algorithm,key){var api=algorithm;if("string"==typeof api&&(api=forge.cipher.getAlgorithm(api))&&(api=api()),!api)throw new Error("Unsupported algorithm: "+algorithm);return new forge.cipher.BlockCipher({algorithm:api,key:key,decrypt:!1})},forge.cipher.createDecipher=function(algorithm,key){var api=algorithm;if("string"==typeof api&&(api=forge.cipher.getAlgorithm(api))&&(api=api()),!api)throw new Error("Unsupported algorithm: "+algorithm);return new forge.cipher.BlockCipher({algorithm:api,key:key,decrypt:!0})},forge.cipher.registerAlgorithm=function(name,algorithm){name=name.toUpperCase(),forge.cipher.algorithms[name]=algorithm},forge.cipher.getAlgorithm=function(name){return(name=name.toUpperCase())in forge.cipher.algorithms?forge.cipher.algorithms[name]:null};var BlockCipher=forge.cipher.BlockCipher=function(options){this.algorithm=options.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=options.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=options.decrypt,this.algorithm.initialize(options)};return BlockCipher.prototype.start=function(options){options=options||{};var opts={};for(var key in options)opts[key]=options[key];opts.decrypt=this._decrypt,this._finish=!1,this._input=forge.util.createBuffer(),this.output=options.output||forge.util.createBuffer(),this.mode.start(opts)},BlockCipher.prototype.update=function(input){for(input&&this._input.putBuffer(input);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},BlockCipher.prototype.finish=function(pad){!pad||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(input){return pad(this.blockSize,input,!1)},this.mode.unpad=function(output){return pad(this.blockSize,output,!0)});var options={};return options.decrypt=this._decrypt,options.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,options))&&(this._finish=!0,this.update(),!(this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,options))&&!(this.mode.afterFinish&&!this.mode.afterFinish(this.output,options)))},cipher}var hasRequiredCipherModes,aes,hasRequiredAes,cipherModes={exports:{}};function requireCipherModes(){if(hasRequiredCipherModes)return cipherModes.exports;hasRequiredCipherModes=1;var forge=requireForge();requireUtil(),forge.cipher=forge.cipher||{};var modes=cipherModes.exports=forge.cipher.modes=forge.cipher.modes||{};function transformIV(iv,blockSize){if("string"==typeof iv&&(iv=forge.util.createBuffer(iv)),forge.util.isArray(iv)&&iv.length>4){var tmp=iv;iv=forge.util.createBuffer();for(var i=0;i<tmp.length;++i)iv.putByte(tmp[i])}if(iv.length()<blockSize)throw new Error("Invalid IV length; got "+iv.length()+" bytes and expected "+blockSize+" bytes.");if(!forge.util.isArray(iv)){var ints=[],blocks=blockSize/4;for(i=0;i<blocks;++i)ints.push(iv.getInt32());iv=ints}return iv}function inc32(block){block[block.length-1]=block[block.length-1]+1&4294967295}function from64To32(num){return[num/4294967296|0,4294967295&num]}return modes.ecb=function(options){options=options||{},this.name="ECB",this.cipher=options.cipher,this.blockSize=options.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},modes.ecb.prototype.start=function(options){},modes.ecb.prototype.encrypt=function(input,output,finish){if(input.length()<this.blockSize&&!(finish&&input.length()>0))return!0;for(var i=0;i<this._ints;++i)this._inBlock[i]=input.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(i=0;i<this._ints;++i)output.putInt32(this._outBlock[i])},modes.ecb.prototype.decrypt=function(input,output,finish){if(input.length()<this.blockSize&&!(finish&&input.length()>0))return!0;for(var i=0;i<this._ints;++i)this._inBlock[i]=input.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(i=0;i<this._ints;++i)output.putInt32(this._outBlock[i])},modes.ecb.prototype.pad=function(input,options){var padding=input.length()===this.blockSize?this.blockSize:this.blockSize-input.length();return input.fillWithByte(padding,padding),!0},modes.ecb.prototype.unpad=function(output,options){if(options.overflow>0)return!1;var len=output.length(),count=output.at(len-1);return!(count>this.blockSize<<2)&&(output.truncate(count),!0)},modes.cbc=function(options){options=options||{},this.name="CBC",this.cipher=options.cipher,this.blockSize=options.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},modes.cbc.prototype.start=function(options){if(null===options.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in options))throw new Error("Invalid IV parameter.");this._iv=transformIV(options.iv,this.blockSize),this._prev=this._iv.slice(0)}},modes.cbc.prototype.encrypt=function(input,output,finish){if(input.length()<this.blockSize&&!(finish&&input.length()>0))return!0;for(var i=0;i<this._ints;++i)this._inBlock[i]=this._prev[i]^input.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(i=0;i<this._ints;++i)output.putInt32(this._outBlock[i]);this._prev=this._outBlock},modes.cbc.prototype.decrypt=function(input,output,finish){if(input.length()<this.blockSize&&!(finish&&input.length()>0))return!0;for(var i=0;i<this._ints;++i)this._inBlock[i]=input.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(i=0;i<this._ints;++i)output.putInt32(this._prev[i]^this._outBlock[i]);this._prev=this._inBlock.slice(0)},modes.cbc.prototype.pad=function(input,options){var padding=input.length()===this.blockSize?this.blockSize:this.blockSize-input.length();return input.fillWithByte(padding,padding),!0},modes.cbc.prototype.unpad=function(output,options){if(options.overflow>0)return!1;var len=output.length(),count=output.at(len-1);return!(count>this.blockSize<<2)&&(output.truncate(count),!0)},modes.cfb=function(options){options=options||{},this.name="CFB",this.cipher=options.cipher,this.blockSize=options.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=forge.util.createBuffer(),this._partialBytes=0},modes.cfb.prototype.start=function(options){if(!("iv"in options))throw new Error("Invalid IV parameter.");this._iv=transformIV(options.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},modes.cfb.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(0===inputLength)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&inputLength>=this.blockSize)for(var i=0;i<this._ints;++i)this._inBlock[i]=input.getInt32()^this._outBlock[i],output.putInt32(this._inBlock[i]);else{var partialBytes=(this.blockSize-inputLength)%this.blockSize;partialBytes>0&&(partialBytes=this.blockSize-partialBytes),this._partialOutput.clear();for(i=0;i<this._ints;++i)this._partialBlock[i]=input.getInt32()^this._outBlock[i],this._partialOutput.putInt32(this._partialBlock[i]);if(partialBytes>0)input.read-=this.blockSize;else for(i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),partialBytes>0&&!finish)return output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes)),this._partialBytes=partialBytes,!0;output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes)),this._partialBytes=0}},modes.cfb.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(0===inputLength)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&inputLength>=this.blockSize)for(var i=0;i<this._ints;++i)this._inBlock[i]=input.getInt32(),output.putInt32(this._inBlock[i]^this._outBlock[i]);else{var partialBytes=(this.blockSize-inputLength)%this.blockSize;partialBytes>0&&(partialBytes=this.blockSize-partialBytes),this._partialOutput.clear();for(i=0;i<this._ints;++i)this._partialBlock[i]=input.getInt32(),this._partialOutput.putInt32(this._partialBlock[i]^this._outBlock[i]);if(partialBytes>0)input.read-=this.blockSize;else for(i=0;i<this._ints;++i)this._inBlock[i]=this._partialBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),partialBytes>0&&!finish)return output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes)),this._partialBytes=partialBytes,!0;output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes)),this._partialBytes=0}},modes.ofb=function(options){options=options||{},this.name="OFB",this.cipher=options.cipher,this.blockSize=options.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=forge.util.createBuffer(),this._partialBytes=0},modes.ofb.prototype.start=function(options){if(!("iv"in options))throw new Error("Invalid IV parameter.");this._iv=transformIV(options.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},modes.ofb.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(0===input.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&inputLength>=this.blockSize)for(var i=0;i<this._ints;++i)output.putInt32(input.getInt32()^this._outBlock[i]),this._inBlock[i]=this._outBlock[i];else{var partialBytes=(this.blockSize-inputLength)%this.blockSize;partialBytes>0&&(partialBytes=this.blockSize-partialBytes),this._partialOutput.clear();for(i=0;i<this._ints;++i)this._partialOutput.putInt32(input.getInt32()^this._outBlock[i]);if(partialBytes>0)input.read-=this.blockSize;else for(i=0;i<this._ints;++i)this._inBlock[i]=this._outBlock[i];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),partialBytes>0&&!finish)return output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes)),this._partialBytes=partialBytes,!0;output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes)),this._partialBytes=0}},modes.ofb.prototype.decrypt=modes.ofb.prototype.encrypt,modes.ctr=function(options){options=options||{},this.name="CTR",this.cipher=options.cipher,this.blockSize=options.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=forge.util.createBuffer(),this._partialBytes=0},modes.ctr.prototype.start=function(options){if(!("iv"in options))throw new Error("Invalid IV parameter.");this._iv=transformIV(options.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},modes.ctr.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(0===inputLength)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&inputLength>=this.blockSize)for(var i=0;i<this._ints;++i)output.putInt32(input.getInt32()^this._outBlock[i]);else{var partialBytes=(this.blockSize-inputLength)%this.blockSize;partialBytes>0&&(partialBytes=this.blockSize-partialBytes),this._partialOutput.clear();for(i=0;i<this._ints;++i)this._partialOutput.putInt32(input.getInt32()^this._outBlock[i]);if(partialBytes>0&&(input.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),partialBytes>0&&!finish)return output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes)),this._partialBytes=partialBytes,!0;output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes)),this._partialBytes=0}inc32(this._inBlock)},modes.ctr.prototype.decrypt=modes.ctr.prototype.encrypt,modes.gcm=function(options){options=options||{},this.name="GCM",this.cipher=options.cipher,this.blockSize=options.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=forge.util.createBuffer(),this._partialBytes=0,this._R=3774873600},modes.gcm.prototype.start=function(options){if(!("iv"in options))throw new Error("Invalid IV parameter.");var additionalData,iv=forge.util.createBuffer(options.iv);if(this._cipherLength=0,additionalData="additionalData"in options?forge.util.createBuffer(options.additionalData):forge.util.createBuffer(),this._tagLength="tagLength"in options?options.tagLength:128,this._tag=null,options.decrypt&&(this._tag=forge.util.createBuffer(options.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var ivLength=iv.length();if(12===ivLength)this._j0=[iv.getInt32(),iv.getInt32(),iv.getInt32(),1];else{for(this._j0=[0,0,0,0];iv.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[iv.getInt32(),iv.getInt32(),iv.getInt32(),iv.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(from64To32(8*ivLength)))}this._inBlock=this._j0.slice(0),inc32(this._inBlock),this._partialBytes=0,additionalData=forge.util.createBuffer(additionalData),this._aDataLength=from64To32(8*additionalData.length());var overflow=additionalData.length()%this.blockSize;for(overflow&&additionalData.fillWithByte(0,this.blockSize-overflow),this._s=[0,0,0,0];additionalData.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[additionalData.getInt32(),additionalData.getInt32(),additionalData.getInt32(),additionalData.getInt32()])},modes.gcm.prototype.encrypt=function(input,output,finish){var inputLength=input.length();if(0===inputLength)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&inputLength>=this.blockSize){for(var i=0;i<this._ints;++i)output.putInt32(this._outBlock[i]^=input.getInt32());this._cipherLength+=this.blockSize}else{var partialBytes=(this.blockSize-inputLength)%this.blockSize;partialBytes>0&&(partialBytes=this.blockSize-partialBytes),this._partialOutput.clear();for(i=0;i<this._ints;++i)this._partialOutput.putInt32(input.getInt32()^this._outBlock[i]);if(partialBytes<=0||finish){if(finish){var overflow=inputLength%this.blockSize;this._cipherLength+=overflow,this._partialOutput.truncate(this.blockSize-overflow)}else this._cipherLength+=this.blockSize;for(i=0;i<this._ints;++i)this._outBlock[i]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),partialBytes>0&&!finish)return input.read-=this.blockSize,output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes)),this._partialBytes=partialBytes,!0;output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),inc32(this._inBlock)},modes.gcm.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(inputLength<this.blockSize&&!(finish&&inputLength>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),inc32(this._inBlock),this._hashBlock[0]=input.getInt32(),this._hashBlock[1]=input.getInt32(),this._hashBlock[2]=input.getInt32(),this._hashBlock[3]=input.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i<this._ints;++i)output.putInt32(this._outBlock[i]^this._hashBlock[i]);inputLength<this.blockSize?this._cipherLength+=inputLength%this.blockSize:this._cipherLength+=this.blockSize},modes.gcm.prototype.afterFinish=function(output,options){var rval=!0;options.decrypt&&options.overflow&&output.truncate(this.blockSize-options.overflow),this.tag=forge.util.createBuffer();var lengths=this._aDataLength.concat(from64To32(8*this._cipherLength));this._s=this.ghash(this._hashSubkey,this._s,lengths);var tag=[];this.cipher.encrypt(this._j0,tag);for(var i=0;i<this._ints;++i)this.tag.putInt32(this._s[i]^tag[i]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),options.decrypt&&this.tag.bytes()!==this._tag&&(rval=!1),rval},modes.gcm.prototype.multiply=function(x,y){for(var z_i=[0,0,0,0],v_i=y.slice(0),i=0;i<128;++i){x[i/32|0]&1<<31-i%32&&(z_i[0]^=v_i[0],z_i[1]^=v_i[1],z_i[2]^=v_i[2],z_i[3]^=v_i[3]),this.pow(v_i,v_i)}return z_i},modes.gcm.prototype.pow=function(x,out){for(var lsb=1&x[3],i=3;i>0;--i)out[i]=x[i]>>>1|(1&x[i-1])<<31;out[0]=x[0]>>>1,lsb&&(out[0]^=this._R)},modes.gcm.prototype.tableMultiply=function(x){for(var z=[0,0,0,0],i=0;i<32;++i){var x_i=x[i/8|0]>>>4*(7-i%8)&15,ah=this._m[i][x_i];z[0]^=ah[0],z[1]^=ah[1],z[2]^=ah[2],z[3]^=ah[3]}return z},modes.gcm.prototype.ghash=function(h,y,x){return y[0]^=x[0],y[1]^=x[1],y[2]^=x[2],y[3]^=x[3],this.tableMultiply(y)},modes.gcm.prototype.generateHashTable=function(h,bits){for(var multiplier=8/bits,perInt=4*multiplier,size=16*multiplier,m=new Array(size),i=0;i<size;++i){var tmp=[0,0,0,0],shft=(perInt-1-i%perInt)*bits;tmp[i/perInt|0]=1<<bits-1<<shft,m[i]=this.generateSubHashTable(this.multiply(tmp,h),bits)}return m},modes.gcm.prototype.generateSubHashTable=function(mid,bits){var size=1<<bits,half=size>>>1,m=new Array(size);m[half]=mid.slice(0);for(var i=half>>>1;i>0;)this.pow(m[2*i],m[i]=[]),i>>=1;for(i=2;i<half;){for(var j=1;j<i;++j){var m_i=m[i],m_j=m[j];m[i+j]=[m_i[0]^m_j[0],m_i[1]^m_j[1],m_i[2]^m_j[2],m_i[3]^m_j[3]]}i*=2}for(m[0]=[0,0,0,0],i=half+1;i<size;++i){var c=m[i^half];m[i]=[mid[0]^c[0],mid[1]^c[1],mid[2]^c[2],mid[3]^c[3]]}return m},cipherModes.exports}function requireAes(){if(hasRequiredAes)return aes;hasRequiredAes=1;var forge=requireForge();function registerAlgorithm(name,mode){forge.cipher.registerAlgorithm(name,function(){return new forge.aes.Algorithm(name,mode)})}requireCipher(),requireCipherModes(),requireUtil(),aes=forge.aes=forge.aes||{},forge.aes.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:!1,mode:mode});return cipher.start(iv),cipher},forge.aes.createEncryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:!1,mode:mode})},forge.aes.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:!0,mode:mode});return cipher.start(iv),cipher},forge.aes.createDecryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:!0,mode:mode})},forge.aes.Algorithm=function(name,mode){init||initialize();var self=this;self.name=name,self.mode=new mode({blockSize:16,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self._w,inBlock,outBlock,!1)},decrypt:function(inBlock,outBlock){return _updateBlock(self._w,inBlock,outBlock,!0)}}}),self._init=!1},forge.aes.Algorithm.prototype.initialize=function(options){if(!this._init){var tmp,key=options.key;if("string"!=typeof key||16!==key.length&&24!==key.length&&32!==key.length){if(forge.util.isArray(key)&&(16===key.length||24===key.length||32===key.length)){tmp=key,key=forge.util.createBuffer();for(var i=0;i<tmp.length;++i)key.putByte(tmp[i])}}else key=forge.util.createBuffer(key);if(!forge.util.isArray(key)){tmp=key,key=[];var len=tmp.length();if(16===len||24===len||32===len){len>>>=2;for(i=0;i<len;++i)key.push(tmp.getInt32())}}if(!forge.util.isArray(key)||4!==key.length&&6!==key.length&&8!==key.length)throw new Error("Invalid key parameter.");var mode=this.mode.name,encryptOp=-1!==["CFB","OFB","CTR","GCM"].indexOf(mode);this._w=_expandKey(key,options.decrypt&&!encryptOp),this._init=!0}},forge.aes._expandKey=function(key,decrypt){return init||initialize(),_expandKey(key,decrypt)},forge.aes._updateBlock=_updateBlock,registerAlgorithm("AES-ECB",forge.cipher.modes.ecb),registerAlgorithm("AES-CBC",forge.cipher.modes.cbc),registerAlgorithm("AES-CFB",forge.cipher.modes.cfb),registerAlgorithm("AES-OFB",forge.cipher.modes.ofb),registerAlgorithm("AES-CTR",forge.cipher.modes.ctr),registerAlgorithm("AES-GCM",forge.cipher.modes.gcm);var sbox,isbox,rcon,mix,imix,init=!1,Nb=4;function initialize(){init=!0,rcon=[0,1,2,4,8,16,32,64,128,27,54];for(var xtime=new Array(256),i=0;i<128;++i)xtime[i]=i<<1,xtime[i+128]=i+128<<1^283;sbox=new Array(256),isbox=new Array(256),mix=new Array(4),imix=new Array(4);for(i=0;i<4;++i)mix[i]=new Array(256),imix[i]=new Array(256);var e2,e4,e8,sx,sx2,me,ime,e=0,ei=0;for(i=0;i<256;++i){sx=(sx=ei^ei<<1^ei<<2^ei<<3^ei<<4)>>8^255&sx^99,sbox[e]=sx,isbox[sx]=e,me=(sx2=xtime[sx])<<24^sx<<16^sx<<8^sx^sx2,ime=((e2=xtime[e])^(e4=xtime[e2])^(e8=xtime[e4]))<<24^(e^e8)<<16^(e^e4^e8)<<8^e^e2^e8;for(var n=0;n<4;++n)mix[n][e]=me,imix[n][sx]=ime,me=me<<24|me>>>8,ime=ime<<24|ime>>>8;0===e?e=ei=1:(e=e2^xtime[xtime[xtime[e2^e8]]],ei^=xtime[xtime[ei]])}}function _expandKey(key,decrypt){for(var temp,w=key.slice(0),iNk=1,Nk=w.length,end=Nb*(Nk+6+1),i=Nk;i<end;++i)temp=w[i-1],i%Nk===0?(temp=sbox[temp>>>16&255]<<24^sbox[temp>>>8&255]<<16^sbox[255&temp]<<8^sbox[temp>>>24]^rcon[iNk]<<24,iNk++):Nk>6&&i%Nk===4&&(temp=sbox[temp>>>24]<<24^sbox[temp>>>16&255]<<16^sbox[temp>>>8&255]<<8^sbox[255&temp]),w[i]=w[i-Nk]^temp;if(decrypt){for(var tmp,m0=imix[0],m1=imix[1],m2=imix[2],m3=imix[3],wnew=w.slice(0),wi=(i=0,(end=w.length)-Nb);i<end;i+=Nb,wi-=Nb)if(0===i||i===end-Nb)wnew[i]=w[wi],wnew[i+1]=w[wi+3],wnew[i+2]=w[wi+2],wnew[i+3]=w[wi+1];else for(var n=0;n<Nb;++n)tmp=w[wi+n],wnew[i+(3&-n)]=m0[sbox[tmp>>>24]]^m1[sbox[tmp>>>16&255]]^m2[sbox[tmp>>>8&255]]^m3[sbox[255&tmp]];w=wnew}return w}function _updateBlock(w,input,output,decrypt){var m0,m1,m2,m3,sub,a,b,c,d,a2,b2,c2,Nr=w.length/4-1;decrypt?(m0=imix[0],m1=imix[1],m2=imix[2],m3=imix[3],sub=isbox):(m0=mix[0],m1=mix[1],m2=mix[2],m3=mix[3],sub=sbox),a=input[0]^w[0],b=input[decrypt?3:1]^w[1],c=input[2]^w[2],d=input[decrypt?1:3]^w[3];for(var i=3,round=1;round<Nr;++round)a2=m0[a>>>24]^m1[b>>>16&255]^m2[c>>>8&255]^m3[255&d]^w[++i],b2=m0[b>>>24]^m1[c>>>16&255]^m2[d>>>8&255]^m3[255&a]^w[++i],c2=m0[c>>>24]^m1[d>>>16&255]^m2[a>>>8&255]^m3[255&b]^w[++i],d=m0[d>>>24]^m1[a>>>16&255]^m2[b>>>8&255]^m3[255&c]^w[++i],a=a2,b=b2,c=c2;output[0]=sub[a>>>24]<<24^sub[b>>>16&255]<<16^sub[c>>>8&255]<<8^sub[255&d]^w[++i],output[decrypt?3:1]=sub[b>>>24]<<24^sub[c>>>16&255]<<16^sub[d>>>8&255]<<8^sub[255&a]^w[++i],output[2]=sub[c>>>24]<<24^sub[d>>>16&255]<<16^sub[a>>>8&255]<<8^sub[255&b]^w[++i],output[decrypt?1:3]=sub[d>>>24]<<24^sub[a>>>16&255]<<16^sub[b>>>8&255]<<8^sub[255&c]^w[++i]}function _createCipher(options){var cipher,algorithm="AES-"+((options=options||{}).mode||"CBC").toUpperCase(),start=(cipher=options.decrypt?forge.cipher.createDecipher(algorithm,options.key):forge.cipher.createCipher(algorithm,options.key)).start;return cipher.start=function(iv,options){var output=null;options instanceof forge.util.ByteBuffer&&(output=options,options={}),(options=options||{}).output=output,options.iv=iv,start.call(cipher,options)},cipher}return aes}var hasRequiredOids,hasRequiredAsn1,aesCipherSuites={exports:{}},asn1={exports:{}},oids={exports:{}};function requireOids(){if(hasRequiredOids)return oids.exports;hasRequiredOids=1;var forge=requireForge();forge.pki=forge.pki||{};var oids$1=oids.exports=forge.pki.oids=forge.oids=forge.oids||{};function _IN(id,name){oids$1[id]=name,oids$1[name]=id}function _I_(id,name){oids$1[id]=name}return _IN("1.2.840.113549.1.1.1","rsaEncryption"),_IN("1.2.840.113549.1.1.4","md5WithRSAEncryption"),_IN("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),_IN("1.2.840.113549.1.1.7","RSAES-OAEP"),_IN("1.2.840.113549.1.1.8","mgf1"),_IN("1.2.840.113549.1.1.9","pSpecified"),_IN("1.2.840.113549.1.1.10","RSASSA-PSS"),_IN("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),_IN("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),_IN("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),_IN("1.3.101.112","EdDSA25519"),_IN("1.2.840.10040.4.3","dsa-with-sha1"),_IN("1.3.14.3.2.7","desCBC"),_IN("1.3.14.3.2.26","sha1"),_IN("1.3.14.3.2.29","sha1WithRSASignature"),_IN("2.16.840.1.101.3.4.2.1","sha256"),_IN("2.16.840.1.101.3.4.2.2","sha384"),_IN("2.16.840.1.101.3.4.2.3","sha512"),_IN("2.16.840.1.101.3.4.2.4","sha224"),_IN("2.16.840.1.101.3.4.2.5","sha512-224"),_IN("2.16.840.1.101.3.4.2.6","sha512-256"),_IN("1.2.840.113549.2.2","md2"),_IN("1.2.840.113549.2.5","md5"),_IN("1.2.840.113549.1.7.1","data"),_IN("1.2.840.113549.1.7.2","signedData"),_IN("1.2.840.113549.1.7.3","envelopedData"),_IN("1.2.840.113549.1.7.4","signedAndEnvelopedData"),_IN("1.2.840.113549.1.7.5","digestedData"),_IN("1.2.840.113549.1.7.6","encryptedData"),_IN("1.2.840.113549.1.9.1","emailAddress"),_IN("1.2.840.113549.1.9.2","unstructuredName"),_IN("1.2.840.113549.1.9.3","contentType"),_IN("1.2.840.113549.1.9.4","messageDigest"),_IN("1.2.840.113549.1.9.5","signingTime"),_IN("1.2.840.113549.1.9.6","counterSignature"),_IN("1.2.840.113549.1.9.7","challengePassword"),_IN("1.2.840.113549.1.9.8","unstructuredAddress"),_IN("1.2.840.113549.1.9.14","extensionRequest"),_IN("1.2.840.113549.1.9.20","friendlyName"),_IN("1.2.840.113549.1.9.21","localKeyId"),_IN("1.2.840.113549.1.9.22.1","x509Certificate"),_IN("1.2.840.113549.1.12.10.1.1","keyBag"),_IN("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),_IN("1.2.840.113549.1.12.10.1.3","certBag"),_IN("1.2.840.113549.1.12.10.1.4","crlBag"),_IN("1.2.840.113549.1.12.10.1.5","secretBag"),_IN("1.2.840.113549.1.12.10.1.6","safeContentsBag"),_IN("1.2.840.113549.1.5.13","pkcs5PBES2"),_IN("1.2.840.113549.1.5.12","pkcs5PBKDF2"),_IN("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),_IN("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),_IN("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),_IN("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),_IN("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),_IN("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),_IN("1.2.840.113549.2.7","hmacWithSHA1"),_IN("1.2.840.113549.2.8","hmacWithSHA224"),_IN("1.2.840.113549.2.9","hmacWithSHA256"),_IN("1.2.840.113549.2.10","hmacWithSHA384"),_IN("1.2.840.113549.2.11","hmacWithSHA512"),_IN("1.2.840.113549.3.7","des-EDE3-CBC"),_IN("2.16.840.1.101.3.4.1.2","aes128-CBC"),_IN("2.16.840.1.101.3.4.1.22","aes192-CBC"),_IN("2.16.840.1.101.3.4.1.42","aes256-CBC"),_IN("2.5.4.3","commonName"),_IN("2.5.4.4","surname"),_IN("2.5.4.5","serialNumber"),_IN("2.5.4.6","countryName"),_IN("2.5.4.7","localityName"),_IN("2.5.4.8","stateOrProvinceName"),_IN("2.5.4.9","streetAddress"),_IN("2.5.4.10","organizationName"),_IN("2.5.4.11","organizationalUnitName"),_IN("2.5.4.12","title"),_IN("2.5.4.13","description"),_IN("2.5.4.15","businessCategory"),_IN("2.5.4.17","postalCode"),_IN("2.5.4.42","givenName"),_IN("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),_IN("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),_IN("2.16.840.1.113730.1.1","nsCertType"),_IN("2.16.840.1.113730.1.13","nsComment"),_I_("2.5.29.1","authorityKeyIdentifier"),_I_("2.5.29.2","keyAttributes"),_I_("2.5.29.3","certificatePolicies"),_I_("2.5.29.4","keyUsageRestriction"),_I_("2.5.29.5","policyMapping"),_I_("2.5.29.6","subtreesConstraint"),_I_("2.5.29.7","subjectAltName"),_I_("2.5.29.8","issuerAltName"),_I_("2.5.29.9","subjectDirectoryAttributes"),_I_("2.5.29.10","basicConstraints"),_I_("2.5.29.11","nameConstraints"),_I_("2.5.29.12","policyConstraints"),_I_("2.5.29.13","basicConstraints"),_IN("2.5.29.14","subjectKeyIdentifier"),_IN("2.5.29.15","keyUsage"),_I_("2.5.29.16","privateKeyUsagePeriod"),_IN("2.5.29.17","subjectAltName"),_IN("2.5.29.18","issuerAltName"),_IN("2.5.29.19","basicConstraints"),_I_("2.5.29.20","cRLNumber"),_I_("2.5.29.21","cRLReason"),_I_("2.5.29.22","expirationDate"),_I_("2.5.29.23","instructionCode"),_I_("2.5.29.24","invalidityDate"),_I_("2.5.29.25","cRLDistributionPoints"),_I_("2.5.29.26","issuingDistributionPoint"),_I_("2.5.29.27","deltaCRLIndicator"),_I_("2.5.29.28","issuingDistributionPoint"),_I_("2.5.29.29","certificateIssuer"),_I_("2.5.29.30","nameConstraints"),_IN("2.5.29.31","cRLDistributionPoints"),_IN("2.5.29.32","certificatePolicies"),_I_("2.5.29.33","policyMappings"),_I_("2.5.29.34","policyConstraints"),_IN("2.5.29.35","authorityKeyIdentifier"),_I_("2.5.29.36","policyConstraints"),_IN("2.5.29.37","extKeyUsage"),_I_("2.5.29.46","freshestCRL"),_I_("2.5.29.54","inhibitAnyPolicy"),_IN("1.3.6.1.4.1.11129.2.4.2","timestampList"),_IN("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),_IN("1.3.6.1.5.5.7.3.1","serverAuth"),_IN("1.3.6.1.5.5.7.3.2","clientAuth"),_IN("1.3.6.1.5.5.7.3.3","codeSigning"),_IN("1.3.6.1.5.5.7.3.4","emailProtection"),_IN("1.3.6.1.5.5.7.3.8","timeStamping"),oids.exports}function requireAsn1(){if(hasRequiredAsn1)return asn1.exports;hasRequiredAsn1=1;var forge=requireForge();requireUtil(),requireOids();var asn1$1=asn1.exports=forge.asn1=forge.asn1||{};function _checkBufferLength(bytes,remaining,n){if(n>remaining){var error=new Error("Too few bytes to parse DER.");throw error.available=bytes.length(),error.remaining=remaining,error.requested=n,error}}asn1$1.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},asn1$1.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},asn1$1.create=function(tagClass,type,constructed,value,options){if(forge.util.isArray(value)){for(var tmp=[],i=0;i<value.length;++i)void 0!==value[i]&&tmp.push(value[i]);value=tmp}var obj={tagClass:tagClass,type:type,constructed:constructed,composed:constructed||forge.util.isArray(value),value:value};return options&&"bitStringContents"in options&&(obj.bitStringContents=options.bitStringContents,obj.original=asn1$1.copy(obj)),obj},asn1$1.copy=function(obj,options){var copy;if(forge.util.isArray(obj)){copy=[];for(var i=0;i<obj.length;++i)copy.push(asn1$1.copy(obj[i],options));return copy}return"string"==typeof obj?obj:(copy={tagClass:obj.tagClass,type:obj.type,constructed:obj.constructed,composed:obj.composed,value:asn1$1.copy(obj.value,options)},options&&!options.excludeBitStringContents&&(copy.bitStringContents=obj.bitStringContents),copy)},asn1$1.equals=function(obj1,obj2,options){if(forge.util.isArray(obj1)){if(!forge.util.isArray(obj2))return!1;if(obj1.length!==obj2.length)return!1;for(var i=0;i<obj1.length;++i)if(!asn1$1.equals(obj1[i],obj2[i]))return!1;return!0}if(typeof obj1!=typeof obj2)return!1;if("string"==typeof obj1)return obj1===obj2;var equal=obj1.tagClass===obj2.tagClass&&obj1.type===obj2.type&&obj1.constructed===obj2.constructed&&obj1.composed===obj2.composed&&asn1$1.equals(obj1.value,obj2.value);return options&&options.includeBitStringContents&&(equal=equal&&obj1.bitStringContents===obj2.bitStringContents),equal},asn1$1.getBerValueLength=function(b){var b2=b.getByte();if(128!==b2)return 128&b2?b.getInt((127&b2)<<3):b2};function _fromDer(bytes,remaining,depth,options){var start;_checkBufferLength(bytes,remaining,2);var b1=bytes.getByte();remaining--;var tagClass=192&b1,type=31&b1;start=bytes.length();var value,bitStringContents,length=function(bytes,remaining){var b2=bytes.getByte();if(remaining--,128!==b2){var length;if(128&b2){var longFormBytes=127&b2;_checkBufferLength(bytes,remaining,longFormBytes),length=bytes.getInt(longFormBytes<<3)}else length=b2;if(length<0)throw new Error("Negative length: "+length);return length}}(bytes,remaining);if(remaining-=start-bytes.length(),void 0!==length&&length>remaining){if(options.strict){var error=new Error("Too few bytes to read ASN.1 value.");throw error.available=bytes.length(),error.remaining=remaining,error.requested=length,error}length=remaining}var constructed=!(32&~b1);if(constructed)if(value=[],void 0===length)for(;;){if(_checkBufferLength(bytes,remaining,2),bytes.bytes(2)===String.fromCharCode(0,0)){bytes.getBytes(2),remaining-=2;break}start=bytes.length(),value.push(_fromDer(bytes,remaining,depth+1,options)),remaining-=start-bytes.length()}else for(;length>0;)start=bytes.length(),value.push(_fromDer(bytes,length,depth+1,options)),remaining-=start-bytes.length(),length-=start-bytes.length();if(void 0===value&&tagClass===asn1$1.Class.UNIVERSAL&&type===asn1$1.Type.BITSTRING&&(bitStringContents=bytes.bytes(length)),void 0===value&&options.decodeBitStrings&&tagClass===asn1$1.Class.UNIVERSAL&&type===asn1$1.Type.BITSTRING&&length>1){var savedRead=bytes.read,savedRemaining=remaining,unused=0;if(type===asn1$1.Type.BITSTRING&&(_checkBufferLength(bytes,remaining,1),unused=bytes.getByte(),remaining--),0===unused)try{start=bytes.length();var composed=_fromDer(bytes,remaining,depth+1,{strict:!0,decodeBitStrings:!0}),used=start-bytes.length();remaining-=used,type==asn1$1.Type.BITSTRING&&used++;var tc=composed.tagClass;used!==length||tc!==asn1$1.Class.UNIVERSAL&&tc!==asn1$1.Class.CONTEXT_SPECIFIC||(value=[composed])}catch(ex){}void 0===value&&(bytes.read=savedRead,remaining=savedRemaining)}if(void 0===value){if(void 0===length){if(options.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");length=remaining}if(type===asn1$1.Type.BMPSTRING)for(value="";length>0;length-=2)_checkBufferLength(bytes,remaining,2),value+=String.fromCharCode(bytes.getInt16()),remaining-=2;else value=bytes.getBytes(length),remaining-=length}var asn1Options=void 0===bitStringContents?null:{bitStringContents:bitStringContents};return asn1$1.create(tagClass,type,constructed,value,asn1Options)}asn1$1.fromDer=function(bytes,options){void 0===options&&(options={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),"boolean"==typeof options&&(options={strict:options,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in options||(options.strict=!0),"parseAllBytes"in options||(options.parseAllBytes=!0),"decodeBitStrings"in options||(options.decodeBitStrings=!0),"string"==typeof bytes&&(bytes=forge.util.createBuffer(bytes));var byteCount=bytes.length(),value=_fromDer(bytes,bytes.length(),0,options);if(options.parseAllBytes&&0!==bytes.length()){var error=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw error.byteCount=byteCount,error.remaining=bytes.length(),error}return value},asn1$1.toDer=function(obj){var bytes=forge.util.createBuffer(),b1=obj.tagClass|obj.type,value=forge.util.createBuffer(),useBitStringContents=!1;if("bitStringContents"in obj&&(useBitStringContents=!0,obj.original&&(useBitStringContents=asn1$1.equals(obj,obj.original))),useBitStringContents)value.putBytes(obj.bitStringContents);else if(obj.composed){obj.constructed?b1|=32:value.putByte(0);for(var i=0;i<obj.value.length;++i)void 0!==obj.value[i]&&value.putBuffer(asn1$1.toDer(obj.value[i]))}else if(obj.type===asn1$1.Type.BMPSTRING)for(i=0;i<obj.value.length;++i)value.putInt16(obj.value.charCodeAt(i));else!(obj.type===asn1$1.Type.INTEGER&&obj.value.length>1)||(0!==obj.value.charCodeAt(0)||128&obj.value.charCodeAt(1))&&(255!==obj.value.charCodeAt(0)||128&~obj.value.charCodeAt(1))?value.putBytes(obj.value):value.putBytes(obj.value.substr(1));if(bytes.putByte(b1),value.length()<=127)bytes.putByte(127&value.length());else{var len=value.length(),lenBytes="";do{lenBytes+=String.fromCharCode(255&len),len>>>=8}while(len>0);bytes.putByte(128|lenBytes.length);for(i=lenBytes.length-1;i>=0;--i)bytes.putByte(lenBytes.charCodeAt(i))}return bytes.putBuffer(value),bytes},asn1$1.oidToDer=function(oid){var last,valueBytes,value,b,values=oid.split("."),bytes=forge.util.createBuffer();bytes.putByte(40*parseInt(values[0],10)+parseInt(values[1],10));for(var i=2;i<values.length;++i){last=!0,valueBytes=[],value=parseInt(values[i],10);do{b=127&value,value>>>=7,last||(b|=128),valueBytes.push(b),last=!1}while(value>0);for(var n=valueBytes.length-1;n>=0;--n)bytes.putByte(valueBytes[n])}return bytes},asn1$1.derToOid=function(bytes){var oid;"string"==typeof bytes&&(bytes=forge.util.createBuffer(bytes));var b=bytes.getByte();oid=Math.floor(b/40)+"."+b%40;for(var value=0;bytes.length()>0;)value<<=7,128&(b=bytes.getByte())?value+=127&b:(oid+="."+(value+b),value=0);return oid},asn1$1.utcTimeToDate=function(utc){var date=new Date,year=parseInt(utc.substr(0,2),10);year=year>=50?1900+year:2e3+year;var MM=parseInt(utc.substr(2,2),10)-1,DD=parseInt(utc.substr(4,2),10),hh=parseInt(utc.substr(6,2),10),mm=parseInt(utc.substr(8,2),10),ss=0;if(utc.length>11){var c=utc.charAt(10),end=10;"+"!==c&&"-"!==c&&(ss=parseInt(utc.substr(10,2),10),end+=2)}if(date.setUTCFullYear(year,MM,DD),date.setUTCHours(hh,mm,ss,0),end&&("+"===(c=utc.charAt(end))||"-"===c)){var offset=60*parseInt(utc.substr(end+1,2),10)+parseInt(utc.substr(end+4,2),10);offset*=6e4,"+"===c?date.setTime(+date-offset):date.setTime(+date+offset)}return date},asn1$1.generalizedTimeToDate=function(gentime){var date=new Date,YYYY=parseInt(gentime.substr(0,4),10),MM=parseInt(gentime.substr(4,2),10)-1,DD=parseInt(gentime.substr(6,2),10),hh=parseInt(gentime.substr(8,2),10),mm=parseInt(gentime.substr(10,2),10),ss=parseInt(gentime.substr(12,2),10),fff=0,offset=0,isUTC=!1;"Z"===gentime.charAt(gentime.length-1)&&(isUTC=!0);var end=gentime.length-5,c=gentime.charAt(end);"+"!==c&&"-"!==c||(offset=60*parseInt(gentime.substr(end+1,2),10)+parseInt(gentime.substr(end+4,2),10),offset*=6e4,"+"===c&&(offset*=-1),isUTC=!0);return"."===gentime.charAt(14)&&(fff=1e3*parseFloat(gentime.substr(14),10)),isUTC?(date.setUTCFullYear(YYYY,MM,DD),date.setUTCHours(hh,mm,ss,fff),date.setTime(+date+offset)):(date.setFullYear(YYYY,MM,DD),date.setHours(hh,mm,ss,fff)),date},asn1$1.dateToUtcTime=function(date){if("string"==typeof date)return date;var rval="",format=[];format.push((""+date.getUTCFullYear()).substr(2)),format.push(""+(date.getUTCMonth()+1)),format.push(""+date.getUTCDate()),format.push(""+date.getUTCHours()),format.push(""+date.getUTCMinutes()),format.push(""+date.getUTCSeconds());for(var i=0;i<format.length;++i)format[i].length<2&&(rval+="0"),rval+=format[i];return rval+="Z"},asn1$1.dateToGeneralizedTime=function(date){if("string"==typeof date)return date;var rval="",format=[];format.push(""+date.getUTCFullYear()),format.push(""+(date.getUTCMonth()+1)),format.push(""+date.getUTCDate()),format.push(""+date.getUTCHours()),format.push(""+date.getUTCMinutes()),format.push(""+date.getUTCSeconds());for(var i=0;i<format.length;++i)format[i].length<2&&(rval+="0"),rval+=format[i];return rval+="Z"},asn1$1.integerToDer=function(x){var rval=forge.util.createBuffer();if(x>=-128&&x<128)return rval.putSignedInt(x,8);if(x>=-32768&&x<32768)return rval.putSignedInt(x,16);if(x>=-8388608&&x<8388608)return rval.putSignedInt(x,24);if(x>=-2147483648&&x<2147483648)return rval.putSignedInt(x,32);var error=new Error("Integer too large; max is 32-bits.");throw error.integer=x,error},asn1$1.derToInteger=function(bytes){"string"==typeof bytes&&(bytes=forge.util.createBuffer(bytes));var n=8*bytes.length();if(n>32)throw new Error("Integer too large; max is 32-bits.");return bytes.getSignedInt(n)},asn1$1.validate=function(obj,v,capture,errors){var rval=!1;if(obj.tagClass!==v.tagClass&&void 0!==v.tagClass||obj.type!==v.type&&void 0!==v.type)errors&&(obj.tagClass!==v.tagClass&&errors.push("["+v.name+'] Expected tag class "'+v.tagClass+'", got "'+obj.tagClass+'"'),obj.type!==v.type&&errors.push("["+v.name+'] Expected type "'+v.type+'", got "'+obj.type+'"'));else if(obj.constructed===v.constructed||void 0===v.constructed){if(rval=!0,v.value&&forge.util.isArray(v.value))for(var j=0,i=0;rval&&i<v.value.length;++i)rval=v.value[i].optional||!1,obj.value[j]&&((rval=asn1$1.validate(obj.value[j],v.value[i],capture,errors))?++j:v.value[i].optional&&(rval=!0)),!rval&&errors&&errors.push("["+v.name+'] Tag class "'+v.tagClass+'", type "'+v.type+'" expected value length "'+v.value.length+'", got "'+obj.value.length+'"');if(rval&&capture&&(v.capture&&(capture[v.capture]=obj.value),v.captureAsn1&&(capture[v.captureAsn1]=obj),v.captureBitStringContents&&"bitStringContents"in obj&&(capture[v.captureBitStringContents]=obj.bitStringContents),v.captureBitStringValue&&"bitStringContents"in obj))if(obj.bitStringContents.length<2)capture[v.captureBitStringValue]="";else{if(0!==obj.bitStringContents.charCodeAt(0))throw new Error("captureBitStringValue only supported for zero unused bits");capture[v.captureBitStringValue]=obj.bitStringContents.slice(1)}}else errors&&errors.push("["+v.name+'] Expected constructed "'+v.constructed+'", got "'+obj.constructed+'"');return rval};var _nonLatinRegex=/[^\\u0000-\\u00ff]/;return asn1$1.prettyPrint=function(obj,level,indentation){var rval="";indentation=indentation||2,(level=level||0)>0&&(rval+="\n");for(var indent="",i=0;i<level*indentation;++i)indent+=" ";switch(rval+=indent+"Tag: ",obj.tagClass){case asn1$1.Class.UNIVERSAL:rval+="Universal:";break;case asn1$1.Class.APPLICATION:rval+="Application:";break;case asn1$1.Class.CONTEXT_SPECIFIC:rval+="Context-Specific:";break;case asn1$1.Class.PRIVATE:rval+="Private:"}if(obj.tagClass===asn1$1.Class.UNIVERSAL)switch(rval+=obj.type,obj.type){case asn1$1.Type.NONE:rval+=" (None)";break;case asn1$1.Type.BOOLEAN:rval+=" (Boolean)";break;case asn1$1.Type.INTEGER:rval+=" (Integer)";break;case asn1$1.Type.BITSTRING:rval+=" (Bit string)";break;case asn1$1.Type.OCTETSTRING:rval+=" (Octet string)";break;case asn1$1.Type.NULL:rval+=" (Null)";break;case asn1$1.Type.OID:rval+=" (Object Identifier)";break;case asn1$1.Type.ODESC:rval+=" (Object Descriptor)";break;case asn1$1.Type.EXTERNAL:rval+=" (External or Instance of)";break;case asn1$1.Type.REAL:rval+=" (Real)";break;case asn1$1.Type.ENUMERATED:rval+=" (Enumerated)";break;case asn1$1.Type.EMBEDDED:rval+=" (Embedded PDV)";break;case asn1$1.Type.UTF8:rval+=" (UTF8)";break;case asn1$1.Type.ROID:rval+=" (Relative Object Identifier)";break;case asn1$1.Type.SEQUENCE:rval+=" (Sequence)";break;case asn1$1.Type.SET:rval+=" (Set)";break;case asn1$1.Type.PRINTABLESTRING:rval+=" (Printable String)";break;case asn1$1.Type.IA5String:rval+=" (IA5String (ASCII))";break;case asn1$1.Type.UTCTIME:rval+=" (UTC time)";break;case asn1$1.Type.GENERALIZEDTIME:rval+=" (Generalized time)";break;case asn1$1.Type.BMPSTRING:rval+=" (BMP String)"}else rval+=obj.type;if(rval+="\n",rval+=indent+"Constructed: "+obj.constructed+"\n",obj.composed){var subvalues=0,sub="";for(i=0;i<obj.value.length;++i)void 0!==obj.value[i]&&(subvalues+=1,sub+=asn1$1.prettyPrint(obj.value[i],level+1,indentation),i+1<obj.value.length&&(sub+=","));rval+=indent+"Sub values: "+subvalues+sub}else{if(rval+=indent+"Value: ",obj.type===asn1$1.Type.OID){var oid=asn1$1.derToOid(obj.value);rval+=oid,forge.pki&&forge.pki.oids&&oid in forge.pki.oids&&(rval+=" ("+forge.pki.oids[oid]+") ")}if(obj.type===asn1$1.Type.INTEGER)try{rval+=asn1$1.derToInteger(obj.value)}catch(ex){rval+="0x"+forge.util.bytesToHex(obj.value)}else if(obj.type===asn1$1.Type.BITSTRING){if(obj.value.length>1?rval+="0x"+forge.util.bytesToHex(obj.value.slice(1)):rval+="(none)",obj.value.length>0){var unused=obj.value.charCodeAt(0);1==unused?rval+=" (1 unused bit shown)":unused>1&&(rval+=" ("+unused+" unused bits shown)")}}else if(obj.type===asn1$1.Type.OCTETSTRING)_nonLatinRegex.test(obj.value)||(rval+="("+obj.value+") "),rval+="0x"+forge.util.bytesToHex(obj.value);else if(obj.type===asn1$1.Type.UTF8)try{rval+=forge.util.decodeUtf8(obj.value)}catch(e){if("URI malformed"!==e.message)throw e;rval+="0x"+forge.util.bytesToHex(obj.value)+" (malformed UTF8)"}else obj.type===asn1$1.Type.PRINTABLESTRING||obj.type===asn1$1.Type.IA5String?rval+=obj.value:_nonLatinRegex.test(obj.value)?rval+="0x"+forge.util.bytesToHex(obj.value):0===obj.value.length?rval+="[null]":rval+=obj.value}return rval},asn1.exports}var md,hasRequiredMd,hasRequiredHmac,hmac={exports:{}};function requireMd(){if(hasRequiredMd)return md;hasRequiredMd=1;var forge=requireForge();return md=forge.md=forge.md||{},forge.md.algorithms=forge.md.algorithms||{},md}function requireHmac(){if(hasRequiredHmac)return hmac.exports;hasRequiredHmac=1;var forge=requireForge();return requireMd(),requireUtil(),(hmac.exports=forge.hmac=forge.hmac||{}).create=function(){var _key=null,_md=null,_ipadding=null,_opadding=null,ctx={start:function(md,key){if(null!==md)if("string"==typeof md){if(!((md=md.toLowerCase())in forge.md.algorithms))throw new Error('Unknown hash algorithm "'+md+'"');_md=forge.md.algorithms[md].create()}else _md=md;if(null===key)key=_key;else{if("string"==typeof key)key=forge.util.createBuffer(key);else if(forge.util.isArray(key)){var tmp=key;key=forge.util.createBuffer();for(var i=0;i<tmp.length;++i)key.putByte(tmp[i])}var keylen=key.length();keylen>_md.blockLength&&(_md.start(),_md.update(key.bytes()),key=_md.digest()),_ipadding=forge.util.createBuffer(),_opadding=forge.util.createBuffer(),keylen=key.length();for(i=0;i<keylen;++i){tmp=key.at(i);_ipadding.putByte(54^tmp),_opadding.putByte(92^tmp)}if(keylen<_md.blockLength)for(tmp=_md.blockLength-keylen,i=0;i<tmp;++i)_ipadding.putByte(54),_opadding.putByte(92);_key=key,_ipadding=_ipadding.bytes(),_opadding=_opadding.bytes()}_md.start(),_md.update(_ipadding)},update:function(bytes){_md.update(bytes)},getMac:function(){var inner=_md.digest().bytes();return _md.start(),_md.update(_opadding),_md.update(inner),_md.digest()}};return ctx.digest=ctx.getMac,ctx},hmac.exports}var hasRequiredMd5,md5={exports:{}};function requireMd5(){if(hasRequiredMd5)return md5.exports;hasRequiredMd5=1;var forge=requireForge();requireMd(),requireUtil();var md5$1=md5.exports=forge.md5=forge.md5||{};forge.md.md5=forge.md.algorithms.md5=md5$1,md5$1.create=function(){_initialized||function _init(){_padding=String.fromCharCode(128),_padding+=forge.util.fillString(String.fromCharCode(0),64),_g=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],_r=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],_k=new Array(64);for(var i=0;i<64;++i)_k[i]=Math.floor(4294967296*Math.abs(Math.sin(i+1)));_initialized=!0}();var _state=null,_input=forge.util.createBuffer(),_w=new Array(16),md={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){md.messageLength=0,md.fullMessageLength=md.messageLength64=[];for(var int32s=md.messageLengthSize/4,i=0;i<int32s;++i)md.fullMessageLength.push(0);return _input=forge.util.createBuffer(),_state={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},md}};return md.start(),md.update=function(msg,encoding){"utf8"===encoding&&(msg=forge.util.encodeUtf8(msg));var len=msg.length;md.messageLength+=len,len=[len/4294967296>>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i)md.fullMessageLength[i]+=len[1],len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0),md.fullMessageLength[i]=md.fullMessageLength[i]>>>0,len[0]=len[1]/4294967296>>>0;return _input.putBytes(msg),_update(_state,_w,_input),(_input.read>2048||0===_input.length())&&_input.compact(),md},md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var overflow=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));for(var bits,carry=0,i=md.fullMessageLength.length-1;i>=0;--i)carry=(bits=8*md.fullMessageLength[i]+carry)/4294967296>>>0,finalBlock.putInt32Le(bits>>>0);var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();return rval.putInt32Le(s2.h0),rval.putInt32Le(s2.h1),rval.putInt32Le(s2.h2),rval.putInt32Le(s2.h3),rval},md};var _padding=null,_g=null,_r=null,_k=null,_initialized=!1;function _update(s,w,bytes){for(var t,a,b,c,d,r,i,len=bytes.length();len>=64;){for(a=s.h0,b=s.h1,c=s.h2,d=s.h3,i=0;i<16;++i)w[i]=bytes.getInt32Le(),t=a+(d^b&(c^d))+_k[i]+w[i],a=d,d=c,c=b,b+=t<<(r=_r[i])|t>>>32-r;for(;i<32;++i)t=a+(c^d&(b^c))+_k[i]+w[_g[i]],a=d,d=c,c=b,b+=t<<(r=_r[i])|t>>>32-r;for(;i<48;++i)t=a+(b^c^d)+_k[i]+w[_g[i]],a=d,d=c,c=b,b+=t<<(r=_r[i])|t>>>32-r;for(;i<64;++i)t=a+(c^(b|~d))+_k[i]+w[_g[i]],a=d,d=c,c=b,b+=t<<(r=_r[i])|t>>>32-r;s.h0=s.h0+a|0,s.h1=s.h1+b|0,s.h2=s.h2+c|0,s.h3=s.h3+d|0,len-=64}}return md5.exports}var hasRequiredPem,pem={exports:{}};function requirePem(){if(hasRequiredPem)return pem.exports;hasRequiredPem=1;var forge=requireForge();requireUtil();var pem$1=pem.exports=forge.pem=forge.pem||{};function foldHeader(header){for(var rval=header.name+": ",values=[],insertSpace=function(match,$1){return" "+$1},i=0;i<header.values.length;++i)values.push(header.values[i].replace(/^(\S+\r\n)/,insertSpace));rval+=values.join(",")+"\r\n";var length=0,candidate=-1;for(i=0;i<rval.length;++i,++length)if(length>65&&-1!==candidate){var insert=rval[candidate];","===insert?(++candidate,rval=rval.substr(0,candidate)+"\r\n "+rval.substr(candidate)):rval=rval.substr(0,candidate)+"\r\n"+insert+rval.substr(candidate+1),length=i-candidate-1,candidate=-1,++i}else" "!==rval[i]&&"\t"!==rval[i]&&","!==rval[i]||(candidate=i);return rval}function ltrim(str){return str.replace(/^\s+/,"")}return pem$1.encode=function(msg,options){options=options||{};var header,rval="-----BEGIN "+msg.type+"-----\r\n";if(msg.procType&&(rval+=foldHeader(header={name:"Proc-Type",values:[String(msg.procType.version),msg.procType.type]})),msg.contentDomain&&(rval+=foldHeader(header={name:"Content-Domain",values:[msg.contentDomain]})),msg.dekInfo&&(header={name:"DEK-Info",values:[msg.dekInfo.algorithm]},msg.dekInfo.parameters&&header.values.push(msg.dekInfo.parameters),rval+=foldHeader(header)),msg.headers)for(var i=0;i<msg.headers.length;++i)rval+=foldHeader(msg.headers[i]);return msg.procType&&(rval+="\r\n"),rval+=forge.util.encode64(msg.body,options.maxline||64)+"\r\n",rval+="-----END "+msg.type+"-----\r\n"},pem$1.decode=function(str){for(var match,rval=[],rMessage=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,rHeader=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,rCRLF=/\r?\n/;match=rMessage.exec(str);){var type=match[1];"NEW CERTIFICATE REQUEST"===type&&(type="CERTIFICATE REQUEST");var msg={type:type,procType:null,contentDomain:null,dekInfo:null,headers:[],body:forge.util.decode64(match[3])};if(rval.push(msg),match[2]){for(var lines=match[2].split(rCRLF),li=0;match&&li<lines.length;){for(var line=lines[li].replace(/\s+$/,""),nl=li+1;nl<lines.length;++nl){var next=lines[nl];if(!/\s/.test(next[0]))break;line+=next,li=nl}if(match=line.match(rHeader)){for(var header={name:match[1],values:[]},values=match[2].split(","),vi=0;vi<values.length;++vi)header.values.push(ltrim(values[vi]));if(msg.procType)if(msg.contentDomain||"Content-Domain"!==header.name)if(msg.dekInfo||"DEK-Info"!==header.name)msg.headers.push(header);else{if(0===header.values.length)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');msg.dekInfo={algorithm:values[0],parameters:values[1]||null}}else msg.contentDomain=values[0]||"";else{if("Proc-Type"!==header.name)throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(2!==header.values.length)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');msg.procType={version:values[0],type:values[1]}}}++li}if("ENCRYPTED"===msg.procType&&!msg.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(0===rval.length)throw new Error("Invalid PEM formatted message.");return rval},pem.exports}var des,hasRequiredDes,pbkdf2,hasRequiredPbkdf2,pki={exports:{}};function requireDes(){if(hasRequiredDes)return des;hasRequiredDes=1;var forge=requireForge();function registerAlgorithm(name,mode){forge.cipher.registerAlgorithm(name,function(){return new forge.des.Algorithm(name,mode)})}requireCipher(),requireCipherModes(),requireUtil(),des=forge.des=forge.des||{},forge.des.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:!1,mode:mode||(null===iv?"ECB":"CBC")});return cipher.start(iv),cipher},forge.des.createEncryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:!1,mode:mode})},forge.des.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key:key,output:output,decrypt:!0,mode:mode||(null===iv?"ECB":"CBC")});return cipher.start(iv),cipher},forge.des.createDecryptionCipher=function(key,mode){return _createCipher({key:key,output:null,decrypt:!0,mode:mode})},forge.des.Algorithm=function(name,mode){var self=this;self.name=name,self.mode=new mode({blockSize:8,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self._keys,inBlock,outBlock,!1)},decrypt:function(inBlock,outBlock){return _updateBlock(self._keys,inBlock,outBlock,!0)}}}),self._init=!1},forge.des.Algorithm.prototype.initialize=function(options){if(!this._init){var key=forge.util.createBuffer(options.key);if(0===this.name.indexOf("3DES")&&24!==key.length())throw new Error("Invalid Triple-DES key size: "+8*key.length());this._keys=function _createKeys(key){for(var tmp,pc2bytes0=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],pc2bytes1=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],pc2bytes2=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],pc2bytes3=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],pc2bytes4=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],pc2bytes5=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],pc2bytes6=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],pc2bytes7=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],pc2bytes8=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],pc2bytes9=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],pc2bytes10=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],pc2bytes11=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],pc2bytes12=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],pc2bytes13=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],iterations=key.length()>8?3:1,keys=[],shifts=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],n=0,j=0;j<iterations;j++){var left=key.getInt32(),right=key.getInt32();left^=(tmp=252645135&(left>>>4^right))<<4,left^=tmp=65535&((right^=tmp)>>>-16^left),left^=(tmp=858993459&(left>>>2^(right^=tmp<<-16)))<<2,left^=tmp=65535&((right^=tmp)>>>-16^left),left^=(tmp=1431655765&(left>>>1^(right^=tmp<<-16)))<<1,left^=tmp=16711935&((right^=tmp)>>>8^left),tmp=(left^=(tmp=1431655765&(left>>>1^(right^=tmp<<8)))<<1)<<8|(right^=tmp)>>>20&240,left=right<<24|right<<8&16711680|right>>>8&65280|right>>>24&240,right=tmp;for(var i=0;i<shifts.length;++i){shifts[i]?(left=left<<2|left>>>26,right=right<<2|right>>>26):(left=left<<1|left>>>27,right=right<<1|right>>>27),right&=-15;var lefttmp=pc2bytes0[(left&=-15)>>>28]|pc2bytes1[left>>>24&15]|pc2bytes2[left>>>20&15]|pc2bytes3[left>>>16&15]|pc2bytes4[left>>>12&15]|pc2bytes5[left>>>8&15]|pc2bytes6[left>>>4&15],righttmp=pc2bytes7[right>>>28]|pc2bytes8[right>>>24&15]|pc2bytes9[right>>>20&15]|pc2bytes10[right>>>16&15]|pc2bytes11[right>>>12&15]|pc2bytes12[right>>>8&15]|pc2bytes13[right>>>4&15];tmp=65535&(righttmp>>>16^lefttmp),keys[n++]=lefttmp^tmp,keys[n++]=righttmp^tmp<<16}}return keys}(key),this._init=!0}},registerAlgorithm("DES-ECB",forge.cipher.modes.ecb),registerAlgorithm("DES-CBC",forge.cipher.modes.cbc),registerAlgorithm("DES-CFB",forge.cipher.modes.cfb),registerAlgorithm("DES-OFB",forge.cipher.modes.ofb),registerAlgorithm("DES-CTR",forge.cipher.modes.ctr),registerAlgorithm("3DES-ECB",forge.cipher.modes.ecb),registerAlgorithm("3DES-CBC",forge.cipher.modes.cbc),registerAlgorithm("3DES-CFB",forge.cipher.modes.cfb),registerAlgorithm("3DES-OFB",forge.cipher.modes.ofb),registerAlgorithm("3DES-CTR",forge.cipher.modes.ctr);var spfunction1=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],spfunction2=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],spfunction3=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],spfunction4=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],spfunction5=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],spfunction6=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],spfunction7=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],spfunction8=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function _updateBlock(keys,input,output,decrypt){var looping,tmp,iterations=32===keys.length?3:9;looping=3===iterations?decrypt?[30,-2,-2]:[0,32,2]:decrypt?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var left=input[0],right=input[1];left^=(tmp=252645135&(left>>>4^right))<<4,left^=(tmp=65535&(left>>>16^(right^=tmp)))<<16,left^=tmp=858993459&((right^=tmp)>>>2^left),left^=tmp=16711935&((right^=tmp<<2)>>>8^left),left=(left^=(tmp=1431655765&(left>>>1^(right^=tmp<<8)))<<1)<<1|left>>>31,right=(right^=tmp)<<1|right>>>31;for(var j=0;j<iterations;j+=3){for(var endloop=looping[j+1],loopinc=looping[j+2],i=looping[j];i!=endloop;i+=loopinc){var right1=right^keys[i],right2=(right>>>4|right<<28)^keys[i+1];tmp=left,left=right,right=tmp^(spfunction2[right1>>>24&63]|spfunction4[right1>>>16&63]|spfunction6[right1>>>8&63]|spfunction8[63&right1]|spfunction1[right2>>>24&63]|spfunction3[right2>>>16&63]|spfunction5[right2>>>8&63]|spfunction7[63&right2])}tmp=left,left=right,right=tmp}right=right>>>1|right<<31,right^=tmp=1431655765&((left=left>>>1|left<<31)>>>1^right),right^=(tmp=16711935&(right>>>8^(left^=tmp<<1)))<<8,right^=(tmp=858993459&(right>>>2^(left^=tmp)))<<2,right^=tmp=65535&((left^=tmp)>>>16^right),right^=tmp=252645135&((left^=tmp<<16)>>>4^right),left^=tmp<<4,output[0]=left,output[1]=right}function _createCipher(options){var cipher,algorithm="DES-"+((options=options||{}).mode||"CBC").toUpperCase(),start=(cipher=options.decrypt?forge.cipher.createDecipher(algorithm,options.key):forge.cipher.createCipher(algorithm,options.key)).start;return cipher.start=function(iv,options){var output=null;options instanceof forge.util.ByteBuffer&&(output=options,options={}),(options=options||{}).output=output,options.iv=iv,start.call(cipher,options)},cipher}return des}function requirePbkdf2(){if(hasRequiredPbkdf2)return pbkdf2;hasRequiredPbkdf2=1;var forge=requireForge();requireHmac(),requireMd(),requireUtil();var crypto,pkcs5=forge.pkcs5=forge.pkcs5||{};return forge.util.isNodejs&&!forge.options.usePureJavaScript&&(crypto=require$$0__default$1.default),pbkdf2=forge.pbkdf2=pkcs5.pbkdf2=function(p,s,c,dkLen,md,callback){if("function"==typeof md&&(callback=md,md=null),forge.util.isNodejs&&!forge.options.usePureJavaScript&&crypto.pbkdf2&&(null===md||"object"!=typeof md)&&(crypto.pbkdf2Sync.length>4||!md||"sha1"===md))return"string"!=typeof md&&(md="sha1"),p=Buffer.from(p,"binary"),s=Buffer.from(s,"binary"),callback?4===crypto.pbkdf2Sync.length?crypto.pbkdf2(p,s,c,dkLen,function(err,key){if(err)return callback(err);callback(null,key.toString("binary"))}):crypto.pbkdf2(p,s,c,dkLen,md,function(err,key){if(err)return callback(err);callback(null,key.toString("binary"))}):4===crypto.pbkdf2Sync.length?crypto.pbkdf2Sync(p,s,c,dkLen).toString("binary"):crypto.pbkdf2Sync(p,s,c,dkLen,md).toString("binary");if(null==md&&(md="sha1"),"string"==typeof md){if(!(md in forge.md.algorithms))throw new Error("Unknown hash algorithm: "+md);md=forge.md[md].create()}var hLen=md.digestLength;if(dkLen>4294967295*hLen){var err=new Error("Derived key is too long.");if(callback)return callback(err);throw err}var len=Math.ceil(dkLen/hLen),r=dkLen-(len-1)*hLen,prf=forge.hmac.create();prf.start(md,p);var xor,u_c,u_c1,dk="";if(!callback){for(var i=1;i<=len;++i){prf.start(null,null),prf.update(s),prf.update(forge.util.int32ToBytes(i)),xor=u_c1=prf.digest().getBytes();for(var j=2;j<=c;++j)prf.start(null,null),prf.update(u_c1),u_c=prf.digest().getBytes(),xor=forge.util.xorBytes(xor,u_c,hLen),u_c1=u_c;dk+=i<len?xor:xor.substr(0,r)}return dk}i=1;function outer(){if(i>len)return callback(null,dk);prf.start(null,null),prf.update(s),prf.update(forge.util.int32ToBytes(i)),xor=u_c1=prf.digest().getBytes(),j=2,inner()}function inner(){if(j<=c)return prf.start(null,null),prf.update(u_c1),u_c=prf.digest().getBytes(),xor=forge.util.xorBytes(xor,u_c,hLen),u_c1=u_c,++j,forge.util.setImmediate(inner);dk+=i<len?xor:xor.substr(0,r),++i,outer()}outer()},pbkdf2}var hasRequiredSha256,random={exports:{}},sha256={exports:{}};function requireSha256(){if(hasRequiredSha256)return sha256.exports;hasRequiredSha256=1;var forge=requireForge();requireMd(),requireUtil();var sha256$1=sha256.exports=forge.sha256=forge.sha256||{};forge.md.sha256=forge.md.algorithms.sha256=sha256$1,sha256$1.create=function(){_initialized||function _init(){_padding=String.fromCharCode(128),_padding+=forge.util.fillString(String.fromCharCode(0),64),_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],_initialized=!0}();var _state=null,_input=forge.util.createBuffer(),_w=new Array(64),md={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){md.messageLength=0,md.fullMessageLength=md.messageLength64=[];for(var int32s=md.messageLengthSize/4,i=0;i<int32s;++i)md.fullMessageLength.push(0);return _input=forge.util.createBuffer(),_state={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},md}};return md.start(),md.update=function(msg,encoding){"utf8"===encoding&&(msg=forge.util.encodeUtf8(msg));var len=msg.length;md.messageLength+=len,len=[len/4294967296>>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i)md.fullMessageLength[i]+=len[1],len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0),md.fullMessageLength[i]=md.fullMessageLength[i]>>>0,len[0]=len[1]/4294967296>>>0;return _input.putBytes(msg),_update(_state,_w,_input),(_input.read>2048||0===_input.length())&&_input.compact(),md},md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var next,overflow=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));for(var bits=8*md.fullMessageLength[0],i=0;i<md.fullMessageLength.length-1;++i)bits+=(next=8*md.fullMessageLength[i+1])/4294967296>>>0,finalBlock.putInt32(bits>>>0),bits=next>>>0;finalBlock.putInt32(bits);var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4,h5:_state.h5,h6:_state.h6,h7:_state.h7};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();return rval.putInt32(s2.h0),rval.putInt32(s2.h1),rval.putInt32(s2.h2),rval.putInt32(s2.h3),rval.putInt32(s2.h4),rval.putInt32(s2.h5),rval.putInt32(s2.h6),rval.putInt32(s2.h7),rval},md};var _padding=null,_initialized=!1,_k=null;function _update(s,w,bytes){for(var t1,t2,s0,maj,i,a,b,c,d,e,f,g,h,len=bytes.length();len>=64;){for(i=0;i<16;++i)w[i]=bytes.getInt32();for(;i<64;++i)t1=((t1=w[i-2])>>>17|t1<<15)^(t1>>>19|t1<<13)^t1>>>10,t2=((t2=w[i-15])>>>7|t2<<25)^(t2>>>18|t2<<14)^t2>>>3,w[i]=t1+w[i-7]+t2+w[i-16]|0;for(a=s.h0,b=s.h1,c=s.h2,d=s.h3,e=s.h4,f=s.h5,g=s.h6,h=s.h7,i=0;i<64;++i)s0=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),maj=a&b|c&(a^b),t1=h+((e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7))+(g^e&(f^g))+_k[i]+w[i],h=g,g=f,f=e,e=d+t1>>>0,d=c,c=b,b=a,a=t1+(t2=s0+maj)>>>0;s.h0=s.h0+a|0,s.h1=s.h1+b|0,s.h2=s.h2+c|0,s.h3=s.h3+d|0,s.h4=s.h4+e|0,s.h5=s.h5+f|0,s.h6=s.h6+g|0,s.h7=s.h7+h|0,len-=64}}return sha256.exports}var hasRequiredPrng,hasRequiredRandom,rc2,hasRequiredRc2,jsbn,hasRequiredJsbn,prng={exports:{}};function requirePrng(){if(hasRequiredPrng)return prng.exports;hasRequiredPrng=1;var forge=requireForge();requireUtil();var _crypto=null;return!forge.util.isNodejs||forge.options.usePureJavaScript||process.versions["node-webkit"]||(_crypto=require$$0__default$1.default),(prng.exports=forge.prng=forge.prng||{}).create=function(plugin){for(var ctx={plugin:plugin,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},md=plugin.md,pools=new Array(32),i=0;i<32;++i)pools[i]=md.create();function _reseedSync(){if(ctx.pools[0].messageLength>=32)return _seed();var needed=32-ctx.pools[0].messageLength<<5;ctx.collect(ctx.seedFileSync(needed)),_seed()}function _seed(){ctx.reseeds=4294967295===ctx.reseeds?0:ctx.reseeds+1;var md=ctx.plugin.md.create();md.update(ctx.keyBytes);for(var _2powK=1,k=0;k<32;++k)ctx.reseeds%_2powK===0&&(md.update(ctx.pools[k].digest().getBytes()),ctx.pools[k].start()),_2powK<<=1;ctx.keyBytes=md.digest().getBytes(),md.start(),md.update(ctx.keyBytes);var seedBytes=md.digest().getBytes();ctx.key=ctx.plugin.formatKey(ctx.keyBytes),ctx.seed=ctx.plugin.formatSeed(seedBytes),ctx.generated=0}function defaultSeedFile(needed){var getRandomValues=null,globalScope=forge.util.globalScope,_crypto=globalScope.crypto||globalScope.msCrypto;_crypto&&_crypto.getRandomValues&&(getRandomValues=function(arr){return _crypto.getRandomValues(arr)});var b=forge.util.createBuffer();if(getRandomValues)for(;b.length()<needed;){var count=Math.max(1,Math.min(needed-b.length(),65536)/4),entropy=new Uint32Array(Math.floor(count));try{getRandomValues(entropy);for(var i=0;i<entropy.length;++i)b.putInt32(entropy[i])}catch(e){if(!("undefined"!=typeof QuotaExceededError&&e instanceof QuotaExceededError))throw e}}if(b.length()<needed)for(var hi,lo,next,seed=Math.floor(65536*Math.random());b.length()<needed;){lo=16807*(65535&seed),lo+=(32767&(hi=16807*(seed>>16)))<<16,seed=4294967295&(lo=(2147483647&(lo+=hi>>15))+(lo>>31));for(i=0;i<3;++i)next=seed>>>(i<<3),next^=Math.floor(256*Math.random()),b.putByte(255&next)}return b.getBytes(needed)}return ctx.pools=pools,ctx.pool=0,ctx.generate=function(count,callback){if(!callback)return ctx.generateSync(count);var cipher=ctx.plugin.cipher,increment=ctx.plugin.increment,formatKey=ctx.plugin.formatKey,formatSeed=ctx.plugin.formatSeed,b=forge.util.createBuffer();ctx.key=null,function generate(err){if(err)return callback(err);if(b.length()>=count)return callback(null,b.getBytes(count));ctx.generated>1048575&&(ctx.key=null);if(null===ctx.key)return forge.util.nextTick(function(){!function _reseed(callback){if(ctx.pools[0].messageLength>=32)return _seed(),callback();var needed=32-ctx.pools[0].messageLength<<5;ctx.seedFile(needed,function(err,bytes){if(err)return callback(err);ctx.collect(bytes),_seed(),callback()})}(generate)});var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length,b.putBytes(bytes),ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed))),ctx.seed=formatSeed(cipher(ctx.key,ctx.seed)),forge.util.setImmediate(generate)}()},ctx.generateSync=function(count){var cipher=ctx.plugin.cipher,increment=ctx.plugin.increment,formatKey=ctx.plugin.formatKey,formatSeed=ctx.plugin.formatSeed;ctx.key=null;for(var b=forge.util.createBuffer();b.length()<count;){ctx.generated>1048575&&(ctx.key=null),null===ctx.key&&_reseedSync();var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length,b.putBytes(bytes),ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed))),ctx.seed=formatSeed(cipher(ctx.key,ctx.seed))}return b.getBytes(count)},_crypto?(ctx.seedFile=function(needed,callback){_crypto.randomBytes(needed,function(err,bytes){if(err)return callback(err);callback(null,bytes.toString())})},ctx.seedFileSync=function(needed){return _crypto.randomBytes(needed).toString()}):(ctx.seedFile=function(needed,callback){try{callback(null,defaultSeedFile(needed))}catch(e){callback(e)}},ctx.seedFileSync=defaultSeedFile),ctx.collect=function(bytes){for(var count=bytes.length,i=0;i<count;++i)ctx.pools[ctx.pool].update(bytes.substr(i,1)),ctx.pool=31===ctx.pool?0:ctx.pool+1},ctx.collectInt=function(i,n){for(var bytes="",x=0;x<n;x+=8)bytes+=String.fromCharCode(i>>x&255);ctx.collect(bytes)},ctx.registerWorker=function(worker){if(worker===self)ctx.seedFile=function(needed,callback){self.addEventListener("message",function listener(e){var data=e.data;data.forge&&data.forge.prng&&(self.removeEventListener("message",listener),callback(data.forge.prng.err,data.forge.prng.bytes))}),self.postMessage({forge:{prng:{needed:needed}}})};else{worker.addEventListener("message",function(e){var data=e.data;data.forge&&data.forge.prng&&ctx.seedFile(data.forge.prng.needed,function(err,bytes){worker.postMessage({forge:{prng:{err:err,bytes:bytes}}})})})}},ctx},prng.exports}function requireRandom(){if(hasRequiredRandom)return random.exports;hasRequiredRandom=1;var forge=requireForge();return requireAes(),requireSha256(),requirePrng(),requireUtil(),forge.random&&forge.random.getBytes?random.exports=forge.random:function(jQuery){var prng_aes={},_prng_aes_output=new Array(4),_prng_aes_buffer=forge.util.createBuffer();function spawnPrng(){var ctx=forge.prng.create(prng_aes);return ctx.getBytes=function(count,callback){return ctx.generate(count,callback)},ctx.getBytesSync=function(count){return ctx.generate(count)},ctx}prng_aes.formatKey=function(key){var tmp=forge.util.createBuffer(key);return(key=new Array(4))[0]=tmp.getInt32(),key[1]=tmp.getInt32(),key[2]=tmp.getInt32(),key[3]=tmp.getInt32(),forge.aes._expandKey(key,!1)},prng_aes.formatSeed=function(seed){var tmp=forge.util.createBuffer(seed);return(seed=new Array(4))[0]=tmp.getInt32(),seed[1]=tmp.getInt32(),seed[2]=tmp.getInt32(),seed[3]=tmp.getInt32(),seed},prng_aes.cipher=function(key,seed){return forge.aes._updateBlock(key,seed,_prng_aes_output,!1),_prng_aes_buffer.putInt32(_prng_aes_output[0]),_prng_aes_buffer.putInt32(_prng_aes_output[1]),_prng_aes_buffer.putInt32(_prng_aes_output[2]),_prng_aes_buffer.putInt32(_prng_aes_output[3]),_prng_aes_buffer.getBytes()},prng_aes.increment=function(seed){return++seed[3],seed},prng_aes.md=forge.md.sha256;var _ctx=spawnPrng(),getRandomValues=null,globalScope=forge.util.globalScope,_crypto=globalScope.crypto||globalScope.msCrypto;if(_crypto&&_crypto.getRandomValues&&(getRandomValues=function(arr){return _crypto.getRandomValues(arr)}),forge.options.usePureJavaScript||!forge.util.isNodejs&&!getRandomValues){if(_ctx.collectInt(+new Date,32),"undefined"!=typeof navigator){var _navBytes="";for(var key in navigator)try{"string"==typeof navigator[key]&&(_navBytes+=navigator[key])}catch(e){}_ctx.collect(_navBytes),_navBytes=null}jQuery&&(jQuery().mousemove(function(e){_ctx.collectInt(e.clientX,16),_ctx.collectInt(e.clientY,16)}),jQuery().keypress(function(e){_ctx.collectInt(e.charCode,8)}))}if(forge.random)for(var key in _ctx)forge.random[key]=_ctx[key];else forge.random=_ctx;forge.random.createInstance=spawnPrng,random.exports=forge.random}("undefined"!=typeof jQuery?jQuery:null),random.exports}function requireRc2(){if(hasRequiredRc2)return rc2;hasRequiredRc2=1;var forge=requireForge();requireUtil();var piTable=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],s=[1,2,3,5],rol=function(word,bits){return word<<bits&65535|(65535&word)>>16-bits},ror=function(word,bits){return(65535&word)>>bits|word<<16-bits&65535};rc2=forge.rc2=forge.rc2||{},forge.rc2.expandKey=function(key,effKeyBits){"string"==typeof key&&(key=forge.util.createBuffer(key)),effKeyBits=effKeyBits||128;var i,L=key,T=key.length(),T1=effKeyBits,T8=Math.ceil(T1/8),TM=255>>(7&T1);for(i=T;i<128;i++)L.putByte(piTable[L.at(i-1)+L.at(i-T)&255]);for(L.setAt(128-T8,piTable[L.at(128-T8)&TM]),i=127-T8;i>=0;i--)L.setAt(i,piTable[L.at(i+1)^L.at(i+T8)]);return L};var createCipher=function(key,bits,encrypt){var mixRound,mashRound,i,j,_finish=!1,_input=null,_output=null,_iv=null,K=[];for(key=forge.rc2.expandKey(key,bits),i=0;i<64;i++)K.push(key.getInt16Le());encrypt?(mixRound=function(R){for(i=0;i<4;i++)R[i]+=K[j]+(R[(i+3)%4]&R[(i+2)%4])+(~R[(i+3)%4]&R[(i+1)%4]),R[i]=rol(R[i],s[i]),j++},mashRound=function(R){for(i=0;i<4;i++)R[i]+=K[63&R[(i+3)%4]]}):(mixRound=function(R){for(i=3;i>=0;i--)R[i]=ror(R[i],s[i]),R[i]-=K[j]+(R[(i+3)%4]&R[(i+2)%4])+(~R[(i+3)%4]&R[(i+1)%4]),j--},mashRound=function(R){for(i=3;i>=0;i--)R[i]-=K[63&R[(i+3)%4]]});var runPlan=function(plan){var R=[];for(i=0;i<4;i++){var val=_input.getInt16Le();null!==_iv&&(encrypt?val^=_iv.getInt16Le():_iv.putInt16Le(val)),R.push(65535&val)}j=encrypt?0:63;for(var ptr=0;ptr<plan.length;ptr++)for(var ctr=0;ctr<plan[ptr][0];ctr++)plan[ptr][1](R);for(i=0;i<4;i++)null!==_iv&&(encrypt?_iv.putInt16Le(R[i]):R[i]^=_iv.getInt16Le()),_output.putInt16Le(R[i])},cipher=null;return cipher={start:function(iv,output){iv&&"string"==typeof iv&&(iv=forge.util.createBuffer(iv)),_finish=!1,_input=forge.util.createBuffer(),_output=output||new forge.util.createBuffer,_iv=iv,cipher.output=_output},update:function(input){for(_finish||_input.putBuffer(input);_input.length()>=8;)runPlan([[5,mixRound],[1,mashRound],[6,mixRound],[1,mashRound],[5,mixRound]])},finish:function(pad){var rval=!0;if(encrypt)if(pad)rval=pad(8,_input,!encrypt);else{var padding=8===_input.length()?8:8-_input.length();_input.fillWithByte(padding,padding)}if(rval&&(_finish=!0,cipher.update()),!encrypt&&(rval=0===_input.length()))if(pad)rval=pad(8,_output,!encrypt);else{var len=_output.length(),count=_output.at(len-1);count>len?rval=!1:_output.truncate(count)}return rval}},cipher};return forge.rc2.startEncrypting=function(key,iv,output){var cipher=forge.rc2.createEncryptionCipher(key,128);return cipher.start(iv,output),cipher},forge.rc2.createEncryptionCipher=function(key,bits){return createCipher(key,bits,!0)},forge.rc2.startDecrypting=function(key,iv,output){var cipher=forge.rc2.createDecryptionCipher(key,128);return cipher.start(iv,output),cipher},forge.rc2.createDecryptionCipher=function(key,bits){return createCipher(key,bits,!1)},rc2}function requireJsbn(){if(hasRequiredJsbn)return jsbn;hasRequiredJsbn=1;var dbits,forge=requireForge();function BigInteger(a,b,c){this.data=[],null!=a&&("number"==typeof a?this.fromNumber(a,b,c):null==b&&"string"!=typeof a?this.fromString(a,256):this.fromString(a,b))}function nbi(){return new BigInteger(null)}function am3(i,x,w,j,c,n){for(var xl=16383&x,xh=x>>14;--n>=0;){var l=16383&this.data[i],h=this.data[i++]>>14,m=xh*l+h*xl;c=((l=xl*l+((16383&m)<<14)+w.data[j]+c)>>28)+(m>>14)+xh*h,w.data[j++]=268435455&l}return c}jsbn=forge.jsbn=forge.jsbn||{},forge.jsbn.BigInteger=BigInteger,"undefined"==typeof navigator?(BigInteger.prototype.am=am3,dbits=28):"Microsoft Internet Explorer"==navigator.appName?(BigInteger.prototype.am=function am2(i,x,w,j,c,n){for(var xl=32767&x,xh=x>>15;--n>=0;){var l=32767&this.data[i],h=this.data[i++]>>15,m=xh*l+h*xl;c=((l=xl*l+((32767&m)<<15)+w.data[j]+(1073741823&c))>>>30)+(m>>>15)+xh*h+(c>>>30),w.data[j++]=1073741823&l}return c},dbits=30):"Netscape"!=navigator.appName?(BigInteger.prototype.am=function am1(i,x,w,j,c,n){for(;--n>=0;){var v=x*this.data[i++]+w.data[j]+c;c=Math.floor(v/67108864),w.data[j++]=67108863&v}return c},dbits=26):(BigInteger.prototype.am=am3,dbits=28),BigInteger.prototype.DB=dbits,BigInteger.prototype.DM=(1<<dbits)-1,BigInteger.prototype.DV=1<<dbits;BigInteger.prototype.FV=Math.pow(2,52),BigInteger.prototype.F1=52-dbits,BigInteger.prototype.F2=2*dbits-52;var rr,vv,BI_RC=new Array;for(rr="0".charCodeAt(0),vv=0;vv<=9;++vv)BI_RC[rr++]=vv;for(rr="a".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;for(rr="A".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;function int2char(n){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(n)}function intAt(s,i){var c=BI_RC[s.charCodeAt(i)];return null==c?-1:c}function nbv(i){var r=nbi();return r.fromInt(i),r}function nbits(x){var t,r=1;return 0!=(t=x>>>16)&&(x=t,r+=16),0!=(t=x>>8)&&(x=t,r+=8),0!=(t=x>>4)&&(x=t,r+=4),0!=(t=x>>2)&&(x=t,r+=2),0!=(t=x>>1)&&(x=t,r+=1),r}function Classic(m){this.m=m}function Montgomery(m){this.m=m,this.mp=m.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<m.DB-15)-1,this.mt2=2*m.t}function op_and(x,y){return x&y}function op_or(x,y){return x|y}function op_xor(x,y){return x^y}function op_andnot(x,y){return x&~y}function lbit(x){if(0==x)return-1;var r=0;return 65535&x||(x>>=16,r+=16),255&x||(x>>=8,r+=8),15&x||(x>>=4,r+=4),3&x||(x>>=2,r+=2),1&x||++r,r}function cbit(x){for(var r=0;0!=x;)x&=x-1,++r;return r}function NullExp(){}function nNop(x){return x}function Barrett(m){this.r2=nbi(),this.q3=nbi(),BigInteger.ONE.dlShiftTo(2*m.t,this.r2),this.mu=this.r2.divide(m),this.m=m}Classic.prototype.convert=function cConvert(x){return x.s<0||x.compareTo(this.m)>=0?x.mod(this.m):x},Classic.prototype.revert=function cRevert(x){return x},Classic.prototype.reduce=function cReduce(x){x.divRemTo(this.m,null,x)},Classic.prototype.mulTo=function cMulTo(x,y,r){x.multiplyTo(y,r),this.reduce(r)},Classic.prototype.sqrTo=function cSqrTo(x,r){x.squareTo(r),this.reduce(r)},Montgomery.prototype.convert=function montConvert(x){var r=nbi();return x.abs().dlShiftTo(this.m.t,r),r.divRemTo(this.m,null,r),x.s<0&&r.compareTo(BigInteger.ZERO)>0&&this.m.subTo(r,r),r},Montgomery.prototype.revert=function montRevert(x){var r=nbi();return x.copyTo(r),this.reduce(r),r},Montgomery.prototype.reduce=function montReduce(x){for(;x.t<=this.mt2;)x.data[x.t++]=0;for(var i=0;i<this.m.t;++i){var j=32767&x.data[i],u0=j*this.mpl+((j*this.mph+(x.data[i]>>15)*this.mpl&this.um)<<15)&x.DM;for(j=i+this.m.t,x.data[j]+=this.m.am(0,u0,x,i,0,this.m.t);x.data[j]>=x.DV;)x.data[j]-=x.DV,x.data[++j]++}x.clamp(),x.drShiftTo(this.m.t,x),x.compareTo(this.m)>=0&&x.subTo(this.m,x)},Montgomery.prototype.mulTo=function montMulTo(x,y,r){x.multiplyTo(y,r),this.reduce(r)},Montgomery.prototype.sqrTo=function montSqrTo(x,r){x.squareTo(r),this.reduce(r)},BigInteger.prototype.copyTo=function bnpCopyTo(r){for(var i=this.t-1;i>=0;--i)r.data[i]=this.data[i];r.t=this.t,r.s=this.s},BigInteger.prototype.fromInt=function bnpFromInt(x){this.t=1,this.s=x<0?-1:0,x>0?this.data[0]=x:x<-1?this.data[0]=x+this.DV:this.t=0},BigInteger.prototype.fromString=function bnpFromString(s,b){var k;if(16==b)k=4;else if(8==b)k=3;else if(256==b)k=8;else if(2==b)k=1;else if(32==b)k=5;else{if(4!=b)return void this.fromRadix(s,b);k=2}this.t=0,this.s=0;for(var i=s.length,mi=!1,sh=0;--i>=0;){var x=8==k?255&s[i]:intAt(s,i);x<0?"-"==s.charAt(i)&&(mi=!0):(mi=!1,0==sh?this.data[this.t++]=x:sh+k>this.DB?(this.data[this.t-1]|=(x&(1<<this.DB-sh)-1)<<sh,this.data[this.t++]=x>>this.DB-sh):this.data[this.t-1]|=x<<sh,(sh+=k)>=this.DB&&(sh-=this.DB))}8==k&&128&s[0]&&(this.s=-1,sh>0&&(this.data[this.t-1]|=(1<<this.DB-sh)-1<<sh)),this.clamp(),mi&&BigInteger.ZERO.subTo(this,this)},BigInteger.prototype.clamp=function bnpClamp(){for(var c=this.s&this.DM;this.t>0&&this.data[this.t-1]==c;)--this.t},BigInteger.prototype.dlShiftTo=function bnpDLShiftTo(n,r){var i;for(i=this.t-1;i>=0;--i)r.data[i+n]=this.data[i];for(i=n-1;i>=0;--i)r.data[i]=0;r.t=this.t+n,r.s=this.s},BigInteger.prototype.drShiftTo=function bnpDRShiftTo(n,r){for(var i=n;i<this.t;++i)r.data[i-n]=this.data[i];r.t=Math.max(this.t-n,0),r.s=this.s},BigInteger.prototype.lShiftTo=function bnpLShiftTo(n,r){var i,bs=n%this.DB,cbs=this.DB-bs,bm=(1<<cbs)-1,ds=Math.floor(n/this.DB),c=this.s<<bs&this.DM;for(i=this.t-1;i>=0;--i)r.data[i+ds+1]=this.data[i]>>cbs|c,c=(this.data[i]&bm)<<bs;for(i=ds-1;i>=0;--i)r.data[i]=0;r.data[ds]=c,r.t=this.t+ds+1,r.s=this.s,r.clamp()},BigInteger.prototype.rShiftTo=function bnpRShiftTo(n,r){r.s=this.s;var ds=Math.floor(n/this.DB);if(ds>=this.t)r.t=0;else{var bs=n%this.DB,cbs=this.DB-bs,bm=(1<<bs)-1;r.data[0]=this.data[ds]>>bs;for(var i=ds+1;i<this.t;++i)r.data[i-ds-1]|=(this.data[i]&bm)<<cbs,r.data[i-ds]=this.data[i]>>bs;bs>0&&(r.data[this.t-ds-1]|=(this.s&bm)<<cbs),r.t=this.t-ds,r.clamp()}},BigInteger.prototype.subTo=function bnpSubTo(a,r){for(var i=0,c=0,m=Math.min(a.t,this.t);i<m;)c+=this.data[i]-a.data[i],r.data[i++]=c&this.DM,c>>=this.DB;if(a.t<this.t){for(c-=a.s;i<this.t;)c+=this.data[i],r.data[i++]=c&this.DM,c>>=this.DB;c+=this.s}else{for(c+=this.s;i<a.t;)c-=a.data[i],r.data[i++]=c&this.DM,c>>=this.DB;c-=a.s}r.s=c<0?-1:0,c<-1?r.data[i++]=this.DV+c:c>0&&(r.data[i++]=c),r.t=i,r.clamp()},BigInteger.prototype.multiplyTo=function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs(),i=x.t;for(r.t=i+y.t;--i>=0;)r.data[i]=0;for(i=0;i<y.t;++i)r.data[i+x.t]=x.am(0,y.data[i],r,i,0,x.t);r.s=0,r.clamp(),this.s!=a.s&&BigInteger.ZERO.subTo(r,r)},BigInteger.prototype.squareTo=function bnpSquareTo(r){for(var x=this.abs(),i=r.t=2*x.t;--i>=0;)r.data[i]=0;for(i=0;i<x.t-1;++i){var c=x.am(i,x.data[i],r,2*i,0,1);(r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1))>=x.DV&&(r.data[i+x.t]-=x.DV,r.data[i+x.t+1]=1)}r.t>0&&(r.data[r.t-1]+=x.am(i,x.data[i],r,2*i,0,1)),r.s=0,r.clamp()},BigInteger.prototype.divRemTo=function bnpDivRemTo(m,q,r){var pm=m.abs();if(!(pm.t<=0)){var pt=this.abs();if(pt.t<pm.t)return null!=q&&q.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=nbi());var y=nbi(),ts=this.s,ms=m.s,nsh=this.DB-nbits(pm.data[pm.t-1]);nsh>0?(pm.lShiftTo(nsh,y),pt.lShiftTo(nsh,r)):(pm.copyTo(y),pt.copyTo(r));var ys=y.t,y0=y.data[ys-1];if(0!=y0){var yt=y0*(1<<this.F1)+(ys>1?y.data[ys-2]>>this.F2:0),d1=this.FV/yt,d2=(1<<this.F1)/yt,e=1<<this.F2,i=r.t,j=i-ys,t=null==q?nbi():q;for(y.dlShiftTo(j,t),r.compareTo(t)>=0&&(r.data[r.t++]=1,r.subTo(t,r)),BigInteger.ONE.dlShiftTo(ys,t),t.subTo(y,y);y.t<ys;)y.data[y.t++]=0;for(;--j>=0;){var qd=r.data[--i]==y0?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);if((r.data[i]+=y.am(0,qd,r,j,0,ys))<qd)for(y.dlShiftTo(j,t),r.subTo(t,r);r.data[i]<--qd;)r.subTo(t,r)}null!=q&&(r.drShiftTo(ys,q),ts!=ms&&BigInteger.ZERO.subTo(q,q)),r.t=ys,r.clamp(),nsh>0&&r.rShiftTo(nsh,r),ts<0&&BigInteger.ZERO.subTo(r,r)}}},BigInteger.prototype.invDigit=function bnpInvDigit(){if(this.t<1)return 0;var x=this.data[0];if(!(1&x))return 0;var y=3&x;return(y=(y=(y=(y=y*(2-(15&x)*y)&15)*(2-(255&x)*y)&255)*(2-((65535&x)*y&65535))&65535)*(2-x*y%this.DV)%this.DV)>0?this.DV-y:-y},BigInteger.prototype.isEven=function bnpIsEven(){return 0==(this.t>0?1&this.data[0]:this.s)},BigInteger.prototype.exp=function bnpExp(e,z){if(e>4294967295||e<1)return BigInteger.ONE;var r=nbi(),r2=nbi(),g=z.convert(this),i=nbits(e)-1;for(g.copyTo(r);--i>=0;)if(z.sqrTo(r,r2),(e&1<<i)>0)z.mulTo(r2,g,r);else{var t=r;r=r2,r2=t}return z.revert(r)},BigInteger.prototype.toString=function bnToString(b){if(this.s<0)return"-"+this.negate().toString(b);var k;if(16==b)k=4;else if(8==b)k=3;else if(2==b)k=1;else if(32==b)k=5;else{if(4!=b)return this.toRadix(b);k=2}var d,km=(1<<k)-1,m=!1,r="",i=this.t,p=this.DB-i*this.DB%k;if(i-- >0)for(p<this.DB&&(d=this.data[i]>>p)>0&&(m=!0,r=int2char(d));i>=0;)p<k?(d=(this.data[i]&(1<<p)-1)<<k-p,d|=this.data[--i]>>(p+=this.DB-k)):(d=this.data[i]>>(p-=k)&km,p<=0&&(p+=this.DB,--i)),d>0&&(m=!0),m&&(r+=int2char(d));return m?r:"0"},BigInteger.prototype.negate=function bnNegate(){var r=nbi();return BigInteger.ZERO.subTo(this,r),r},BigInteger.prototype.abs=function bnAbs(){return this.s<0?this.negate():this},BigInteger.prototype.compareTo=function bnCompareTo(a){var r=this.s-a.s;if(0!=r)return r;var i=this.t;if(0!=(r=i-a.t))return this.s<0?-r:r;for(;--i>=0;)if(0!=(r=this.data[i]-a.data[i]))return r;return 0},BigInteger.prototype.bitLength=function bnBitLength(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this.data[this.t-1]^this.s&this.DM)},BigInteger.prototype.mod=function bnMod(a){var r=nbi();return this.abs().divRemTo(a,null,r),this.s<0&&r.compareTo(BigInteger.ZERO)>0&&a.subTo(r,r),r},BigInteger.prototype.modPowInt=function bnModPowInt(e,m){var z;return z=e<256||m.isEven()?new Classic(m):new Montgomery(m),this.exp(e,z)},BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1),NullExp.prototype.convert=nNop,NullExp.prototype.revert=nNop,NullExp.prototype.mulTo=function nMulTo(x,y,r){x.multiplyTo(y,r)},NullExp.prototype.sqrTo=function nSqrTo(x,r){x.squareTo(r)},Barrett.prototype.convert=function barrettConvert(x){if(x.s<0||x.t>2*this.m.t)return x.mod(this.m);if(x.compareTo(this.m)<0)return x;var r=nbi();return x.copyTo(r),this.reduce(r),r},Barrett.prototype.revert=function barrettRevert(x){return x},Barrett.prototype.reduce=function barrettReduce(x){for(x.drShiftTo(this.m.t-1,this.r2),x.t>this.m.t+1&&(x.t=this.m.t+1,x.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);x.compareTo(this.r2)<0;)x.dAddOffset(1,this.m.t+1);for(x.subTo(this.r2,x);x.compareTo(this.m)>=0;)x.subTo(this.m,x)},Barrett.prototype.mulTo=function barrettMulTo(x,y,r){x.multiplyTo(y,r),this.reduce(r)},Barrett.prototype.sqrTo=function barrettSqrTo(x,r){x.squareTo(r),this.reduce(r)};var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],lplim=(1<<26)/lowprimes[lowprimes.length-1];return BigInteger.prototype.chunkSize=function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))},BigInteger.prototype.toRadix=function bnpToRadix(b){if(null==b&&(b=10),0==this.signum()||b<2||b>36)return"0";var cs=this.chunkSize(b),a=Math.pow(b,cs),d=nbv(a),y=nbi(),z=nbi(),r="";for(this.divRemTo(d,y,z);y.signum()>0;)r=(a+z.intValue()).toString(b).substr(1)+r,y.divRemTo(d,y,z);return z.intValue().toString(b)+r},BigInteger.prototype.fromRadix=function bnpFromRadix(s,b){this.fromInt(0),null==b&&(b=10);for(var cs=this.chunkSize(b),d=Math.pow(b,cs),mi=!1,j=0,w=0,i=0;i<s.length;++i){var x=intAt(s,i);x<0?"-"==s.charAt(i)&&0==this.signum()&&(mi=!0):(w=b*w+x,++j>=cs&&(this.dMultiply(d),this.dAddOffset(w,0),j=0,w=0))}j>0&&(this.dMultiply(Math.pow(b,j)),this.dAddOffset(w,0)),mi&&BigInteger.ZERO.subTo(this,this)},BigInteger.prototype.fromNumber=function bnpFromNumber(a,b,c){if("number"==typeof b)if(a<2)this.fromInt(1);else for(this.fromNumber(a,c),this.testBit(a-1)||this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(b);)this.dAddOffset(2,0),this.bitLength()>a&&this.subTo(BigInteger.ONE.shiftLeft(a-1),this);else{var x=new Array,t=7&a;x.length=1+(a>>3),b.nextBytes(x),t>0?x[0]&=(1<<t)-1:x[0]=0,this.fromString(x,256)}},BigInteger.prototype.bitwiseTo=function bnpBitwiseTo(a,op,r){var i,f,m=Math.min(a.t,this.t);for(i=0;i<m;++i)r.data[i]=op(this.data[i],a.data[i]);if(a.t<this.t){for(f=a.s&this.DM,i=m;i<this.t;++i)r.data[i]=op(this.data[i],f);r.t=this.t}else{for(f=this.s&this.DM,i=m;i<a.t;++i)r.data[i]=op(f,a.data[i]);r.t=a.t}r.s=op(this.s,a.s),r.clamp()},BigInteger.prototype.changeBit=function bnpChangeBit(n,op){var r=BigInteger.ONE.shiftLeft(n);return this.bitwiseTo(r,op,r),r},BigInteger.prototype.addTo=function bnpAddTo(a,r){for(var i=0,c=0,m=Math.min(a.t,this.t);i<m;)c+=this.data[i]+a.data[i],r.data[i++]=c&this.DM,c>>=this.DB;if(a.t<this.t){for(c+=a.s;i<this.t;)c+=this.data[i],r.data[i++]=c&this.DM,c>>=this.DB;c+=this.s}else{for(c+=this.s;i<a.t;)c+=a.data[i],r.data[i++]=c&this.DM,c>>=this.DB;c+=a.s}r.s=c<0?-1:0,c>0?r.data[i++]=c:c<-1&&(r.data[i++]=this.DV+c),r.t=i,r.clamp()},BigInteger.prototype.dMultiply=function bnpDMultiply(n){this.data[this.t]=this.am(0,n-1,this,0,0,this.t),++this.t,this.clamp()},BigInteger.prototype.dAddOffset=function bnpDAddOffset(n,w){if(0!=n){for(;this.t<=w;)this.data[this.t++]=0;for(this.data[w]+=n;this.data[w]>=this.DV;)this.data[w]-=this.DV,++w>=this.t&&(this.data[this.t++]=0),++this.data[w]}},BigInteger.prototype.multiplyLowerTo=function bnpMultiplyLowerTo(a,n,r){var j,i=Math.min(this.t+a.t,n);for(r.s=0,r.t=i;i>0;)r.data[--i]=0;for(j=r.t-this.t;i<j;++i)r.data[i+this.t]=this.am(0,a.data[i],r,i,0,this.t);for(j=Math.min(a.t,n);i<j;++i)this.am(0,a.data[i],r,i,0,n-i);r.clamp()},BigInteger.prototype.multiplyUpperTo=function bnpMultiplyUpperTo(a,n,r){--n;var i=r.t=this.t+a.t-n;for(r.s=0;--i>=0;)r.data[i]=0;for(i=Math.max(n-this.t,0);i<a.t;++i)r.data[this.t+i-n]=this.am(n-i,a.data[i],r,0,0,this.t+i-n);r.clamp(),r.drShiftTo(1,r)},BigInteger.prototype.modInt=function bnpModInt(n){if(n<=0)return 0;var d=this.DV%n,r=this.s<0?n-1:0;if(this.t>0)if(0==d)r=this.data[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this.data[i])%n;return r},BigInteger.prototype.millerRabin=function bnpMillerRabin(t){var n1=this.subtract(BigInteger.ONE),k=n1.getLowestSetBit();if(k<=0)return!1;for(var a,r=n1.shiftRight(k),prng=function bnGetPrng(){return{nextBytes:function(x){for(var i=0;i<x.length;++i)x[i]=Math.floor(256*Math.random())}}}(),i=0;i<t;++i){do{a=new BigInteger(this.bitLength(),prng)}while(a.compareTo(BigInteger.ONE)<=0||a.compareTo(n1)>=0);var y=a.modPow(r,this);if(0!=y.compareTo(BigInteger.ONE)&&0!=y.compareTo(n1)){for(var j=1;j++<k&&0!=y.compareTo(n1);)if(0==(y=y.modPowInt(2,this)).compareTo(BigInteger.ONE))return!1;if(0!=y.compareTo(n1))return!1}}return!0},BigInteger.prototype.clone=function bnClone(){var r=nbi();return this.copyTo(r),r},BigInteger.prototype.intValue=function bnIntValue(){if(this.s<0){if(1==this.t)return this.data[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this.data[0];if(0==this.t)return 0}return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]},BigInteger.prototype.byteValue=function bnByteValue(){return 0==this.t?this.s:this.data[0]<<24>>24},BigInteger.prototype.shortValue=function bnShortValue(){return 0==this.t?this.s:this.data[0]<<16>>16},BigInteger.prototype.signum=function bnSigNum(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},BigInteger.prototype.toByteArray=function bnToByteArray(){var i=this.t,r=new Array;r[0]=this.s;var d,p=this.DB-i*this.DB%8,k=0;if(i-- >0)for(p<this.DB&&(d=this.data[i]>>p)!=(this.s&this.DM)>>p&&(r[k++]=d|this.s<<this.DB-p);i>=0;)p<8?(d=(this.data[i]&(1<<p)-1)<<8-p,d|=this.data[--i]>>(p+=this.DB-8)):(d=this.data[i]>>(p-=8)&255,p<=0&&(p+=this.DB,--i)),128&d&&(d|=-256),0==k&&(128&this.s)!=(128&d)&&++k,(k>0||d!=this.s)&&(r[k++]=d);return r},BigInteger.prototype.equals=function bnEquals(a){return 0==this.compareTo(a)},BigInteger.prototype.min=function bnMin(a){return this.compareTo(a)<0?this:a},BigInteger.prototype.max=function bnMax(a){return this.compareTo(a)>0?this:a},BigInteger.prototype.and=function bnAnd(a){var r=nbi();return this.bitwiseTo(a,op_and,r),r},BigInteger.prototype.or=function bnOr(a){var r=nbi();return this.bitwiseTo(a,op_or,r),r},BigInteger.prototype.xor=function bnXor(a){var r=nbi();return this.bitwiseTo(a,op_xor,r),r},BigInteger.prototype.andNot=function bnAndNot(a){var r=nbi();return this.bitwiseTo(a,op_andnot,r),r},BigInteger.prototype.not=function bnNot(){for(var r=nbi(),i=0;i<this.t;++i)r.data[i]=this.DM&~this.data[i];return r.t=this.t,r.s=~this.s,r},BigInteger.prototype.shiftLeft=function bnShiftLeft(n){var r=nbi();return n<0?this.rShiftTo(-n,r):this.lShiftTo(n,r),r},BigInteger.prototype.shiftRight=function bnShiftRight(n){var r=nbi();return n<0?this.lShiftTo(-n,r):this.rShiftTo(n,r),r},BigInteger.prototype.getLowestSetBit=function bnGetLowestSetBit(){for(var i=0;i<this.t;++i)if(0!=this.data[i])return i*this.DB+lbit(this.data[i]);return this.s<0?this.t*this.DB:-1},BigInteger.prototype.bitCount=function bnBitCount(){for(var r=0,x=this.s&this.DM,i=0;i<this.t;++i)r+=cbit(this.data[i]^x);return r},BigInteger.prototype.testBit=function bnTestBit(n){var j=Math.floor(n/this.DB);return j>=this.t?0!=this.s:!!(this.data[j]&1<<n%this.DB)},BigInteger.prototype.setBit=function bnSetBit(n){return this.changeBit(n,op_or)},BigInteger.prototype.clearBit=function bnClearBit(n){return this.changeBit(n,op_andnot)},BigInteger.prototype.flipBit=function bnFlipBit(n){return this.changeBit(n,op_xor)},BigInteger.prototype.add=function bnAdd(a){var r=nbi();return this.addTo(a,r),r},BigInteger.prototype.subtract=function bnSubtract(a){var r=nbi();return this.subTo(a,r),r},BigInteger.prototype.multiply=function bnMultiply(a){var r=nbi();return this.multiplyTo(a,r),r},BigInteger.prototype.divide=function bnDivide(a){var r=nbi();return this.divRemTo(a,r,null),r},BigInteger.prototype.remainder=function bnRemainder(a){var r=nbi();return this.divRemTo(a,null,r),r},BigInteger.prototype.divideAndRemainder=function bnDivideAndRemainder(a){var q=nbi(),r=nbi();return this.divRemTo(a,q,r),new Array(q,r)},BigInteger.prototype.modPow=function bnModPow(e,m){var k,z,i=e.bitLength(),r=nbv(1);if(i<=0)return r;k=i<18?1:i<48?3:i<144?4:i<768?5:6,z=i<8?new Classic(m):m.isEven()?new Barrett(m):new Montgomery(m);var g=new Array,n=3,k1=k-1,km=(1<<k)-1;if(g[1]=z.convert(this),k>1){var g2=nbi();for(z.sqrTo(g[1],g2);n<=km;)g[n]=nbi(),z.mulTo(g2,g[n-2],g[n]),n+=2}var w,t,j=e.t-1,is1=!0,r2=nbi();for(i=nbits(e.data[j])-1;j>=0;){for(i>=k1?w=e.data[j]>>i-k1&km:(w=(e.data[j]&(1<<i+1)-1)<<k1-i,j>0&&(w|=e.data[j-1]>>this.DB+i-k1)),n=k;!(1&w);)w>>=1,--n;if((i-=n)<0&&(i+=this.DB,--j),is1)g[w].copyTo(r),is1=!1;else{for(;n>1;)z.sqrTo(r,r2),z.sqrTo(r2,r),n-=2;n>0?z.sqrTo(r,r2):(t=r,r=r2,r2=t),z.mulTo(r2,g[w],r)}for(;j>=0&&!(e.data[j]&1<<i);)z.sqrTo(r,r2),t=r,r=r2,r2=t,--i<0&&(i=this.DB-1,--j)}return z.revert(r)},BigInteger.prototype.modInverse=function bnModInverse(m){var ac=m.isEven();if(this.isEven()&&ac||0==m.signum())return BigInteger.ZERO;for(var u=m.clone(),v=this.clone(),a=nbv(1),b=nbv(0),c=nbv(0),d=nbv(1);0!=u.signum();){for(;u.isEven();)u.rShiftTo(1,u),ac?(a.isEven()&&b.isEven()||(a.addTo(this,a),b.subTo(m,b)),a.rShiftTo(1,a)):b.isEven()||b.subTo(m,b),b.rShiftTo(1,b);for(;v.isEven();)v.rShiftTo(1,v),ac?(c.isEven()&&d.isEven()||(c.addTo(this,c),d.subTo(m,d)),c.rShiftTo(1,c)):d.isEven()||d.subTo(m,d),d.rShiftTo(1,d);u.compareTo(v)>=0?(u.subTo(v,u),ac&&a.subTo(c,a),b.subTo(d,b)):(v.subTo(u,v),ac&&c.subTo(a,c),d.subTo(b,d))}return 0!=v.compareTo(BigInteger.ONE)?BigInteger.ZERO:d.compareTo(m)>=0?d.subtract(m):d.signum()<0?(d.addTo(m,d),d.signum()<0?d.add(m):d):d},BigInteger.prototype.pow=function bnPow(e){return this.exp(e,new NullExp)},BigInteger.prototype.gcd=function bnGCD(a){var x=this.s<0?this.negate():this.clone(),y=a.s<0?a.negate():a.clone();if(x.compareTo(y)<0){var t=x;x=y,y=t}var i=x.getLowestSetBit(),g=y.getLowestSetBit();if(g<0)return x;for(i<g&&(g=i),g>0&&(x.rShiftTo(g,x),y.rShiftTo(g,y));x.signum()>0;)(i=x.getLowestSetBit())>0&&x.rShiftTo(i,x),(i=y.getLowestSetBit())>0&&y.rShiftTo(i,y),x.compareTo(y)>=0?(x.subTo(y,x),x.rShiftTo(1,x)):(y.subTo(x,y),y.rShiftTo(1,y));return g>0&&y.lShiftTo(g,y),y},BigInteger.prototype.isProbablePrime=function bnIsProbablePrime(t){var i,x=this.abs();if(1==x.t&&x.data[0]<=lowprimes[lowprimes.length-1]){for(i=0;i<lowprimes.length;++i)if(x.data[0]==lowprimes[i])return!0;return!1}if(x.isEven())return!1;for(i=1;i<lowprimes.length;){for(var m=lowprimes[i],j=i+1;j<lowprimes.length&&m<lplim;)m*=lowprimes[j++];for(m=x.modInt(m);i<j;)if(m%lowprimes[i++]==0)return!1}return x.millerRabin(t)},jsbn}var hasRequiredSha1$1,hasRequiredPkcs1,pkcs1={exports:{}},sha1$2={exports:{}};function requireSha1$1(){if(hasRequiredSha1$1)return sha1$2.exports;hasRequiredSha1$1=1;var forge=requireForge();requireMd(),requireUtil();var sha1=sha1$2.exports=forge.sha1=forge.sha1||{};forge.md.sha1=forge.md.algorithms.sha1=sha1,sha1.create=function(){_initialized||function _init(){_padding=String.fromCharCode(128),_padding+=forge.util.fillString(String.fromCharCode(0),64),_initialized=!0}();var _state=null,_input=forge.util.createBuffer(),_w=new Array(80),md={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){md.messageLength=0,md.fullMessageLength=md.messageLength64=[];for(var int32s=md.messageLengthSize/4,i=0;i<int32s;++i)md.fullMessageLength.push(0);return _input=forge.util.createBuffer(),_state={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},md}};return md.start(),md.update=function(msg,encoding){"utf8"===encoding&&(msg=forge.util.encodeUtf8(msg));var len=msg.length;md.messageLength+=len,len=[len/4294967296>>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i)md.fullMessageLength[i]+=len[1],len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0),md.fullMessageLength[i]=md.fullMessageLength[i]>>>0,len[0]=len[1]/4294967296>>>0;return _input.putBytes(msg),_update(_state,_w,_input),(_input.read>2048||0===_input.length())&&_input.compact(),md},md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var next,overflow=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));for(var bits=8*md.fullMessageLength[0],i=0;i<md.fullMessageLength.length-1;++i)bits+=(next=8*md.fullMessageLength[i+1])/4294967296>>>0,finalBlock.putInt32(bits>>>0),bits=next>>>0;finalBlock.putInt32(bits);var s2={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4};_update(s2,_w,finalBlock);var rval=forge.util.createBuffer();return rval.putInt32(s2.h0),rval.putInt32(s2.h1),rval.putInt32(s2.h2),rval.putInt32(s2.h3),rval.putInt32(s2.h4),rval},md};var _padding=null,_initialized=!1;function _update(s,w,bytes){for(var t,a,b,c,d,e,i,len=bytes.length();len>=64;){for(a=s.h0,b=s.h1,c=s.h2,d=s.h3,e=s.h4,i=0;i<16;++i)t=bytes.getInt32(),w[i]=t,t=(a<<5|a>>>27)+(d^b&(c^d))+e+1518500249+t,e=d,d=c,c=(b<<30|b>>>2)>>>0,b=a,a=t;for(;i<20;++i)t=(t=w[i-3]^w[i-8]^w[i-14]^w[i-16])<<1|t>>>31,w[i]=t,t=(a<<5|a>>>27)+(d^b&(c^d))+e+1518500249+t,e=d,d=c,c=(b<<30|b>>>2)>>>0,b=a,a=t;for(;i<32;++i)t=(t=w[i-3]^w[i-8]^w[i-14]^w[i-16])<<1|t>>>31,w[i]=t,t=(a<<5|a>>>27)+(b^c^d)+e+1859775393+t,e=d,d=c,c=(b<<30|b>>>2)>>>0,b=a,a=t;for(;i<40;++i)t=(t=w[i-6]^w[i-16]^w[i-28]^w[i-32])<<2|t>>>30,w[i]=t,t=(a<<5|a>>>27)+(b^c^d)+e+1859775393+t,e=d,d=c,c=(b<<30|b>>>2)>>>0,b=a,a=t;for(;i<60;++i)t=(t=w[i-6]^w[i-16]^w[i-28]^w[i-32])<<2|t>>>30,w[i]=t,t=(a<<5|a>>>27)+(b&c|d&(b^c))+e+2400959708+t,e=d,d=c,c=(b<<30|b>>>2)>>>0,b=a,a=t;for(;i<80;++i)t=(t=w[i-6]^w[i-16]^w[i-28]^w[i-32])<<2|t>>>30,w[i]=t,t=(a<<5|a>>>27)+(b^c^d)+e+3395469782+t,e=d,d=c,c=(b<<30|b>>>2)>>>0,b=a,a=t;s.h0=s.h0+a|0,s.h1=s.h1+b|0,s.h2=s.h2+c|0,s.h3=s.h3+d|0,s.h4=s.h4+e|0,len-=64}}return sha1$2.exports}function requirePkcs1(){if(hasRequiredPkcs1)return pkcs1.exports;hasRequiredPkcs1=1;var forge=requireForge();requireUtil(),requireRandom(),requireSha1$1();var pkcs1$1=pkcs1.exports=forge.pkcs1=forge.pkcs1||{};function rsa_mgf1(seed,maskLength,hash){hash||(hash=forge.md.sha1.create());for(var t="",count=Math.ceil(maskLength/hash.digestLength),i=0;i<count;++i){var c=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,255&i);hash.start(),hash.update(seed+c),t+=hash.digest().getBytes()}return t.substring(0,maskLength)}return pkcs1$1.encode_rsa_oaep=function(key,message,options){var label,seed,md,mgf1Md;"string"==typeof options?(label=options,seed=arguments[3]||void 0,md=arguments[4]||void 0):options&&(label=options.label||void 0,seed=options.seed||void 0,md=options.md||void 0,options.mgf1&&options.mgf1.md&&(mgf1Md=options.mgf1.md)),md?md.start():md=forge.md.sha1.create(),mgf1Md||(mgf1Md=md);var keyLength=Math.ceil(key.n.bitLength()/8),maxLength=keyLength-2*md.digestLength-2;if(message.length>maxLength)throw(error=new Error("RSAES-OAEP input message length is too long.")).length=message.length,error.maxLength=maxLength,error;label||(label=""),md.update(label,"raw");for(var lHash=md.digest(),PS="",PS_length=maxLength-message.length,i=0;i<PS_length;i++)PS+="\0";var DB=lHash.getBytes()+PS+""+message;if(seed){if(seed.length!==md.digestLength){var error;throw(error=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.")).seedLength=seed.length,error.digestLength=md.digestLength,error}}else seed=forge.random.getBytes(md.digestLength);var dbMask=rsa_mgf1(seed,keyLength-md.digestLength-1,mgf1Md),maskedDB=forge.util.xorBytes(DB,dbMask,DB.length),seedMask=rsa_mgf1(maskedDB,md.digestLength,mgf1Md);return"\0"+forge.util.xorBytes(seed,seedMask,seed.length)+maskedDB},pkcs1$1.decode_rsa_oaep=function(key,em,options){var label,md,mgf1Md;"string"==typeof options?(label=options,md=arguments[3]||void 0):options&&(label=options.label||void 0,md=options.md||void 0,options.mgf1&&options.mgf1.md&&(mgf1Md=options.mgf1.md));var keyLength=Math.ceil(key.n.bitLength()/8);if(em.length!==keyLength)throw(error=new Error("RSAES-OAEP encoded message length is invalid.")).length=em.length,error.expectedLength=keyLength,error;if(void 0===md?md=forge.md.sha1.create():md.start(),mgf1Md||(mgf1Md=md),keyLength<2*md.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");label||(label=""),md.update(label,"raw");for(var lHash=md.digest().getBytes(),y=em.charAt(0),maskedSeed=em.substring(1,md.digestLength+1),maskedDB=em.substring(1+md.digestLength),seedMask=rsa_mgf1(maskedDB,md.digestLength,mgf1Md),dbMask=rsa_mgf1(forge.util.xorBytes(maskedSeed,seedMask,maskedSeed.length),keyLength-md.digestLength-1,mgf1Md),db=forge.util.xorBytes(maskedDB,dbMask,maskedDB.length),lHashPrime=db.substring(0,md.digestLength),error="\0"!==y,i=0;i<md.digestLength;++i)error|=lHash.charAt(i)!==lHashPrime.charAt(i);for(var in_ps=1,index=md.digestLength,j=md.digestLength;j<db.length;j++){var code=db.charCodeAt(j);error|=code&(in_ps?65534:0),index+=in_ps&=1&code^1}if(error||1!==db.charCodeAt(index))throw new Error("Invalid RSAES-OAEP padding.");return db.substring(index+1)},pkcs1.exports}var hasRequiredPrime,rsa,hasRequiredRsa,pbe,hasRequiredPbe,prime={exports:{}};function requirePrime(){if(hasRequiredPrime)return prime.exports;hasRequiredPrime=1;var forge=requireForge();return requireUtil(),requireJsbn(),requireRandom(),function(){if(forge.prime)prime.exports=forge.prime;else{var prime$1=prime.exports=forge.prime=forge.prime||{},BigInteger=forge.jsbn.BigInteger,GCD_30_DELTA=[6,4,2,4,2,4,6,2],THIRTY=new BigInteger(null);THIRTY.fromInt(30);var op_or=function(x,y){return x|y};prime$1.generateProbablePrime=function(bits,options,callback){"function"==typeof options&&(callback=options,options={});var algorithm=(options=options||{}).algorithm||"PRIMEINC";"string"==typeof algorithm&&(algorithm={name:algorithm}),algorithm.options=algorithm.options||{};var prng=options.prng||forge.random,rng={nextBytes:function(x){for(var b=prng.getBytesSync(x.length),i=0;i<x.length;++i)x[i]=b.charCodeAt(i)}};if("PRIMEINC"===algorithm.name)return function primeincFindPrime(bits,rng,options,callback){if("workers"in options)return function primeincFindPrimeWithWorkers(bits,rng,options,callback){if("undefined"==typeof Worker)return primeincFindPrimeWithoutWorkers(bits,rng,options,callback);var num=generateRandom(bits,rng),numWorkers=options.workers,workLoad=options.workLoad||100,range=30*workLoad/8,workerScript=options.workerScript||"forge/prime.worker.js";if(-1===numWorkers)return forge.util.estimateCores(function(err,cores){err&&(cores=2),numWorkers=cores-1,generate()});function generate(){numWorkers=Math.max(1,numWorkers);for(var workers=[],i=0;i<numWorkers;++i)workers[i]=new Worker(workerScript);for(i=0;i<numWorkers;++i)workers[i].addEventListener("message",workerMessage);var found=!1;function workerMessage(e){if(!found){var data=e.data;if(data.found){for(var i=0;i<workers.length;++i)workers[i].terminate();return found=!0,callback(null,new BigInteger(data.prime,16))}num.bitLength()>bits&&(num=generateRandom(bits,rng));var hex=num.toString(16);e.target.postMessage({hex:hex,workLoad:workLoad}),num.dAddOffset(range,0)}}}generate()}(bits,rng,options,callback);return primeincFindPrimeWithoutWorkers(bits,rng,options,callback)}(bits,rng,algorithm.options,callback);throw new Error("Invalid prime generation algorithm: "+algorithm.name)}}function primeincFindPrimeWithoutWorkers(bits,rng,options,callback){var num=generateRandom(bits,rng),mrTests=function getMillerRabinTests(bits){return bits<=100?27:bits<=150?18:bits<=200?15:bits<=250?12:bits<=300?9:bits<=350?8:bits<=400?7:bits<=500?6:bits<=600?5:bits<=800?4:bits<=1250?3:2}(num.bitLength());"millerRabinTests"in options&&(mrTests=options.millerRabinTests);var maxBlockTime=10;"maxBlockTime"in options&&(maxBlockTime=options.maxBlockTime),_primeinc(num,bits,rng,0,mrTests,maxBlockTime,callback)}function _primeinc(num,bits,rng,deltaIdx,mrTests,maxBlockTime,callback){var start=+new Date;do{if(num.bitLength()>bits&&(num=generateRandom(bits,rng)),num.isProbablePrime(mrTests))return callback(null,num);num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}while(maxBlockTime<0||+new Date-start<maxBlockTime);forge.util.setImmediate(function(){_primeinc(num,bits,rng,deltaIdx,mrTests,maxBlockTime,callback)})}function generateRandom(bits,rng){var num=new BigInteger(bits,rng),bits1=bits-1;return num.testBit(bits1)||num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,num),num.dAddOffset(31-num.mod(THIRTY).byteValue(),0),num}}(),prime.exports}function requireRsa(){if(hasRequiredRsa)return rsa;hasRequiredRsa=1;var forge=requireForge();if(requireAsn1(),requireJsbn(),requireOids(),requirePkcs1(),requirePrime(),requireRandom(),requireUtil(),void 0===BigInteger)var BigInteger=forge.jsbn.BigInteger;var _crypto=forge.util.isNodejs?require$$0__default$1.default:null,asn1=forge.asn1,util=forge.util;forge.pki=forge.pki||{},rsa=forge.pki.rsa=forge.rsa=forge.rsa||{};var pki=forge.pki,GCD_30_DELTA=[6,4,2,4,2,4,6,2],privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},rsaPrivateKeyValidator={name:"RSAPrivateKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},rsaPublicKeyValidator={name:"RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},publicKeyValidator=forge.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},digestInfoValidator={name:"DigestInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},emsaPkcs1v15encode=function(md){var oid;if(!(md.algorithm in pki.oids)){var error=new Error("Unknown message digest algorithm.");throw error.algorithm=md.algorithm,error}oid=pki.oids[md.algorithm];var oidBytes=asn1.oidToDer(oid).getBytes(),digestInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]),digestAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]);digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,oidBytes)),digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,""));var digest=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,md.digest().getBytes());return digestInfo.value.push(digestAlgorithm),digestInfo.value.push(digest),asn1.toDer(digestInfo).getBytes()},_modPow=function(x,key,pub){if(pub)return x.modPow(key.e,key.n);if(!key.p||!key.q)return x.modPow(key.d,key.n);var r;key.dP||(key.dP=key.d.mod(key.p.subtract(BigInteger.ONE))),key.dQ||(key.dQ=key.d.mod(key.q.subtract(BigInteger.ONE))),key.qInv||(key.qInv=key.q.modInverse(key.p));do{r=new BigInteger(forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength()/8)),16)}while(r.compareTo(key.n)>=0||!r.gcd(key.n).equals(BigInteger.ONE));for(var xp=(x=x.multiply(r.modPow(key.e,key.n)).mod(key.n)).mod(key.p).modPow(key.dP,key.p),xq=x.mod(key.q).modPow(key.dQ,key.q);xp.compareTo(xq)<0;)xp=xp.add(key.p);var y=xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq);return y=y.multiply(r.modInverse(key.n)).mod(key.n)};function _encodePkcs1_v1_5(m,key,bt){var eb=forge.util.createBuffer(),k=Math.ceil(key.n.bitLength()/8);if(m.length>k-11){var error=new Error("Message is too long for PKCS#1 v1.5 padding.");throw error.length=m.length,error.max=k-11,error}eb.putByte(0),eb.putByte(bt);var padByte,padNum=k-3-m.length;if(0===bt||1===bt){padByte=0===bt?0:255;for(var i=0;i<padNum;++i)eb.putByte(padByte)}else for(;padNum>0;){var numZeros=0,padBytes=forge.random.getBytes(padNum);for(i=0;i<padNum;++i)0===(padByte=padBytes.charCodeAt(i))?++numZeros:eb.putByte(padByte);padNum=numZeros}return eb.putByte(0),eb.putBytes(m),eb}function _decodePkcs1_v1_5(em,key,pub,ml){var k=Math.ceil(key.n.bitLength()/8),eb=forge.util.createBuffer(em),first=eb.getByte(),bt=eb.getByte();if(0!==first||pub&&0!==bt&&1!==bt||!pub&&2!=bt||pub&&0===bt&&void 0===ml)throw new Error("Encryption block is invalid.");var padNum=0;if(0===bt){padNum=k-3-ml;for(var i=0;i<padNum;++i)if(0!==eb.getByte())throw new Error("Encryption block is invalid.")}else if(1===bt)for(padNum=0;eb.length()>1;){if(255!==eb.getByte()){--eb.read;break}++padNum}else if(2===bt)for(padNum=0;eb.length()>1;){if(0===eb.getByte()){--eb.read;break}++padNum}if(0!==eb.getByte()||padNum!==k-3-eb.length())throw new Error("Encryption block is invalid.");return eb.getBytes()}function _bnToBytes(b){var hex=b.toString(16);hex[0]>="8"&&(hex="00"+hex);var bytes=forge.util.hexToBytes(hex);return!(bytes.length>1)||(0!==bytes.charCodeAt(0)||128&bytes.charCodeAt(1))&&(255!==bytes.charCodeAt(0)||128&~bytes.charCodeAt(1))?bytes:bytes.substr(1)}function _getMillerRabinTests(bits){return bits<=100?27:bits<=150?18:bits<=200?15:bits<=250?12:bits<=300?9:bits<=350?8:bits<=400?7:bits<=500?6:bits<=600?5:bits<=800?4:bits<=1250?3:2}function _detectNodeCrypto(fn){return forge.util.isNodejs&&"function"==typeof _crypto[fn]}function _detectSubtleCrypto(fn){return void 0!==util.globalScope&&"object"==typeof util.globalScope.crypto&&"object"==typeof util.globalScope.crypto.subtle&&"function"==typeof util.globalScope.crypto.subtle[fn]}function _detectSubtleMsCrypto(fn){return void 0!==util.globalScope&&"object"==typeof util.globalScope.msCrypto&&"object"==typeof util.globalScope.msCrypto.subtle&&"function"==typeof util.globalScope.msCrypto.subtle[fn]}function _intToUint8Array(x){for(var bytes=forge.util.hexToBytes(x.toString(16)),buffer=new Uint8Array(bytes.length),i=0;i<bytes.length;++i)buffer[i]=bytes.charCodeAt(i);return buffer}return pki.rsa.encrypt=function(m,key,bt){var eb,pub=bt,k=Math.ceil(key.n.bitLength()/8);!1!==bt&&!0!==bt?(pub=2===bt,eb=_encodePkcs1_v1_5(m,key,bt)):(eb=forge.util.createBuffer()).putBytes(m);for(var x=new BigInteger(eb.toHex(),16),yhex=_modPow(x,key,pub).toString(16),ed=forge.util.createBuffer(),zeros=k-Math.ceil(yhex.length/2);zeros>0;)ed.putByte(0),--zeros;return ed.putBytes(forge.util.hexToBytes(yhex)),ed.getBytes()},pki.rsa.decrypt=function(ed,key,pub,ml){var k=Math.ceil(key.n.bitLength()/8);if(ed.length!==k){var error=new Error("Encrypted message length is invalid.");throw error.length=ed.length,error.expected=k,error}var y=new BigInteger(forge.util.createBuffer(ed).toHex(),16);if(y.compareTo(key.n)>=0)throw new Error("Encrypted message is invalid.");for(var xhex=_modPow(y,key,pub).toString(16),eb=forge.util.createBuffer(),zeros=k-Math.ceil(xhex.length/2);zeros>0;)eb.putByte(0),--zeros;return eb.putBytes(forge.util.hexToBytes(xhex)),!1!==ml?_decodePkcs1_v1_5(eb.getBytes(),key,pub):eb.getBytes()},pki.rsa.createKeyPairGenerationState=function(bits,e,options){"string"==typeof bits&&(bits=parseInt(bits,10)),bits=bits||2048;var rval,prng=(options=options||{}).prng||forge.random,rng={nextBytes:function(x){for(var b=prng.getBytesSync(x.length),i=0;i<x.length;++i)x[i]=b.charCodeAt(i)}},algorithm=options.algorithm||"PRIMEINC";if("PRIMEINC"!==algorithm)throw new Error("Invalid key generation algorithm: "+algorithm);return(rval={algorithm:algorithm,state:0,bits:bits,rng:rng,eInt:e||65537,e:new BigInteger(null),p:null,q:null,qBits:bits>>1,pBits:bits-(bits>>1),pqState:0,num:null,keys:null}).e.fromInt(rval.eInt),rval},pki.rsa.stepKeyPairGenerationState=function(state,n){"algorithm"in state||(state.algorithm="PRIMEINC");var THIRTY=new BigInteger(null);THIRTY.fromInt(30);for(var t2,deltaIdx=0,op_or=function(x,y){return x|y},t1=+new Date,total=0;null===state.keys&&(n<=0||total<n);){if(0===state.state){var bits=null===state.p?state.pBits:state.qBits,bits1=bits-1;0===state.pqState?(state.num=new BigInteger(bits,state.rng),state.num.testBit(bits1)||state.num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,state.num),state.num.dAddOffset(31-state.num.mod(THIRTY).byteValue(),0),deltaIdx=0,++state.pqState):1===state.pqState?state.num.bitLength()>bits?state.pqState=0:state.num.isProbablePrime(_getMillerRabinTests(state.num.bitLength()))?++state.pqState:state.num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0):2===state.pqState?state.pqState=0===state.num.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE)?3:0:3===state.pqState&&(state.pqState=0,null===state.p?state.p=state.num:state.q=state.num,null!==state.p&&null!==state.q&&++state.state,state.num=null)}else if(1===state.state)state.p.compareTo(state.q)<0&&(state.num=state.p,state.p=state.q,state.q=state.num),++state.state;else if(2===state.state)state.p1=state.p.subtract(BigInteger.ONE),state.q1=state.q.subtract(BigInteger.ONE),state.phi=state.p1.multiply(state.q1),++state.state;else if(3===state.state)0===state.phi.gcd(state.e).compareTo(BigInteger.ONE)?++state.state:(state.p=null,state.q=null,state.state=0);else if(4===state.state)state.n=state.p.multiply(state.q),state.n.bitLength()===state.bits?++state.state:(state.q=null,state.state=0);else if(5===state.state){var d=state.e.modInverse(state.phi);state.keys={privateKey:pki.rsa.setPrivateKey(state.n,state.e,d,state.p,state.q,d.mod(state.p1),d.mod(state.q1),state.q.modInverse(state.p)),publicKey:pki.rsa.setPublicKey(state.n,state.e)}}total+=(t2=+new Date)-t1,t1=t2}return null!==state.keys},pki.rsa.generateKeyPair=function(bits,e,options,callback){if(1===arguments.length?"object"==typeof bits?(options=bits,bits=void 0):"function"==typeof bits&&(callback=bits,bits=void 0):2===arguments.length?"number"==typeof bits?"function"==typeof e?(callback=e,e=void 0):"number"!=typeof e&&(options=e,e=void 0):(options=bits,callback=e,bits=void 0,e=void 0):3===arguments.length&&("number"==typeof e?"function"==typeof options&&(callback=options,options=void 0):(callback=options,options=e,e=void 0)),options=options||{},void 0===bits&&(bits=options.bits||2048),void 0===e&&(e=options.e||65537),!forge.options.usePureJavaScript&&!options.prng&&bits>=256&&bits<=16384&&(65537===e||3===e))if(callback){if(_detectNodeCrypto("generateKeyPair"))return _crypto.generateKeyPair("rsa",{modulusLength:bits,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(err,pub,priv){if(err)return callback(err);callback(null,{privateKey:pki.privateKeyFromPem(priv),publicKey:pki.publicKeyFromPem(pub)})});if(_detectSubtleCrypto("generateKey")&&_detectSubtleCrypto("exportKey"))return util.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:bits,publicExponent:_intToUint8Array(e),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(pair){return util.globalScope.crypto.subtle.exportKey("pkcs8",pair.privateKey)}).then(void 0,function(err){callback(err)}).then(function(pkcs8){if(pkcs8){var privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));callback(null,{privateKey:privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})}});if(_detectSubtleMsCrypto("generateKey")&&_detectSubtleMsCrypto("exportKey")){var genOp=util.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:bits,publicExponent:_intToUint8Array(e),hash:{name:"SHA-256"}},!0,["sign","verify"]);return genOp.oncomplete=function(e){var pair=e.target.result,exportOp=util.globalScope.msCrypto.subtle.exportKey("pkcs8",pair.privateKey);exportOp.oncomplete=function(e){var pkcs8=e.target.result,privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge.util.createBuffer(pkcs8)));callback(null,{privateKey:privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})},exportOp.onerror=function(err){callback(err)}},void(genOp.onerror=function(err){callback(err)})}}else if(_detectNodeCrypto("generateKeyPairSync")){var keypair=_crypto.generateKeyPairSync("rsa",{modulusLength:bits,publicExponent:e,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:pki.privateKeyFromPem(keypair.privateKey),publicKey:pki.publicKeyFromPem(keypair.publicKey)}}var state=pki.rsa.createKeyPairGenerationState(bits,e,options);if(!callback)return pki.rsa.stepKeyPairGenerationState(state,0),state.keys;!function _generateKeyPair(state,options,callback){"function"==typeof options&&(callback=options,options={});options=options||{};var opts={algorithm:{name:options.algorithm||"PRIMEINC",options:{workers:options.workers||2,workLoad:options.workLoad||100,workerScript:options.workerScript}}};"prng"in options&&(opts.prng=options.prng);function generate(){getPrime(state.pBits,function(err,num){return err?callback(err):(state.p=num,null!==state.q?finish(err,state.q):void getPrime(state.qBits,finish))})}function getPrime(bits,callback){forge.prime.generateProbablePrime(bits,opts,callback)}function finish(err,num){if(err)return callback(err);if(state.q=num,state.p.compareTo(state.q)<0){var tmp=state.p;state.p=state.q,state.q=tmp}if(0!==state.p.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE))return state.p=null,void generate();if(0!==state.q.subtract(BigInteger.ONE).gcd(state.e).compareTo(BigInteger.ONE))return state.q=null,void getPrime(state.qBits,finish);if(state.p1=state.p.subtract(BigInteger.ONE),state.q1=state.q.subtract(BigInteger.ONE),state.phi=state.p1.multiply(state.q1),0!==state.phi.gcd(state.e).compareTo(BigInteger.ONE))return state.p=state.q=null,void generate();if(state.n=state.p.multiply(state.q),state.n.bitLength()!==state.bits)return state.q=null,void getPrime(state.qBits,finish);var d=state.e.modInverse(state.phi);state.keys={privateKey:pki.rsa.setPrivateKey(state.n,state.e,d,state.p,state.q,d.mod(state.p1),d.mod(state.q1),state.q.modInverse(state.p)),publicKey:pki.rsa.setPublicKey(state.n,state.e)},callback(null,state.keys)}generate()}(state,options,callback)},pki.setRsaPublicKey=pki.rsa.setPublicKey=function(n,e){var key={n:n,e:e,encrypt:function(data,scheme,schemeOptions){if("string"==typeof scheme?scheme=scheme.toUpperCase():void 0===scheme&&(scheme="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===scheme)scheme={encode:function(m,key,pub){return _encodePkcs1_v1_5(m,key,2).getBytes()}};else if("RSA-OAEP"===scheme||"RSAES-OAEP"===scheme)scheme={encode:function(m,key){return forge.pkcs1.encode_rsa_oaep(key,m,schemeOptions)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(scheme))scheme={encode:function(e){return e}};else if("string"==typeof scheme)throw new Error('Unsupported encryption scheme: "'+scheme+'".');var e=scheme.encode(data,key,!0);return pki.rsa.encrypt(e,key,!0)},verify:function(digest,signature,scheme,options){"string"==typeof scheme?scheme=scheme.toUpperCase():void 0===scheme&&(scheme="RSASSA-PKCS1-V1_5"),void 0===options&&(options={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in options||(options._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===scheme?scheme={verify:function(digest,d){d=_decodePkcs1_v1_5(d,key,!0);var obj=asn1.fromDer(d,{parseAllBytes:options._parseAllDigestBytes}),capture={},errors=[];if(!asn1.validate(obj,digestInfoValidator,capture,errors))throw(error=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=errors,error;var error,oid=asn1.derToOid(capture.algorithmIdentifier);if(oid!==forge.oids.md2&&oid!==forge.oids.md5&&oid!==forge.oids.sha1&&oid!==forge.oids.sha224&&oid!==forge.oids.sha256&&oid!==forge.oids.sha384&&oid!==forge.oids.sha512&&oid!==forge.oids["sha512-224"]&&oid!==forge.oids["sha512-256"])throw(error=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=oid,error;if((oid===forge.oids.md2||oid===forge.oids.md5)&&!("parameters"in capture))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return digest===capture.digest}}:"NONE"!==scheme&&"NULL"!==scheme&&null!==scheme||(scheme={verify:function(digest,d){return digest===(d=_decodePkcs1_v1_5(d,key,!0))}});var d=pki.rsa.decrypt(signature,key,!0,!1);return scheme.verify(digest,d,key.n.bitLength())}};return key},pki.setRsaPrivateKey=pki.rsa.setPrivateKey=function(n,e,d,p,q,dP,dQ,qInv){var key={n:n,e:e,d:d,p:p,q:q,dP:dP,dQ:dQ,qInv:qInv,decrypt:function(data,scheme,schemeOptions){"string"==typeof scheme?scheme=scheme.toUpperCase():void 0===scheme&&(scheme="RSAES-PKCS1-V1_5");var d=pki.rsa.decrypt(data,key,!1,!1);if("RSAES-PKCS1-V1_5"===scheme)scheme={decode:_decodePkcs1_v1_5};else if("RSA-OAEP"===scheme||"RSAES-OAEP"===scheme)scheme={decode:function(d,key){return forge.pkcs1.decode_rsa_oaep(key,d,schemeOptions)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(scheme))throw new Error('Unsupported encryption scheme: "'+scheme+'".');scheme={decode:function(d){return d}}}return scheme.decode(d,key,!1)},sign:function(md,scheme){var bt=!1;"string"==typeof scheme&&(scheme=scheme.toUpperCase()),void 0===scheme||"RSASSA-PKCS1-V1_5"===scheme?(scheme={encode:emsaPkcs1v15encode},bt=1):"NONE"!==scheme&&"NULL"!==scheme&&null!==scheme||(scheme={encode:function(){return md}},bt=1);var d=scheme.encode(md,key.n.bitLength());return pki.rsa.encrypt(d,key,bt)}};return key},pki.wrapRsaPrivateKey=function(rsaKey){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,asn1.toDer(rsaKey).getBytes())])},pki.privateKeyFromAsn1=function(obj){var n,e,d,p,q,dP,dQ,qInv,capture={},errors=[];if(asn1.validate(obj,privateKeyValidator,capture,errors)&&(obj=asn1.fromDer(forge.util.createBuffer(capture.privateKey))),capture={},errors=[],!asn1.validate(obj,rsaPrivateKeyValidator,capture,errors)){var error=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw error.errors=errors,error}return n=forge.util.createBuffer(capture.privateKeyModulus).toHex(),e=forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(),d=forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(),p=forge.util.createBuffer(capture.privateKeyPrime1).toHex(),q=forge.util.createBuffer(capture.privateKeyPrime2).toHex(),dP=forge.util.createBuffer(capture.privateKeyExponent1).toHex(),dQ=forge.util.createBuffer(capture.privateKeyExponent2).toHex(),qInv=forge.util.createBuffer(capture.privateKeyCoefficient).toHex(),pki.setRsaPrivateKey(new BigInteger(n,16),new BigInteger(e,16),new BigInteger(d,16),new BigInteger(p,16),new BigInteger(q,16),new BigInteger(dP,16),new BigInteger(dQ,16),new BigInteger(qInv,16))},pki.privateKeyToAsn1=pki.privateKeyToRSAPrivateKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.e)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.d)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.p)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.q)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.dP)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.dQ)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.qInv))])},pki.publicKeyFromAsn1=function(obj){var capture={},errors=[];if(asn1.validate(obj,publicKeyValidator,capture,errors)){var error,oid=asn1.derToOid(capture.publicKeyOid);if(oid!==pki.oids.rsaEncryption)throw(error=new Error("Cannot read public key. Unknown OID.")).oid=oid,error;obj=capture.rsaPublicKey}if(errors=[],!asn1.validate(obj,rsaPublicKeyValidator,capture,errors))throw(error=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=errors,error;var n=forge.util.createBuffer(capture.publicKeyModulus).toHex(),e=forge.util.createBuffer(capture.publicKeyExponent).toHex();return pki.setRsaPublicKey(new BigInteger(n,16),new BigInteger(e,16))},pki.publicKeyToAsn1=pki.publicKeyToSubjectPublicKeyInfo=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,!1,[pki.publicKeyToRSAPublicKey(key)])])},pki.publicKeyToRSAPublicKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,_bnToBytes(key.e))])},rsa}function requirePbe(){if(hasRequiredPbe)return pbe;hasRequiredPbe=1;var forge=requireForge();if(requireAes(),requireAsn1(),requireDes(),requireMd(),requireOids(),requirePbkdf2(),requirePem(),requireRandom(),requireRc2(),requireRsa(),requireUtil(),void 0===BigInteger)var BigInteger=forge.jsbn.BigInteger;var asn1=forge.asn1,pki=forge.pki=forge.pki||{};pbe=pki.pbe=forge.pbe=forge.pbe||{};var oids=pki.oids,encryptedPrivateKeyValidator={name:"EncryptedPrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},PBES2AlgorithmsValidator={name:"PBES2Algorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},pkcs12PbeParamsValidator={name:"pkcs-12PbeParams",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"iterations"}]};function hash(md,bytes){return md.start().update(bytes).digest().getBytes()}function prfOidToMessageDigest(prfOid){var prfAlgorithm;if(prfOid){if(!(prfAlgorithm=pki.oids[asn1.derToOid(prfOid)])){var error=new Error("Unsupported PRF OID.");throw error.oid=prfOid,error.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],error}}else prfAlgorithm="hmacWithSHA1";return prfAlgorithmToMessageDigest(prfAlgorithm)}function prfAlgorithmToMessageDigest(prfAlgorithm){var factory=forge.md;switch(prfAlgorithm){case"hmacWithSHA224":factory=forge.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":prfAlgorithm=prfAlgorithm.substr(8).toLowerCase();break;default:var error=new Error("Unsupported PRF algorithm.");throw error.algorithm=prfAlgorithm,error.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],error}if(!factory||!(prfAlgorithm in factory))throw new Error("Unknown hash algorithm: "+prfAlgorithm);return factory[prfAlgorithm].create()}return pki.encryptPrivateKeyInfo=function(obj,password,options){(options=options||{}).saltSize=options.saltSize||8,options.count=options.count||2048,options.algorithm=options.algorithm||"aes128",options.prfAlgorithm=options.prfAlgorithm||"sha1";var dkLen,encryptionAlgorithm,encryptedData,salt=forge.random.getBytesSync(options.saltSize),count=options.count,countBytes=asn1.integerToDer(count);if(0===options.algorithm.indexOf("aes")||"des"===options.algorithm){var ivLen,encOid,cipherFn;switch(options.algorithm){case"aes128":dkLen=16,ivLen=16,encOid=oids["aes128-CBC"],cipherFn=forge.aes.createEncryptionCipher;break;case"aes192":dkLen=24,ivLen=16,encOid=oids["aes192-CBC"],cipherFn=forge.aes.createEncryptionCipher;break;case"aes256":dkLen=32,ivLen=16,encOid=oids["aes256-CBC"],cipherFn=forge.aes.createEncryptionCipher;break;case"des":dkLen=8,ivLen=8,encOid=oids.desCBC,cipherFn=forge.des.createEncryptionCipher;break;default:throw(error=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=options.algorithm,error}var prfAlgorithm="hmacWith"+options.prfAlgorithm.toUpperCase(),md=prfAlgorithmToMessageDigest(prfAlgorithm),dk=forge.pkcs5.pbkdf2(password,salt,count,dkLen,md),iv=forge.random.getBytesSync(ivLen);(cipher=cipherFn(dk)).start(iv),cipher.update(asn1.toDer(obj)),cipher.finish(),encryptedData=cipher.output.getBytes();var params=function createPbkdf2Params(salt,countBytes,dkLen,prfAlgorithm){var params=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,salt),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,countBytes.getBytes())]);"hmacWithSHA1"!==prfAlgorithm&¶ms.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,forge.util.hexToBytes(dkLen.toString(16))),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")]));return params}(salt,countBytes,dkLen,prfAlgorithm);encryptionAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids.pkcs5PBES2).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids.pkcs5PBKDF2).getBytes()),params]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(encOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,iv)])])])}else{var error;if("3des"!==options.algorithm)throw(error=new Error("Cannot encrypt private key. Unknown encryption algorithm.")).algorithm=options.algorithm,error;dkLen=24;var cipher,saltBytes=new forge.util.ByteBuffer(salt);dk=pki.pbe.generatePkcs12Key(password,saltBytes,1,count,dkLen),iv=pki.pbe.generatePkcs12Key(password,saltBytes,2,count,dkLen);(cipher=forge.des.createEncryptionCipher(dk)).start(iv),cipher.update(asn1.toDer(obj)),cipher.finish(),encryptedData=cipher.output.getBytes(),encryptionAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,salt),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,countBytes.getBytes())])])}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[encryptionAlgorithm,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,encryptedData)])},pki.decryptPrivateKeyInfo=function(obj,password){var rval=null,capture={},errors=[];if(!asn1.validate(obj,encryptedPrivateKeyValidator,capture,errors)){var error=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw error.errors=errors,error}var oid=asn1.derToOid(capture.encryptionOid),cipher=pki.pbe.getCipher(oid,capture.encryptionParams,password),encrypted=forge.util.createBuffer(capture.encryptedData);return cipher.update(encrypted),cipher.finish()&&(rval=asn1.fromDer(cipher.output)),rval},pki.encryptedPrivateKeyToPem=function(epki,maxline){var msg={type:"ENCRYPTED PRIVATE KEY",body:asn1.toDer(epki).getBytes()};return forge.pem.encode(msg,{maxline:maxline})},pki.encryptedPrivateKeyFromPem=function(pem){var msg=forge.pem.decode(pem)[0];if("ENCRYPTED PRIVATE KEY"!==msg.type){var error=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw error.headerType=msg.type,error}if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return asn1.fromDer(msg.body)},pki.encryptRsaPrivateKey=function(rsaKey,password,options){if(!(options=options||{}).legacy){var rval=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));return rval=pki.encryptPrivateKeyInfo(rval,password,options),pki.encryptedPrivateKeyToPem(rval)}var algorithm,iv,dkLen,cipherFn;switch(options.algorithm){case"aes128":algorithm="AES-128-CBC",dkLen=16,iv=forge.random.getBytesSync(16),cipherFn=forge.aes.createEncryptionCipher;break;case"aes192":algorithm="AES-192-CBC",dkLen=24,iv=forge.random.getBytesSync(16),cipherFn=forge.aes.createEncryptionCipher;break;case"aes256":algorithm="AES-256-CBC",dkLen=32,iv=forge.random.getBytesSync(16),cipherFn=forge.aes.createEncryptionCipher;break;case"3des":algorithm="DES-EDE3-CBC",dkLen=24,iv=forge.random.getBytesSync(8),cipherFn=forge.des.createEncryptionCipher;break;case"des":algorithm="DES-CBC",dkLen=8,iv=forge.random.getBytesSync(8),cipherFn=forge.des.createEncryptionCipher;break;default:var error=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+options.algorithm+'".');throw error.algorithm=options.algorithm,error}var cipher=cipherFn(forge.pbe.opensslDeriveBytes(password,iv.substr(0,8),dkLen));cipher.start(iv),cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))),cipher.finish();var msg={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:algorithm,parameters:forge.util.bytesToHex(iv).toUpperCase()},body:cipher.output.getBytes()};return forge.pem.encode(msg)},pki.decryptRsaPrivateKey=function(pem,password){var rval=null,msg=forge.pem.decode(pem)[0];if("ENCRYPTED PRIVATE KEY"!==msg.type&&"PRIVATE KEY"!==msg.type&&"RSA PRIVATE KEY"!==msg.type)throw(error=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".')).headerType=error,error;if(msg.procType&&"ENCRYPTED"===msg.procType.type){var dkLen,cipherFn;switch(msg.dekInfo.algorithm){case"DES-CBC":dkLen=8,cipherFn=forge.des.createDecryptionCipher;break;case"DES-EDE3-CBC":dkLen=24,cipherFn=forge.des.createDecryptionCipher;break;case"AES-128-CBC":dkLen=16,cipherFn=forge.aes.createDecryptionCipher;break;case"AES-192-CBC":dkLen=24,cipherFn=forge.aes.createDecryptionCipher;break;case"AES-256-CBC":dkLen=32,cipherFn=forge.aes.createDecryptionCipher;break;case"RC2-40-CBC":dkLen=5,cipherFn=function(key){return forge.rc2.createDecryptionCipher(key,40)};break;case"RC2-64-CBC":dkLen=8,cipherFn=function(key){return forge.rc2.createDecryptionCipher(key,64)};break;case"RC2-128-CBC":dkLen=16,cipherFn=function(key){return forge.rc2.createDecryptionCipher(key,128)};break;default:var error;throw(error=new Error('Could not decrypt private key; unsupported encryption algorithm "'+msg.dekInfo.algorithm+'".')).algorithm=msg.dekInfo.algorithm,error}var iv=forge.util.hexToBytes(msg.dekInfo.parameters),cipher=cipherFn(forge.pbe.opensslDeriveBytes(password,iv.substr(0,8),dkLen));if(cipher.start(iv),cipher.update(forge.util.createBuffer(msg.body)),!cipher.finish())return rval;rval=cipher.output.getBytes()}else rval=msg.body;return null!==(rval="ENCRYPTED PRIVATE KEY"===msg.type?pki.decryptPrivateKeyInfo(asn1.fromDer(rval),password):asn1.fromDer(rval))&&(rval=pki.privateKeyFromAsn1(rval)),rval},pki.pbe.generatePkcs12Key=function(password,salt,id,iter,n,md){var j,l;if(null==md){if(!("sha1"in forge.md))throw new Error('"sha1" hash algorithm unavailable.');md=forge.md.sha1.create()}var u=md.digestLength,v=md.blockLength,result=new forge.util.ByteBuffer,passBuf=new forge.util.ByteBuffer;if(null!=password){for(l=0;l<password.length;l++)passBuf.putInt16(password.charCodeAt(l));passBuf.putInt16(0)}var p=passBuf.length(),s=salt.length(),D=new forge.util.ByteBuffer;D.fillWithByte(id,v);var Slen=v*Math.ceil(s/v),S=new forge.util.ByteBuffer;for(l=0;l<Slen;l++)S.putByte(salt.at(l%s));var Plen=v*Math.ceil(p/v),P=new forge.util.ByteBuffer;for(l=0;l<Plen;l++)P.putByte(passBuf.at(l%p));var I=S;I.putBuffer(P);for(var c=Math.ceil(n/u),i=1;i<=c;i++){var buf=new forge.util.ByteBuffer;buf.putBytes(D.bytes()),buf.putBytes(I.bytes());for(var round=0;round<iter;round++)md.start(),md.update(buf.getBytes()),buf=md.digest();var B=new forge.util.ByteBuffer;for(l=0;l<v;l++)B.putByte(buf.at(l%u));var k=Math.ceil(s/v)+Math.ceil(p/v),Inew=new forge.util.ByteBuffer;for(j=0;j<k;j++){var chunk=new forge.util.ByteBuffer(I.getBytes(v)),x=511;for(l=B.length()-1;l>=0;l--)x>>=8,x+=B.at(l)+chunk.at(l),chunk.setAt(l,255&x);Inew.putBuffer(chunk)}I=Inew,result.putBuffer(buf)}return result.truncate(result.length()-n),result},pki.pbe.getCipher=function(oid,params,password){switch(oid){case pki.oids.pkcs5PBES2:return pki.pbe.getCipherForPBES2(oid,params,password);case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:return pki.pbe.getCipherForPKCS12PBE(oid,params,password);default:var error=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw error.oid=oid,error.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],error}},pki.pbe.getCipherForPBES2=function(oid,params,password){var error,capture={},errors=[];if(!asn1.validate(params,PBES2AlgorithmsValidator,capture,errors))throw(error=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=errors,error;if((oid=asn1.derToOid(capture.kdfOid))!==pki.oids.pkcs5PBKDF2)throw(error=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=oid,error.supportedOids=["pkcs5PBKDF2"],error;if((oid=asn1.derToOid(capture.encOid))!==pki.oids["aes128-CBC"]&&oid!==pki.oids["aes192-CBC"]&&oid!==pki.oids["aes256-CBC"]&&oid!==pki.oids["des-EDE3-CBC"]&&oid!==pki.oids.desCBC)throw(error=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=oid,error.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],error;var dkLen,cipherFn,salt=capture.kdfSalt,count=forge.util.createBuffer(capture.kdfIterationCount);switch(count=count.getInt(count.length()<<3),pki.oids[oid]){case"aes128-CBC":dkLen=16,cipherFn=forge.aes.createDecryptionCipher;break;case"aes192-CBC":dkLen=24,cipherFn=forge.aes.createDecryptionCipher;break;case"aes256-CBC":dkLen=32,cipherFn=forge.aes.createDecryptionCipher;break;case"des-EDE3-CBC":dkLen=24,cipherFn=forge.des.createDecryptionCipher;break;case"desCBC":dkLen=8,cipherFn=forge.des.createDecryptionCipher}var md=prfOidToMessageDigest(capture.prfOid),dk=forge.pkcs5.pbkdf2(password,salt,count,dkLen,md),iv=capture.encIv,cipher=cipherFn(dk);return cipher.start(iv),cipher},pki.pbe.getCipherForPKCS12PBE=function(oid,params,password){var capture={},errors=[];if(!asn1.validate(params,pkcs12PbeParamsValidator,capture,errors))throw(error=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=errors,error;var dkLen,dIvLen,cipherFn,salt=forge.util.createBuffer(capture.salt),count=forge.util.createBuffer(capture.iterations);switch(count=count.getInt(count.length()<<3),oid){case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:dkLen=24,dIvLen=8,cipherFn=forge.des.startDecrypting;break;case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:dkLen=5,dIvLen=8,cipherFn=function(key,iv){var cipher=forge.rc2.createDecryptionCipher(key,40);return cipher.start(iv,null),cipher};break;default:var error;throw(error=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=oid,error}var md=prfOidToMessageDigest(capture.prfOid),key=pki.pbe.generatePkcs12Key(password,salt,1,count,dkLen,md);return md.start(),cipherFn(key,pki.pbe.generatePkcs12Key(password,salt,2,count,dIvLen,md))},pki.pbe.opensslDeriveBytes=function(password,salt,dkLen,md){if(null==md){if(!("md5"in forge.md))throw new Error('"md5" hash algorithm unavailable.');md=forge.md.md5.create()}null===salt&&(salt="");for(var digests=[hash(md,password+salt)],length=16,i=1;length<dkLen;++i,length+=16)digests.push(hash(md,digests[i-1]+password+salt));return digests.join("").substr(0,dkLen)},pbe}var hasRequiredPkcs7asn1,pkcs12={exports:{}},pkcs7asn1={exports:{}};function requirePkcs7asn1(){if(hasRequiredPkcs7asn1)return pkcs7asn1.exports;hasRequiredPkcs7asn1=1;var forge=requireForge();requireAsn1(),requireUtil();var asn1=forge.asn1,p7v=pkcs7asn1.exports=forge.pkcs7asn1=forge.pkcs7asn1||{};forge.pkcs7=forge.pkcs7||{},forge.pkcs7.asn1=p7v;var contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};p7v.contentInfoValidator=contentInfoValidator;var encryptedContentInfoValidator={name:"EncryptedContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:asn1.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};p7v.envelopedDataValidator={name:"EnvelopedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(encryptedContentInfoValidator)},p7v.encryptedDataValidator={name:"EncryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"version"}].concat(encryptedContentInfoValidator)};var signerValidator={name:"SignerInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:asn1.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};return p7v.signedDataValidator={name:"SignedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},contentInfoValidator,{name:"SignedData.Certificates",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,capture:"signerInfos",optional:!0,value:[signerValidator]}]},p7v.recipientInfoValidator={name:"RecipientInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:asn1.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]},pkcs7asn1.exports}var hasRequiredMgf1,mgf,hasRequiredMgf,x509={exports:{}},mgf1={exports:{}};function requireMgf1(){if(hasRequiredMgf1)return mgf1.exports;hasRequiredMgf1=1;var forge=requireForge();return requireUtil(),forge.mgf=forge.mgf||{},(mgf1.exports=forge.mgf.mgf1=forge.mgf1=forge.mgf1||{}).create=function(md){return{generate:function(seed,maskLen){for(var t=new forge.util.ByteBuffer,len=Math.ceil(maskLen/md.digestLength),i=0;i<len;i++){var c=new forge.util.ByteBuffer;c.putInt32(i),md.start(),md.update(seed+c.getBytes()),t.putBuffer(md.digest())}return t.truncate(t.length()-maskLen),t.getBytes()}}},mgf1.exports}var hasRequiredPss,hasRequiredX509,hasRequiredPkcs12,hasRequiredPki,tls_1,hasRequiredTls,hasRequiredAesCipherSuites,pss={exports:{}};function requirePss(){if(hasRequiredPss)return pss.exports;hasRequiredPss=1;var forge=requireForge();return requireRandom(),requireUtil(),(pss.exports=forge.pss=forge.pss||{}).create=function(options){3===arguments.length&&(options={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var sLen,hash=options.md,mgf=options.mgf,hLen=hash.digestLength,salt_=options.salt||null;if("string"==typeof salt_&&(salt_=forge.util.createBuffer(salt_)),"saltLength"in options)sLen=options.saltLength;else{if(null===salt_)throw new Error("Salt length not specified or specific salt not given.");sLen=salt_.length()}if(null!==salt_&&salt_.length()!==sLen)throw new Error("Given salt length does not match length of given salt.");var prng=options.prng||forge.random,pssobj={encode:function(md,modBits){var i,salt,emBits=modBits-1,emLen=Math.ceil(emBits/8),mHash=md.digest().getBytes();if(emLen<hLen+sLen+2)throw new Error("Message is too long to encrypt.");salt=null===salt_?prng.getBytesSync(sLen):salt_.bytes();var m_=new forge.util.ByteBuffer;m_.fillWithByte(0,8),m_.putBytes(mHash),m_.putBytes(salt),hash.start(),hash.update(m_.getBytes());var h=hash.digest().getBytes(),ps=new forge.util.ByteBuffer;ps.fillWithByte(0,emLen-sLen-hLen-2),ps.putByte(1),ps.putBytes(salt);var db=ps.getBytes(),maskLen=emLen-hLen-1,dbMask=mgf.generate(h,maskLen),maskedDB="";for(i=0;i<maskLen;i++)maskedDB+=String.fromCharCode(db.charCodeAt(i)^dbMask.charCodeAt(i));var mask=65280>>8*emLen-emBits&255;return(maskedDB=String.fromCharCode(maskedDB.charCodeAt(0)&~mask)+maskedDB.substr(1))+h+String.fromCharCode(188)},verify:function(mHash,em,modBits){var i,emBits=modBits-1,emLen=Math.ceil(emBits/8);if(em=em.substr(-emLen),emLen<hLen+sLen+2)throw new Error("Inconsistent parameters to PSS signature verification.");if(188!==em.charCodeAt(emLen-1))throw new Error("Encoded message does not end in 0xBC.");var maskLen=emLen-hLen-1,maskedDB=em.substr(0,maskLen),h=em.substr(maskLen,hLen),mask=65280>>8*emLen-emBits&255;if(0!==(maskedDB.charCodeAt(0)&mask))throw new Error("Bits beyond keysize not zero as expected.");var dbMask=mgf.generate(h,maskLen),db="";for(i=0;i<maskLen;i++)db+=String.fromCharCode(maskedDB.charCodeAt(i)^dbMask.charCodeAt(i));db=String.fromCharCode(db.charCodeAt(0)&~mask)+db.substr(1);var checkLen=emLen-hLen-sLen-2;for(i=0;i<checkLen;i++)if(0!==db.charCodeAt(i))throw new Error("Leftmost octets not zero as expected");if(1!==db.charCodeAt(checkLen))throw new Error("Inconsistent PSS signature, 0x01 marker not found");var salt=db.substr(-sLen),m_=new forge.util.ByteBuffer;return m_.fillWithByte(0,8),m_.putBytes(mHash),m_.putBytes(salt),hash.start(),hash.update(m_.getBytes()),h===hash.digest().getBytes()}};return pssobj},pss.exports}function requireX509(){if(hasRequiredX509)return x509.exports;hasRequiredX509=1;var forge=requireForge();requireAes(),requireAsn1(),requireDes(),requireMd(),function requireMgf(){if(hasRequiredMgf)return mgf;hasRequiredMgf=1;var forge=requireForge();return requireMgf1(),mgf=forge.mgf=forge.mgf||{},forge.mgf.mgf1=forge.mgf1,mgf}(),requireOids(),requirePem(),requirePss(),requireRsa(),requireUtil();var asn1=forge.asn1,pki=x509.exports=forge.pki=forge.pki||{},oids=pki.oids,_shortNames={};_shortNames.CN=oids.commonName,_shortNames.commonName="CN",_shortNames.C=oids.countryName,_shortNames.countryName="C",_shortNames.L=oids.localityName,_shortNames.localityName="L",_shortNames.ST=oids.stateOrProvinceName,_shortNames.stateOrProvinceName="ST",_shortNames.O=oids.organizationName,_shortNames.organizationName="O",_shortNames.OU=oids.organizationalUnitName,_shortNames.organizationalUnitName="OU",_shortNames.E=oids.emailAddress,_shortNames.emailAddress="E";var publicKeyValidator=forge.pki.rsa.publicKeyValidator,x509CertificateValidator={name:"Certificate",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:asn1.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:asn1.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},rsassaPssParameterValidator={name:"rsapss",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},certificationRequestInfoValidator={name:"CertificationRequestInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},publicKeyValidator,{name:"CertificationRequestInfo.attributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:!0}]}]}]},certificationRequestValidator={name:"CertificationRequest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[certificationRequestInfoValidator,{name:"CertificationRequest.signatureAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};function _getAttribute(obj,options){"string"==typeof options&&(options={shortName:options});for(var attr,rval=null,i=0;null===rval&&i<obj.attributes.length;++i)attr=obj.attributes[i],(options.type&&options.type===attr.type||options.name&&options.name===attr.name||options.shortName&&options.shortName===attr.shortName)&&(rval=attr);return rval}pki.RDNAttributesAsArray=function(rdn,md){for(var set,attr,obj,rval=[],si=0;si<rdn.value.length;++si){set=rdn.value[si];for(var i=0;i<set.value.length;++i)obj={},attr=set.value[i],obj.type=asn1.derToOid(attr.value[0].value),obj.value=attr.value[1].value,obj.valueTagClass=attr.value[1].type,obj.type in oids&&(obj.name=oids[obj.type],obj.name in _shortNames&&(obj.shortName=_shortNames[obj.name])),md&&(md.update(obj.type),md.update(obj.value)),rval.push(obj)}return rval},pki.CRIAttributesAsArray=function(attributes){for(var rval=[],si=0;si<attributes.length;++si)for(var seq=attributes[si],type=asn1.derToOid(seq.value[0].value),values=seq.value[1].value,vi=0;vi<values.length;++vi){var obj={};if(obj.type=type,obj.value=values[vi].value,obj.valueTagClass=values[vi].type,obj.type in oids&&(obj.name=oids[obj.type],obj.name in _shortNames&&(obj.shortName=_shortNames[obj.name])),obj.type===oids.extensionRequest){obj.extensions=[];for(var ei=0;ei<obj.value.length;++ei)obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]))}rval.push(obj)}return rval};var _readSignatureParameters=function(oid,obj,fillDefaults){var params={};if(oid!==oids["RSASSA-PSS"])return params;fillDefaults&&(params={hash:{algorithmOid:oids.sha1},mgf:{algorithmOid:oids.mgf1,hash:{algorithmOid:oids.sha1}},saltLength:20});var capture={},errors=[];if(!asn1.validate(obj,rsassaPssParameterValidator,capture,errors)){var error=new Error("Cannot read RSASSA-PSS parameter block.");throw error.errors=errors,error}return void 0!==capture.hashOid&&(params.hash=params.hash||{},params.hash.algorithmOid=asn1.derToOid(capture.hashOid)),void 0!==capture.maskGenOid&&(params.mgf=params.mgf||{},params.mgf.algorithmOid=asn1.derToOid(capture.maskGenOid),params.mgf.hash=params.mgf.hash||{},params.mgf.hash.algorithmOid=asn1.derToOid(capture.maskGenHashOid)),void 0!==capture.saltLength&&(params.saltLength=capture.saltLength.charCodeAt(0)),params},_createSignatureDigest=function(options){switch(oids[options.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return forge.md.sha1.create();case"md5WithRSAEncryption":return forge.md.md5.create();case"sha256WithRSAEncryption":case"RSASSA-PSS":return forge.md.sha256.create();case"sha384WithRSAEncryption":return forge.md.sha384.create();case"sha512WithRSAEncryption":return forge.md.sha512.create();default:var error=new Error("Could not compute "+options.type+" digest. Unknown signature OID.");throw error.signatureOid=options.signatureOid,error}},_verifySignature=function(options){var scheme,cert=options.certificate;switch(cert.signatureOid){case oids.sha1WithRSAEncryption:case oids.sha1WithRSASignature:break;case oids["RSASSA-PSS"]:var hash,mgf,error;if(void 0===(hash=oids[cert.signatureParameters.mgf.hash.algorithmOid])||void 0===forge.md[hash])throw(error=new Error("Unsupported MGF hash function.")).oid=cert.signatureParameters.mgf.hash.algorithmOid,error.name=hash,error;if(void 0===(mgf=oids[cert.signatureParameters.mgf.algorithmOid])||void 0===forge.mgf[mgf])throw(error=new Error("Unsupported MGF function.")).oid=cert.signatureParameters.mgf.algorithmOid,error.name=mgf,error;if(mgf=forge.mgf[mgf].create(forge.md[hash].create()),void 0===(hash=oids[cert.signatureParameters.hash.algorithmOid])||void 0===forge.md[hash])throw(error=new Error("Unsupported RSASSA-PSS hash function.")).oid=cert.signatureParameters.hash.algorithmOid,error.name=hash,error;scheme=forge.pss.create(forge.md[hash].create(),mgf,cert.signatureParameters.saltLength)}return cert.publicKey.verify(options.md.digest().getBytes(),options.signature,scheme)};function _dnToAsn1(obj){for(var attr,set,rval=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]),attrs=obj.attributes,i=0;i<attrs.length;++i){var value=(attr=attrs[i]).value,valueTagClass=asn1.Type.PRINTABLESTRING;"valueTagClass"in attr&&(valueTagClass=attr.valueTagClass)===asn1.Type.UTF8&&(value=forge.util.encodeUtf8(value)),set=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,valueTagClass,!1,value)])]),rval.value.push(set)}return rval}function _fillMissingFields(attrs){for(var attr,i=0;i<attrs.length;++i){if(void 0===(attr=attrs[i]).name&&(attr.type&&attr.type in pki.oids?attr.name=pki.oids[attr.type]:attr.shortName&&attr.shortName in _shortNames&&(attr.name=pki.oids[_shortNames[attr.shortName]])),void 0===attr.type){if(!attr.name||!(attr.name in pki.oids))throw(error=new Error("Attribute type not specified.")).attribute=attr,error;attr.type=pki.oids[attr.name]}if(void 0===attr.shortName&&attr.name&&attr.name in _shortNames&&(attr.shortName=_shortNames[attr.name]),attr.type===oids.extensionRequest&&(attr.valueConstructed=!0,attr.valueTagClass=asn1.Type.SEQUENCE,!attr.value&&attr.extensions)){attr.value=[];for(var ei=0;ei<attr.extensions.length;++ei)attr.value.push(pki.certificateExtensionToAsn1(_fillMissingExtensionFields(attr.extensions[ei])))}var error;if(void 0===attr.value)throw(error=new Error("Attribute value not specified.")).attribute=attr,error}}function _fillMissingExtensionFields(e,options){if(options=options||{},void 0===e.name&&e.id&&e.id in pki.oids&&(e.name=pki.oids[e.id]),void 0===e.id){if(!e.name||!(e.name in pki.oids))throw(error=new Error("Extension ID not specified.")).extension=e,error;e.id=pki.oids[e.name]}if(void 0!==e.value)return e;if("keyUsage"===e.name){var unused=0,b2=0,b3=0;e.digitalSignature&&(b2|=128,unused=7),e.nonRepudiation&&(b2|=64,unused=6),e.keyEncipherment&&(b2|=32,unused=5),e.dataEncipherment&&(b2|=16,unused=4),e.keyAgreement&&(b2|=8,unused=3),e.keyCertSign&&(b2|=4,unused=2),e.cRLSign&&(b2|=2,unused=1),e.encipherOnly&&(b2|=1,unused=0),e.decipherOnly&&(b3|=128,unused=7);var value=String.fromCharCode(unused);0!==b3?value+=String.fromCharCode(b2)+String.fromCharCode(b3):0!==b2&&(value+=String.fromCharCode(b2)),e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,!1,value)}else if("basicConstraints"===e.name)e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]),e.cA&&e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BOOLEAN,!1,String.fromCharCode(255))),"pathLenConstraint"in e&&e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(e.pathLenConstraint).getBytes()));else if("extKeyUsage"===e.name){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]);var seq=e.value.value;for(var key in e)!0===e[key]&&(key in oids?seq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oids[key]).getBytes())):-1!==key.indexOf(".")&&seq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(key).getBytes())))}else if("nsCertType"===e.name){unused=0,b2=0;e.client&&(b2|=128,unused=7),e.server&&(b2|=64,unused=6),e.email&&(b2|=32,unused=5),e.objsign&&(b2|=16,unused=4),e.reserved&&(b2|=8,unused=3),e.sslCA&&(b2|=4,unused=2),e.emailCA&&(b2|=2,unused=1),e.objCA&&(b2|=1,unused=0);value=String.fromCharCode(unused);0!==b2&&(value+=String.fromCharCode(b2)),e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,!1,value)}else if("subjectAltName"===e.name||"issuerAltName"===e.name){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]);for(var n=0;n<e.altNames.length;++n){value=(altName=e.altNames[n]).value;if(7===altName.type&&altName.ip){if(null===(value=forge.util.bytesFromIP(altName.ip)))throw(error=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.')).extension=e,error}else 8===altName.type&&(value=altName.oid?asn1.oidToDer(asn1.oidToDer(altName.oid)):asn1.oidToDer(value));e.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,!1,value))}}else if("nsComment"===e.name&&options.cert){if(!/^[\x00-\x7F]*$/.test(e.comment)||e.comment.length<1||e.comment.length>128)throw new Error('Invalid "nsComment" content.');e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&options.cert){var ski=options.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=ski.toHex(),e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,ski.getBytes())}else if("authorityKeyIdentifier"===e.name&&options.cert){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]);seq=e.value.value;if(e.keyIdentifier){var keyIdentifier=!0===e.keyIdentifier?options.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!1,keyIdentifier))}if(e.authorityCertIssuer){var authorityCertIssuer=[asn1.create(asn1.Class.CONTEXT_SPECIFIC,4,!0,[_dnToAsn1(!0===e.authorityCertIssuer?options.cert.issuer:e.authorityCertIssuer)])];seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,!0,authorityCertIssuer))}if(e.serialNumber){var serialNumber=forge.util.hexToBytes(!0===e.serialNumber?options.cert.serialNumber:e.serialNumber);seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,!1,serialNumber))}}else if("cRLDistributionPoints"===e.name){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]);seq=e.value.value;var altName,subSeq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]),fullNameGeneralNames=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[]);for(n=0;n<e.altNames.length;++n){value=(altName=e.altNames[n]).value;if(7===altName.type&&altName.ip){if(null===(value=forge.util.bytesFromIP(altName.ip)))throw(error=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.')).extension=e,error}else 8===altName.type&&(value=altName.oid?asn1.oidToDer(asn1.oidToDer(altName.oid)):asn1.oidToDer(value));fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,!1,value))}subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[fullNameGeneralNames])),seq.push(subSeq)}var error;if(void 0===e.value)throw(error=new Error("Extension value not specified.")).extension=e,error;return e}function _signatureParametersToAsn1(oid,params){if(oid===oids["RSASSA-PSS"]){var parts=[];return void 0!==params.hash.algorithmOid&&parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(params.hash.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")])])),void 0!==params.mgf.algorithmOid&&parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(params.mgf.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")])])])),void 0!==params.saltLength&&parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(params.saltLength).getBytes())])),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,parts)}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")}function _CRIAttributesToAsn1(csr){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[]);if(0===csr.attributes.length)return rval;for(var attrs=csr.attributes,i=0;i<attrs.length;++i){var attr=attrs[i],value=attr.value,valueTagClass=asn1.Type.UTF8;"valueTagClass"in attr&&(valueTagClass=attr.valueTagClass),valueTagClass===asn1.Type.UTF8&&(value=forge.util.encodeUtf8(value));var valueConstructed=!1;"valueConstructed"in attr&&(valueConstructed=attr.valueConstructed);var seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,[asn1.create(asn1.Class.UNIVERSAL,valueTagClass,valueConstructed,value)])]);rval.value.push(seq)}return rval}pki.certificateFromPem=function(pem,computeHash,strict){var msg=forge.pem.decode(pem)[0];if("CERTIFICATE"!==msg.type&&"X509 CERTIFICATE"!==msg.type&&"TRUSTED CERTIFICATE"!==msg.type){var error=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw error.headerType=msg.type,error}if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var obj=asn1.fromDer(msg.body,strict);return pki.certificateFromAsn1(obj,computeHash)},pki.certificateToPem=function(cert,maxline){var msg={type:"CERTIFICATE",body:asn1.toDer(pki.certificateToAsn1(cert)).getBytes()};return forge.pem.encode(msg,{maxline:maxline})},pki.publicKeyFromPem=function(pem){var msg=forge.pem.decode(pem)[0];if("PUBLIC KEY"!==msg.type&&"RSA PUBLIC KEY"!==msg.type){var error=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw error.headerType=msg.type,error}if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert public key from PEM; PEM is encrypted.");var obj=asn1.fromDer(msg.body);return pki.publicKeyFromAsn1(obj)},pki.publicKeyToPem=function(key,maxline){var msg={type:"PUBLIC KEY",body:asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()};return forge.pem.encode(msg,{maxline:maxline})},pki.publicKeyToRSAPublicKeyPem=function(key,maxline){var msg={type:"RSA PUBLIC KEY",body:asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()};return forge.pem.encode(msg,{maxline:maxline})},pki.getPublicKeyFingerprint=function(key,options){var bytes,md=(options=options||{}).md||forge.md.sha1.create();switch(options.type||"RSAPublicKey"){case"RSAPublicKey":bytes=asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();break;case"SubjectPublicKeyInfo":bytes=asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();break;default:throw new Error('Unknown fingerprint type "'+options.type+'".')}md.start(),md.update(bytes);var digest=md.digest();if("hex"===options.encoding){var hex=digest.toHex();return options.delimiter?hex.match(/.{2}/g).join(options.delimiter):hex}if("binary"===options.encoding)return digest.getBytes();if(options.encoding)throw new Error('Unknown encoding "'+options.encoding+'".');return digest},pki.certificationRequestFromPem=function(pem,computeHash,strict){var msg=forge.pem.decode(pem)[0];if("CERTIFICATE REQUEST"!==msg.type){var error=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw error.headerType=msg.type,error}if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert certification request from PEM; PEM is encrypted.");var obj=asn1.fromDer(msg.body,strict);return pki.certificationRequestFromAsn1(obj,computeHash)},pki.certificationRequestToPem=function(csr,maxline){var msg={type:"CERTIFICATE REQUEST",body:asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()};return forge.pem.encode(msg,{maxline:maxline})},pki.createCertificate=function(){var cert={version:2,serialNumber:"00",signatureOid:null,signature:null,siginfo:{}};return cert.siginfo.algorithmOid=null,cert.validity={},cert.validity.notBefore=new Date,cert.validity.notAfter=new Date,cert.issuer={},cert.issuer.getField=function(sn){return _getAttribute(cert.issuer,sn)},cert.issuer.addField=function(attr){_fillMissingFields([attr]),cert.issuer.attributes.push(attr)},cert.issuer.attributes=[],cert.issuer.hash=null,cert.subject={},cert.subject.getField=function(sn){return _getAttribute(cert.subject,sn)},cert.subject.addField=function(attr){_fillMissingFields([attr]),cert.subject.attributes.push(attr)},cert.subject.attributes=[],cert.subject.hash=null,cert.extensions=[],cert.publicKey=null,cert.md=null,cert.setSubject=function(attrs,uniqueId){_fillMissingFields(attrs),cert.subject.attributes=attrs,delete cert.subject.uniqueId,uniqueId&&(cert.subject.uniqueId=uniqueId),cert.subject.hash=null},cert.setIssuer=function(attrs,uniqueId){_fillMissingFields(attrs),cert.issuer.attributes=attrs,delete cert.issuer.uniqueId,uniqueId&&(cert.issuer.uniqueId=uniqueId),cert.issuer.hash=null},cert.setExtensions=function(exts){for(var i=0;i<exts.length;++i)_fillMissingExtensionFields(exts[i],{cert:cert});cert.extensions=exts},cert.getExtension=function(options){"string"==typeof options&&(options={name:options});for(var ext,rval=null,i=0;null===rval&&i<cert.extensions.length;++i)ext=cert.extensions[i],(options.id&&ext.id===options.id||options.name&&ext.name===options.name)&&(rval=ext);return rval},cert.sign=function(key,md){cert.md=md||forge.md.sha1.create();var algorithmOid=oids[cert.md.algorithm+"WithRSAEncryption"];if(!algorithmOid){var error=new Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw error.algorithm=cert.md.algorithm,error}cert.signatureOid=cert.siginfo.algorithmOid=algorithmOid,cert.tbsCertificate=pki.getTBSCertificate(cert);var bytes=asn1.toDer(cert.tbsCertificate);cert.md.update(bytes.getBytes()),cert.signature=key.sign(cert.md)},cert.verify=function(child){var rval=!1;if(!cert.issued(child)){var issuer=child.issuer,subject=cert.subject,error=new Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw error.expectedIssuer=subject.attributes,error.actualIssuer=issuer.attributes,error}var md=child.md;if(null===md){md=_createSignatureDigest({signatureOid:child.signatureOid,type:"certificate"});var tbsCertificate=child.tbsCertificate||pki.getTBSCertificate(child),bytes=asn1.toDer(tbsCertificate);md.update(bytes.getBytes())}return null!==md&&(rval=_verifySignature({certificate:cert,md:md,signature:child.signature})),rval},cert.isIssuer=function(parent){var rval=!1,i=cert.issuer,s=parent.subject;if(i.hash&&s.hash)rval=i.hash===s.hash;else if(i.attributes.length===s.attributes.length){var iattr,sattr;rval=!0;for(var n=0;rval&&n<i.attributes.length;++n)iattr=i.attributes[n],sattr=s.attributes[n],iattr.type===sattr.type&&iattr.value===sattr.value||(rval=!1)}return rval},cert.issued=function(child){return child.isIssuer(cert)},cert.generateSubjectKeyIdentifier=function(){return pki.getPublicKeyFingerprint(cert.publicKey,{type:"RSAPublicKey"})},cert.verifySubjectKeyIdentifier=function(){for(var oid=oids.subjectKeyIdentifier,i=0;i<cert.extensions.length;++i){var ext=cert.extensions[i];if(ext.id===oid){var ski=cert.generateSubjectKeyIdentifier().getBytes();return forge.util.hexToBytes(ext.subjectKeyIdentifier)===ski}}return!1},cert},pki.certificateFromAsn1=function(obj,computeHash){var capture={},errors=[];if(!asn1.validate(obj,x509CertificateValidator,capture,errors)){var error=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw error.errors=errors,error}if(asn1.derToOid(capture.publicKeyOid)!==pki.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var cert=pki.createCertificate();cert.version=capture.certVersion?capture.certVersion.charCodeAt(0):0;var serial=forge.util.createBuffer(capture.certSerialNumber);cert.serialNumber=serial.toHex(),cert.signatureOid=forge.asn1.derToOid(capture.certSignatureOid),cert.signatureParameters=_readSignatureParameters(cert.signatureOid,capture.certSignatureParams,!0),cert.siginfo.algorithmOid=forge.asn1.derToOid(capture.certinfoSignatureOid),cert.siginfo.parameters=_readSignatureParameters(cert.siginfo.algorithmOid,capture.certinfoSignatureParams,!1),cert.signature=capture.certSignature;var validity=[];if(void 0!==capture.certValidity1UTCTime&&validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)),void 0!==capture.certValidity2GeneralizedTime&&validity.push(asn1.generalizedTimeToDate(capture.certValidity2GeneralizedTime)),void 0!==capture.certValidity3UTCTime&&validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)),void 0!==capture.certValidity4GeneralizedTime&&validity.push(asn1.generalizedTimeToDate(capture.certValidity4GeneralizedTime)),validity.length>2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(validity.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(cert.validity.notBefore=validity[0],cert.validity.notAfter=validity[1],cert.tbsCertificate=capture.tbsCertificate,computeHash){cert.md=_createSignatureDigest({signatureOid:cert.signatureOid,type:"certificate"});var bytes=asn1.toDer(cert.tbsCertificate);cert.md.update(bytes.getBytes())}var imd=forge.md.sha1.create(),ibytes=asn1.toDer(capture.certIssuer);imd.update(ibytes.getBytes()),cert.issuer.getField=function(sn){return _getAttribute(cert.issuer,sn)},cert.issuer.addField=function(attr){_fillMissingFields([attr]),cert.issuer.attributes.push(attr)},cert.issuer.attributes=pki.RDNAttributesAsArray(capture.certIssuer),capture.certIssuerUniqueId&&(cert.issuer.uniqueId=capture.certIssuerUniqueId),cert.issuer.hash=imd.digest().toHex();var smd=forge.md.sha1.create(),sbytes=asn1.toDer(capture.certSubject);return smd.update(sbytes.getBytes()),cert.subject.getField=function(sn){return _getAttribute(cert.subject,sn)},cert.subject.addField=function(attr){_fillMissingFields([attr]),cert.subject.attributes.push(attr)},cert.subject.attributes=pki.RDNAttributesAsArray(capture.certSubject),capture.certSubjectUniqueId&&(cert.subject.uniqueId=capture.certSubjectUniqueId),cert.subject.hash=smd.digest().toHex(),capture.certExtensions?cert.extensions=pki.certificateExtensionsFromAsn1(capture.certExtensions):cert.extensions=[],cert.publicKey=pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo),cert},pki.certificateExtensionsFromAsn1=function(exts){for(var rval=[],i=0;i<exts.value.length;++i)for(var extseq=exts.value[i],ei=0;ei<extseq.value.length;++ei)rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));return rval},pki.certificateExtensionFromAsn1=function(ext){var e={};if(e.id=asn1.derToOid(ext.value[0].value),e.critical=!1,ext.value[1].type===asn1.Type.BOOLEAN?(e.critical=0!==ext.value[1].value.charCodeAt(0),e.value=ext.value[2].value):e.value=ext.value[1].value,e.id in oids)if(e.name=oids[e.id],"keyUsage"===e.name){var b2=0,b3=0;(ev=asn1.fromDer(e.value)).value.length>1&&(b2=ev.value.charCodeAt(1),b3=ev.value.length>2?ev.value.charCodeAt(2):0),e.digitalSignature=!(128&~b2),e.nonRepudiation=!(64&~b2),e.keyEncipherment=!(32&~b2),e.dataEncipherment=!(16&~b2),e.keyAgreement=!(8&~b2),e.keyCertSign=!(4&~b2),e.cRLSign=!(2&~b2),e.encipherOnly=!(1&~b2),e.decipherOnly=!(128&~b3)}else if("basicConstraints"===e.name){(ev=asn1.fromDer(e.value)).value.length>0&&ev.value[0].type===asn1.Type.BOOLEAN?e.cA=0!==ev.value[0].value.charCodeAt(0):e.cA=!1;var value=null;ev.value.length>0&&ev.value[0].type===asn1.Type.INTEGER?value=ev.value[0].value:ev.value.length>1&&(value=ev.value[1].value),null!==value&&(e.pathLenConstraint=asn1.derToInteger(value))}else if("extKeyUsage"===e.name)for(var ev=asn1.fromDer(e.value),vi=0;vi<ev.value.length;++vi){var oid=asn1.derToOid(ev.value[vi].value);oid in oids?e[oids[oid]]=!0:e[oid]=!0}else if("nsCertType"===e.name){b2=0;(ev=asn1.fromDer(e.value)).value.length>1&&(b2=ev.value.charCodeAt(1)),e.client=!(128&~b2),e.server=!(64&~b2),e.email=!(32&~b2),e.objsign=!(16&~b2),e.reserved=!(8&~b2),e.sslCA=!(4&~b2),e.emailCA=!(2&~b2),e.objCA=!(1&~b2)}else if("subjectAltName"===e.name||"issuerAltName"===e.name){var gn;e.altNames=[];ev=asn1.fromDer(e.value);for(var n=0;n<ev.value.length;++n){var altName={type:(gn=ev.value[n]).type,value:gn.value};switch(e.altNames.push(altName),gn.type){case 1:case 2:case 6:break;case 7:altName.ip=forge.util.bytesToIP(gn.value);break;case 8:altName.oid=asn1.derToOid(gn.value)}}}else if("subjectKeyIdentifier"===e.name){ev=asn1.fromDer(e.value);e.subjectKeyIdentifier=forge.util.bytesToHex(ev.value)}return e},pki.certificationRequestFromAsn1=function(obj,computeHash){var capture={},errors=[];if(!asn1.validate(obj,certificationRequestValidator,capture,errors)){var error=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw error.errors=errors,error}if(asn1.derToOid(capture.publicKeyOid)!==pki.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var csr=pki.createCertificationRequest();if(csr.version=capture.csrVersion?capture.csrVersion.charCodeAt(0):0,csr.signatureOid=forge.asn1.derToOid(capture.csrSignatureOid),csr.signatureParameters=_readSignatureParameters(csr.signatureOid,capture.csrSignatureParams,!0),csr.siginfo.algorithmOid=forge.asn1.derToOid(capture.csrSignatureOid),csr.siginfo.parameters=_readSignatureParameters(csr.siginfo.algorithmOid,capture.csrSignatureParams,!1),csr.signature=capture.csrSignature,csr.certificationRequestInfo=capture.certificationRequestInfo,computeHash){csr.md=_createSignatureDigest({signatureOid:csr.signatureOid,type:"certification request"});var bytes=asn1.toDer(csr.certificationRequestInfo);csr.md.update(bytes.getBytes())}var smd=forge.md.sha1.create();return csr.subject.getField=function(sn){return _getAttribute(csr.subject,sn)},csr.subject.addField=function(attr){_fillMissingFields([attr]),csr.subject.attributes.push(attr)},csr.subject.attributes=pki.RDNAttributesAsArray(capture.certificationRequestInfoSubject,smd),csr.subject.hash=smd.digest().toHex(),csr.publicKey=pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo),csr.getAttribute=function(sn){return _getAttribute(csr,sn)},csr.addAttribute=function(attr){_fillMissingFields([attr]),csr.attributes.push(attr)},csr.attributes=pki.CRIAttributesAsArray(capture.certificationRequestInfoAttributes||[]),csr},pki.createCertificationRequest=function(){var csr={version:0,signatureOid:null,signature:null,siginfo:{}};return csr.siginfo.algorithmOid=null,csr.subject={},csr.subject.getField=function(sn){return _getAttribute(csr.subject,sn)},csr.subject.addField=function(attr){_fillMissingFields([attr]),csr.subject.attributes.push(attr)},csr.subject.attributes=[],csr.subject.hash=null,csr.publicKey=null,csr.attributes=[],csr.getAttribute=function(sn){return _getAttribute(csr,sn)},csr.addAttribute=function(attr){_fillMissingFields([attr]),csr.attributes.push(attr)},csr.md=null,csr.setSubject=function(attrs){_fillMissingFields(attrs),csr.subject.attributes=attrs,csr.subject.hash=null},csr.setAttributes=function(attrs){_fillMissingFields(attrs),csr.attributes=attrs},csr.sign=function(key,md){csr.md=md||forge.md.sha1.create();var algorithmOid=oids[csr.md.algorithm+"WithRSAEncryption"];if(!algorithmOid){var error=new Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw error.algorithm=csr.md.algorithm,error}csr.signatureOid=csr.siginfo.algorithmOid=algorithmOid,csr.certificationRequestInfo=pki.getCertificationRequestInfo(csr);var bytes=asn1.toDer(csr.certificationRequestInfo);csr.md.update(bytes.getBytes()),csr.signature=key.sign(csr.md)},csr.verify=function(){var rval=!1,md=csr.md;if(null===md){md=_createSignatureDigest({signatureOid:csr.signatureOid,type:"certification request"});var cri=csr.certificationRequestInfo||pki.getCertificationRequestInfo(csr),bytes=asn1.toDer(cri);md.update(bytes.getBytes())}return null!==md&&(rval=_verifySignature({certificate:csr,md:md,signature:csr.signature})),rval},csr};var jan_1_1950=new Date("1950-01-01T00:00:00Z"),jan_1_2050=new Date("2050-01-01T00:00:00Z");function _dateToAsn1(date){return date>=jan_1_1950&&date<jan_1_2050?asn1.create(asn1.Class.UNIVERSAL,asn1.Type.UTCTIME,!1,asn1.dateToUtcTime(date)):asn1.create(asn1.Class.UNIVERSAL,asn1.Type.GENERALIZEDTIME,!1,asn1.dateToGeneralizedTime(date))}return pki.getTBSCertificate=function(cert){var notBefore=_dateToAsn1(cert.validity.notBefore),notAfter=_dateToAsn1(cert.validity.notAfter),tbs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(cert.version).getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,forge.util.hexToBytes(cert.serialNumber)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),_signatureParametersToAsn1(cert.siginfo.algorithmOid,cert.siginfo.parameters)]),_dnToAsn1(cert.issuer),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[notBefore,notAfter]),_dnToAsn1(cert.subject),pki.publicKeyToAsn1(cert.publicKey)]);return cert.issuer.uniqueId&&tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,!1,String.fromCharCode(0)+cert.issuer.uniqueId)])),cert.subject.uniqueId&&tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,!1,String.fromCharCode(0)+cert.subject.uniqueId)])),cert.extensions.length>0&&tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)),tbs},pki.getCertificationRequestInfo=function(csr){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(csr.version).getBytes()),_dnToAsn1(csr.subject),pki.publicKeyToAsn1(csr.publicKey),_CRIAttributesToAsn1(csr)])},pki.distinguishedNameToAsn1=function(dn){return _dnToAsn1(dn)},pki.certificateToAsn1=function(cert){var tbsCertificate=cert.tbsCertificate||pki.getTBSCertificate(cert);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[tbsCertificate,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(cert.signatureOid).getBytes()),_signatureParametersToAsn1(cert.signatureOid,cert.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,!1,String.fromCharCode(0)+cert.signature)])},pki.certificateExtensionsToAsn1=function(exts){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,3,!0,[]),seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]);rval.value.push(seq);for(var i=0;i<exts.length;++i)seq.value.push(pki.certificateExtensionToAsn1(exts[i]));return rval},pki.certificateExtensionToAsn1=function(ext){var extseq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[]);extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(ext.id).getBytes())),ext.critical&&extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BOOLEAN,!1,String.fromCharCode(255)));var value=ext.value;return"string"!=typeof ext.value&&(value=asn1.toDer(value).getBytes()),extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,value)),extseq},pki.certificationRequestToAsn1=function(csr){var cri=csr.certificationRequestInfo||pki.getCertificationRequestInfo(csr);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[cri,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(csr.signatureOid).getBytes()),_signatureParametersToAsn1(csr.signatureOid,csr.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,!1,String.fromCharCode(0)+csr.signature)])},pki.createCaStore=function(certs){var caStore={certs:{}};function getBySubject(subject){return ensureSubjectHasHash(subject),caStore.certs[subject.hash]||null}function ensureSubjectHasHash(subject){if(!subject.hash){var md=forge.md.sha1.create();subject.attributes=pki.RDNAttributesAsArray(_dnToAsn1(subject),md),subject.hash=md.digest().toHex()}}if(caStore.getIssuer=function(cert){return getBySubject(cert.issuer)},caStore.addCertificate=function(cert){if("string"==typeof cert&&(cert=forge.pki.certificateFromPem(cert)),ensureSubjectHasHash(cert.subject),!caStore.hasCertificate(cert))if(cert.subject.hash in caStore.certs){var tmp=caStore.certs[cert.subject.hash];forge.util.isArray(tmp)||(tmp=[tmp]),tmp.push(cert),caStore.certs[cert.subject.hash]=tmp}else caStore.certs[cert.subject.hash]=cert},caStore.hasCertificate=function(cert){"string"==typeof cert&&(cert=forge.pki.certificateFromPem(cert));var match=getBySubject(cert.subject);if(!match)return!1;forge.util.isArray(match)||(match=[match]);for(var der1=asn1.toDer(pki.certificateToAsn1(cert)).getBytes(),i=0;i<match.length;++i){if(der1===asn1.toDer(pki.certificateToAsn1(match[i])).getBytes())return!0}return!1},caStore.listAllCertificates=function(){var certList=[];for(var hash in caStore.certs)if(caStore.certs.hasOwnProperty(hash)){var value=caStore.certs[hash];if(forge.util.isArray(value))for(var i=0;i<value.length;++i)certList.push(value[i]);else certList.push(value)}return certList},caStore.removeCertificate=function(cert){var result;if("string"==typeof cert&&(cert=forge.pki.certificateFromPem(cert)),ensureSubjectHasHash(cert.subject),!caStore.hasCertificate(cert))return null;var match=getBySubject(cert.subject);if(!forge.util.isArray(match))return result=caStore.certs[cert.subject.hash],delete caStore.certs[cert.subject.hash],result;for(var der1=asn1.toDer(pki.certificateToAsn1(cert)).getBytes(),i=0;i<match.length;++i){der1===asn1.toDer(pki.certificateToAsn1(match[i])).getBytes()&&(result=match[i],match.splice(i,1))}return 0===match.length&&delete caStore.certs[cert.subject.hash],result},certs)for(var i=0;i<certs.length;++i){var cert=certs[i];caStore.addCertificate(cert)}return caStore},pki.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"},pki.verifyCertificateChain=function(caStore,chain,options){"function"==typeof options&&(options={verify:options}),options=options||{};var certs=(chain=chain.slice(0)).slice(0),validityCheckDate=options.validityCheckDate;void 0===validityCheckDate&&(validityCheckDate=new Date);var first=!0,error=null,depth=0;do{var cert=chain.shift(),parent=null,selfSigned=!1;if(validityCheckDate&&(validityCheckDate<cert.validity.notBefore||validityCheckDate>cert.validity.notAfter)&&(error={message:"Certificate is not valid yet or has expired.",error:pki.certificateError.certificate_expired,notBefore:cert.validity.notBefore,notAfter:cert.validity.notAfter,now:validityCheckDate}),null===error){if(null===(parent=chain[0]||caStore.getIssuer(cert))&&cert.isIssuer(cert)&&(selfSigned=!0,parent=cert),parent){var parents=parent;forge.util.isArray(parents)||(parents=[parents]);for(var verified=!1;!verified&&parents.length>0;){parent=parents.shift();try{verified=parent.verify(cert)}catch(ex){}}verified||(error={message:"Certificate signature is invalid.",error:pki.certificateError.bad_certificate})}null!==error||parent&&!selfSigned||caStore.hasCertificate(cert)||(error={message:"Certificate is not trusted.",error:pki.certificateError.unknown_ca})}if(null===error&&parent&&!cert.isIssuer(parent)&&(error={message:"Certificate issuer is invalid.",error:pki.certificateError.bad_certificate}),null===error)for(var se={keyUsage:!0,basicConstraints:!0},i=0;null===error&&i<cert.extensions.length;++i){var ext=cert.extensions[i];ext.critical&&!(ext.name in se)&&(error={message:"Certificate has an unsupported critical extension.",error:pki.certificateError.unsupported_certificate})}if(null===error&&(!first||0===chain.length&&(!parent||selfSigned))){var bcExt=cert.getExtension("basicConstraints"),keyUsageExt=cert.getExtension("keyUsage");if(null!==keyUsageExt&&(keyUsageExt.keyCertSign&&null!==bcExt||(error={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:pki.certificateError.bad_certificate})),null!==error||null===bcExt||bcExt.cA||(error={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:pki.certificateError.bad_certificate}),null===error&&null!==keyUsageExt&&"pathLenConstraint"in bcExt)depth-1>bcExt.pathLenConstraint&&(error={message:"Certificate basicConstraints pathLenConstraint violated.",error:pki.certificateError.bad_certificate})}var vfd=null===error||error.error,ret=options.verify?options.verify(vfd,depth,certs):vfd;if(!0!==ret)throw!0===vfd&&(error={message:"The application rejected the certificate.",error:pki.certificateError.bad_certificate}),(ret||0===ret)&&("object"!=typeof ret||forge.util.isArray(ret)?"string"==typeof ret&&(error.error=ret):(ret.message&&(error.message=ret.message),ret.error&&(error.error=ret.error))),error;error=null,first=!1,++depth}while(chain.length>0);return!0},x509.exports}function requirePkcs12(){if(hasRequiredPkcs12)return pkcs12.exports;hasRequiredPkcs12=1;var forge=requireForge();requireAsn1(),requireHmac(),requireOids(),requirePkcs7asn1(),requirePbe(),requireRandom(),requireRsa(),requireSha1$1(),requireUtil(),requireX509();var asn1=forge.asn1,pki=forge.pki,p12=pkcs12.exports=forge.pkcs12=forge.pkcs12||{},contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},pfxValidator={name:"PFX",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"version"},contentInfoValidator,{name:"PFX.macData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},safeBagValidator={name:"SafeBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},attributeValidator={name:"Attribute",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:!0,capture:"values"}]},certBagValidator={name:"CertBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function _getBagsByAttribute(safeContents,attrName,attrValue,bagType){for(var result=[],i=0;i<safeContents.length;i++)for(var j=0;j<safeContents[i].safeBags.length;j++){var bag=safeContents[i].safeBags[j];void 0!==bagType&&bag.type!==bagType||(null!==attrName?void 0!==bag.attributes[attrName]&&bag.attributes[attrName].indexOf(attrValue)>=0&&result.push(bag):result.push(bag))}return result}function _decodePkcs7Data(data){if(data.composed||data.constructed){for(var value=forge.util.createBuffer(),i=0;i<data.value.length;++i)value.putBytes(data.value[i].value);data.composed=data.constructed=!1,data.value=value.getBytes()}return data}function _decryptSafeContents(data,password){var capture={},errors=[];if(!asn1.validate(data,forge.pkcs7.asn1.encryptedDataValidator,capture,errors))throw(error=new Error("Cannot read EncryptedContentInfo.")).errors=errors,error;var error,oid=asn1.derToOid(capture.contentType);if(oid!==pki.oids.data)throw(error=new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.")).oid=oid,error;oid=asn1.derToOid(capture.encAlgorithm);var cipher=pki.pbe.getCipher(oid,capture.encParameter,password),encryptedContentAsn1=_decodePkcs7Data(capture.encryptedContentAsn1),encrypted=forge.util.createBuffer(encryptedContentAsn1.value);if(cipher.update(encrypted),!cipher.finish())throw new Error("Failed to decrypt PKCS#12 SafeContents.");return cipher.output.getBytes()}function _decodeSafeContents(safeContents,strict,password){if(!strict&&0===safeContents.length)return[];if((safeContents=asn1.fromDer(safeContents,strict)).tagClass!==asn1.Class.UNIVERSAL||safeContents.type!==asn1.Type.SEQUENCE||!0!==safeContents.constructed)throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");for(var res=[],i=0;i<safeContents.value.length;i++){var safeBag=safeContents.value[i],capture={},errors=[];if(!asn1.validate(safeBag,safeBagValidator,capture,errors))throw(error=new Error("Cannot read SafeBag.")).errors=errors,error;var validator,decoder,bag={type:asn1.derToOid(capture.bagId),attributes:_decodeBagAttributes(capture.bagAttributes)};res.push(bag);var bagAsn1=capture.bagValue.value[0];switch(bag.type){case pki.oids.pkcs8ShroudedKeyBag:if(null===(bagAsn1=pki.decryptPrivateKeyInfo(bagAsn1,password)))throw new Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case pki.oids.keyBag:try{bag.key=pki.privateKeyFromAsn1(bagAsn1)}catch(e){bag.key=null,bag.asn1=bagAsn1}continue;case pki.oids.certBag:validator=certBagValidator,decoder=function(){if(asn1.derToOid(capture.certId)!==pki.oids.x509Certificate){var error=new Error("Unsupported certificate type, only X.509 supported.");throw error.oid=asn1.derToOid(capture.certId),error}var certAsn1=asn1.fromDer(capture.cert,strict);try{bag.cert=pki.certificateFromAsn1(certAsn1,!0)}catch(e){bag.cert=null,bag.asn1=certAsn1}};break;default:var error;throw(error=new Error("Unsupported PKCS#12 SafeBag type.")).oid=bag.type,error}if(void 0!==validator&&!asn1.validate(bagAsn1,validator,capture,errors))throw(error=new Error("Cannot read PKCS#12 "+validator.name)).errors=errors,error;decoder()}return res}function _decodeBagAttributes(attributes){var decodedAttrs={};if(void 0!==attributes)for(var i=0;i<attributes.length;++i){var capture={},errors=[];if(!asn1.validate(attributes[i],attributeValidator,capture,errors)){var error=new Error("Cannot read PKCS#12 BagAttribute.");throw error.errors=errors,error}var oid=asn1.derToOid(capture.oid);if(void 0!==pki.oids[oid]){decodedAttrs[pki.oids[oid]]=[];for(var j=0;j<capture.values.length;++j)decodedAttrs[pki.oids[oid]].push(capture.values[j].value)}}return decodedAttrs}return p12.pkcs12FromAsn1=function(obj,strict,password){"string"==typeof strict?(password=strict,strict=!0):void 0===strict&&(strict=!0);var capture={};if(!asn1.validate(obj,pfxValidator,capture,[]))throw(error=new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.")).errors=error,error;var error,pfx={version:capture.version.charCodeAt(0),safeContents:[],getBags:function(filter){var localKeyId,rval={};return"localKeyId"in filter?localKeyId=filter.localKeyId:"localKeyIdHex"in filter&&(localKeyId=forge.util.hexToBytes(filter.localKeyIdHex)),void 0===localKeyId&&!("friendlyName"in filter)&&"bagType"in filter&&(rval[filter.bagType]=_getBagsByAttribute(pfx.safeContents,null,null,filter.bagType)),void 0!==localKeyId&&(rval.localKeyId=_getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,filter.bagType)),"friendlyName"in filter&&(rval.friendlyName=_getBagsByAttribute(pfx.safeContents,"friendlyName",filter.friendlyName,filter.bagType)),rval},getBagsByFriendlyName:function(friendlyName,bagType){return _getBagsByAttribute(pfx.safeContents,"friendlyName",friendlyName,bagType)},getBagsByLocalKeyId:function(localKeyId,bagType){return _getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,bagType)}};if(3!==capture.version.charCodeAt(0))throw(error=new Error("PKCS#12 PFX of version other than 3 not supported.")).version=capture.version.charCodeAt(0),error;if(asn1.derToOid(capture.contentType)!==pki.oids.data)throw(error=new Error("Only PKCS#12 PFX in password integrity mode supported.")).oid=asn1.derToOid(capture.contentType),error;var data=capture.content.value[0];if(data.tagClass!==asn1.Class.UNIVERSAL||data.type!==asn1.Type.OCTETSTRING)throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(data=_decodePkcs7Data(data),capture.mac){var md=null,macKeyBytes=0,macAlgorithm=asn1.derToOid(capture.macAlgorithm);switch(macAlgorithm){case pki.oids.sha1:md=forge.md.sha1.create(),macKeyBytes=20;break;case pki.oids.sha256:md=forge.md.sha256.create(),macKeyBytes=32;break;case pki.oids.sha384:md=forge.md.sha384.create(),macKeyBytes=48;break;case pki.oids.sha512:md=forge.md.sha512.create(),macKeyBytes=64;break;case pki.oids.md5:md=forge.md.md5.create(),macKeyBytes=16}if(null===md)throw new Error("PKCS#12 uses unsupported MAC algorithm: "+macAlgorithm);var macSalt=new forge.util.ByteBuffer(capture.macSalt),macIterations="macIterations"in capture?parseInt(forge.util.bytesToHex(capture.macIterations),16):1,macKey=p12.generateKey(password,macSalt,3,macIterations,macKeyBytes,md),mac=forge.hmac.create();if(mac.start(md,macKey),mac.update(data.value),mac.getMac().getBytes()!==capture.macDigest)throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}return function _decodeAuthenticatedSafe(pfx,authSafe,strict,password){if(authSafe=asn1.fromDer(authSafe,strict),authSafe.tagClass!==asn1.Class.UNIVERSAL||authSafe.type!==asn1.Type.SEQUENCE||!0!==authSafe.constructed)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var i=0;i<authSafe.value.length;i++){var contentInfo=authSafe.value[i],capture={},errors=[];if(!asn1.validate(contentInfo,contentInfoValidator,capture,errors))throw(error=new Error("Cannot read ContentInfo.")).errors=errors,error;var obj={encrypted:!1},safeContents=null,data=capture.content.value[0];switch(asn1.derToOid(capture.contentType)){case pki.oids.data:if(data.tagClass!==asn1.Class.UNIVERSAL||data.type!==asn1.Type.OCTETSTRING)throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");safeContents=_decodePkcs7Data(data).value;break;case pki.oids.encryptedData:safeContents=_decryptSafeContents(data,password),obj.encrypted=!0;break;default:var error;throw(error=new Error("Unsupported PKCS#12 contentType.")).contentType=asn1.derToOid(capture.contentType),error}obj.safeBags=_decodeSafeContents(safeContents,strict,password),pfx.safeContents.push(obj)}}(pfx,data.value,strict,password),pfx},p12.toPkcs12Asn1=function(key,cert,password,options){(options=options||{}).saltSize=options.saltSize||8,options.count=options.count||2048,options.algorithm=options.algorithm||options.encAlgorithm||"aes128","useMac"in options||(options.useMac=!0),"localKeyId"in options||(options.localKeyId=null),"generateLocalKeyId"in options||(options.generateLocalKeyId=!0);var bagAttrs,localKeyId=options.localKeyId;if(null!==localKeyId)localKeyId=forge.util.hexToBytes(localKeyId);else if(options.generateLocalKeyId)if(cert){var pairedCert=forge.util.isArray(cert)?cert[0]:cert;"string"==typeof pairedCert&&(pairedCert=pki.certificateFromPem(pairedCert)),(sha1=forge.md.sha1.create()).update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()),localKeyId=sha1.digest().getBytes()}else localKeyId=forge.random.getBytes(20);var attrs=[];null!==localKeyId&&attrs.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.localKeyId).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,localKeyId)])])),"friendlyName"in options&&attrs.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.friendlyName).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BMPSTRING,!1,options.friendlyName)])])),attrs.length>0&&(bagAttrs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,attrs));var contents=[],chain=[];null!==cert&&(chain=forge.util.isArray(cert)?cert:[cert]);for(var certSafeBags=[],i=0;i<chain.length;++i){"string"==typeof(cert=chain[i])&&(cert=pki.certificateFromPem(cert));var certBagAttrs=0===i?bagAttrs:void 0,certAsn1=pki.certificateToAsn1(cert),certSafeBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.certBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.x509Certificate).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,asn1.toDer(certAsn1).getBytes())])])]),certBagAttrs]);certSafeBags.push(certSafeBag)}if(certSafeBags.length>0){var certSafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,certSafeBags),certCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,asn1.toDer(certSafeContents).getBytes())])]);contents.push(certCI)}var keyBag=null;if(null!==key){var pkAsn1=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));keyBag=null===password?asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.keyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[pkAsn1]),bagAttrs]):asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[pki.encryptPrivateKeyInfo(pkAsn1,password,options)]),bagAttrs]);var keySafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[keyBag]),keyCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,asn1.toDer(keySafeContents).getBytes())])]);contents.push(keyCI)}var macData,safe=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,contents);if(options.useMac){var sha1=forge.md.sha1.create(),macSalt=new forge.util.ByteBuffer(forge.random.getBytes(options.saltSize)),count=options.count,mac=(key=p12.generateKey(password,macSalt,3,count,20),forge.hmac.create());mac.start(sha1,key),mac.update(asn1.toDer(safe).getBytes());var macValue=mac.getMac();macData=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.sha1).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,macValue.getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,macSalt.getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(count).getBytes())])}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(3).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,asn1.toDer(safe).getBytes())])]),macData])},p12.generateKey=forge.pbe.generatePkcs12Key,pkcs12.exports}function requirePki(){if(hasRequiredPki)return pki.exports;hasRequiredPki=1;var forge=requireForge();requireAsn1(),requireOids(),requirePbe(),requirePem(),requirePbkdf2(),requirePkcs12(),requirePss(),requireRsa(),requireUtil(),requireX509();var asn1=forge.asn1,pki$1=pki.exports=forge.pki=forge.pki||{};return pki$1.pemToDer=function(pem){var msg=forge.pem.decode(pem)[0];if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert PEM to DER; PEM is encrypted.");return forge.util.createBuffer(msg.body)},pki$1.privateKeyFromPem=function(pem){var msg=forge.pem.decode(pem)[0];if("PRIVATE KEY"!==msg.type&&"RSA PRIVATE KEY"!==msg.type){var error=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw error.headerType=msg.type,error}if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert private key from PEM; PEM is encrypted.");var obj=asn1.fromDer(msg.body);return pki$1.privateKeyFromAsn1(obj)},pki$1.privateKeyToPem=function(key,maxline){var msg={type:"RSA PRIVATE KEY",body:asn1.toDer(pki$1.privateKeyToAsn1(key)).getBytes()};return forge.pem.encode(msg,{maxline:maxline})},pki$1.privateKeyInfoToPem=function(pki,maxline){var msg={type:"PRIVATE KEY",body:asn1.toDer(pki).getBytes()};return forge.pem.encode(msg,{maxline:maxline})},pki.exports}function requireTls(){if(hasRequiredTls)return tls_1;hasRequiredTls=1;var forge=requireForge();requireAsn1(),requireHmac(),requireMd5(),requirePem(),requirePki(),requireRandom(),requireSha1$1(),requireUtil();var prf_TLS1=function(secret,label,seed,length){var rval=forge.util.createBuffer(),idx=secret.length>>1,slen=idx+(1&secret.length),s1=secret.substr(0,slen),s2=secret.substr(idx,slen),ai=forge.util.createBuffer(),hmac=forge.hmac.create();seed=label+seed;var md5itr=Math.ceil(length/16),sha1itr=Math.ceil(length/20);hmac.start("MD5",s1);var md5bytes=forge.util.createBuffer();ai.putBytes(seed);for(var i=0;i<md5itr;++i)hmac.start(null,null),hmac.update(ai.getBytes()),ai.putBuffer(hmac.digest()),hmac.start(null,null),hmac.update(ai.bytes()+seed),md5bytes.putBuffer(hmac.digest());hmac.start("SHA1",s2);var sha1bytes=forge.util.createBuffer();ai.clear(),ai.putBytes(seed);for(i=0;i<sha1itr;++i)hmac.start(null,null),hmac.update(ai.getBytes()),ai.putBuffer(hmac.digest()),hmac.start(null,null),hmac.update(ai.bytes()+seed),sha1bytes.putBuffer(hmac.digest());return rval.putBytes(forge.util.xorBytes(md5bytes.getBytes(),sha1bytes.getBytes(),length)),rval},deflate=function(c,record,s){var rval=!1;try{var bytes=c.deflate(record.fragment.getBytes());record.fragment=forge.util.createBuffer(bytes),record.length=bytes.length,rval=!0}catch(ex){}return rval},inflate=function(c,record,s){var rval=!1;try{var bytes=c.inflate(record.fragment.getBytes());record.fragment=forge.util.createBuffer(bytes),record.length=bytes.length,rval=!0}catch(ex){}return rval},readVector=function(b,lenBytes){var len=0;switch(lenBytes){case 1:len=b.getByte();break;case 2:len=b.getInt16();break;case 3:len=b.getInt24();break;case 4:len=b.getInt32()}return forge.util.createBuffer(b.getBytes(len))},writeVector=function(b,lenBytes,v){b.putInt(v.length(),lenBytes<<3),b.putBuffer(v)},tls={Versions:{TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}}};tls.SupportedVersions=[tls.Versions.TLS_1_1,tls.Versions.TLS_1_0],tls.Version=tls.SupportedVersions[0],tls.MaxFragment=15360,tls.ConnectionEnd={server:0,client:1},tls.PRFAlgorithm={tls_prf_sha256:0},tls.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2},tls.CipherType={stream:0,block:1,aead:2},tls.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4},tls.CompressionMethod={none:0,deflate:1},tls.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24},tls.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20},tls.Alert={},tls.Alert.Level={warning:1,fatal:2},tls.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100},tls.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2},tls.CipherSuites={},tls.getCipherSuite=function(twoBytes){var rval=null;for(var key in tls.CipherSuites){var cs=tls.CipherSuites[key];if(cs.id[0]===twoBytes.charCodeAt(0)&&cs.id[1]===twoBytes.charCodeAt(1)){rval=cs;break}}return rval},tls.handleUnexpected=function(c,record){!c.open&&c.entity===tls.ConnectionEnd.client||c.error(c,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unexpected_message}})},tls.handleHelloRequest=function(c,record,length){!c.handshaking&&c.handshakes>0&&(tls.queue(c,tls.createAlert(c,{level:tls.Alert.Level.warning,description:tls.Alert.Description.no_renegotiation})),tls.flush(c)),c.process()},tls.parseHelloMessage=function(c,record,length){var msg=null,client=c.entity===tls.ConnectionEnd.client;if(length<38)c.error(c,{message:client?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}});else{var b=record.fragment,remaining=b.length();if(msg={version:{major:b.getByte(),minor:b.getByte()},random:forge.util.createBuffer(b.getBytes(32)),session_id:readVector(b,1),extensions:[]},client?(msg.cipher_suite=b.getBytes(2),msg.compression_method=b.getByte()):(msg.cipher_suites=readVector(b,2),msg.compression_methods=readVector(b,1)),(remaining=length-(remaining-b.length()))>0){for(var exts=readVector(b,2);exts.length()>0;)msg.extensions.push({type:[exts.getByte(),exts.getByte()],data:readVector(exts,2)});if(!client)for(var i=0;i<msg.extensions.length;++i){var ext=msg.extensions[i];if(0===ext.type[0]&&0===ext.type[1])for(var snl=readVector(ext.data,2);snl.length()>0;){if(0!==snl.getByte())break;c.session.extensions.server_name.serverNameList.push(readVector(snl,2).getBytes())}}}if(c.session.version&&(msg.version.major!==c.session.version.major||msg.version.minor!==c.session.version.minor))return c.error(c,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}});if(client)c.session.cipherSuite=tls.getCipherSuite(msg.cipher_suite);else for(var tmp=forge.util.createBuffer(msg.cipher_suites.bytes());tmp.length()>0&&(c.session.cipherSuite=tls.getCipherSuite(tmp.getBytes(2)),null===c.session.cipherSuite););if(null===c.session.cipherSuite)return c.error(c,{message:"No cipher suites in common.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.handshake_failure},cipherSuite:forge.util.bytesToHex(msg.cipher_suite)});c.session.compressionMethod=client?msg.compression_method:tls.CompressionMethod.none}return msg},tls.createSecurityParameters=function(c,msg){var client=c.entity===tls.ConnectionEnd.client,msgRandom=msg.random.bytes(),cRandom=client?c.session.sp.client_random:msgRandom,sRandom=client?msgRandom:tls.createRandom().getBytes();c.session.sp={entity:c.entity,prf_algorithm:tls.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:c.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:cRandom,server_random:sRandom}},tls.handleServerHello=function(c,record,length){var msg=tls.parseHelloMessage(c,record,length);if(!c.fail){if(!(msg.version.minor<=c.version.minor))return c.error(c,{message:"Incompatible TLS version.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}});c.version.minor=msg.version.minor,c.session.version=c.version;var sessionId=msg.session_id.bytes();sessionId.length>0&&sessionId===c.session.id?(c.expect=SCC,c.session.resuming=!0,c.session.sp.server_random=msg.random.bytes()):(c.expect=SCE,c.session.resuming=!1,tls.createSecurityParameters(c,msg)),c.session.id=sessionId,c.process()}},tls.handleClientHello=function(c,record,length){var msg=tls.parseHelloMessage(c,record,length);if(!c.fail){var sessionId=msg.session_id.bytes(),session=null;if(c.sessionCache&&(null===(session=c.sessionCache.getSession(sessionId))?sessionId="":(session.version.major!==msg.version.major||session.version.minor>msg.version.minor)&&(session=null,sessionId="")),0===sessionId.length&&(sessionId=forge.random.getBytes(32)),c.session.id=sessionId,c.session.clientHelloVersion=msg.version,c.session.sp={},session)c.version=c.session.version=session.version,c.session.sp=session.sp;else{for(var version,i=1;i<tls.SupportedVersions.length&&!((version=tls.SupportedVersions[i]).minor<=msg.version.minor);++i);c.version={major:version.major,minor:version.minor},c.session.version=c.version}null!==session?(c.expect=CCC,c.session.resuming=!0,c.session.sp.client_random=msg.random.bytes()):(c.expect=!1!==c.verifyClient?CCE:CKE,c.session.resuming=!1,tls.createSecurityParameters(c,msg)),c.open=!0,tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createServerHello(c)})),c.session.resuming?(tls.queue(c,tls.createRecord(c,{type:tls.ContentType.change_cipher_spec,data:tls.createChangeCipherSpec()})),c.state.pending=tls.createConnectionState(c),c.state.current.write=c.state.pending.write,tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createFinished(c)}))):(tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificate(c)})),c.fail||(tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createServerKeyExchange(c)})),!1!==c.verifyClient&&tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificateRequest(c)})),tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createServerHelloDone(c)})))),tls.flush(c),c.process()}},tls.handleCertificate=function(c,record,length){if(length<3)return c.error(c,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}});var cert,asn1,b=record.fragment,msg={certificate_list:readVector(b,3)},certs=[];try{for(;msg.certificate_list.length()>0;)cert=readVector(msg.certificate_list,3),asn1=forge.asn1.fromDer(cert),cert=forge.pki.certificateFromAsn1(asn1,!0),certs.push(cert)}catch(ex){return c.error(c,{message:"Could not parse certificate list.",cause:ex,send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_certificate}})}var client=c.entity===tls.ConnectionEnd.client;!client&&!0!==c.verifyClient||0!==certs.length?0===certs.length?c.expect=client?SKE:CKE:(client?c.session.serverCertificate=certs[0]:c.session.clientCertificate=certs[0],tls.verifyCertificateChain(c,certs)&&(c.expect=client?SKE:CKE)):c.error(c,{message:client?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}}),c.process()},tls.handleServerKeyExchange=function(c,record,length){if(length>0)return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unsupported_certificate}});c.expect=SCR,c.process()},tls.handleClientKeyExchange=function(c,record,length){if(length<48)return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unsupported_certificate}});var b=record.fragment,msg={enc_pre_master_secret:readVector(b,2).getBytes()},privateKey=null;if(c.getPrivateKey)try{privateKey=c.getPrivateKey(c,c.session.serverCertificate),privateKey=forge.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}if(null===privateKey)return c.error(c,{message:"No private key set.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}});try{var sp=c.session.sp;sp.pre_master_secret=privateKey.decrypt(msg.enc_pre_master_secret);var version=c.session.clientHelloVersion;if(version.major!==sp.pre_master_secret.charCodeAt(0)||version.minor!==sp.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch(ex){sp.pre_master_secret=forge.random.getBytes(48)}c.expect=CCC,null!==c.session.clientCertificate&&(c.expect=CCV),c.process()},tls.handleCertificateRequest=function(c,record,length){if(length<3)return c.error(c,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}});var b=record.fragment,msg={certificate_types:readVector(b,1),certificate_authorities:readVector(b,2)};c.session.certificateRequest=msg,c.expect=SHD,c.process()},tls.handleCertificateVerify=function(c,record,length){if(length<2)return c.error(c,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}});var b=record.fragment;b.read-=4;var msgBytes=b.bytes();b.read+=4;var msg={signature:readVector(b,2).getBytes()},verify=forge.util.createBuffer();verify.putBuffer(c.session.md5.digest()),verify.putBuffer(c.session.sha1.digest()),verify=verify.getBytes();try{if(!c.session.clientCertificate.publicKey.verify(verify,msg.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");c.session.md5.update(msgBytes),c.session.sha1.update(msgBytes)}catch(ex){return c.error(c,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.handshake_failure}})}c.expect=CCC,c.process()},tls.handleServerHelloDone=function(c,record,length){if(length>0)return c.error(c,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.record_overflow}});if(null===c.serverCertificate){var error={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.insufficient_security}},ret=c.verify(c,error.alert.description,0,[]);if(!0!==ret)return(ret||0===ret)&&("object"!=typeof ret||forge.util.isArray(ret)?"number"==typeof ret&&(error.alert.description=ret):(ret.message&&(error.message=ret.message),ret.alert&&(error.alert.description=ret.alert))),c.error(c,error)}null!==c.session.certificateRequest&&(record=tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificate(c)}),tls.queue(c,record)),record=tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createClientKeyExchange(c)}),tls.queue(c,record),c.expect=SER;var callback=function(c,signature){null!==c.session.certificateRequest&&null!==c.session.clientCertificate&&tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createCertificateVerify(c,signature)})),tls.queue(c,tls.createRecord(c,{type:tls.ContentType.change_cipher_spec,data:tls.createChangeCipherSpec()})),c.state.pending=tls.createConnectionState(c),c.state.current.write=c.state.pending.write,tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createFinished(c)})),c.expect=SCC,tls.flush(c),c.process()};if(null===c.session.certificateRequest||null===c.session.clientCertificate)return callback(c,null);tls.getClientSignature(c,callback)},tls.handleChangeCipherSpec=function(c,record){if(1!==record.fragment.getByte())return c.error(c,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.illegal_parameter}});var client=c.entity===tls.ConnectionEnd.client;(c.session.resuming&&client||!c.session.resuming&&!client)&&(c.state.pending=tls.createConnectionState(c)),c.state.current.read=c.state.pending.read,(!c.session.resuming&&client||c.session.resuming&&!client)&&(c.state.pending=null),c.expect=client?SFI:CFI,c.process()},tls.handleFinished=function(c,record,length){var b=record.fragment;b.read-=4;var msgBytes=b.bytes();b.read+=4;var vd=record.fragment.getBytes();(b=forge.util.createBuffer()).putBuffer(c.session.md5.digest()),b.putBuffer(c.session.sha1.digest());var client=c.entity===tls.ConnectionEnd.client,label=client?"server finished":"client finished",sp=c.session.sp;if((b=prf_TLS1(sp.master_secret,label,b.getBytes(),12)).getBytes()!==vd)return c.error(c,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.decrypt_error}});c.session.md5.update(msgBytes),c.session.sha1.update(msgBytes),(c.session.resuming&&client||!c.session.resuming&&!client)&&(tls.queue(c,tls.createRecord(c,{type:tls.ContentType.change_cipher_spec,data:tls.createChangeCipherSpec()})),c.state.current.write=c.state.pending.write,c.state.pending=null,tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createFinished(c)}))),c.expect=client?SAD:CAD,c.handshaking=!1,++c.handshakes,c.peerCertificate=client?c.session.serverCertificate:c.session.clientCertificate,tls.flush(c),c.isConnected=!0,c.connected(c),c.process()},tls.handleAlert=function(c,record){var msg,b=record.fragment,alert={level:b.getByte(),description:b.getByte()};switch(alert.description){case tls.Alert.Description.close_notify:msg="Connection closed.";break;case tls.Alert.Description.unexpected_message:msg="Unexpected message.";break;case tls.Alert.Description.bad_record_mac:msg="Bad record MAC.";break;case tls.Alert.Description.decryption_failed:msg="Decryption failed.";break;case tls.Alert.Description.record_overflow:msg="Record overflow.";break;case tls.Alert.Description.decompression_failure:msg="Decompression failed.";break;case tls.Alert.Description.handshake_failure:msg="Handshake failure.";break;case tls.Alert.Description.bad_certificate:msg="Bad certificate.";break;case tls.Alert.Description.unsupported_certificate:msg="Unsupported certificate.";break;case tls.Alert.Description.certificate_revoked:msg="Certificate revoked.";break;case tls.Alert.Description.certificate_expired:msg="Certificate expired.";break;case tls.Alert.Description.certificate_unknown:msg="Certificate unknown.";break;case tls.Alert.Description.illegal_parameter:msg="Illegal parameter.";break;case tls.Alert.Description.unknown_ca:msg="Unknown certificate authority.";break;case tls.Alert.Description.access_denied:msg="Access denied.";break;case tls.Alert.Description.decode_error:msg="Decode error.";break;case tls.Alert.Description.decrypt_error:msg="Decrypt error.";break;case tls.Alert.Description.export_restriction:msg="Export restriction.";break;case tls.Alert.Description.protocol_version:msg="Unsupported protocol version.";break;case tls.Alert.Description.insufficient_security:msg="Insufficient security.";break;case tls.Alert.Description.internal_error:msg="Internal error.";break;case tls.Alert.Description.user_canceled:msg="User canceled.";break;case tls.Alert.Description.no_renegotiation:msg="Renegotiation not supported.";break;default:msg="Unknown error."}if(alert.description===tls.Alert.Description.close_notify)return c.close();c.error(c,{message:msg,send:!1,origin:c.entity===tls.ConnectionEnd.client?"server":"client",alert:alert}),c.process()},tls.handleHandshake=function(c,record){var b=record.fragment,type=b.getByte(),length=b.getInt24();if(length>b.length())return c.fragmented=record,record.fragment=forge.util.createBuffer(),b.read-=4,c.process();c.fragmented=null,b.read-=4;var bytes=b.bytes(length+4);b.read+=4,type in hsTable[c.entity][c.expect]?(c.entity!==tls.ConnectionEnd.server||c.open||c.fail||(c.handshaking=!0,c.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:forge.md.md5.create(),sha1:forge.md.sha1.create()}),type!==tls.HandshakeType.hello_request&&type!==tls.HandshakeType.certificate_verify&&type!==tls.HandshakeType.finished&&(c.session.md5.update(bytes),c.session.sha1.update(bytes)),hsTable[c.entity][c.expect][type](c,record,length)):tls.handleUnexpected(c,record)},tls.handleApplicationData=function(c,record){c.data.putBuffer(record.fragment),c.dataReady(c),c.process()},tls.handleHeartbeat=function(c,record){var b=record.fragment,type=b.getByte(),length=b.getInt16(),payload=b.getBytes(length);if(type===tls.HeartbeatMessageType.heartbeat_request){if(c.handshaking||length>payload.length)return c.process();tls.queue(c,tls.createRecord(c,{type:tls.ContentType.heartbeat,data:tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_response,payload)})),tls.flush(c)}else if(type===tls.HeartbeatMessageType.heartbeat_response){if(payload!==c.expectedHeartbeatPayload)return c.process();c.heartbeatReceived&&c.heartbeatReceived(c,forge.util.createBuffer(payload))}c.process()};var SCE=1,SKE=2,SCR=3,SHD=4,SCC=5,SFI=6,SAD=7,SER=8,CCE=1,CKE=2,CCV=3,CCC=4,CFI=5,CAD=6,__=tls.handleUnexpected,R0=tls.handleChangeCipherSpec,R1=tls.handleAlert,R2=tls.handleHandshake,R3=tls.handleApplicationData,R4=tls.handleHeartbeat,ctTable=[];ctTable[tls.ConnectionEnd.client]=[[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[R0,R1,__,__,R4],[__,R1,R2,__,R4],[__,R1,R2,R3,R4],[__,R1,R2,__,R4]],ctTable[tls.ConnectionEnd.server]=[[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[__,R1,R2,__,R4],[R0,R1,__,__,R4],[__,R1,R2,__,R4],[__,R1,R2,R3,R4],[__,R1,R2,__,R4]];var H0=tls.handleHelloRequest,H1=tls.handleServerHello,H2=tls.handleCertificate,H3=tls.handleServerKeyExchange,H4=tls.handleCertificateRequest,H5=tls.handleServerHelloDone,H6=tls.handleFinished,hsTable=[];hsTable[tls.ConnectionEnd.client]=[[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];var H7=tls.handleClientHello,H8=tls.handleClientKeyExchange,H9=tls.handleCertificateVerify;hsTable[tls.ConnectionEnd.server]=[[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]],tls.generateKeys=function(c,sp){var prf=prf_TLS1,random=sp.client_random+sp.server_random;c.session.resuming||(sp.master_secret=prf(sp.pre_master_secret,"master secret",random,48).bytes(),sp.pre_master_secret=null),random=sp.server_random+sp.client_random;var length=2*sp.mac_key_length+2*sp.enc_key_length,tls10=c.version.major===tls.Versions.TLS_1_0.major&&c.version.minor===tls.Versions.TLS_1_0.minor;tls10&&(length+=2*sp.fixed_iv_length);var km=prf(sp.master_secret,"key expansion",random,length),rval={client_write_MAC_key:km.getBytes(sp.mac_key_length),server_write_MAC_key:km.getBytes(sp.mac_key_length),client_write_key:km.getBytes(sp.enc_key_length),server_write_key:km.getBytes(sp.enc_key_length)};return tls10&&(rval.client_write_IV=km.getBytes(sp.fixed_iv_length),rval.server_write_IV=km.getBytes(sp.fixed_iv_length)),rval},tls.createConnectionState=function(c){var client=c.entity===tls.ConnectionEnd.client,createMode=function(){var mode={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(record){return!0},compressionState:null,compressFunction:function(record){return!0},updateSequenceNumber:function(){4294967295===mode.sequenceNumber[1]?(mode.sequenceNumber[1]=0,++mode.sequenceNumber[0]):++mode.sequenceNumber[1]}};return mode},state={read:createMode(),write:createMode()};if(state.read.update=function(c,record){return state.read.cipherFunction(record,state.read)?state.read.compressFunction(c,record,state.read)||c.error(c,{message:"Could not decompress record.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.decompression_failure}}):c.error(c,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_record_mac}}),!c.fail},state.write.update=function(c,record){return state.write.compressFunction(c,record,state.write)?state.write.cipherFunction(record,state.write)||c.error(c,{message:"Could not encrypt record.",send:!1,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}}):c.error(c,{message:"Could not compress record.",send:!1,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}}),!c.fail},c.session){var sp=c.session.sp;switch(c.session.cipherSuite.initSecurityParameters(sp),sp.keys=tls.generateKeys(c,sp),state.read.macKey=client?sp.keys.server_write_MAC_key:sp.keys.client_write_MAC_key,state.write.macKey=client?sp.keys.client_write_MAC_key:sp.keys.server_write_MAC_key,c.session.cipherSuite.initConnectionState(state,c,sp),sp.compression_algorithm){case tls.CompressionMethod.none:break;case tls.CompressionMethod.deflate:state.read.compressFunction=inflate,state.write.compressFunction=deflate;break;default:throw new Error("Unsupported compression algorithm.")}}return state},tls.createRandom=function(){var d=new Date,utc=+d+6e4*d.getTimezoneOffset(),rval=forge.util.createBuffer();return rval.putInt32(utc),rval.putBytes(forge.random.getBytes(28)),rval},tls.createRecord=function(c,options){return options.data?{type:options.type,version:{major:c.version.major,minor:c.version.minor},length:options.data.length(),fragment:options.data}:null},tls.createAlert=function(c,alert){var b=forge.util.createBuffer();return b.putByte(alert.level),b.putByte(alert.description),tls.createRecord(c,{type:tls.ContentType.alert,data:b})},tls.createClientHello=function(c){c.session.clientHelloVersion={major:c.version.major,minor:c.version.minor};for(var cipherSuites=forge.util.createBuffer(),i=0;i<c.cipherSuites.length;++i){var cs=c.cipherSuites[i];cipherSuites.putByte(cs.id[0]),cipherSuites.putByte(cs.id[1])}var cSuites=cipherSuites.length(),compressionMethods=forge.util.createBuffer();compressionMethods.putByte(tls.CompressionMethod.none);var cMethods=compressionMethods.length(),extensions=forge.util.createBuffer();if(c.virtualHost){var ext=forge.util.createBuffer();ext.putByte(0),ext.putByte(0);var serverName=forge.util.createBuffer();serverName.putByte(0),writeVector(serverName,2,forge.util.createBuffer(c.virtualHost));var snList=forge.util.createBuffer();writeVector(snList,2,serverName),writeVector(ext,2,snList),extensions.putBuffer(ext)}var extLength=extensions.length();extLength>0&&(extLength+=2);var sessionId=c.session.id,length=sessionId.length+1+2+4+28+2+cSuites+1+cMethods+extLength,rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.client_hello),rval.putInt24(length),rval.putByte(c.version.major),rval.putByte(c.version.minor),rval.putBytes(c.session.sp.client_random),writeVector(rval,1,forge.util.createBuffer(sessionId)),writeVector(rval,2,cipherSuites),writeVector(rval,1,compressionMethods),extLength>0&&writeVector(rval,2,extensions),rval},tls.createServerHello=function(c){var sessionId=c.session.id,length=sessionId.length+1+2+4+28+2+1,rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.server_hello),rval.putInt24(length),rval.putByte(c.version.major),rval.putByte(c.version.minor),rval.putBytes(c.session.sp.server_random),writeVector(rval,1,forge.util.createBuffer(sessionId)),rval.putByte(c.session.cipherSuite.id[0]),rval.putByte(c.session.cipherSuite.id[1]),rval.putByte(c.session.compressionMethod),rval},tls.createCertificate=function(c){var hint,client=c.entity===tls.ConnectionEnd.client,cert=null;c.getCertificate&&(hint=client?c.session.certificateRequest:c.session.extensions.server_name.serverNameList,cert=c.getCertificate(c,hint));var certList=forge.util.createBuffer();if(null!==cert)try{forge.util.isArray(cert)||(cert=[cert]);for(var asn1=null,i=0;i<cert.length;++i){var msg=forge.pem.decode(cert[i])[0];if("CERTIFICATE"!==msg.type&&"X509 CERTIFICATE"!==msg.type&&"TRUSTED CERTIFICATE"!==msg.type){var error=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw error.headerType=msg.type,error}if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var der=forge.util.createBuffer(msg.body);null===asn1&&(asn1=forge.asn1.fromDer(der.bytes(),!1));var certBuffer=forge.util.createBuffer();writeVector(certBuffer,3,der),certList.putBuffer(certBuffer)}cert=forge.pki.certificateFromAsn1(asn1),client?c.session.clientCertificate=cert:c.session.serverCertificate=cert}catch(ex){return c.error(c,{message:"Could not send certificate list.",cause:ex,send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_certificate}})}var length=3+certList.length(),rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.certificate),rval.putInt24(length),writeVector(rval,3,certList),rval},tls.createClientKeyExchange=function(c){var b=forge.util.createBuffer();b.putByte(c.session.clientHelloVersion.major),b.putByte(c.session.clientHelloVersion.minor),b.putBytes(forge.random.getBytes(46));var sp=c.session.sp;sp.pre_master_secret=b.getBytes();var length=(b=c.session.serverCertificate.publicKey.encrypt(sp.pre_master_secret)).length+2,rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.client_key_exchange),rval.putInt24(length),rval.putInt16(b.length),rval.putBytes(b),rval},tls.createServerKeyExchange=function(c){return forge.util.createBuffer()},tls.getClientSignature=function(c,callback){var b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest()),b.putBuffer(c.session.sha1.digest()),b=b.getBytes(),c.getSignature=c.getSignature||function(c,b,callback){var privateKey=null;if(c.getPrivateKey)try{privateKey=c.getPrivateKey(c,c.session.clientCertificate),privateKey=forge.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}})}null===privateKey?c.error(c,{message:"No private key set.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.internal_error}}):b=privateKey.sign(b,null),callback(c,b)},c.getSignature(c,b,callback)},tls.createCertificateVerify=function(c,signature){var length=signature.length+2,rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.certificate_verify),rval.putInt24(length),rval.putInt16(signature.length),rval.putBytes(signature),rval},tls.createCertificateRequest=function(c){var certTypes=forge.util.createBuffer();certTypes.putByte(1);var cAs=forge.util.createBuffer();for(var key in c.caStore.certs){var cert=c.caStore.certs[key],dn=forge.pki.distinguishedNameToAsn1(cert.subject),byteBuffer=forge.asn1.toDer(dn);cAs.putInt16(byteBuffer.length()),cAs.putBuffer(byteBuffer)}var length=1+certTypes.length()+2+cAs.length(),rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.certificate_request),rval.putInt24(length),writeVector(rval,1,certTypes),writeVector(rval,2,cAs),rval},tls.createServerHelloDone=function(c){var rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.server_hello_done),rval.putInt24(0),rval},tls.createChangeCipherSpec=function(){var rval=forge.util.createBuffer();return rval.putByte(1),rval},tls.createFinished=function(c){var b=forge.util.createBuffer();b.putBuffer(c.session.md5.digest()),b.putBuffer(c.session.sha1.digest());var client=c.entity===tls.ConnectionEnd.client,sp=c.session.sp,label=client?"client finished":"server finished";b=prf_TLS1(sp.master_secret,label,b.getBytes(),12);var rval=forge.util.createBuffer();return rval.putByte(tls.HandshakeType.finished),rval.putInt24(b.length()),rval.putBuffer(b),rval},tls.createHeartbeat=function(type,payload,payloadLength){void 0===payloadLength&&(payloadLength=payload.length);var rval=forge.util.createBuffer();rval.putByte(type),rval.putInt16(payloadLength),rval.putBytes(payload);var plaintextLength=rval.length(),paddingLength=Math.max(16,plaintextLength-payloadLength-3);return rval.putBytes(forge.random.getBytes(paddingLength)),rval},tls.queue=function(c,record){if(record&&(0!==record.fragment.length()||record.type!==tls.ContentType.handshake&&record.type!==tls.ContentType.alert&&record.type!==tls.ContentType.change_cipher_spec)){if(record.type===tls.ContentType.handshake){var bytes=record.fragment.bytes();c.session.md5.update(bytes),c.session.sha1.update(bytes),bytes=null}var records;if(record.fragment.length()<=tls.MaxFragment)records=[record];else{records=[];for(var data=record.fragment.bytes();data.length>tls.MaxFragment;)records.push(tls.createRecord(c,{type:record.type,data:forge.util.createBuffer(data.slice(0,tls.MaxFragment))})),data=data.slice(tls.MaxFragment);data.length>0&&records.push(tls.createRecord(c,{type:record.type,data:forge.util.createBuffer(data)}))}for(var i=0;i<records.length&&!c.fail;++i){var rec=records[i];c.state.current.write.update(c,rec)&&c.records.push(rec)}}},tls.flush=function(c){for(var i=0;i<c.records.length;++i){var record=c.records[i];c.tlsData.putByte(record.type),c.tlsData.putByte(record.version.major),c.tlsData.putByte(record.version.minor),c.tlsData.putInt16(record.fragment.length()),c.tlsData.putBuffer(c.records[i].fragment)}return c.records=[],c.tlsDataReady(c)};var _certErrorToAlertDesc=function(error){switch(error){case!0:return!0;case forge.pki.certificateError.bad_certificate:return tls.Alert.Description.bad_certificate;case forge.pki.certificateError.unsupported_certificate:return tls.Alert.Description.unsupported_certificate;case forge.pki.certificateError.certificate_revoked:return tls.Alert.Description.certificate_revoked;case forge.pki.certificateError.certificate_expired:return tls.Alert.Description.certificate_expired;case forge.pki.certificateError.certificate_unknown:return tls.Alert.Description.certificate_unknown;case forge.pki.certificateError.unknown_ca:return tls.Alert.Description.unknown_ca;default:return tls.Alert.Description.bad_certificate}};for(var key in tls.verifyCertificateChain=function(c,chain){try{var options={};for(var key in c.verifyOptions)options[key]=c.verifyOptions[key];options.verify=function(vfd,depth,chain){_certErrorToAlertDesc(vfd);var ret=c.verify(c,vfd,depth,chain);if(!0!==ret){if("object"==typeof ret&&!forge.util.isArray(ret)){var error=new Error("The application rejected the certificate.");throw error.send=!0,error.alert={level:tls.Alert.Level.fatal,description:tls.Alert.Description.bad_certificate},ret.message&&(error.message=ret.message),ret.alert&&(error.alert.description=ret.alert),error}ret!==vfd&&(ret=function(desc){switch(desc){case!0:return!0;case tls.Alert.Description.bad_certificate:return forge.pki.certificateError.bad_certificate;case tls.Alert.Description.unsupported_certificate:return forge.pki.certificateError.unsupported_certificate;case tls.Alert.Description.certificate_revoked:return forge.pki.certificateError.certificate_revoked;case tls.Alert.Description.certificate_expired:return forge.pki.certificateError.certificate_expired;case tls.Alert.Description.certificate_unknown:return forge.pki.certificateError.certificate_unknown;case tls.Alert.Description.unknown_ca:return forge.pki.certificateError.unknown_ca;default:return forge.pki.certificateError.bad_certificate}}(ret))}return ret},forge.pki.verifyCertificateChain(c.caStore,chain,options)}catch(ex){var err=ex;("object"!=typeof err||forge.util.isArray(err))&&(err={send:!0,alert:{level:tls.Alert.Level.fatal,description:_certErrorToAlertDesc(ex)}}),"send"in err||(err.send=!0),"alert"in err||(err.alert={level:tls.Alert.Level.fatal,description:_certErrorToAlertDesc(err.error)}),c.error(c,err)}return!c.fail},tls.createSessionCache=function(cache,capacity){var rval=null;if(cache&&cache.getSession&&cache.setSession&&cache.order)rval=cache;else{for(var key in(rval={}).cache=cache||{},rval.capacity=Math.max(capacity||100,1),rval.order=[],cache)rval.order.length<=capacity?rval.order.push(key):delete cache[key];rval.getSession=function(sessionId){var session=null,key=null;if(sessionId?key=forge.util.bytesToHex(sessionId):rval.order.length>0&&(key=rval.order[0]),null!==key&&key in rval.cache)for(var i in session=rval.cache[key],delete rval.cache[key],rval.order)if(rval.order[i]===key){rval.order.splice(i,1);break}return session},rval.setSession=function(sessionId,session){if(rval.order.length===rval.capacity){var key=rval.order.shift();delete rval.cache[key]}key=forge.util.bytesToHex(sessionId);rval.order.push(key),rval.cache[key]=session}}return rval},tls.createConnection=function(options){var caStore=null;caStore=options.caStore?forge.util.isArray(options.caStore)?forge.pki.createCaStore(options.caStore):options.caStore:forge.pki.createCaStore();var cipherSuites=options.cipherSuites||null;if(null===cipherSuites)for(var key in cipherSuites=[],tls.CipherSuites)cipherSuites.push(tls.CipherSuites[key]);var entity=options.server?tls.ConnectionEnd.server:tls.ConnectionEnd.client,sessionCache=options.sessionCache?tls.createSessionCache(options.sessionCache):null,c={version:{major:tls.Version.major,minor:tls.Version.minor},entity:entity,sessionId:options.sessionId,caStore:caStore,sessionCache:sessionCache,cipherSuites:cipherSuites,connected:options.connected,virtualHost:options.virtualHost||null,verifyClient:options.verifyClient||!1,verify:options.verify||function(cn,vfd,dpth,cts){return vfd},verifyOptions:options.verifyOptions||{},getCertificate:options.getCertificate||null,getPrivateKey:options.getPrivateKey||null,getSignature:options.getSignature||null,input:forge.util.createBuffer(),tlsData:forge.util.createBuffer(),data:forge.util.createBuffer(),tlsDataReady:options.tlsDataReady,dataReady:options.dataReady,heartbeatReceived:options.heartbeatReceived,closed:options.closed,error:function(c,ex){ex.origin=ex.origin||(c.entity===tls.ConnectionEnd.client?"client":"server"),ex.send&&(tls.queue(c,tls.createAlert(c,ex.alert)),tls.flush(c));var fatal=!1!==ex.fatal;fatal&&(c.fail=!0),options.error(c,ex),fatal&&c.close(!1)},deflate:options.deflate||null,inflate:options.inflate||null,reset:function(clearFail){c.version={major:tls.Version.major,minor:tls.Version.minor},c.record=null,c.session=null,c.peerCertificate=null,c.state={pending:null,current:null},c.expect=(c.entity,tls.ConnectionEnd.client,0),c.fragmented=null,c.records=[],c.open=!1,c.handshakes=0,c.handshaking=!1,c.isConnected=!1,c.fail=!(clearFail||void 0===clearFail),c.input.clear(),c.tlsData.clear(),c.data.clear(),c.state.current=tls.createConnectionState(c)}};c.reset();return c.handshake=function(sessionId){if(c.entity!==tls.ConnectionEnd.client)c.error(c,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(c.handshaking)c.error(c,{message:"Handshake already in progress.",fatal:!1});else{c.fail&&!c.open&&0===c.handshakes&&(c.fail=!1),c.handshaking=!0;var session=null;(sessionId=sessionId||"").length>0&&(c.sessionCache&&(session=c.sessionCache.getSession(sessionId)),null===session&&(sessionId="")),0===sessionId.length&&c.sessionCache&&null!==(session=c.sessionCache.getSession())&&(sessionId=session.id),c.session={id:sessionId,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:forge.md.md5.create(),sha1:forge.md.sha1.create()},session&&(c.version=session.version,c.session.sp=session.sp),c.session.sp.client_random=tls.createRandom().getBytes(),c.open=!0,tls.queue(c,tls.createRecord(c,{type:tls.ContentType.handshake,data:tls.createClientHello(c)})),tls.flush(c)}},c.process=function(data){var rval=0;return data&&c.input.putBytes(data),c.fail||(null!==c.record&&c.record.ready&&c.record.fragment.isEmpty()&&(c.record=null),null===c.record&&(rval=function(c){var rval=0,b=c.input,len=b.length();if(len<5)rval=5-len;else{c.record={type:b.getByte(),version:{major:b.getByte(),minor:b.getByte()},length:b.getInt16(),fragment:forge.util.createBuffer(),ready:!1};var compatibleVersion=c.record.version.major===c.version.major;compatibleVersion&&c.session&&c.session.version&&(compatibleVersion=c.record.version.minor===c.version.minor),compatibleVersion||c.error(c,{message:"Incompatible TLS version.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.protocol_version}})}return rval}(c)),c.fail||null===c.record||c.record.ready||(rval=function(c){var rval=0,b=c.input,len=b.length();return len<c.record.length?rval=c.record.length-len:(c.record.fragment.putBytes(b.getBytes(c.record.length)),b.compact(),c.state.current.read.update(c,c.record)&&(null!==c.fragmented&&(c.fragmented.type===c.record.type?(c.fragmented.fragment.putBuffer(c.record.fragment),c.record=c.fragmented):c.error(c,{message:"Invalid fragmented record.",send:!0,alert:{level:tls.Alert.Level.fatal,description:tls.Alert.Description.unexpected_message}})),c.record.ready=!0)),rval}(c)),!c.fail&&null!==c.record&&c.record.ready&&function(c,record){var aligned=record.type-tls.ContentType.change_cipher_spec,handlers=ctTable[c.entity][c.expect];aligned in handlers?handlers[aligned](c,record):tls.handleUnexpected(c,record)}(c,c.record)),rval},c.prepare=function(data){return tls.queue(c,tls.createRecord(c,{type:tls.ContentType.application_data,data:forge.util.createBuffer(data)})),tls.flush(c)},c.prepareHeartbeatRequest=function(payload,payloadLength){return payload instanceof forge.util.ByteBuffer&&(payload=payload.bytes()),void 0===payloadLength&&(payloadLength=payload.length),c.expectedHeartbeatPayload=payload,tls.queue(c,tls.createRecord(c,{type:tls.ContentType.heartbeat,data:tls.createHeartbeat(tls.HeartbeatMessageType.heartbeat_request,payload,payloadLength)})),tls.flush(c)},c.close=function(clearFail){if(!c.fail&&c.sessionCache&&c.session){var session={id:c.session.id,version:c.session.version,sp:c.session.sp};session.sp.keys=null,c.sessionCache.setSession(session.id,session)}c.open&&(c.open=!1,c.input.clear(),(c.isConnected||c.handshaking)&&(c.isConnected=c.handshaking=!1,tls.queue(c,tls.createAlert(c,{level:tls.Alert.Level.warning,description:tls.Alert.Description.close_notify})),tls.flush(c)),c.closed(c)),c.reset(clearFail)},c},tls_1=forge.tls=forge.tls||{},tls)"function"!=typeof tls[key]&&(forge.tls[key]=tls[key]);return forge.tls.prf_tls1=prf_TLS1,forge.tls.hmac_sha1=function(key,seqNum,record){var hmac=forge.hmac.create();hmac.start("SHA1",key);var b=forge.util.createBuffer();return b.putInt32(seqNum[0]),b.putInt32(seqNum[1]),b.putByte(record.type),b.putByte(record.version.major),b.putByte(record.version.minor),b.putInt16(record.length),b.putBytes(record.fragment.bytes()),hmac.update(b.getBytes()),hmac.digest().getBytes()},forge.tls.createSessionCache=tls.createSessionCache,forge.tls.createConnection=tls.createConnection,tls_1}function requireAesCipherSuites(){if(hasRequiredAesCipherSuites)return aesCipherSuites.exports;hasRequiredAesCipherSuites=1;var forge=requireForge();requireAes(),requireTls();var tls=aesCipherSuites.exports=forge.tls;function initConnectionState(state,c,sp){var client=c.entity===forge.tls.ConnectionEnd.client;state.read.cipherState={init:!1,cipher:forge.cipher.createDecipher("AES-CBC",client?sp.keys.server_write_key:sp.keys.client_write_key),iv:client?sp.keys.server_write_IV:sp.keys.client_write_IV},state.write.cipherState={init:!1,cipher:forge.cipher.createCipher("AES-CBC",client?sp.keys.client_write_key:sp.keys.server_write_key),iv:client?sp.keys.client_write_IV:sp.keys.server_write_IV},state.read.cipherFunction=decrypt_aes_cbc_sha1,state.write.cipherFunction=encrypt_aes_cbc_sha1,state.read.macLength=state.write.macLength=sp.mac_length,state.read.macFunction=state.write.macFunction=tls.hmac_sha1}function encrypt_aes_cbc_sha1(record,s){var iv,rval=!1,mac=s.macFunction(s.macKey,s.sequenceNumber,record);record.fragment.putBytes(mac),s.updateSequenceNumber(),iv=record.version.minor===tls.Versions.TLS_1_0.minor?s.cipherState.init?null:s.cipherState.iv:forge.random.getBytesSync(16),s.cipherState.init=!0;var cipher=s.cipherState.cipher;return cipher.start({iv:iv}),record.version.minor>=tls.Versions.TLS_1_1.minor&&cipher.output.putBytes(iv),cipher.update(record.fragment),cipher.finish(encrypt_aes_cbc_sha1_padding)&&(record.fragment=cipher.output,record.length=record.fragment.length(),rval=!0),rval}function encrypt_aes_cbc_sha1_padding(blockSize,input,decrypt){if(!decrypt){var padding=blockSize-input.length()%blockSize;input.fillWithByte(padding-1,padding)}return!0}function decrypt_aes_cbc_sha1_padding(blockSize,output,decrypt){var rval=!0;if(decrypt){for(var len=output.length(),paddingLength=output.last(),i=len-1-paddingLength;i<len-1;++i)rval=rval&&output.at(i)==paddingLength;rval&&output.truncate(paddingLength+1)}return rval}function decrypt_aes_cbc_sha1(record,s){var iv,rval=!1;iv=record.version.minor===tls.Versions.TLS_1_0.minor?s.cipherState.init?null:s.cipherState.iv:record.fragment.getBytes(16),s.cipherState.init=!0;var cipher=s.cipherState.cipher;cipher.start({iv:iv}),cipher.update(record.fragment),rval=cipher.finish(decrypt_aes_cbc_sha1_padding);var macLen=s.macLength,mac=forge.random.getBytesSync(macLen),len=cipher.output.length();len>=macLen?(record.fragment=cipher.output.getBytes(len-macLen),mac=cipher.output.getBytes(macLen)):record.fragment=cipher.output.getBytes(),record.fragment=forge.util.createBuffer(record.fragment),record.length=record.fragment.length();var mac2=s.macFunction(s.macKey,s.sequenceNumber,record);return s.updateSequenceNumber(),rval=function compareMacs(key,mac1,mac2){var hmac=forge.hmac.create();return hmac.start("SHA1",key),hmac.update(mac1),mac1=hmac.digest().getBytes(),hmac.start(null,null),hmac.update(mac2),mac2=hmac.digest().getBytes(),mac1===mac2}(s.macKey,mac,mac2)&&rval,rval}return tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(sp){sp.bulk_cipher_algorithm=tls.BulkCipherAlgorithm.aes,sp.cipher_type=tls.CipherType.block,sp.enc_key_length=16,sp.block_length=16,sp.fixed_iv_length=16,sp.record_iv_length=16,sp.mac_algorithm=tls.MACAlgorithm.hmac_sha1,sp.mac_length=20,sp.mac_key_length=20},initConnectionState:initConnectionState},tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(sp){sp.bulk_cipher_algorithm=tls.BulkCipherAlgorithm.aes,sp.cipher_type=tls.CipherType.block,sp.enc_key_length=32,sp.block_length=16,sp.fixed_iv_length=16,sp.record_iv_length=16,sp.mac_algorithm=tls.MACAlgorithm.hmac_sha1,sp.mac_length=20,sp.mac_key_length=20},initConnectionState:initConnectionState},aesCipherSuites.exports}var hasRequiredSha512,sha512={exports:{}};function requireSha512(){if(hasRequiredSha512)return sha512.exports;hasRequiredSha512=1;var forge=requireForge();requireMd(),requireUtil();var sha512$1=sha512.exports=forge.sha512=forge.sha512||{};forge.md.sha512=forge.md.algorithms.sha512=sha512$1;var sha384=forge.sha384=forge.sha512.sha384=forge.sha512.sha384||{};sha384.create=function(){return sha512$1.create("SHA-384")},forge.md.sha384=forge.md.algorithms.sha384=sha384,forge.sha512.sha256=forge.sha512.sha256||{create:function(){return sha512$1.create("SHA-512/256")}},forge.md["sha512/256"]=forge.md.algorithms["sha512/256"]=forge.sha512.sha256,forge.sha512.sha224=forge.sha512.sha224||{create:function(){return sha512$1.create("SHA-512/224")}},forge.md["sha512/224"]=forge.md.algorithms["sha512/224"]=forge.sha512.sha224,sha512$1.create=function(algorithm){if(_initialized||function _init(){_padding=String.fromCharCode(128),_padding+=forge.util.fillString(String.fromCharCode(0),128),_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]],(_states={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],_states["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],_states["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],_states["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],_initialized=!0}(),void 0===algorithm&&(algorithm="SHA-512"),!(algorithm in _states))throw new Error("Invalid SHA-512 algorithm: "+algorithm);for(var _state=_states[algorithm],_h=null,_input=forge.util.createBuffer(),_w=new Array(80),wi=0;wi<80;++wi)_w[wi]=new Array(2);var digestLength=64;switch(algorithm){case"SHA-384":digestLength=48;break;case"SHA-512/256":digestLength=32;break;case"SHA-512/224":digestLength=28}var md={algorithm:algorithm.replace("-","").toLowerCase(),blockLength:128,digestLength:digestLength,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){md.messageLength=0,md.fullMessageLength=md.messageLength128=[];for(var int32s=md.messageLengthSize/4,i=0;i<int32s;++i)md.fullMessageLength.push(0);_input=forge.util.createBuffer(),_h=new Array(_state.length);for(i=0;i<_state.length;++i)_h[i]=_state[i].slice(0);return md}};return md.start(),md.update=function(msg,encoding){"utf8"===encoding&&(msg=forge.util.encodeUtf8(msg));var len=msg.length;md.messageLength+=len,len=[len/4294967296>>>0,len>>>0];for(var i=md.fullMessageLength.length-1;i>=0;--i)md.fullMessageLength[i]+=len[1],len[1]=len[0]+(md.fullMessageLength[i]/4294967296>>>0),md.fullMessageLength[i]=md.fullMessageLength[i]>>>0,len[0]=len[1]/4294967296>>>0;return _input.putBytes(msg),_update(_h,_w,_input),(_input.read>2048||0===_input.length())&&_input.compact(),md},md.digest=function(){var finalBlock=forge.util.createBuffer();finalBlock.putBytes(_input.bytes());var next,overflow=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));for(var bits=8*md.fullMessageLength[0],i=0;i<md.fullMessageLength.length-1;++i)bits+=(next=8*md.fullMessageLength[i+1])/4294967296>>>0,finalBlock.putInt32(bits>>>0),bits=next>>>0;finalBlock.putInt32(bits);var h=new Array(_h.length);for(i=0;i<_h.length;++i)h[i]=_h[i].slice(0);_update(h,_w,finalBlock);var hlen,rval=forge.util.createBuffer();hlen="SHA-512"===algorithm?h.length:"SHA-384"===algorithm?h.length-2:h.length-4;for(i=0;i<hlen;++i)rval.putInt32(h[i][0]),i===hlen-1&&"SHA-512/224"===algorithm||rval.putInt32(h[i][1]);return rval},md};var _padding=null,_initialized=!1,_k=null,_states=null;function _update(s,w,bytes){for(var t1_hi,t1_lo,t2_hi,t2_lo,s0_hi,s0_lo,s1_hi,ch_hi,maj_hi,maj_lo,a_hi,a_lo,b_hi,b_lo,c_hi,c_lo,d_hi,d_lo,e_hi,e_lo,f_hi,f_lo,g_hi,g_lo,h_hi,h_lo,i,hi,lo,w2,w7,w15,w16,len=bytes.length();len>=128;){for(i=0;i<16;++i)w[i][0]=bytes.getInt32()>>>0,w[i][1]=bytes.getInt32()>>>0;for(;i<80;++i)t1_hi=(((hi=(w2=w[i-2])[0])>>>19|(lo=w2[1])<<13)^(lo>>>29|hi<<3)^hi>>>6)>>>0,t1_lo=((hi<<13|lo>>>19)^(lo<<3|hi>>>29)^(hi<<26|lo>>>6))>>>0,t2_hi=(((hi=(w15=w[i-15])[0])>>>1|(lo=w15[1])<<31)^(hi>>>8|lo<<24)^hi>>>7)>>>0,t2_lo=((hi<<31|lo>>>1)^(hi<<24|lo>>>8)^(hi<<25|lo>>>7))>>>0,w7=w[i-7],w16=w[i-16],lo=t1_lo+w7[1]+t2_lo+w16[1],w[i][0]=t1_hi+w7[0]+t2_hi+w16[0]+(lo/4294967296>>>0)>>>0,w[i][1]=lo>>>0;for(a_hi=s[0][0],a_lo=s[0][1],b_hi=s[1][0],b_lo=s[1][1],c_hi=s[2][0],c_lo=s[2][1],d_hi=s[3][0],d_lo=s[3][1],e_hi=s[4][0],e_lo=s[4][1],f_hi=s[5][0],f_lo=s[5][1],g_hi=s[6][0],g_lo=s[6][1],h_hi=s[7][0],h_lo=s[7][1],i=0;i<80;++i)s1_hi=((e_hi>>>14|e_lo<<18)^(e_hi>>>18|e_lo<<14)^(e_lo>>>9|e_hi<<23))>>>0,ch_hi=(g_hi^e_hi&(f_hi^g_hi))>>>0,s0_hi=((a_hi>>>28|a_lo<<4)^(a_lo>>>2|a_hi<<30)^(a_lo>>>7|a_hi<<25))>>>0,s0_lo=((a_hi<<4|a_lo>>>28)^(a_lo<<30|a_hi>>>2)^(a_lo<<25|a_hi>>>7))>>>0,maj_hi=(a_hi&b_hi|c_hi&(a_hi^b_hi))>>>0,maj_lo=(a_lo&b_lo|c_lo&(a_lo^b_lo))>>>0,lo=h_lo+(((e_hi<<18|e_lo>>>14)^(e_hi<<14|e_lo>>>18)^(e_lo<<23|e_hi>>>9))>>>0)+((g_lo^e_lo&(f_lo^g_lo))>>>0)+_k[i][1]+w[i][1],t1_hi=h_hi+s1_hi+ch_hi+_k[i][0]+w[i][0]+(lo/4294967296>>>0)>>>0,t1_lo=lo>>>0,t2_hi=s0_hi+maj_hi+((lo=s0_lo+maj_lo)/4294967296>>>0)>>>0,t2_lo=lo>>>0,h_hi=g_hi,h_lo=g_lo,g_hi=f_hi,g_lo=f_lo,f_hi=e_hi,f_lo=e_lo,e_hi=d_hi+t1_hi+((lo=d_lo+t1_lo)/4294967296>>>0)>>>0,e_lo=lo>>>0,d_hi=c_hi,d_lo=c_lo,c_hi=b_hi,c_lo=b_lo,b_hi=a_hi,b_lo=a_lo,a_hi=t1_hi+t2_hi+((lo=t1_lo+t2_lo)/4294967296>>>0)>>>0,a_lo=lo>>>0;lo=s[0][1]+a_lo,s[0][0]=s[0][0]+a_hi+(lo/4294967296>>>0)>>>0,s[0][1]=lo>>>0,lo=s[1][1]+b_lo,s[1][0]=s[1][0]+b_hi+(lo/4294967296>>>0)>>>0,s[1][1]=lo>>>0,lo=s[2][1]+c_lo,s[2][0]=s[2][0]+c_hi+(lo/4294967296>>>0)>>>0,s[2][1]=lo>>>0,lo=s[3][1]+d_lo,s[3][0]=s[3][0]+d_hi+(lo/4294967296>>>0)>>>0,s[3][1]=lo>>>0,lo=s[4][1]+e_lo,s[4][0]=s[4][0]+e_hi+(lo/4294967296>>>0)>>>0,s[4][1]=lo>>>0,lo=s[5][1]+f_lo,s[5][0]=s[5][0]+f_hi+(lo/4294967296>>>0)>>>0,s[5][1]=lo>>>0,lo=s[6][1]+g_lo,s[6][0]=s[6][0]+g_hi+(lo/4294967296>>>0)>>>0,s[6][1]=lo>>>0,lo=s[7][1]+h_lo,s[7][0]=s[7][0]+h_hi+(lo/4294967296>>>0)>>>0,s[7][1]=lo>>>0,len-=128}}return sha512.exports}var hasRequiredAsn1Validator,ed25519_1,hasRequiredEd25519,kem,hasRequiredKem,log,hasRequiredLog,md_all,hasRequiredMd_all,asn1Validator={};function requireAsn1Validator(){if(hasRequiredAsn1Validator)return asn1Validator;hasRequiredAsn1Validator=1;var forge=requireForge();requireAsn1();var asn1=forge.asn1;return asn1Validator.privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},asn1Validator.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]},asn1Validator}function requireEd25519(){if(hasRequiredEd25519)return ed25519_1;hasRequiredEd25519=1;var forge=requireForge();requireJsbn(),requireRandom(),requireSha512(),requireUtil();var asn1Validator=requireAsn1Validator(),publicKeyValidator=asn1Validator.publicKeyValidator,privateKeyValidator=asn1Validator.privateKeyValidator;if(void 0===BigInteger)var BigInteger=forge.jsbn.BigInteger;var ByteBuffer=forge.util.ByteBuffer,NativeBuffer="undefined"==typeof Buffer?Uint8Array:Buffer;forge.pki=forge.pki||{},ed25519_1=forge.pki.ed25519=forge.ed25519=forge.ed25519||{};var ed25519=forge.ed25519;function messageToNativeBuffer(options){var message=options.message;if(message instanceof Uint8Array||message instanceof NativeBuffer)return message;var encoding=options.encoding;if(void 0===message){if(!options.md)throw new TypeError('"options.message" or "options.md" not specified.');message=options.md.digest().getBytes(),encoding="binary"}if("string"==typeof message&&!encoding)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if("string"==typeof message){if("undefined"!=typeof Buffer)return Buffer.from(message,encoding);message=new ByteBuffer(message,encoding)}else if(!(message instanceof ByteBuffer))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var buffer=new NativeBuffer(message.length()),i=0;i<buffer.length;++i)buffer[i]=message.at(i);return buffer}ed25519.constants={},ed25519.constants.PUBLIC_KEY_BYTE_LENGTH=32,ed25519.constants.PRIVATE_KEY_BYTE_LENGTH=64,ed25519.constants.SEED_BYTE_LENGTH=32,ed25519.constants.SIGN_BYTE_LENGTH=64,ed25519.constants.HASH_BYTE_LENGTH=64,ed25519.generateKeyPair=function(options){var seed=(options=options||{}).seed;if(void 0===seed)seed=forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);else if("string"==typeof seed){if(seed.length!==ed25519.constants.SEED_BYTE_LENGTH)throw new TypeError('"seed" must be '+ed25519.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(seed instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');seed=messageToNativeBuffer({message:seed,encoding:"binary"});for(var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH),sk=new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH),i=0;i<32;++i)sk[i]=seed[i];return function crypto_sign_keypair(pk,sk){var i,p=[gf(),gf(),gf(),gf()],d=sha512(sk,32);for(d[0]&=248,d[31]&=127,d[31]|=64,scalarbase(p,d),pack(pk,p),i=0;i<32;++i)sk[i+32]=pk[i];return 0}(pk,sk),{publicKey:pk,privateKey:sk}},ed25519.privateKeyFromAsn1=function(obj){var capture={},errors=[];if(!forge.asn1.validate(obj,privateKeyValidator,capture,errors)){var error=new Error("Invalid Key.");throw error.errors=errors,error}var oid=forge.asn1.derToOid(capture.privateKeyOid),ed25519Oid=forge.oids.EdDSA25519;if(oid!==ed25519Oid)throw new Error('Invalid OID "'+oid+'"; OID must be "'+ed25519Oid+'".');var privateKey=capture.privateKey;return{privateKeyBytes:messageToNativeBuffer({message:forge.asn1.fromDer(privateKey).value,encoding:"binary"})}},ed25519.publicKeyFromAsn1=function(obj){var capture={},errors=[];if(!forge.asn1.validate(obj,publicKeyValidator,capture,errors)){var error=new Error("Invalid Key.");throw error.errors=errors,error}var oid=forge.asn1.derToOid(capture.publicKeyOid),ed25519Oid=forge.oids.EdDSA25519;if(oid!==ed25519Oid)throw new Error('Invalid OID "'+oid+'"; OID must be "'+ed25519Oid+'".');var publicKeyBytes=capture.ed25519PublicKey;if(publicKeyBytes.length!==ed25519.constants.PUBLIC_KEY_BYTE_LENGTH)throw new Error("Key length is invalid.");return messageToNativeBuffer({message:publicKeyBytes,encoding:"binary"})},ed25519.publicKeyFromPrivateKey=function(options){var privateKey=messageToNativeBuffer({message:(options=options||{}).privateKey,encoding:"binary"});if(privateKey.length!==ed25519.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);for(var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH),i=0;i<pk.length;++i)pk[i]=privateKey[32+i];return pk},ed25519.sign=function(options){var msg=messageToNativeBuffer(options=options||{}),privateKey=messageToNativeBuffer({message:options.privateKey,encoding:"binary"});if(privateKey.length===ed25519.constants.SEED_BYTE_LENGTH)privateKey=ed25519.generateKeyPair({seed:privateKey}).privateKey;else if(privateKey.length!==ed25519.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+ed25519.constants.SEED_BYTE_LENGTH+" or "+ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);var signedMsg=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH+msg.length);!function crypto_sign(sm,m,n,sk){var i,j,x=new Float64Array(64),p=[gf(),gf(),gf(),gf()],d=sha512(sk,32);d[0]&=248,d[31]&=127,d[31]|=64;var smlen=n+64;for(i=0;i<n;++i)sm[64+i]=m[i];for(i=0;i<32;++i)sm[32+i]=d[32+i];var r=sha512(sm.subarray(32),n+32);for(reduce(r),scalarbase(p,r),pack(sm,p),i=32;i<64;++i)sm[i]=sk[i];var h=sha512(sm,n+64);for(reduce(h),i=32;i<64;++i)x[i]=0;for(i=0;i<32;++i)x[i]=r[i];for(i=0;i<32;++i)for(j=0;j<32;j++)x[i+j]+=h[i]*d[j];return modL(sm.subarray(32),x),smlen}(signedMsg,msg,msg.length,privateKey);for(var sig=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH),i=0;i<sig.length;++i)sig[i]=signedMsg[i];return sig},ed25519.verify=function(options){var msg=messageToNativeBuffer(options=options||{});if(void 0===options.signature)throw new TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var sig=messageToNativeBuffer({message:options.signature,encoding:"binary"});if(sig.length!==ed25519.constants.SIGN_BYTE_LENGTH)throw new TypeError('"options.signature" must have a byte length of '+ed25519.constants.SIGN_BYTE_LENGTH);var publicKey=messageToNativeBuffer({message:options.publicKey,encoding:"binary"});if(publicKey.length!==ed25519.constants.PUBLIC_KEY_BYTE_LENGTH)throw new TypeError('"options.publicKey" must have a byte length of '+ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);var i,sm=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH+msg.length),m=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH+msg.length);for(i=0;i<ed25519.constants.SIGN_BYTE_LENGTH;++i)sm[i]=sig[i];for(i=0;i<msg.length;++i)sm[i+ed25519.constants.SIGN_BYTE_LENGTH]=msg[i];return function crypto_sign_open(m,sm,n,pk){var i,t=new NativeBuffer(32),p=[gf(),gf(),gf(),gf()],q=[gf(),gf(),gf(),gf()];if(n<64)return-1;if(function unpackneg(r,p){var t=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r[2],gf1),function unpack25519(o,n){var i;for(i=0;i<16;++i)o[i]=n[2*i]+(n[2*i+1]<<8);o[15]&=32767}(r[1],p),S(num,r[1]),M(den,num,D),Z(num,num,r[2]),A(den,r[2],den),S(den2,den),S(den4,den2),M(den6,den4,den2),M(t,den6,num),M(t,t,den),function pow2523(o,i){var a,c=gf();for(a=0;a<16;++a)c[a]=i[a];for(a=250;a>=0;--a)S(c,c),1!==a&&M(c,c,i);for(a=0;a<16;++a)o[a]=c[a]}(t,t),M(t,t,num),M(t,t,den),M(t,t,den),M(r[0],t,den),S(chk,r[0]),M(chk,chk,den),neq25519(chk,num)&&M(r[0],r[0],I);if(S(chk,r[0]),M(chk,chk,den),neq25519(chk,num))return-1;par25519(r[0])===p[31]>>7&&Z(r[0],gf0,r[0]);return M(r[3],r[0],r[1]),0}(q,pk))return-1;for(i=0;i<n;++i)m[i]=sm[i];for(i=0;i<32;++i)m[i+32]=pk[i];var h=sha512(m,n);if(reduce(h),scalarmult(p,q,h),scalarbase(q,sm.subarray(32)),add(p,q),pack(t,p),n-=64,crypto_verify_32(sm,0,t,0)){for(i=0;i<n;++i)m[i]=0;return-1}for(i=0;i<n;++i)m[i]=sm[i+64];return n}(m,sm,sm.length,publicKey)>=0};var gf0=gf(),gf1=gf([1]),D=gf([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),D2=gf([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),X=gf([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Y=gf([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),L=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),I=gf([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function sha512(msg,msgLen){var md=forge.md.sha512.create(),buffer=new ByteBuffer(msg);md.update(buffer.getBytes(msgLen),"binary");var hash=md.digest().getBytes();if("undefined"!=typeof Buffer)return Buffer.from(hash,"binary");for(var out=new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH),i=0;i<64;++i)out[i]=hash.charCodeAt(i);return out}function modL(r,x){var carry,i,j,k;for(i=63;i>=32;--i){for(carry=0,j=i-32,k=i-12;j<k;++j)x[j]+=carry-16*x[i]*L[j-(i-32)],carry=x[j]+128>>8,x[j]-=256*carry;x[j]+=carry,x[i]=0}for(carry=0,j=0;j<32;++j)x[j]+=carry-(x[31]>>4)*L[j],carry=x[j]>>8,x[j]&=255;for(j=0;j<32;++j)x[j]-=carry*L[j];for(i=0;i<32;++i)x[i+1]+=x[i]>>8,r[i]=255&x[i]}function reduce(r){for(var x=new Float64Array(64),i=0;i<64;++i)x[i]=r[i],r[i]=0;modL(r,x)}function add(p,q){var a=gf(),b=gf(),c=gf(),d=gf(),e=gf(),f=gf(),g=gf(),h=gf(),t=gf();Z(a,p[1],p[0]),Z(t,q[1],q[0]),M(a,a,t),A(b,p[0],p[1]),A(t,q[0],q[1]),M(b,b,t),M(c,p[3],q[3]),M(c,c,D2),M(d,p[2],q[2]),A(d,d,d),Z(e,b,a),Z(f,d,c),A(g,d,c),A(h,b,a),M(p[0],e,f),M(p[1],h,g),M(p[2],g,f),M(p[3],e,h)}function cswap(p,q,b){for(var i=0;i<4;++i)sel25519(p[i],q[i],b)}function pack(r,p){var tx=gf(),ty=gf(),zi=gf();!function inv25519(o,i){var a,c=gf();for(a=0;a<16;++a)c[a]=i[a];for(a=253;a>=0;--a)S(c,c),2!==a&&4!==a&&M(c,c,i);for(a=0;a<16;++a)o[a]=c[a]}(zi,p[2]),M(tx,p[0],zi),M(ty,p[1],zi),pack25519(r,ty),r[31]^=par25519(tx)<<7}function pack25519(o,n){var i,j,b,m=gf(),t=gf();for(i=0;i<16;++i)t[i]=n[i];for(car25519(t),car25519(t),car25519(t),j=0;j<2;++j){for(m[0]=t[0]-65517,i=1;i<15;++i)m[i]=t[i]-65535-(m[i-1]>>16&1),m[i-1]&=65535;m[15]=t[15]-32767-(m[14]>>16&1),b=m[15]>>16&1,m[14]&=65535,sel25519(t,m,1-b)}for(i=0;i<16;i++)o[2*i]=255&t[i],o[2*i+1]=t[i]>>8}function neq25519(a,b){var c=new NativeBuffer(32),d=new NativeBuffer(32);return pack25519(c,a),pack25519(d,b),crypto_verify_32(c,0,d,0)}function crypto_verify_32(x,xi,y,yi){return function vn(x,xi,y,yi,n){var i,d=0;for(i=0;i<n;++i)d|=x[xi+i]^y[yi+i];return(1&d-1>>>8)-1}(x,xi,y,yi,32)}function par25519(a){var d=new NativeBuffer(32);return pack25519(d,a),1&d[0]}function scalarmult(p,q,s){var b,i;for(set25519(p[0],gf0),set25519(p[1],gf1),set25519(p[2],gf1),set25519(p[3],gf0),i=255;i>=0;--i)cswap(p,q,b=s[i/8|0]>>(7&i)&1),add(q,p),add(p,p),cswap(p,q,b)}function scalarbase(p,s){var q=[gf(),gf(),gf(),gf()];set25519(q[0],X),set25519(q[1],Y),set25519(q[2],gf1),M(q[3],X,Y),scalarmult(p,q,s)}function set25519(r,a){var i;for(i=0;i<16;i++)r[i]=0|a[i]}function car25519(o){var i,v,c=1;for(i=0;i<16;++i)v=o[i]+c+65535,c=Math.floor(v/65536),o[i]=v-65536*c;o[0]+=c-1+37*(c-1)}function sel25519(p,q,b){for(var t,c=~(b-1),i=0;i<16;++i)t=c&(p[i]^q[i]),p[i]^=t,q[i]^=t}function gf(init){var i,r=new Float64Array(16);if(init)for(i=0;i<init.length;++i)r[i]=init[i];return r}function A(o,a,b){for(var i=0;i<16;++i)o[i]=a[i]+b[i]}function Z(o,a,b){for(var i=0;i<16;++i)o[i]=a[i]-b[i]}function S(o,a){M(o,a,a)}function M(o,a,b){var v,c,t0=0,t1=0,t2=0,t3=0,t4=0,t5=0,t6=0,t7=0,t8=0,t9=0,t10=0,t11=0,t12=0,t13=0,t14=0,t15=0,t16=0,t17=0,t18=0,t19=0,t20=0,t21=0,t22=0,t23=0,t24=0,t25=0,t26=0,t27=0,t28=0,t29=0,t30=0,b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5],b6=b[6],b7=b[7],b8=b[8],b9=b[9],b10=b[10],b11=b[11],b12=b[12],b13=b[13],b14=b[14],b15=b[15];t0+=(v=a[0])*b0,t1+=v*b1,t2+=v*b2,t3+=v*b3,t4+=v*b4,t5+=v*b5,t6+=v*b6,t7+=v*b7,t8+=v*b8,t9+=v*b9,t10+=v*b10,t11+=v*b11,t12+=v*b12,t13+=v*b13,t14+=v*b14,t15+=v*b15,t1+=(v=a[1])*b0,t2+=v*b1,t3+=v*b2,t4+=v*b3,t5+=v*b4,t6+=v*b5,t7+=v*b6,t8+=v*b7,t9+=v*b8,t10+=v*b9,t11+=v*b10,t12+=v*b11,t13+=v*b12,t14+=v*b13,t15+=v*b14,t16+=v*b15,t2+=(v=a[2])*b0,t3+=v*b1,t4+=v*b2,t5+=v*b3,t6+=v*b4,t7+=v*b5,t8+=v*b6,t9+=v*b7,t10+=v*b8,t11+=v*b9,t12+=v*b10,t13+=v*b11,t14+=v*b12,t15+=v*b13,t16+=v*b14,t17+=v*b15,t3+=(v=a[3])*b0,t4+=v*b1,t5+=v*b2,t6+=v*b3,t7+=v*b4,t8+=v*b5,t9+=v*b6,t10+=v*b7,t11+=v*b8,t12+=v*b9,t13+=v*b10,t14+=v*b11,t15+=v*b12,t16+=v*b13,t17+=v*b14,t18+=v*b15,t4+=(v=a[4])*b0,t5+=v*b1,t6+=v*b2,t7+=v*b3,t8+=v*b4,t9+=v*b5,t10+=v*b6,t11+=v*b7,t12+=v*b8,t13+=v*b9,t14+=v*b10,t15+=v*b11,t16+=v*b12,t17+=v*b13,t18+=v*b14,t19+=v*b15,t5+=(v=a[5])*b0,t6+=v*b1,t7+=v*b2,t8+=v*b3,t9+=v*b4,t10+=v*b5,t11+=v*b6,t12+=v*b7,t13+=v*b8,t14+=v*b9,t15+=v*b10,t16+=v*b11,t17+=v*b12,t18+=v*b13,t19+=v*b14,t20+=v*b15,t6+=(v=a[6])*b0,t7+=v*b1,t8+=v*b2,t9+=v*b3,t10+=v*b4,t11+=v*b5,t12+=v*b6,t13+=v*b7,t14+=v*b8,t15+=v*b9,t16+=v*b10,t17+=v*b11,t18+=v*b12,t19+=v*b13,t20+=v*b14,t21+=v*b15,t7+=(v=a[7])*b0,t8+=v*b1,t9+=v*b2,t10+=v*b3,t11+=v*b4,t12+=v*b5,t13+=v*b6,t14+=v*b7,t15+=v*b8,t16+=v*b9,t17+=v*b10,t18+=v*b11,t19+=v*b12,t20+=v*b13,t21+=v*b14,t22+=v*b15,t8+=(v=a[8])*b0,t9+=v*b1,t10+=v*b2,t11+=v*b3,t12+=v*b4,t13+=v*b5,t14+=v*b6,t15+=v*b7,t16+=v*b8,t17+=v*b9,t18+=v*b10,t19+=v*b11,t20+=v*b12,t21+=v*b13,t22+=v*b14,t23+=v*b15,t9+=(v=a[9])*b0,t10+=v*b1,t11+=v*b2,t12+=v*b3,t13+=v*b4,t14+=v*b5,t15+=v*b6,t16+=v*b7,t17+=v*b8,t18+=v*b9,t19+=v*b10,t20+=v*b11,t21+=v*b12,t22+=v*b13,t23+=v*b14,t24+=v*b15,t10+=(v=a[10])*b0,t11+=v*b1,t12+=v*b2,t13+=v*b3,t14+=v*b4,t15+=v*b5,t16+=v*b6,t17+=v*b7,t18+=v*b8,t19+=v*b9,t20+=v*b10,t21+=v*b11,t22+=v*b12,t23+=v*b13,t24+=v*b14,t25+=v*b15,t11+=(v=a[11])*b0,t12+=v*b1,t13+=v*b2,t14+=v*b3,t15+=v*b4,t16+=v*b5,t17+=v*b6,t18+=v*b7,t19+=v*b8,t20+=v*b9,t21+=v*b10,t22+=v*b11,t23+=v*b12,t24+=v*b13,t25+=v*b14,t26+=v*b15,t12+=(v=a[12])*b0,t13+=v*b1,t14+=v*b2,t15+=v*b3,t16+=v*b4,t17+=v*b5,t18+=v*b6,t19+=v*b7,t20+=v*b8,t21+=v*b9,t22+=v*b10,t23+=v*b11,t24+=v*b12,t25+=v*b13,t26+=v*b14,t27+=v*b15,t13+=(v=a[13])*b0,t14+=v*b1,t15+=v*b2,t16+=v*b3,t17+=v*b4,t18+=v*b5,t19+=v*b6,t20+=v*b7,t21+=v*b8,t22+=v*b9,t23+=v*b10,t24+=v*b11,t25+=v*b12,t26+=v*b13,t27+=v*b14,t28+=v*b15,t14+=(v=a[14])*b0,t15+=v*b1,t16+=v*b2,t17+=v*b3,t18+=v*b4,t19+=v*b5,t20+=v*b6,t21+=v*b7,t22+=v*b8,t23+=v*b9,t24+=v*b10,t25+=v*b11,t26+=v*b12,t27+=v*b13,t28+=v*b14,t29+=v*b15,t15+=(v=a[15])*b0,t1+=38*(t17+=v*b2),t2+=38*(t18+=v*b3),t3+=38*(t19+=v*b4),t4+=38*(t20+=v*b5),t5+=38*(t21+=v*b6),t6+=38*(t22+=v*b7),t7+=38*(t23+=v*b8),t8+=38*(t24+=v*b9),t9+=38*(t25+=v*b10),t10+=38*(t26+=v*b11),t11+=38*(t27+=v*b12),t12+=38*(t28+=v*b13),t13+=38*(t29+=v*b14),t14+=38*(t30+=v*b15),t0=(v=(t0+=38*(t16+=v*b1))+(c=1)+65535)-65536*(c=Math.floor(v/65536)),t1=(v=t1+c+65535)-65536*(c=Math.floor(v/65536)),t2=(v=t2+c+65535)-65536*(c=Math.floor(v/65536)),t3=(v=t3+c+65535)-65536*(c=Math.floor(v/65536)),t4=(v=t4+c+65535)-65536*(c=Math.floor(v/65536)),t5=(v=t5+c+65535)-65536*(c=Math.floor(v/65536)),t6=(v=t6+c+65535)-65536*(c=Math.floor(v/65536)),t7=(v=t7+c+65535)-65536*(c=Math.floor(v/65536)),t8=(v=t8+c+65535)-65536*(c=Math.floor(v/65536)),t9=(v=t9+c+65535)-65536*(c=Math.floor(v/65536)),t10=(v=t10+c+65535)-65536*(c=Math.floor(v/65536)),t11=(v=t11+c+65535)-65536*(c=Math.floor(v/65536)),t12=(v=t12+c+65535)-65536*(c=Math.floor(v/65536)),t13=(v=t13+c+65535)-65536*(c=Math.floor(v/65536)),t14=(v=t14+c+65535)-65536*(c=Math.floor(v/65536)),t15=(v=t15+c+65535)-65536*(c=Math.floor(v/65536)),t0=(v=(t0+=c-1+37*(c-1))+(c=1)+65535)-65536*(c=Math.floor(v/65536)),t1=(v=t1+c+65535)-65536*(c=Math.floor(v/65536)),t2=(v=t2+c+65535)-65536*(c=Math.floor(v/65536)),t3=(v=t3+c+65535)-65536*(c=Math.floor(v/65536)),t4=(v=t4+c+65535)-65536*(c=Math.floor(v/65536)),t5=(v=t5+c+65535)-65536*(c=Math.floor(v/65536)),t6=(v=t6+c+65535)-65536*(c=Math.floor(v/65536)),t7=(v=t7+c+65535)-65536*(c=Math.floor(v/65536)),t8=(v=t8+c+65535)-65536*(c=Math.floor(v/65536)),t9=(v=t9+c+65535)-65536*(c=Math.floor(v/65536)),t10=(v=t10+c+65535)-65536*(c=Math.floor(v/65536)),t11=(v=t11+c+65535)-65536*(c=Math.floor(v/65536)),t12=(v=t12+c+65535)-65536*(c=Math.floor(v/65536)),t13=(v=t13+c+65535)-65536*(c=Math.floor(v/65536)),t14=(v=t14+c+65535)-65536*(c=Math.floor(v/65536)),t15=(v=t15+c+65535)-65536*(c=Math.floor(v/65536)),t0+=c-1+37*(c-1),o[0]=t0,o[1]=t1,o[2]=t2,o[3]=t3,o[4]=t4,o[5]=t5,o[6]=t6,o[7]=t7,o[8]=t8,o[9]=t9,o[10]=t10,o[11]=t11,o[12]=t12,o[13]=t13,o[14]=t14,o[15]=t15}return ed25519_1}var hasRequiredPkcs7,pkcs7={exports:{}};function requirePkcs7(){if(hasRequiredPkcs7)return pkcs7.exports;hasRequiredPkcs7=1;var forge=requireForge();requireAes(),requireAsn1(),requireDes(),requireOids(),requirePem(),requirePkcs7asn1(),requireRandom(),requireUtil(),requireX509();var asn1=forge.asn1,p7=pkcs7.exports=forge.pkcs7=forge.pkcs7||{};function _recipientFromAsn1(obj){var capture={},errors=[];if(!asn1.validate(obj,p7.asn1.recipientInfoValidator,capture,errors)){var error=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw error.errors=errors,error}return{version:capture.version.charCodeAt(0),issuer:forge.pki.RDNAttributesAsArray(capture.issuer),serialNumber:forge.util.createBuffer(capture.serial).toHex(),encryptedContent:{algorithm:asn1.derToOid(capture.encAlgorithm),parameter:capture.encParameter?capture.encParameter.value:void 0,content:capture.encKey}}}function _recipientToAsn1(obj){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(obj.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[forge.pki.distinguishedNameToAsn1({attributes:obj.issuer}),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,forge.util.hexToBytes(obj.serialNumber))]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,obj.encryptedContent.content)])}function _recipientsToAsn1(recipients){for(var ret=[],i=0;i<recipients.length;++i)ret.push(_recipientToAsn1(recipients[i]));return ret}function _signerToAsn1(obj){var rval=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(obj.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[forge.pki.distinguishedNameToAsn1({attributes:obj.issuer}),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,forge.util.hexToBytes(obj.serialNumber))]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(obj.digestAlgorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")])]);if(obj.authenticatedAttributesAsn1&&rval.value.push(obj.authenticatedAttributesAsn1),rval.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(obj.signatureAlgorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")])),rval.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,obj.signature)),obj.unauthenticatedAttributes.length>0){for(var attrsAsn1=asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,!0,[]),i=0;i<obj.unauthenticatedAttributes.length;++i){var attr=obj.unauthenticatedAttributes[i];attrsAsn1.values.push(_attributeToAsn1(attr))}rval.value.push(attrsAsn1)}return rval}function _attributeToAsn1(attr){var value;if(attr.type===forge.pki.oids.contentType)value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(attr.value).getBytes());else if(attr.type===forge.pki.oids.messageDigest)value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,attr.value.bytes());else if(attr.type===forge.pki.oids.signingTime){var jan_1_1950=new Date("1950-01-01T00:00:00Z"),jan_1_2050=new Date("2050-01-01T00:00:00Z"),date=attr.value;if("string"==typeof date){var timestamp=Date.parse(date);date=isNaN(timestamp)?13===date.length?asn1.utcTimeToDate(date):asn1.generalizedTimeToDate(date):new Date(timestamp)}value=date>=jan_1_1950&&date<jan_1_2050?asn1.create(asn1.Class.UNIVERSAL,asn1.Type.UTCTIME,!1,asn1.dateToUtcTime(date)):asn1.create(asn1.Class.UNIVERSAL,asn1.Type.GENERALIZEDTIME,!1,asn1.dateToGeneralizedTime(date))}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,[value])])}function _fromAsn1(msg,obj,validator){var capture={};if(!asn1.validate(obj,validator,capture,[])){var error=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw error.errors=error,error}if(asn1.derToOid(capture.contentType)!==forge.pki.oids.data)throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(capture.encryptedContent){var content="";if(forge.util.isArray(capture.encryptedContent))for(var i=0;i<capture.encryptedContent.length;++i){if(capture.encryptedContent[i].type!==asn1.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");content+=capture.encryptedContent[i].value}else content=capture.encryptedContent;msg.encryptedContent={algorithm:asn1.derToOid(capture.encAlgorithm),parameter:forge.util.createBuffer(capture.encParameter.value),content:forge.util.createBuffer(content)}}if(capture.content){content="";if(forge.util.isArray(capture.content))for(i=0;i<capture.content.length;++i){if(capture.content[i].type!==asn1.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");content+=capture.content[i].value}else content=capture.content;msg.content=forge.util.createBuffer(content)}return msg.version=capture.version.charCodeAt(0),msg.rawCapture=capture,capture}function _decryptContent(msg){if(void 0===msg.encryptedContent.key)throw new Error("Symmetric key not available.");if(void 0===msg.content){var ciph;switch(msg.encryptedContent.algorithm){case forge.pki.oids["aes128-CBC"]:case forge.pki.oids["aes192-CBC"]:case forge.pki.oids["aes256-CBC"]:ciph=forge.aes.createDecryptionCipher(msg.encryptedContent.key);break;case forge.pki.oids.desCBC:case forge.pki.oids["des-EDE3-CBC"]:ciph=forge.des.createDecryptionCipher(msg.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+msg.encryptedContent.algorithm)}if(ciph.start(msg.encryptedContent.parameter),ciph.update(msg.encryptedContent.content),!ciph.finish())throw new Error("Symmetric decryption failed.");msg.content=ciph.output}}return p7.messageFromPem=function(pem){var msg=forge.pem.decode(pem)[0];if("PKCS7"!==msg.type){var error=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw error.headerType=msg.type,error}if(msg.procType&&"ENCRYPTED"===msg.procType.type)throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var obj=asn1.fromDer(msg.body);return p7.messageFromAsn1(obj)},p7.messageToPem=function(msg,maxline){var pemObj={type:"PKCS7",body:asn1.toDer(msg.toAsn1()).getBytes()};return forge.pem.encode(pemObj,{maxline:maxline})},p7.messageFromAsn1=function(obj){var capture={},errors=[];if(!asn1.validate(obj,p7.asn1.contentInfoValidator,capture,errors)){var error=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw error.errors=errors,error}var msg,contentType=asn1.derToOid(capture.contentType);switch(contentType){case forge.pki.oids.envelopedData:msg=p7.createEnvelopedData();break;case forge.pki.oids.encryptedData:msg=p7.createEncryptedData();break;case forge.pki.oids.signedData:msg=p7.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+contentType+" is not (yet) supported.")}return msg.fromAsn1(capture.content.value[0]),msg},p7.createSignedData=function(){var msg=null;return msg={type:forge.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(obj){if(_fromAsn1(msg,obj,p7.asn1.signedDataValidator),msg.certificates=[],msg.crls=[],msg.digestAlgorithmIdentifiers=[],msg.contentInfo=null,msg.signerInfos=[],msg.rawCapture.certificates)for(var certs=msg.rawCapture.certificates.value,i=0;i<certs.length;++i)msg.certificates.push(forge.pki.certificateFromAsn1(certs[i]))},toAsn1:function(){msg.contentInfo||msg.sign();for(var certs=[],i=0;i<msg.certificates.length;++i)certs.push(forge.pki.certificateToAsn1(msg.certificates[i]));var crls=[],signedData=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(msg.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,msg.digestAlgorithmIdentifiers),msg.contentInfo])]);return certs.length>0&&signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,certs)),crls.length>0&&signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,!0,crls)),signedData.value[0].value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,msg.signerInfos)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(msg.type).getBytes()),signedData])},addSigner:function(signer){var issuer=signer.issuer,serialNumber=signer.serialNumber;if(signer.certificate){var cert=signer.certificate;"string"==typeof cert&&(cert=forge.pki.certificateFromPem(cert)),issuer=cert.issuer.attributes,serialNumber=cert.serialNumber}var key=signer.key;if(!key)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof key&&(key=forge.pki.privateKeyFromPem(key));var digestAlgorithm=signer.digestAlgorithm||forge.pki.oids.sha1;switch(digestAlgorithm){case forge.pki.oids.sha1:case forge.pki.oids.sha256:case forge.pki.oids.sha384:case forge.pki.oids.sha512:case forge.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+digestAlgorithm)}var authenticatedAttributes=signer.authenticatedAttributes||[];if(authenticatedAttributes.length>0){for(var contentType=!1,messageDigest=!1,i=0;i<authenticatedAttributes.length;++i){var attr=authenticatedAttributes[i];if(contentType||attr.type!==forge.pki.oids.contentType){if(messageDigest||attr.type!==forge.pki.oids.messageDigest);else if(messageDigest=!0,contentType)break}else if(contentType=!0,messageDigest)break}if(!contentType||!messageDigest)throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}msg.signers.push({key:key,version:1,issuer:issuer,serialNumber:serialNumber,digestAlgorithm:digestAlgorithm,signatureAlgorithm:forge.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:authenticatedAttributes,unauthenticatedAttributes:[]})},sign:function(options){var content;(options=options||{},"object"!=typeof msg.content||null===msg.contentInfo)&&(msg.contentInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(forge.pki.oids.data).getBytes())]),"content"in msg&&(msg.content instanceof forge.util.ByteBuffer?content=msg.content.bytes():"string"==typeof msg.content&&(content=forge.util.encodeUtf8(msg.content)),options.detached?msg.detachedContent=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,content):msg.contentInfo.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,content)]))));0!==msg.signers.length&&function addSignerInfos(mds){var content;content=msg.detachedContent?msg.detachedContent:(content=msg.contentInfo.value[1]).value[0];if(!content)throw new Error("Could not sign PKCS#7 message; there is no content to sign.");var contentType=asn1.derToOid(msg.contentInfo.value[0].value),bytes=asn1.toDer(content);for(var oid in bytes.getByte(),asn1.getBerValueLength(bytes),bytes=bytes.getBytes(),mds)mds[oid].start().update(bytes);for(var signingTime=new Date,i=0;i<msg.signers.length;++i){var signer=msg.signers[i];if(0===signer.authenticatedAttributes.length){if(contentType!==forge.pki.oids.data)throw new Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{signer.authenticatedAttributesAsn1=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var attrsAsn1=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,[]),ai=0;ai<signer.authenticatedAttributes.length;++ai){var attr=signer.authenticatedAttributes[ai];attr.type===forge.pki.oids.messageDigest?attr.value=mds[signer.digestAlgorithm].digest():attr.type===forge.pki.oids.signingTime&&(attr.value||(attr.value=signingTime)),attrsAsn1.value.push(_attributeToAsn1(attr)),signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr))}bytes=asn1.toDer(attrsAsn1).getBytes(),signer.md.start().update(bytes)}signer.signature=signer.key.sign(signer.md,"RSASSA-PKCS1-V1_5")}msg.signerInfos=function _signersToAsn1(signers){for(var ret=[],i=0;i<signers.length;++i)ret.push(_signerToAsn1(signers[i]));return ret}(msg.signers)}(function addDigestAlgorithmIds(){for(var mds={},i=0;i<msg.signers.length;++i){var signer=msg.signers[i];(oid=signer.digestAlgorithm)in mds||(mds[oid]=forge.md[forge.pki.oids[oid]].create()),0===signer.authenticatedAttributes.length?signer.md=mds[oid]:signer.md=forge.md[forge.pki.oids[oid]].create()}for(var oid in msg.digestAlgorithmIdentifiers=[],mds)msg.digestAlgorithmIdentifiers.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(oid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,!1,"")]));return mds}())},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(cert){"string"==typeof cert&&(cert=forge.pki.certificateFromPem(cert)),msg.certificates.push(cert)},addCertificateRevokationList:function(crl){throw new Error("PKCS#7 CRL support not yet implemented.")}}},p7.createEncryptedData=function(){var msg=null;return msg={type:forge.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:forge.pki.oids["aes256-CBC"]},fromAsn1:function(obj){_fromAsn1(msg,obj,p7.asn1.encryptedDataValidator)},decrypt:function(key){void 0!==key&&(msg.encryptedContent.key=key),_decryptContent(msg)}}},p7.createEnvelopedData=function(){var msg=null;return msg={type:forge.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:forge.pki.oids["aes256-CBC"]},fromAsn1:function(obj){var capture=_fromAsn1(msg,obj,p7.asn1.envelopedDataValidator);msg.recipients=function _recipientsFromAsn1(infos){for(var ret=[],i=0;i<infos.length;++i)ret.push(_recipientFromAsn1(infos[i]));return ret}(capture.recipientInfos.value)},toAsn1:function(){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(msg.type).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,!1,asn1.integerToDer(msg.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,!0,_recipientsToAsn1(msg.recipients)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,(ec=msg.encryptedContent,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(forge.pki.oids.data).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,!1,asn1.oidToDer(ec.algorithm).getBytes()),ec.parameter?asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,ec.parameter.getBytes()):void 0]),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,!0,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,!1,ec.content.getBytes())])]))])])]);var ec},findRecipient:function(cert){for(var sAttr=cert.issuer.attributes,i=0;i<msg.recipients.length;++i){var r=msg.recipients[i],rAttr=r.issuer;if(r.serialNumber===cert.serialNumber&&rAttr.length===sAttr.length){for(var match=!0,j=0;j<sAttr.length;++j)if(rAttr[j].type!==sAttr[j].type||rAttr[j].value!==sAttr[j].value){match=!1;break}if(match)return r}}return null},decrypt:function(recipient,privKey){if(void 0===msg.encryptedContent.key&&void 0!==recipient&&void 0!==privKey)switch(recipient.encryptedContent.algorithm){case forge.pki.oids.rsaEncryption:case forge.pki.oids.desCBC:var key=privKey.decrypt(recipient.encryptedContent.content);msg.encryptedContent.key=forge.util.createBuffer(key);break;default:throw new Error("Unsupported asymmetric cipher, OID "+recipient.encryptedContent.algorithm)}_decryptContent(msg)},addRecipient:function(cert){msg.recipients.push({version:0,issuer:cert.issuer.attributes,serialNumber:cert.serialNumber,encryptedContent:{algorithm:forge.pki.oids.rsaEncryption,key:cert.publicKey}})},encrypt:function(key,cipher){if(void 0===msg.encryptedContent.content){var keyLen,ivLen,ciphFn;switch(cipher=cipher||msg.encryptedContent.algorithm,key=key||msg.encryptedContent.key,cipher){case forge.pki.oids["aes128-CBC"]:keyLen=16,ivLen=16,ciphFn=forge.aes.createEncryptionCipher;break;case forge.pki.oids["aes192-CBC"]:keyLen=24,ivLen=16,ciphFn=forge.aes.createEncryptionCipher;break;case forge.pki.oids["aes256-CBC"]:keyLen=32,ivLen=16,ciphFn=forge.aes.createEncryptionCipher;break;case forge.pki.oids["des-EDE3-CBC"]:keyLen=24,ivLen=8,ciphFn=forge.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+cipher)}if(void 0===key)key=forge.util.createBuffer(forge.random.getBytes(keyLen));else if(key.length()!=keyLen)throw new Error("Symmetric key has wrong length; got "+key.length()+" bytes, expected "+keyLen+".");msg.encryptedContent.algorithm=cipher,msg.encryptedContent.key=key,msg.encryptedContent.parameter=forge.util.createBuffer(forge.random.getBytes(ivLen));var ciph=ciphFn(key);if(ciph.start(msg.encryptedContent.parameter.copy()),ciph.update(msg.content),!ciph.finish())throw new Error("Symmetric encryption failed.");msg.encryptedContent.content=ciph.output}for(var i=0;i<msg.recipients.length;++i){var recipient=msg.recipients[i];if(void 0===recipient.encryptedContent.content){if(recipient.encryptedContent.algorithm!==forge.pki.oids.rsaEncryption)throw new Error("Unsupported asymmetric cipher, OID "+recipient.encryptedContent.algorithm);recipient.encryptedContent.content=recipient.encryptedContent.key.encrypt(msg.encryptedContent.key.data)}}}},msg},pkcs7.exports}var hasRequiredSsh,lib$1,hasRequiredLib$1,ssh={exports:{}};var libExports$1=function requireLib$1(){return hasRequiredLib$1||(hasRequiredLib$1=1,lib$1=requireForge(),requireAes(),requireAesCipherSuites(),requireAsn1(),requireCipher(),requireDes(),requireEd25519(),requireHmac(),function requireKem(){if(hasRequiredKem)return kem;hasRequiredKem=1;var forge=requireForge();requireUtil(),requireRandom(),requireJsbn(),kem=forge.kem=forge.kem||{};var BigInteger=forge.jsbn.BigInteger;function _createKDF(kdf,md,counterStart,digestLength){kdf.generate=function(x,length){for(var key=new forge.util.ByteBuffer,k=Math.ceil(length/digestLength)+counterStart,c=new forge.util.ByteBuffer,i=counterStart;i<k;++i){c.putInt32(i),md.start(),md.update(x+c.getBytes());var hash=md.digest();key.putBytes(hash.getBytes(digestLength))}return key.truncate(key.length()-length),key.getBytes()}}return forge.kem.rsa={},forge.kem.rsa.create=function(kdf,options){var prng=(options=options||{}).prng||forge.random;return{encrypt:function(publicKey,keyLength){var r,byteLength=Math.ceil(publicKey.n.bitLength()/8);do{r=new BigInteger(forge.util.bytesToHex(prng.getBytesSync(byteLength)),16).mod(publicKey.n)}while(r.compareTo(BigInteger.ONE)<=0);var zeros=byteLength-(r=forge.util.hexToBytes(r.toString(16))).length;return zeros>0&&(r=forge.util.fillString(String.fromCharCode(0),zeros)+r),{encapsulation:publicKey.encrypt(r,"NONE"),key:kdf.generate(r,keyLength)}},decrypt:function(privateKey,encapsulation,keyLength){var r=privateKey.decrypt(encapsulation,"NONE");return kdf.generate(r,keyLength)}}},forge.kem.kdf1=function(md,digestLength){_createKDF(this,md,0,digestLength||md.digestLength)},forge.kem.kdf2=function(md,digestLength){_createKDF(this,md,1,digestLength||md.digestLength)},kem}(),function requireLog(){if(hasRequiredLog)return log;hasRequiredLog=1;var forge=requireForge();requireUtil(),log=forge.log=forge.log||{},forge.log.levels=["none","error","warning","info","debug","verbose","max"];var sLevelInfo={},sLoggers=[],sConsoleLogger=null;forge.log.LEVEL_LOCKED=2,forge.log.NO_LEVEL_CHECK=4,forge.log.INTERPOLATE=8;for(var i=0;i<forge.log.levels.length;++i){var level=forge.log.levels[i];sLevelInfo[level]={index:i,name:level.toUpperCase()}}forge.log.logMessage=function(message){for(var messageLevelIndex=sLevelInfo[message.level].index,i=0;i<sLoggers.length;++i){var logger=sLoggers[i];logger.flags&forge.log.NO_LEVEL_CHECK?logger.f(message):messageLevelIndex<=sLevelInfo[logger.level].index&&logger.f(logger,message)}},forge.log.prepareStandard=function(message){"standard"in message||(message.standard=sLevelInfo[message.level].name+" ["+message.category+"] "+message.message)},forge.log.prepareFull=function(message){if(!("full"in message)){var args=[message.message];args=args.concat([]||message.arguments),message.full=forge.util.format.apply(this,args)}},forge.log.prepareStandardFull=function(message){"standardFull"in message||(forge.log.prepareStandard(message),message.standardFull=message.standard)};var levels=["error","warning","info","debug","verbose"];for(i=0;i<levels.length;++i)(function(level){forge.log[level]=function(category,message){var args=Array.prototype.slice.call(arguments).slice(2),msg={timestamp:new Date,level:level,category:category,message:message,arguments:args};forge.log.logMessage(msg)}})(levels[i]);if(forge.log.makeLogger=function(logFunction){var logger={flags:0,f:logFunction};return forge.log.setLevel(logger,"none"),logger},forge.log.setLevel=function(logger,level){var rval=!1;if(logger&&!(logger.flags&forge.log.LEVEL_LOCKED))for(var i=0;i<forge.log.levels.length;++i)if(level==forge.log.levels[i]){logger.level=level,rval=!0;break}return rval},forge.log.lock=function(logger,lock){void 0===lock||lock?logger.flags|=forge.log.LEVEL_LOCKED:logger.flags&=~forge.log.LEVEL_LOCKED},forge.log.addLogger=function(logger){sLoggers.push(logger)},"undefined"!=typeof console&&"log"in console){var logger;if(console.error&&console.warn&&console.info&&console.debug){var levelHandlers={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},f=function(logger,message){forge.log.prepareStandard(message);var handler=levelHandlers[message.level],args=[message.standard];args=args.concat(message.arguments.slice()),handler.apply(console,args)};logger=forge.log.makeLogger(f)}else f=function(logger,message){forge.log.prepareStandardFull(message),console.log(message.standardFull)},logger=forge.log.makeLogger(f);forge.log.setLevel(logger,"debug"),forge.log.addLogger(logger),sConsoleLogger=logger}else console={log:function(){}};if(null!==sConsoleLogger&&"undefined"!=typeof window&&window.location){var query=new URL(window.location.href).searchParams;query.has("console.level")&&forge.log.setLevel(sConsoleLogger,query.get("console.level").slice(-1)[0]),query.has("console.lock")&&"true"==query.get("console.lock").slice(-1)[0]&&forge.log.lock(sConsoleLogger)}return forge.log.consoleLogger=sConsoleLogger,log}(),function requireMd_all(){return hasRequiredMd_all||(hasRequiredMd_all=1,md_all=requireMd(),requireMd5(),requireSha1$1(),requireSha256(),requireSha512()),md_all}(),requireMgf1(),requirePbkdf2(),requirePem(),requirePkcs1(),requirePkcs12(),requirePkcs7(),requirePki(),requirePrime(),requirePrng(),requirePss(),requireRandom(),requireRc2(),function requireSsh(){if(hasRequiredSsh)return ssh.exports;hasRequiredSsh=1;var forge=requireForge();requireAes(),requireHmac(),requireMd5(),requireSha1$1(),requireUtil();var ssh$1=ssh.exports=forge.ssh=forge.ssh||{};function _addBigIntegerToBuffer(buffer,val){var hexVal=val.toString(16);hexVal[0]>="8"&&(hexVal="00"+hexVal);var bytes=forge.util.hexToBytes(hexVal);buffer.putInt32(bytes.length),buffer.putBytes(bytes)}function _addStringToBuffer(buffer,val){buffer.putInt32(val.length),buffer.putString(val)}function _sha1(){for(var sha=forge.md.sha1.create(),num=arguments.length,i=0;i<num;++i)sha.update(arguments[i]);return sha.digest()}return ssh$1.privateKeyToPutty=function(privateKey,passphrase,comment){var encryptionAlgorithm=""===(passphrase=passphrase||"")?"none":"aes256-cbc",ppk="PuTTY-User-Key-File-2: ssh-rsa\r\n";ppk+="Encryption: "+encryptionAlgorithm+"\r\n",ppk+="Comment: "+(comment=comment||"")+"\r\n";var pubbuffer=forge.util.createBuffer();_addStringToBuffer(pubbuffer,"ssh-rsa"),_addBigIntegerToBuffer(pubbuffer,privateKey.e),_addBigIntegerToBuffer(pubbuffer,privateKey.n);var pub=forge.util.encode64(pubbuffer.bytes(),64),length=Math.floor(pub.length/66)+1;ppk+="Public-Lines: "+length+"\r\n",ppk+=pub;var priv,privbuffer=forge.util.createBuffer();if(_addBigIntegerToBuffer(privbuffer,privateKey.d),_addBigIntegerToBuffer(privbuffer,privateKey.p),_addBigIntegerToBuffer(privbuffer,privateKey.q),_addBigIntegerToBuffer(privbuffer,privateKey.qInv),passphrase){var encLen=privbuffer.length()+16-1;encLen-=encLen%16;var padding=_sha1(privbuffer.bytes());padding.truncate(padding.length()-encLen+privbuffer.length()),privbuffer.putBuffer(padding);var aeskey=forge.util.createBuffer();aeskey.putBuffer(_sha1("\0\0\0\0",passphrase)),aeskey.putBuffer(_sha1("\0\0\0",passphrase));var cipher=forge.aes.createEncryptionCipher(aeskey.truncate(8),"CBC");cipher.start(forge.util.createBuffer().fillWithByte(0,16)),cipher.update(privbuffer.copy()),cipher.finish();var encrypted=cipher.output;encrypted.truncate(16),priv=forge.util.encode64(encrypted.bytes(),64)}else priv=forge.util.encode64(privbuffer.bytes(),64);ppk+="\r\nPrivate-Lines: "+(length=Math.floor(priv.length/66)+1)+"\r\n",ppk+=priv;var mackey=_sha1("putty-private-key-file-mac-key",passphrase),macbuffer=forge.util.createBuffer();_addStringToBuffer(macbuffer,"ssh-rsa"),_addStringToBuffer(macbuffer,encryptionAlgorithm),_addStringToBuffer(macbuffer,comment),macbuffer.putInt32(pubbuffer.length()),macbuffer.putBuffer(pubbuffer),macbuffer.putInt32(privbuffer.length()),macbuffer.putBuffer(privbuffer);var hmac=forge.hmac.create();return hmac.start("sha1",mackey),hmac.update(macbuffer.bytes()),ppk+"\r\nPrivate-MAC: "+hmac.digest().toHex()+"\r\n"},ssh$1.publicKeyToOpenSSH=function(key,comment){comment=comment||"";var buffer=forge.util.createBuffer();return _addStringToBuffer(buffer,"ssh-rsa"),_addBigIntegerToBuffer(buffer,key.e),_addBigIntegerToBuffer(buffer,key.n),"ssh-rsa "+forge.util.encode64(buffer.bytes())+" "+comment},ssh$1.privateKeyToOpenSSH=function(privateKey,passphrase){return passphrase?forge.pki.encryptRsaPrivateKey(privateKey,passphrase,{legacy:!0,algorithm:"aes128"}):forge.pki.privateKeyToPem(privateKey)},ssh$1.getPublicKeyFingerprint=function(key,options){var md=(options=options||{}).md||forge.md.md5.create(),buffer=forge.util.createBuffer();_addStringToBuffer(buffer,"ssh-rsa"),_addBigIntegerToBuffer(buffer,key.e),_addBigIntegerToBuffer(buffer,key.n),md.start(),md.update(buffer.getBytes());var digest=md.digest();if("hex"===options.encoding){var hex=digest.toHex();return options.delimiter?hex.match(/.{2}/g).join(options.delimiter):hex}if("binary"===options.encoding)return digest.getBytes();if(options.encoding)throw new Error('Unknown encoding "'+options.encoding+'".');return digest},ssh.exports}(),requireTls(),requireUtil()),lib$1}(),forge=getDefaultExportFromCjs(libExports$1);const baseDir$1=path__default.default.dirname(require$$0$9.fileURLToPath("undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs",document.baseURI).href)),dir="../resources/certs";class LoadCertificate{config;certificate;cert_key;constructor(config){this.config=config,this.certificate="",this.cert_key=""}loadCertificateWithPEM(){return new Promise((resolve,reject)=>{try{const pfxPath=this.config.dfe.pathCertificado,pfxPassword=this.config.dfe.senhaCertificado,pfxFile=fs__default.default.readFileSync(pfxPath),certsDir=path__default.default.resolve(baseDir$1,dir),caCerts=fs__default.default.readdirSync(certsDir).map(filename=>{const tmp=`${certsDir}/${filename}`;return fs__default.default.readFileSync(tmp)});pem__default.default.readPkcs12(pfxFile,{p12Password:pfxPassword},async(error,result)=>{if(error)return error.message.toLowerCase().includes("mac verify error")?reject(new Error("Erro ao ler o certificado: Senha incorreta.")):reject(new Error(`Erro ao ler o certificado: ${error.message}`));const key=result.key;this.cert_key=key;const cert=result.cert;this.certificate=cert;const certForge=forge.pki.certificateFromPem(cert),now=new Date;if(now<certForge.validity.notBefore||now>certForge.validity.notAfter)return reject(new Error("Erro ao carregar o certificado: O certificado fornecido expirou ou ainda não é válido."));const agent=new https__default.default.Agent({key:key,cert:cert,ca:caCerts});resolve({success:!0,agent:agent,message:"Certificado Carregado com Sucesso."})})}catch(error){logger.error("Erro ao validar certificado",error,{context:"LoadCertificate",method:"loadCertificateWithPEM"}),reject(new Error(error.message))}})}loadCertificateWithNodeForge(){return new Promise((resolve,reject)=>{try{const pfxPath=this.config.dfe.pathCertificado,pfxPassword=this.config.dfe.senhaCertificado,pfxFile=fs__default.default.readFileSync(pfxPath),p12Asn1=forge.asn1.fromDer(pfxFile.toString("binary")),p12=forge.pkcs12.pkcs12FromAsn1(p12Asn1,pfxPassword),keyBags=p12.getBags({bagType:forge.pki.oids.pkcs8ShroudedKeyBag}),certBags=p12.getBags({bagType:forge.pki.oids.certBag}),key=keyBags[forge.pki.oids.pkcs8ShroudedKeyBag]?.[0]?.key;if(!key)return reject(new Error("Erro ao carregar chave privada do certificado."));const keyPem=forge.pki.privateKeyToPem(key);this.cert_key=keyPem;const cert=certBags[forge.pki.oids.certBag]?.[0]?.cert;if(!cert)return reject(new Error("Erro ao validar certificado."));const certPem=forge.pki.certificateToPem(cert);this.certificate=certPem;const certForge=forge.pki.certificateFromPem(forge.pki.certificateToPem(cert)),now=new Date;if(now<certForge.validity.notBefore||now>certForge.validity.notAfter)return reject(new Error("Erro ao carregar o certificado: O certificado fornecido expirou ou ainda não é válido."));const certsDir=path__default.default.resolve(baseDir$1,dir),caCerts=fs__default.default.readdirSync(certsDir).map(filename=>{const tmp=`${certsDir}/${filename}`;return fs__default.default.readFileSync(tmp)});resolve({success:!0,agent:new https__default.default.Agent({key:keyPem,cert:certPem,ca:caCerts}),message:"Certificado Carregado com Sucesso."})}catch(error){logger.error("Erro ao validar certificado",error,{context:"LoadCertificate",method:"loadCertificateWithNodeForge"}),reject(new Error(error.message))}})}async loadCertificate(){if(logger.info("Validando certificado",{context:"LoadCertificate"}),this.config.lib?.useOpenSSL||void 0===this.config.lib?.useOpenSSL){const{agent:agent}=await this.loadCertificateWithPEM();return{certificate:this.certificate,cert_key:this.cert_key,agent:agent}}const{agent:agent}=await this.loadCertificateWithNodeForge();return{certificate:this.certificate,cert_key:this.cert_key,agent:agent}}}class Environment{config;certificate;cert_key;agent;isLoaded;constructor(config){this.config=config,this.certificate="",this.cert_key="",this.agent={},this.isLoaded=!1}getIsLoaded(){return this.isLoaded}getConfig(){return this.config}getCertKey(){return this.cert_key}getCert(){return this.certificate}getHttpAgent(){return this.agent}LoggerInit(config){try{config.lib?.log&&logger.initialize({exibirLogNoConsole:config.lib.log.exibirLogNoConsole??!1,armazenarLogs:config.lib.log.armazenarLogs??!1,pathLogs:config.lib.log.pathLogs}),logger.info("Inicializando ambiente NFeWizard",{context:"Environment"})}catch(error){throw logger.error("Erro ao inicializar ambiente NFeWizard",error,{context:"Environment"}),error}}async loadEnvironment(){this.LoggerInit(this.config);(new ValidateEnvironment).checkRequiredSettings(this.config);const loadCertificate=new LoadCertificate(this.config),{agent:agent,certificate:certificate,cert_key:cert_key}=await loadCertificate.loadCertificate();this.agent=agent,this.certificate=certificate,this.cert_key=cert_key;const httpClient=new AxiosHttpClient,axios=new HttpClientBuilder(this.config,this.agent,httpClient).createHttpClient();return this.isLoaded=!0,logger.info("Ambiente NFe Wizard inicializado com sucesso",{context:"Environment"}),{axios:axios}}}const getCodIBGE=UF=>({RO:11,AC:12,AM:13,RR:14,PA:15,AP:16,TO:17,MA:21,PI:22,CE:23,RN:24,PB:25,PE:26,AL:27,SE:28,BA:29,MG:31,ES:32,RJ:33,SP:35,PR:41,SC:42,RS:43,MS:50,MT:51,GO:52,DF:53,AN:91}[UF]);class BaseNFE{environment;utility;metodo;xmlBuilder;chaveNfe;axios;saveFiles;gerarConsulta;modelo;constructor(environment,utility,xmlBuilder,metodo,axios,saveFiles,gerarConsulta){this.environment=environment,this.utility=utility,this.xmlBuilder=xmlBuilder,this.metodo=metodo,this.axios=axios,this.saveFiles=saveFiles,this.gerarConsulta=gerarConsulta,this.chaveNfe="",this.modelo="NFe"}gerarXml(data){throw new Error("O método 'gerarXml' não foi implementado na subclasse.")}setContentType(){const UF=this.environment.config.dfe.UF;return["MG","GO","MT","MS","AM","DF"].includes(UF)?"application/soap+xml":"text/xml; charset=utf-8"}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType};logger.http("Iniciando comunicação com o webservice",{context:"BaseNFE",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"BaseNFE",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}getModelo(data){return this.modelo||"NFe"}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXml(data);const modelo=this.getModelo(data),{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,void 0,void 0,modelo);xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent);if(responseInJson=(new XmlParser).convertXmlToJson(xmlRetorno.data,this.metodo),responseInJson.xMotivo.includes("Rejeição"))throw new Error(responseInJson.xMotivo);return responseInJson}finally{this.saveFiles.salvaArquivos(xmlConsulta,responseInJson,xmlRetorno,this.metodo,xmlConsultaSoap)}}}class NFEStatusServicoService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEStatusServico",axios,saveFiles,gerarConsulta)}gerarXml(){logger.info("Montando estrutuda do XML em JSON",{context:"NFEStatusServicoService"});const{nfe:{ambiente:ambiente,versaoDF:versaoDF},dfe:{UF:UF}}=this.environment.getConfig(),xmlObject={$:{versao:versaoDF,xmlns:"http://www.portalfiscal.inf.br/nfe"},tpAmb:ambiente,cUF:getCodIBGE(UF),xServ:"STATUS"};return this.xmlBuilder.gerarXml(xmlObject,"consStatServ",this.metodo)}}class NFEConsultaProtocolo{nfeConsultaProtocoloService;constructor(nfeConsultaProtocoloService){this.nfeConsultaProtocoloService=nfeConsultaProtocoloService}async Exec(data){return await this.nfeConsultaProtocoloService.Exec(data)}}class NFEEpec{nfeEpecServiceService;constructor(nfeEpecServiceService){this.nfeEpecServiceService=nfeEpecServiceService}async Exec(data){return await this.nfeEpecServiceService.Exec(data)}}class NFECancelamento{nfeCancelamentoServiceService;constructor(nfeCancelamentoServiceService){this.nfeCancelamentoServiceService=nfeCancelamentoServiceService}async Exec(data){return await this.nfeCancelamentoServiceService.Exec(data)}}class NFECienciaDaOperacao{nfeCienciaDaOperacaoServiceService;constructor(nfeCienciaDaOperacaoServiceService){this.nfeCienciaDaOperacaoServiceService=nfeCienciaDaOperacaoServiceService}async Exec(data){return await this.nfeCienciaDaOperacaoServiceService.Exec(data)}}class NFEConfirmacaoDaOperacao{nfeConfirmacaoDaOperacaoServiceService;constructor(nfeConfirmacaoDaOperacaoServiceService){this.nfeConfirmacaoDaOperacaoServiceService=nfeConfirmacaoDaOperacaoServiceService}async Exec(data){return await this.nfeConfirmacaoDaOperacaoServiceService.Exec(data)}}class NFEOperacaoNaoRealizada{nfeOperacaoNaoRealizadaServiceService;constructor(nfeOperacaoNaoRealizadaServiceService){this.nfeOperacaoNaoRealizadaServiceService=nfeOperacaoNaoRealizadaServiceService}async Exec(data){return await this.nfeOperacaoNaoRealizadaServiceService.Exec(data)}}var cookies,hasRequiredCookies,nodemailer$1={},shared={exports:{}},fetch$1={exports:{}};var hasRequiredFetch,hasRequiredShared,mimeTypes_1,hasRequiredMimeTypes,punycode_1,hasRequiredPunycode,base64,hasRequiredBase64,qp,hasRequiredQp,mimeFuncs,hasRequiredMimeFuncs,addressparser_1,hasRequiredAddressparser,lastNewline,hasRequiredLastNewline,leWindows,hasRequiredLeWindows,leUnix,hasRequiredLeUnix,mimeNode,hasRequiredMimeNode,mailComposer,hasRequiredMailComposer,messageParser,hasRequiredMessageParser,relaxedBody,hasRequiredRelaxedBody,require$$9={name:"nodemailer",version:"6.10.1",description:"Easy as cake e-mail sending from your Node.js applications",main:"lib/nodemailer.js",scripts:{test:"node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js","test:coverage":"c8 node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js",lint:"eslint .",update:"rm -rf node_modules/ package-lock.json && ncu -u && npm install"},repository:{type:"git",url:"https://github.com/nodemailer/nodemailer.git"},keywords:["Nodemailer"],author:"Andris Reinman",license:"MIT-0",bugs:{url:"https://github.com/nodemailer/nodemailer/issues"},homepage:"https://nodemailer.com/",devDependencies:{"@aws-sdk/client-ses":"3.731.1",bunyan:"1.8.15",c8:"10.1.3",eslint:"8.57.0","eslint-config-nodemailer":"1.2.0","eslint-config-prettier":"9.1.0",libbase64:"1.3.0",libmime:"5.3.6",libqp:"2.1.1","nodemailer-ntlm-auth":"1.0.4",proxy:"1.0.2","proxy-test-server":"1.0.0","smtp-server":"3.13.6"},engines:{node:">=6.0.0"}};function requireFetch(){if(hasRequiredFetch)return fetch$1.exports;hasRequiredFetch=1;const http=require$$0__default$5.default,https=https__default.default,urllib=require$$0__default$6.default,zlib=zlib__default.default,PassThrough=require$$0__default$4.default.PassThrough,Cookies=function requireCookies(){if(hasRequiredCookies)return cookies;hasRequiredCookies=1;const urllib=require$$0__default$6.default;return cookies=class Cookies{constructor(options){this.options=options||{},this.cookies=[]}set(cookieStr,url){let domain,urlparts=urllib.parse(url||""),cookie=this.parse(cookieStr);return cookie.domain?(domain=cookie.domain.replace(/^\./,""),(urlparts.hostname.length<domain.length||("."+urlparts.hostname).substr(1-domain.length)!=="."+domain)&&(cookie.domain=urlparts.hostname)):cookie.domain=urlparts.hostname,cookie.path||(cookie.path=this.getPath(urlparts.pathname)),cookie.expires||(cookie.expires=new Date(Date.now()+1e3*(Number(this.options.sessionTimeout||1800)||1800))),this.add(cookie)}get(url){return this.list(url).map(cookie=>cookie.name+"="+cookie.value).join("; ")}list(url){let i,cookie,result=[];for(i=this.cookies.length-1;i>=0;i--)cookie=this.cookies[i],this.isExpired(cookie)?this.cookies.splice(i,i):this.match(cookie,url)&&result.unshift(cookie);return result}parse(cookieStr){let cookie={};return(cookieStr||"").toString().split(";").forEach(cookiePart=>{let domain,valueParts=cookiePart.split("="),key=valueParts.shift().trim().toLowerCase(),value=valueParts.join("=").trim();if(key)switch(key){case"expires":value=new Date(value),"Invalid Date"!==value.toString()&&(cookie.expires=value);break;case"path":cookie.path=value;break;case"domain":domain=value.toLowerCase(),domain.length&&"."!==domain.charAt(0)&&(domain="."+domain),cookie.domain=domain;break;case"max-age":cookie.expires=new Date(Date.now()+1e3*(Number(value)||0));break;case"secure":cookie.secure=!0;break;case"httponly":cookie.httponly=!0;break;default:cookie.name||(cookie.name=key,cookie.value=value)}}),cookie}match(cookie,url){let urlparts=urllib.parse(url||"");return(urlparts.hostname===cookie.domain||"."===cookie.domain.charAt(0)&&("."+urlparts.hostname).substr(-cookie.domain.length)===cookie.domain)&&this.getPath(urlparts.pathname).substr(0,cookie.path.length)===cookie.path&&(!cookie.secure||"https:"===urlparts.protocol)}add(cookie){let i,len;if(!cookie||!cookie.name)return!1;for(i=0,len=this.cookies.length;i<len;i++)if(this.compare(this.cookies[i],cookie))return this.isExpired(cookie)?(this.cookies.splice(i,1),!1):(this.cookies[i]=cookie,!0);return this.isExpired(cookie)||this.cookies.push(cookie),!0}compare(a,b){return a.name===b.name&&a.path===b.path&&a.domain===b.domain&&a.secure===b.secure&&a.httponly==a.httponly}isExpired(cookie){return cookie.expires&&cookie.expires<new Date||!cookie.value}getPath(pathname){let path=(pathname||"/").split("/");return path.pop(),path=path.join("/").trim(),"/"!==path.charAt(0)&&(path="/"+path),"/"!==path.substr(-1)&&(path+="/"),path}},cookies}(),packageData=require$$9,net=require$$7__default.default;function nmfetch(url,options){(options=options||{}).fetchRes=options.fetchRes||new PassThrough,options.cookies=options.cookies||new Cookies,options.redirects=options.redirects||0,options.maxRedirects=isNaN(options.maxRedirects)?5:options.maxRedirects,options.cookie&&([].concat(options.cookie||[]).forEach(cookie=>{options.cookies.set(cookie,url)}),options.cookie=!1);let cookies,body,req,fetchRes=options.fetchRes,parsed=urllib.parse(url),method=(options.method||"").toString().trim().toUpperCase()||"GET",finished=!1,handler="https:"===parsed.protocol?https:http,headers={"accept-encoding":"gzip,deflate","user-agent":"nodemailer/"+packageData.version};if(Object.keys(options.headers||{}).forEach(key=>{headers[key.toLowerCase().trim()]=options.headers[key]}),options.userAgent&&(headers["user-agent"]=options.userAgent),parsed.auth&&(headers.Authorization="Basic "+Buffer.from(parsed.auth).toString("base64")),(cookies=options.cookies.get(url))&&(headers.cookie=cookies),options.body){if(!1!==options.contentType&&(headers["Content-Type"]=options.contentType||"application/x-www-form-urlencoded"),"function"==typeof options.body.pipe)headers["Transfer-Encoding"]="chunked",body=options.body,body.on("error",err=>{finished||(finished=!0,err.type="FETCH",err.sourceUrl=url,fetchRes.emit("error",err))});else{if(options.body instanceof Buffer)body=options.body;else if("object"==typeof options.body)try{body=Buffer.from(Object.keys(options.body).map(key=>{let value=options.body[key].toString().trim();return encodeURIComponent(key)+"="+encodeURIComponent(value)}).join("&"))}catch(E){if(finished)return;return finished=!0,E.type="FETCH",E.sourceUrl=url,void fetchRes.emit("error",E)}else body=Buffer.from(options.body.toString().trim());headers["Content-Type"]=options.contentType||"application/x-www-form-urlencoded",headers["Content-Length"]=body.length}method=(options.method||"").toString().trim().toUpperCase()||"POST"}let reqOptions={method:method,host:parsed.hostname,path:parsed.path,port:parsed.port?parsed.port:"https:"===parsed.protocol?443:80,headers:headers,rejectUnauthorized:!1,agent:!1};options.tls&&Object.keys(options.tls).forEach(key=>{reqOptions[key]=options.tls[key]}),"https:"!==parsed.protocol||!parsed.hostname||parsed.hostname===reqOptions.host||net.isIP(parsed.hostname)||reqOptions.servername||(reqOptions.servername=parsed.hostname);try{req=handler.request(reqOptions)}catch(E){return finished=!0,setImmediate(()=>{E.type="FETCH",E.sourceUrl=url,fetchRes.emit("error",E)}),fetchRes}return options.timeout&&req.setTimeout(options.timeout,()=>{if(finished)return;finished=!0,req.abort();let err=new Error("Request Timeout");err.type="FETCH",err.sourceUrl=url,fetchRes.emit("error",err)}),req.on("error",err=>{finished||(finished=!0,err.type="FETCH",err.sourceUrl=url,fetchRes.emit("error",err))}),req.on("response",res=>{let inflate;if(!finished){switch(res.headers["content-encoding"]){case"gzip":case"deflate":inflate=zlib.createUnzip()}if(res.headers["set-cookie"]&&[].concat(res.headers["set-cookie"]||[]).forEach(cookie=>{options.cookies.set(cookie,url)}),[301,302,303,307,308].includes(res.statusCode)&&res.headers.location){if(options.redirects++,options.redirects>options.maxRedirects){finished=!0;let err=new Error("Maximum redirect count exceeded");return err.type="FETCH",err.sourceUrl=url,fetchRes.emit("error",err),void req.abort()}return options.method="GET",options.body=!1,nmfetch(urllib.resolve(url,res.headers.location),options)}if(fetchRes.statusCode=res.statusCode,fetchRes.headers=res.headers,res.statusCode>=300&&!options.allowErrorResponse){finished=!0;let err=new Error("Invalid status code "+res.statusCode);return err.type="FETCH",err.sourceUrl=url,fetchRes.emit("error",err),void req.abort()}res.on("error",err=>{finished||(finished=!0,err.type="FETCH",err.sourceUrl=url,fetchRes.emit("error",err),req.abort())}),inflate?(res.pipe(inflate).pipe(fetchRes),inflate.on("error",err=>{finished||(finished=!0,err.type="FETCH",err.sourceUrl=url,fetchRes.emit("error",err),req.abort())})):res.pipe(fetchRes)}}),setImmediate(()=>{if(body)try{if("function"==typeof body.pipe)return body.pipe(req);req.write(body)}catch(err){return finished=!0,err.type="FETCH",err.sourceUrl=url,void fetchRes.emit("error",err)}req.end()}),fetchRes}return fetch$1.exports=function(url,options){return nmfetch(url,options)},fetch$1.exports.Cookies=Cookies,fetch$1.exports}function requireShared(){return hasRequiredShared||(hasRequiredShared=1,function(module){const urllib=require$$0__default$6.default,util=require$$0__default$2.default,fs=fs__default.default,nmfetch=requireFetch(),dns=require$$4__default$2.default,net=require$$7__default.default,os=require$$0__default$3.default;let networkInterfaces;try{networkInterfaces=os.networkInterfaces()}catch(err){}module.exports.networkInterfaces=networkInterfaces;const isFamilySupported=(family,allowInternal)=>{let networkInterfaces=module.exports.networkInterfaces;if(!networkInterfaces)return!0;return Object.keys(networkInterfaces).map(key=>networkInterfaces[key]).reduce((acc,val)=>acc.concat(val),[]).filter(i=>!i.internal||allowInternal).filter(i=>i.family==="IPv"+family||i.family===family).length>0},resolver=(family,hostname,options,callback)=>{if(!isFamilySupported(family,(options=options||{}).allowInternalNetworkInterfaces))return callback(null,[]);(dns.Resolver?new dns.Resolver(options):dns)["resolve"+family](hostname,(err,addresses)=>{if(err){switch(err.code){case dns.NODATA:case dns.NOTFOUND:case dns.NOTIMP:case dns.SERVFAIL:case dns.CONNREFUSED:case dns.REFUSED:case"EAI_AGAIN":return callback(null,[])}return callback(err)}return callback(null,Array.isArray(addresses)?addresses:[].concat(addresses||[]))})},dnsCache=module.exports.dnsCache=new Map,formatDNSValue=(value,extra)=>value?Object.assign({servername:value.servername,host:value.addresses&&value.addresses.length?1===value.addresses.length?value.addresses[0]:value.addresses[Math.floor(Math.random()*value.addresses.length)]:null},extra||{}):Object.assign({},extra||{});function resolveStream(stream,callback){let responded=!1,chunks=[],chunklen=0;stream.on("error",err=>{responded||(responded=!0,callback(err))}),stream.on("readable",()=>{let chunk;for(;null!==(chunk=stream.read());)chunks.push(chunk),chunklen+=chunk.length}),stream.on("end",()=>{if(responded)return;let value;responded=!0;try{value=Buffer.concat(chunks,chunklen)}catch(E){return callback(E)}callback(null,value)})}module.exports.resolveHostname=(options,callback)=>{if(!(options=options||{}).host&&options.servername&&(options.host=options.servername),!options.host||net.isIP(options.host)){let value={addresses:[options.host],servername:options.servername||!1};return callback(null,formatDNSValue(value,{cached:!1}))}let cached;if(dnsCache.has(options.host)&&(cached=dnsCache.get(options.host),!cached.expires||cached.expires>=Date.now()))return callback(null,formatDNSValue(cached.value,{cached:!0}));resolver(4,options.host,options,(err,addresses)=>{if(err)return cached?callback(null,formatDNSValue(cached.value,{cached:!0,error:err})):callback(err);if(addresses&&addresses.length){let value={addresses:addresses,servername:options.servername||options.host};return dnsCache.set(options.host,{value:value,expires:Date.now()+(options.dnsTtl||3e5)}),callback(null,formatDNSValue(value,{cached:!1}))}resolver(6,options.host,options,(err,addresses)=>{if(err)return cached?callback(null,formatDNSValue(cached.value,{cached:!0,error:err})):callback(err);if(addresses&&addresses.length){let value={addresses:addresses,servername:options.servername||options.host};return dnsCache.set(options.host,{value:value,expires:Date.now()+(options.dnsTtl||3e5)}),callback(null,formatDNSValue(value,{cached:!1}))}try{dns.lookup(options.host,{all:!0},(err,addresses)=>{if(err)return cached?callback(null,formatDNSValue(cached.value,{cached:!0,error:err})):callback(err);let address=!!addresses&&addresses.filter(addr=>isFamilySupported(addr.family)).map(addr=>addr.address).shift();if(addresses&&addresses.length&&!address&&console.warn(`Failed to resolve IPv${addresses[0].family} addresses with current network`),!address&&cached)return callback(null,formatDNSValue(cached.value,{cached:!0}));let value={addresses:address?[address]:[options.host],servername:options.servername||options.host};return dnsCache.set(options.host,{value:value,expires:Date.now()+(options.dnsTtl||3e5)}),callback(null,formatDNSValue(value,{cached:!1}))})}catch(err){return cached?callback(null,formatDNSValue(cached.value,{cached:!0,error:err})):callback(err)}})})},module.exports.parseConnectionUrl=str=>{str=str||"";let options={};return[urllib.parse(str,!0)].forEach(url=>{let auth;switch(url.protocol){case"smtp:":options.secure=!1;break;case"smtps:":options.secure=!0;break;case"direct:":options.direct=!0}!isNaN(url.port)&&Number(url.port)&&(options.port=Number(url.port)),url.hostname&&(options.host=url.hostname),url.auth&&(auth=url.auth.split(":"),options.auth||(options.auth={}),options.auth.user=auth.shift(),options.auth.pass=auth.join(":")),Object.keys(url.query||{}).forEach(key=>{let obj=options,lKey=key,value=url.query[key];switch(isNaN(value)||(value=Number(value)),value){case"true":value=!0;break;case"false":value=!1}if(0===key.indexOf("tls."))lKey=key.substr(4),options.tls||(options.tls={}),obj=options.tls;else if(key.indexOf(".")>=0)return;lKey in obj||(obj[lKey]=value)})}),options},module.exports._logFunc=(logger,level,defaults,data,message,...args)=>{let entry={};Object.keys(defaults||{}).forEach(key=>{"level"!==key&&(entry[key]=defaults[key])}),Object.keys(data||{}).forEach(key=>{"level"!==key&&(entry[key]=data[key])}),logger[level](entry,message,...args)},module.exports.getLogger=(options,defaults)=>{let response={},levels=["trace","debug","info","warn","error","fatal"];if(!(options=options||{}).logger)return levels.forEach(level=>{response[level]=()=>!1}),response;let logger=options.logger;return!0===options.logger&&(logger=function createDefaultLogger(levels){let levelMaxLen=0,levelNames=new Map;levels.forEach(level=>{level.length>levelMaxLen&&(levelMaxLen=level.length)}),levels.forEach(level=>{let levelName=level.toUpperCase();levelName.length<levelMaxLen&&(levelName+=" ".repeat(levelMaxLen-levelName.length)),levelNames.set(level,levelName)});let print=(level,entry,message,...args)=>{let prefix="";entry&&("server"===entry.tnx?prefix="S: ":"client"===entry.tnx&&(prefix="C: "),entry.sid&&(prefix="["+entry.sid+"] "+prefix),entry.cid&&(prefix="[#"+entry.cid+"] "+prefix)),(message=util.format(message,...args)).split(/\r?\n/).forEach(line=>{console.log("[%s] %s %s",(new Date).toISOString().substr(0,19).replace(/T/," "),levelNames.get(level),prefix+line)})},logger={};return levels.forEach(level=>{logger[level]=print.bind(null,level)}),logger}(levels)),levels.forEach(level=>{response[level]=(data,message,...args)=>{module.exports._logFunc(logger,level,defaults,data,message,...args)}}),response},module.exports.callbackPromise=(resolve,reject)=>function(){let args=Array.from(arguments),err=args.shift();err?reject(err):resolve(...args)},module.exports.parseDataURI=uri=>{let input=uri,commaPos=input.indexOf(",");if(!commaPos)return uri;let encoding,data=input.substring(commaPos+1),metaEntries=input.substring(5,commaPos).split(";"),lastMetaEntry=metaEntries.length>1&&metaEntries[metaEntries.length-1];lastMetaEntry&&lastMetaEntry.indexOf("=")<0&&(encoding=lastMetaEntry.toLowerCase(),metaEntries.pop());let contentType=metaEntries.shift()||"application/octet-stream",params={};for(let entry of metaEntries){let sep=entry.indexOf("=");if(sep>=0){let key=entry.substring(0,sep),value=entry.substring(sep+1);params[key]=value}}switch(encoding){case"base64":data=Buffer.from(data,"base64");break;case"utf8":data=Buffer.from(data);break;default:try{data=Buffer.from(decodeURIComponent(data))}catch(err){data=Buffer.from(data)}data=Buffer.from(data)}return{data:data,encoding:encoding,contentType:contentType,params:params}},module.exports.resolveContent=(data,key,callback)=>{let promise;callback||(promise=new Promise((resolve,reject)=>{callback=module.exports.callbackPromise(resolve,reject)}));let contentStream,content=data&&data[key]&&data[key].content||data[key],encoding=("object"==typeof data[key]&&data[key].encoding||"utf8").toString().toLowerCase().replace(/[-_\s]/g,"");if(!content)return callback(null,content);if("object"==typeof content){if("function"==typeof content.pipe)return resolveStream(content,(err,value)=>{if(err)return callback(err);data[key].content?data[key].content=value:data[key]=value,callback(null,value)});if(/^https?:\/\//i.test(content.path||content.href))return contentStream=nmfetch(content.path||content.href),resolveStream(contentStream,callback);if(/^data:/i.test(content.path||content.href)){let parsedDataUri=module.exports.parseDataURI(content.path||content.href);return parsedDataUri&&parsedDataUri.data?callback(null,parsedDataUri.data):callback(null,Buffer.from(0))}if(content.path)return resolveStream(fs.createReadStream(content.path),callback)}return"string"!=typeof data[key].content||["utf8","usascii","ascii"].includes(encoding)||(content=Buffer.from(data[key].content,encoding)),setImmediate(()=>callback(null,content)),promise},module.exports.assign=function(){let args=Array.from(arguments),target=args.shift()||{};return args.forEach(source=>{Object.keys(source||{}).forEach(key=>{["tls","auth"].includes(key)&&source[key]&&"object"==typeof source[key]?(target[key]||(target[key]={}),Object.keys(source[key]).forEach(subKey=>{target[key][subKey]=source[key][subKey]})):target[key]=source[key]})}),target},module.exports.encodeXText=str=>{if(!/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/.test(str))return str;let buf=Buffer.from(str),result="";for(let i=0,len=buf.length;i<len;i++){let c=buf[i];result+=c<33||c>126||43===c||61===c?"+"+(c<16?"0":"")+c.toString(16).toUpperCase():String.fromCharCode(c)}return result}}(shared)),shared.exports}function requireMimeTypes(){if(hasRequiredMimeTypes)return mimeTypes_1;hasRequiredMimeTypes=1;const path=path__default.default,mimeTypes=new Map([["application/acad","dwg"],["application/applixware","aw"],["application/arj","arj"],["application/atom+xml","xml"],["application/atomcat+xml","atomcat"],["application/atomsvc+xml","atomsvc"],["application/base64",["mm","mme"]],["application/binhex","hqx"],["application/binhex4","hqx"],["application/book",["book","boo"]],["application/ccxml+xml,","ccxml"],["application/cdf","cdf"],["application/cdmi-capability","cdmia"],["application/cdmi-container","cdmic"],["application/cdmi-domain","cdmid"],["application/cdmi-object","cdmio"],["application/cdmi-queue","cdmiq"],["application/clariscad","ccad"],["application/commonground","dp"],["application/cu-seeme","cu"],["application/davmount+xml","davmount"],["application/drafting","drw"],["application/dsptype","tsp"],["application/dssc+der","dssc"],["application/dssc+xml","xdssc"],["application/dxf","dxf"],["application/ecmascript",["js","es"]],["application/emma+xml","emma"],["application/envoy","evy"],["application/epub+zip","epub"],["application/excel",["xls","xl","xla","xlb","xlc","xld","xlk","xll","xlm","xlt","xlv","xlw"]],["application/exi","exi"],["application/font-tdpfr","pfr"],["application/fractals","fif"],["application/freeloader","frl"],["application/futuresplash","spl"],["application/geo+json","geojson"],["application/gnutar","tgz"],["application/groupwise","vew"],["application/hlp","hlp"],["application/hta","hta"],["application/hyperstudio","stk"],["application/i-deas","unv"],["application/iges",["iges","igs"]],["application/inf","inf"],["application/internet-property-stream","acx"],["application/ipfix","ipfix"],["application/java","class"],["application/java-archive","jar"],["application/java-byte-code","class"],["application/java-serialized-object","ser"],["application/java-vm","class"],["application/javascript","js"],["application/json","json"],["application/lha","lha"],["application/lzx","lzx"],["application/mac-binary","bin"],["application/mac-binhex","hqx"],["application/mac-binhex40","hqx"],["application/mac-compactpro","cpt"],["application/macbinary","bin"],["application/mads+xml","mads"],["application/marc","mrc"],["application/marcxml+xml","mrcx"],["application/mathematica","ma"],["application/mathml+xml","mathml"],["application/mbedlet","mbd"],["application/mbox","mbox"],["application/mcad","mcd"],["application/mediaservercontrol+xml","mscml"],["application/metalink4+xml","meta4"],["application/mets+xml","mets"],["application/mime","aps"],["application/mods+xml","mods"],["application/mp21","m21"],["application/mp4","mp4"],["application/mspowerpoint",["ppt","pot","pps","ppz"]],["application/msword",["doc","dot","w6w","wiz","word"]],["application/mswrite","wri"],["application/mxf","mxf"],["application/netmc","mcp"],["application/octet-stream",["*"]],["application/oda","oda"],["application/oebps-package+xml","opf"],["application/ogg","ogx"],["application/olescript","axs"],["application/onenote","onetoc"],["application/patch-ops-error+xml","xer"],["application/pdf","pdf"],["application/pgp-encrypted","asc"],["application/pgp-signature","pgp"],["application/pics-rules","prf"],["application/pkcs-12","p12"],["application/pkcs-crl","crl"],["application/pkcs10","p10"],["application/pkcs7-mime",["p7c","p7m"]],["application/pkcs7-signature","p7s"],["application/pkcs8","p8"],["application/pkix-attr-cert","ac"],["application/pkix-cert",["cer","crt"]],["application/pkix-crl","crl"],["application/pkix-pkipath","pkipath"],["application/pkixcmp","pki"],["application/plain","text"],["application/pls+xml","pls"],["application/postscript",["ps","ai","eps"]],["application/powerpoint","ppt"],["application/pro_eng",["part","prt"]],["application/prs.cww","cww"],["application/pskc+xml","pskcxml"],["application/rdf+xml","rdf"],["application/reginfo+xml","rif"],["application/relax-ng-compact-syntax","rnc"],["application/resource-lists+xml","rl"],["application/resource-lists-diff+xml","rld"],["application/ringing-tones","rng"],["application/rls-services+xml","rs"],["application/rsd+xml","rsd"],["application/rss+xml","xml"],["application/rtf",["rtf","rtx"]],["application/sbml+xml","sbml"],["application/scvp-cv-request","scq"],["application/scvp-cv-response","scs"],["application/scvp-vp-request","spq"],["application/scvp-vp-response","spp"],["application/sdp","sdp"],["application/sea","sea"],["application/set","set"],["application/set-payment-initiation","setpay"],["application/set-registration-initiation","setreg"],["application/shf+xml","shf"],["application/sla","stl"],["application/smil",["smi","smil"]],["application/smil+xml","smi"],["application/solids","sol"],["application/sounder","sdr"],["application/sparql-query","rq"],["application/sparql-results+xml","srx"],["application/srgs","gram"],["application/srgs+xml","grxml"],["application/sru+xml","sru"],["application/ssml+xml","ssml"],["application/step",["step","stp"]],["application/streamingmedia","ssm"],["application/tei+xml","tei"],["application/thraud+xml","tfi"],["application/timestamped-data","tsd"],["application/toolbook","tbk"],["application/vda","vda"],["application/vnd.3gpp.pic-bw-large","plb"],["application/vnd.3gpp.pic-bw-small","psb"],["application/vnd.3gpp.pic-bw-var","pvb"],["application/vnd.3gpp2.tcap","tcap"],["application/vnd.3m.post-it-notes","pwn"],["application/vnd.accpac.simply.aso","aso"],["application/vnd.accpac.simply.imp","imp"],["application/vnd.acucobol","acu"],["application/vnd.acucorp","atc"],["application/vnd.adobe.air-application-installer-package+zip","air"],["application/vnd.adobe.fxp","fxp"],["application/vnd.adobe.xdp+xml","xdp"],["application/vnd.adobe.xfdf","xfdf"],["application/vnd.ahead.space","ahead"],["application/vnd.airzip.filesecure.azf","azf"],["application/vnd.airzip.filesecure.azs","azs"],["application/vnd.amazon.ebook","azw"],["application/vnd.americandynamics.acc","acc"],["application/vnd.amiga.ami","ami"],["application/vnd.android.package-archive","apk"],["application/vnd.anser-web-certificate-issue-initiation","cii"],["application/vnd.anser-web-funds-transfer-initiation","fti"],["application/vnd.antix.game-component","atx"],["application/vnd.apple.installer+xml","mpkg"],["application/vnd.apple.mpegurl","m3u8"],["application/vnd.aristanetworks.swi","swi"],["application/vnd.audiograph","aep"],["application/vnd.blueice.multipass","mpm"],["application/vnd.bmi","bmi"],["application/vnd.businessobjects","rep"],["application/vnd.chemdraw+xml","cdxml"],["application/vnd.chipnuts.karaoke-mmd","mmd"],["application/vnd.cinderella","cdy"],["application/vnd.claymore","cla"],["application/vnd.cloanto.rp9","rp9"],["application/vnd.clonk.c4group","c4g"],["application/vnd.cluetrust.cartomobile-config","c11amc"],["application/vnd.cluetrust.cartomobile-config-pkg","c11amz"],["application/vnd.commonspace","csp"],["application/vnd.contact.cmsg","cdbcmsg"],["application/vnd.cosmocaller","cmc"],["application/vnd.crick.clicker","clkx"],["application/vnd.crick.clicker.keyboard","clkk"],["application/vnd.crick.clicker.palette","clkp"],["application/vnd.crick.clicker.template","clkt"],["application/vnd.crick.clicker.wordbank","clkw"],["application/vnd.criticaltools.wbs+xml","wbs"],["application/vnd.ctc-posml","pml"],["application/vnd.cups-ppd","ppd"],["application/vnd.curl.car","car"],["application/vnd.curl.pcurl","pcurl"],["application/vnd.data-vision.rdz","rdz"],["application/vnd.denovo.fcselayout-link","fe_launch"],["application/vnd.dna","dna"],["application/vnd.dolby.mlp","mlp"],["application/vnd.dpgraph","dpg"],["application/vnd.dreamfactory","dfac"],["application/vnd.dvb.ait","ait"],["application/vnd.dvb.service","svc"],["application/vnd.dynageo","geo"],["application/vnd.ecowin.chart","mag"],["application/vnd.enliven","nml"],["application/vnd.epson.esf","esf"],["application/vnd.epson.msf","msf"],["application/vnd.epson.quickanime","qam"],["application/vnd.epson.salt","slt"],["application/vnd.epson.ssf","ssf"],["application/vnd.eszigno3+xml","es3"],["application/vnd.ezpix-album","ez2"],["application/vnd.ezpix-package","ez3"],["application/vnd.fdf","fdf"],["application/vnd.fdsn.seed","seed"],["application/vnd.flographit","gph"],["application/vnd.fluxtime.clip","ftc"],["application/vnd.framemaker","fm"],["application/vnd.frogans.fnc","fnc"],["application/vnd.frogans.ltf","ltf"],["application/vnd.fsc.weblaunch","fsc"],["application/vnd.fujitsu.oasys","oas"],["application/vnd.fujitsu.oasys2","oa2"],["application/vnd.fujitsu.oasys3","oa3"],["application/vnd.fujitsu.oasysgp","fg5"],["application/vnd.fujitsu.oasysprs","bh2"],["application/vnd.fujixerox.ddd","ddd"],["application/vnd.fujixerox.docuworks","xdw"],["application/vnd.fujixerox.docuworks.binder","xbd"],["application/vnd.fuzzysheet","fzs"],["application/vnd.genomatix.tuxedo","txd"],["application/vnd.geogebra.file","ggb"],["application/vnd.geogebra.tool","ggt"],["application/vnd.geometry-explorer","gex"],["application/vnd.geonext","gxt"],["application/vnd.geoplan","g2w"],["application/vnd.geospace","g3w"],["application/vnd.gmx","gmx"],["application/vnd.google-earth.kml+xml","kml"],["application/vnd.google-earth.kmz","kmz"],["application/vnd.grafeq","gqf"],["application/vnd.groove-account","gac"],["application/vnd.groove-help","ghf"],["application/vnd.groove-identity-message","gim"],["application/vnd.groove-injector","grv"],["application/vnd.groove-tool-message","gtm"],["application/vnd.groove-tool-template","tpl"],["application/vnd.groove-vcard","vcg"],["application/vnd.hal+xml","hal"],["application/vnd.handheld-entertainment+xml","zmm"],["application/vnd.hbci","hbci"],["application/vnd.hhe.lesson-player","les"],["application/vnd.hp-hpgl",["hgl","hpg","hpgl"]],["application/vnd.hp-hpid","hpid"],["application/vnd.hp-hps","hps"],["application/vnd.hp-jlyt","jlt"],["application/vnd.hp-pcl","pcl"],["application/vnd.hp-pclxl","pclxl"],["application/vnd.hydrostatix.sof-data","sfd-hdstx"],["application/vnd.hzn-3d-crossword","x3d"],["application/vnd.ibm.minipay","mpy"],["application/vnd.ibm.modcap","afp"],["application/vnd.ibm.rights-management","irm"],["application/vnd.ibm.secure-container","sc"],["application/vnd.iccprofile","icc"],["application/vnd.igloader","igl"],["application/vnd.immervision-ivp","ivp"],["application/vnd.immervision-ivu","ivu"],["application/vnd.insors.igm","igm"],["application/vnd.intercon.formnet","xpw"],["application/vnd.intergeo","i2g"],["application/vnd.intu.qbo","qbo"],["application/vnd.intu.qfx","qfx"],["application/vnd.ipunplugged.rcprofile","rcprofile"],["application/vnd.irepository.package+xml","irp"],["application/vnd.is-xpr","xpr"],["application/vnd.isac.fcs","fcs"],["application/vnd.jam","jam"],["application/vnd.jcp.javame.midlet-rms","rms"],["application/vnd.jisp","jisp"],["application/vnd.joost.joda-archive","joda"],["application/vnd.kahootz","ktz"],["application/vnd.kde.karbon","karbon"],["application/vnd.kde.kchart","chrt"],["application/vnd.kde.kformula","kfo"],["application/vnd.kde.kivio","flw"],["application/vnd.kde.kontour","kon"],["application/vnd.kde.kpresenter","kpr"],["application/vnd.kde.kspread","ksp"],["application/vnd.kde.kword","kwd"],["application/vnd.kenameaapp","htke"],["application/vnd.kidspiration","kia"],["application/vnd.kinar","kne"],["application/vnd.koan","skp"],["application/vnd.kodak-descriptor","sse"],["application/vnd.las.las+xml","lasxml"],["application/vnd.llamagraphics.life-balance.desktop","lbd"],["application/vnd.llamagraphics.life-balance.exchange+xml","lbe"],["application/vnd.lotus-1-2-3","123"],["application/vnd.lotus-approach","apr"],["application/vnd.lotus-freelance","pre"],["application/vnd.lotus-notes","nsf"],["application/vnd.lotus-organizer","org"],["application/vnd.lotus-screencam","scm"],["application/vnd.lotus-wordpro","lwp"],["application/vnd.macports.portpkg","portpkg"],["application/vnd.mcd","mcd"],["application/vnd.medcalcdata","mc1"],["application/vnd.mediastation.cdkey","cdkey"],["application/vnd.mfer","mwf"],["application/vnd.mfmp","mfm"],["application/vnd.micrografx.flo","flo"],["application/vnd.micrografx.igx","igx"],["application/vnd.mif","mif"],["application/vnd.mobius.daf","daf"],["application/vnd.mobius.dis","dis"],["application/vnd.mobius.mbk","mbk"],["application/vnd.mobius.mqy","mqy"],["application/vnd.mobius.msl","msl"],["application/vnd.mobius.plc","plc"],["application/vnd.mobius.txf","txf"],["application/vnd.mophun.application","mpn"],["application/vnd.mophun.certificate","mpc"],["application/vnd.mozilla.xul+xml","xul"],["application/vnd.ms-artgalry","cil"],["application/vnd.ms-cab-compressed","cab"],["application/vnd.ms-excel",["xls","xla","xlc","xlm","xlt","xlw","xlb","xll"]],["application/vnd.ms-excel.addin.macroenabled.12","xlam"],["application/vnd.ms-excel.sheet.binary.macroenabled.12","xlsb"],["application/vnd.ms-excel.sheet.macroenabled.12","xlsm"],["application/vnd.ms-excel.template.macroenabled.12","xltm"],["application/vnd.ms-fontobject","eot"],["application/vnd.ms-htmlhelp","chm"],["application/vnd.ms-ims","ims"],["application/vnd.ms-lrm","lrm"],["application/vnd.ms-officetheme","thmx"],["application/vnd.ms-outlook","msg"],["application/vnd.ms-pki.certstore","sst"],["application/vnd.ms-pki.pko","pko"],["application/vnd.ms-pki.seccat","cat"],["application/vnd.ms-pki.stl","stl"],["application/vnd.ms-pkicertstore","sst"],["application/vnd.ms-pkiseccat","cat"],["application/vnd.ms-pkistl","stl"],["application/vnd.ms-powerpoint",["ppt","pot","pps","ppa","pwz"]],["application/vnd.ms-powerpoint.addin.macroenabled.12","ppam"],["application/vnd.ms-powerpoint.presentation.macroenabled.12","pptm"],["application/vnd.ms-powerpoint.slide.macroenabled.12","sldm"],["application/vnd.ms-powerpoint.slideshow.macroenabled.12","ppsm"],["application/vnd.ms-powerpoint.template.macroenabled.12","potm"],["application/vnd.ms-project","mpp"],["application/vnd.ms-word.document.macroenabled.12","docm"],["application/vnd.ms-word.template.macroenabled.12","dotm"],["application/vnd.ms-works",["wks","wcm","wdb","wps"]],["application/vnd.ms-wpl","wpl"],["application/vnd.ms-xpsdocument","xps"],["application/vnd.mseq","mseq"],["application/vnd.musician","mus"],["application/vnd.muvee.style","msty"],["application/vnd.neurolanguage.nlu","nlu"],["application/vnd.noblenet-directory","nnd"],["application/vnd.noblenet-sealer","nns"],["application/vnd.noblenet-web","nnw"],["application/vnd.nokia.configuration-message","ncm"],["application/vnd.nokia.n-gage.data","ngdat"],["application/vnd.nokia.n-gage.symbian.install","n-gage"],["application/vnd.nokia.radio-preset","rpst"],["application/vnd.nokia.radio-presets","rpss"],["application/vnd.nokia.ringing-tone","rng"],["application/vnd.novadigm.edm","edm"],["application/vnd.novadigm.edx","edx"],["application/vnd.novadigm.ext","ext"],["application/vnd.oasis.opendocument.chart","odc"],["application/vnd.oasis.opendocument.chart-template","otc"],["application/vnd.oasis.opendocument.database","odb"],["application/vnd.oasis.opendocument.formula","odf"],["application/vnd.oasis.opendocument.formula-template","odft"],["application/vnd.oasis.opendocument.graphics","odg"],["application/vnd.oasis.opendocument.graphics-template","otg"],["application/vnd.oasis.opendocument.image","odi"],["application/vnd.oasis.opendocument.image-template","oti"],["application/vnd.oasis.opendocument.presentation","odp"],["application/vnd.oasis.opendocument.presentation-template","otp"],["application/vnd.oasis.opendocument.spreadsheet","ods"],["application/vnd.oasis.opendocument.spreadsheet-template","ots"],["application/vnd.oasis.opendocument.text","odt"],["application/vnd.oasis.opendocument.text-master","odm"],["application/vnd.oasis.opendocument.text-template","ott"],["application/vnd.oasis.opendocument.text-web","oth"],["application/vnd.olpc-sugar","xo"],["application/vnd.oma.dd2+xml","dd2"],["application/vnd.openofficeorg.extension","oxt"],["application/vnd.openxmlformats-officedocument.presentationml.presentation","pptx"],["application/vnd.openxmlformats-officedocument.presentationml.slide","sldx"],["application/vnd.openxmlformats-officedocument.presentationml.slideshow","ppsx"],["application/vnd.openxmlformats-officedocument.presentationml.template","potx"],["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xlsx"],["application/vnd.openxmlformats-officedocument.spreadsheetml.template","xltx"],["application/vnd.openxmlformats-officedocument.wordprocessingml.document","docx"],["application/vnd.openxmlformats-officedocument.wordprocessingml.template","dotx"],["application/vnd.osgeo.mapguide.package","mgp"],["application/vnd.osgi.dp","dp"],["application/vnd.palm","pdb"],["application/vnd.pawaafile","paw"],["application/vnd.pg.format","str"],["application/vnd.pg.osasli","ei6"],["application/vnd.picsel","efif"],["application/vnd.pmi.widget","wg"],["application/vnd.pocketlearn","plf"],["application/vnd.powerbuilder6","pbd"],["application/vnd.previewsystems.box","box"],["application/vnd.proteus.magazine","mgz"],["application/vnd.publishare-delta-tree","qps"],["application/vnd.pvi.ptid1","ptid"],["application/vnd.quark.quarkxpress","qxd"],["application/vnd.realvnc.bed","bed"],["application/vnd.recordare.musicxml","mxl"],["application/vnd.recordare.musicxml+xml","musicxml"],["application/vnd.rig.cryptonote","cryptonote"],["application/vnd.rim.cod","cod"],["application/vnd.rn-realmedia","rm"],["application/vnd.rn-realplayer","rnx"],["application/vnd.route66.link66+xml","link66"],["application/vnd.sailingtracker.track","st"],["application/vnd.seemail","see"],["application/vnd.sema","sema"],["application/vnd.semd","semd"],["application/vnd.semf","semf"],["application/vnd.shana.informed.formdata","ifm"],["application/vnd.shana.informed.formtemplate","itp"],["application/vnd.shana.informed.interchange","iif"],["application/vnd.shana.informed.package","ipk"],["application/vnd.simtech-mindmapper","twd"],["application/vnd.smaf","mmf"],["application/vnd.smart.teacher","teacher"],["application/vnd.solent.sdkm+xml","sdkm"],["application/vnd.spotfire.dxp","dxp"],["application/vnd.spotfire.sfs","sfs"],["application/vnd.stardivision.calc","sdc"],["application/vnd.stardivision.draw","sda"],["application/vnd.stardivision.impress","sdd"],["application/vnd.stardivision.math","smf"],["application/vnd.stardivision.writer","sdw"],["application/vnd.stardivision.writer-global","sgl"],["application/vnd.stepmania.stepchart","sm"],["application/vnd.sun.xml.calc","sxc"],["application/vnd.sun.xml.calc.template","stc"],["application/vnd.sun.xml.draw","sxd"],["application/vnd.sun.xml.draw.template","std"],["application/vnd.sun.xml.impress","sxi"],["application/vnd.sun.xml.impress.template","sti"],["application/vnd.sun.xml.math","sxm"],["application/vnd.sun.xml.writer","sxw"],["application/vnd.sun.xml.writer.global","sxg"],["application/vnd.sun.xml.writer.template","stw"],["application/vnd.sus-calendar","sus"],["application/vnd.svd","svd"],["application/vnd.symbian.install","sis"],["application/vnd.syncml+xml","xsm"],["application/vnd.syncml.dm+wbxml","bdm"],["application/vnd.syncml.dm+xml","xdm"],["application/vnd.tao.intent-module-archive","tao"],["application/vnd.tmobile-livetv","tmo"],["application/vnd.trid.tpt","tpt"],["application/vnd.triscape.mxs","mxs"],["application/vnd.trueapp","tra"],["application/vnd.ufdl","ufd"],["application/vnd.uiq.theme","utz"],["application/vnd.umajin","umj"],["application/vnd.unity","unityweb"],["application/vnd.uoml+xml","uoml"],["application/vnd.vcx","vcx"],["application/vnd.visio","vsd"],["application/vnd.visionary","vis"],["application/vnd.vsf","vsf"],["application/vnd.wap.wbxml","wbxml"],["application/vnd.wap.wmlc","wmlc"],["application/vnd.wap.wmlscriptc","wmlsc"],["application/vnd.webturbo","wtb"],["application/vnd.wolfram.player","nbp"],["application/vnd.wordperfect","wpd"],["application/vnd.wqd","wqd"],["application/vnd.wt.stf","stf"],["application/vnd.xara",["web","xar"]],["application/vnd.xfdl","xfdl"],["application/vnd.yamaha.hv-dic","hvd"],["application/vnd.yamaha.hv-script","hvs"],["application/vnd.yamaha.hv-voice","hvp"],["application/vnd.yamaha.openscoreformat","osf"],["application/vnd.yamaha.openscoreformat.osfpvg+xml","osfpvg"],["application/vnd.yamaha.smaf-audio","saf"],["application/vnd.yamaha.smaf-phrase","spf"],["application/vnd.yellowriver-custom-menu","cmp"],["application/vnd.zul","zir"],["application/vnd.zzazz.deck+xml","zaz"],["application/vocaltec-media-desc","vmd"],["application/vocaltec-media-file","vmf"],["application/voicexml+xml","vxml"],["application/widget","wgt"],["application/winhlp","hlp"],["application/wordperfect",["wp","wp5","wp6","wpd"]],["application/wordperfect6.0",["w60","wp5"]],["application/wordperfect6.1","w61"],["application/wsdl+xml","wsdl"],["application/wspolicy+xml","wspolicy"],["application/x-123","wk1"],["application/x-7z-compressed","7z"],["application/x-abiword","abw"],["application/x-ace-compressed","ace"],["application/x-aim","aim"],["application/x-authorware-bin","aab"],["application/x-authorware-map","aam"],["application/x-authorware-seg","aas"],["application/x-bcpio","bcpio"],["application/x-binary","bin"],["application/x-binhex40","hqx"],["application/x-bittorrent","torrent"],["application/x-bsh",["bsh","sh","shar"]],["application/x-bytecode.elisp","elc"],["application/x-bytecode.python","pyc"],["application/x-bzip","bz"],["application/x-bzip2",["boz","bz2"]],["application/x-cdf","cdf"],["application/x-cdlink","vcd"],["application/x-chat",["cha","chat"]],["application/x-chess-pgn","pgn"],["application/x-cmu-raster","ras"],["application/x-cocoa","cco"],["application/x-compactpro","cpt"],["application/x-compress","z"],["application/x-compressed",["tgz","gz","z","zip"]],["application/x-conference","nsc"],["application/x-cpio","cpio"],["application/x-cpt","cpt"],["application/x-csh","csh"],["application/x-debian-package","deb"],["application/x-deepv","deepv"],["application/x-director",["dir","dcr","dxr"]],["application/x-doom","wad"],["application/x-dtbncx+xml","ncx"],["application/x-dtbook+xml","dtb"],["application/x-dtbresource+xml","res"],["application/x-dvi","dvi"],["application/x-elc","elc"],["application/x-envoy",["env","evy"]],["application/x-esrehber","es"],["application/x-excel",["xls","xla","xlb","xlc","xld","xlk","xll","xlm","xlt","xlv","xlw"]],["application/x-font-bdf","bdf"],["application/x-font-ghostscript","gsf"],["application/x-font-linux-psf","psf"],["application/x-font-otf","otf"],["application/x-font-pcf","pcf"],["application/x-font-snf","snf"],["application/x-font-ttf","ttf"],["application/x-font-type1","pfa"],["application/x-font-woff","woff"],["application/x-frame","mif"],["application/x-freelance","pre"],["application/x-futuresplash","spl"],["application/x-gnumeric","gnumeric"],["application/x-gsp","gsp"],["application/x-gss","gss"],["application/x-gtar","gtar"],["application/x-gzip",["gz","gzip"]],["application/x-hdf","hdf"],["application/x-helpfile",["help","hlp"]],["application/x-httpd-imap","imap"],["application/x-ima","ima"],["application/x-internet-signup",["ins","isp"]],["application/x-internett-signup","ins"],["application/x-inventor","iv"],["application/x-ip2","ip"],["application/x-iphone","iii"],["application/x-java-class","class"],["application/x-java-commerce","jcm"],["application/x-java-jnlp-file","jnlp"],["application/x-javascript","js"],["application/x-koan",["skd","skm","skp","skt"]],["application/x-ksh","ksh"],["application/x-latex",["latex","ltx"]],["application/x-lha","lha"],["application/x-lisp","lsp"],["application/x-livescreen","ivy"],["application/x-lotus","wq1"],["application/x-lotusscreencam","scm"],["application/x-lzh","lzh"],["application/x-lzx","lzx"],["application/x-mac-binhex40","hqx"],["application/x-macbinary","bin"],["application/x-magic-cap-package-1.0","mc$"],["application/x-mathcad","mcd"],["application/x-meme","mm"],["application/x-midi",["mid","midi"]],["application/x-mif","mif"],["application/x-mix-transfer","nix"],["application/x-mobipocket-ebook","prc"],["application/x-mplayer2","asx"],["application/x-ms-application","application"],["application/x-ms-wmd","wmd"],["application/x-ms-wmz","wmz"],["application/x-ms-xbap","xbap"],["application/x-msaccess","mdb"],["application/x-msbinder","obd"],["application/x-mscardfile","crd"],["application/x-msclip","clp"],["application/x-msdownload",["exe","dll"]],["application/x-msexcel",["xls","xla","xlw"]],["application/x-msmediaview",["mvb","m13","m14"]],["application/x-msmetafile","wmf"],["application/x-msmoney","mny"],["application/x-mspowerpoint","ppt"],["application/x-mspublisher","pub"],["application/x-msschedule","scd"],["application/x-msterminal","trm"],["application/x-mswrite","wri"],["application/x-navi-animation","ani"],["application/x-navidoc","nvd"],["application/x-navimap","map"],["application/x-navistyle","stl"],["application/x-netcdf",["cdf","nc"]],["application/x-newton-compatible-pkg","pkg"],["application/x-nokia-9000-communicator-add-on-software","aos"],["application/x-omc","omc"],["application/x-omcdatamaker","omcd"],["application/x-omcregerator","omcr"],["application/x-pagemaker",["pm4","pm5"]],["application/x-pcl","pcl"],["application/x-perfmon",["pma","pmc","pml","pmr","pmw"]],["application/x-pixclscript","plx"],["application/x-pkcs10","p10"],["application/x-pkcs12",["p12","pfx"]],["application/x-pkcs7-certificates",["p7b","spc"]],["application/x-pkcs7-certreqresp","p7r"],["application/x-pkcs7-mime",["p7m","p7c"]],["application/x-pkcs7-signature",["p7s","p7a"]],["application/x-pointplus","css"],["application/x-portable-anymap","pnm"],["application/x-project",["mpc","mpt","mpv","mpx"]],["application/x-qpro","wb1"],["application/x-rar-compressed","rar"],["application/x-rtf","rtf"],["application/x-sdp","sdp"],["application/x-sea","sea"],["application/x-seelogo","sl"],["application/x-sh","sh"],["application/x-shar",["shar","sh"]],["application/x-shockwave-flash","swf"],["application/x-silverlight-app","xap"],["application/x-sit","sit"],["application/x-sprite",["spr","sprite"]],["application/x-stuffit","sit"],["application/x-stuffitx","sitx"],["application/x-sv4cpio","sv4cpio"],["application/x-sv4crc","sv4crc"],["application/x-tar","tar"],["application/x-tbook",["sbk","tbk"]],["application/x-tcl","tcl"],["application/x-tex","tex"],["application/x-tex-tfm","tfm"],["application/x-texinfo",["texi","texinfo"]],["application/x-troff",["roff","t","tr"]],["application/x-troff-man","man"],["application/x-troff-me","me"],["application/x-troff-ms","ms"],["application/x-troff-msvideo","avi"],["application/x-ustar","ustar"],["application/x-visio",["vsd","vst","vsw"]],["application/x-vnd.audioexplosion.mzz","mzz"],["application/x-vnd.ls-xpix","xpix"],["application/x-vrml","vrml"],["application/x-wais-source",["src","wsrc"]],["application/x-winhelp","hlp"],["application/x-wintalk","wtk"],["application/x-world",["wrl","svr"]],["application/x-wpwin","wpd"],["application/x-wri","wri"],["application/x-x509-ca-cert",["cer","crt","der"]],["application/x-x509-user-cert","crt"],["application/x-xfig","fig"],["application/x-xpinstall","xpi"],["application/x-zip-compressed","zip"],["application/xcap-diff+xml","xdf"],["application/xenc+xml","xenc"],["application/xhtml+xml","xhtml"],["application/xml","xml"],["application/xml-dtd","dtd"],["application/xop+xml","xop"],["application/xslt+xml","xslt"],["application/xspf+xml","xspf"],["application/xv+xml","mxml"],["application/yang","yang"],["application/yin+xml","yin"],["application/ynd.ms-pkipko","pko"],["application/zip","zip"],["audio/adpcm","adp"],["audio/aiff",["aiff","aif","aifc"]],["audio/basic",["snd","au"]],["audio/it","it"],["audio/make",["funk","my","pfunk"]],["audio/make.my.funk","pfunk"],["audio/mid",["mid","rmi"]],["audio/midi",["midi","kar","mid"]],["audio/mod","mod"],["audio/mp4","mp4a"],["audio/mpeg",["mpga","mp3","m2a","mp2","mpa","mpg"]],["audio/mpeg3","mp3"],["audio/nspaudio",["la","lma"]],["audio/ogg","oga"],["audio/s3m","s3m"],["audio/tsp-audio","tsi"],["audio/tsplayer","tsp"],["audio/vnd.dece.audio","uva"],["audio/vnd.digital-winds","eol"],["audio/vnd.dra","dra"],["audio/vnd.dts","dts"],["audio/vnd.dts.hd","dtshd"],["audio/vnd.lucent.voice","lvp"],["audio/vnd.ms-playready.media.pya","pya"],["audio/vnd.nuera.ecelp4800","ecelp4800"],["audio/vnd.nuera.ecelp7470","ecelp7470"],["audio/vnd.nuera.ecelp9600","ecelp9600"],["audio/vnd.qcelp","qcp"],["audio/vnd.rip","rip"],["audio/voc","voc"],["audio/voxware","vox"],["audio/wav","wav"],["audio/webm","weba"],["audio/x-aac","aac"],["audio/x-adpcm","snd"],["audio/x-aiff",["aiff","aif","aifc"]],["audio/x-au","au"],["audio/x-gsm",["gsd","gsm"]],["audio/x-jam","jam"],["audio/x-liveaudio","lam"],["audio/x-mid",["mid","midi"]],["audio/x-midi",["midi","mid"]],["audio/x-mod","mod"],["audio/x-mpeg","mp2"],["audio/x-mpeg-3","mp3"],["audio/x-mpegurl","m3u"],["audio/x-mpequrl","m3u"],["audio/x-ms-wax","wax"],["audio/x-ms-wma","wma"],["audio/x-nspaudio",["la","lma"]],["audio/x-pn-realaudio",["ra","ram","rm","rmm","rmp"]],["audio/x-pn-realaudio-plugin",["ra","rmp","rpm"]],["audio/x-psid","sid"],["audio/x-realaudio","ra"],["audio/x-twinvq","vqf"],["audio/x-twinvq-plugin",["vqe","vql"]],["audio/x-vnd.audioexplosion.mjuicemediafile","mjf"],["audio/x-voc","voc"],["audio/x-wav","wav"],["audio/xm","xm"],["chemical/x-cdx","cdx"],["chemical/x-cif","cif"],["chemical/x-cmdf","cmdf"],["chemical/x-cml","cml"],["chemical/x-csml","csml"],["chemical/x-pdb",["pdb","xyz"]],["chemical/x-xyz","xyz"],["drawing/x-dwf","dwf"],["i-world/i-vrml","ivr"],["image/bmp",["bmp","bm"]],["image/cgm","cgm"],["image/cis-cod","cod"],["image/cmu-raster",["ras","rast"]],["image/fif","fif"],["image/florian",["flo","turbot"]],["image/g3fax","g3"],["image/gif","gif"],["image/ief",["ief","iefs"]],["image/jpeg",["jpeg","jpe","jpg","jfif","jfif-tbnl"]],["image/jutvision","jut"],["image/ktx","ktx"],["image/naplps",["nap","naplps"]],["image/pict",["pic","pict"]],["image/pipeg","jfif"],["image/pjpeg",["jfif","jpe","jpeg","jpg"]],["image/png",["png","x-png"]],["image/prs.btif","btif"],["image/svg+xml","svg"],["image/tiff",["tif","tiff"]],["image/vasa","mcf"],["image/vnd.adobe.photoshop","psd"],["image/vnd.dece.graphic","uvi"],["image/vnd.djvu","djvu"],["image/vnd.dvb.subtitle","sub"],["image/vnd.dwg",["dwg","dxf","svf"]],["image/vnd.dxf","dxf"],["image/vnd.fastbidsheet","fbs"],["image/vnd.fpx","fpx"],["image/vnd.fst","fst"],["image/vnd.fujixerox.edmics-mmr","mmr"],["image/vnd.fujixerox.edmics-rlc","rlc"],["image/vnd.ms-modi","mdi"],["image/vnd.net-fpx",["fpx","npx"]],["image/vnd.rn-realflash","rf"],["image/vnd.rn-realpix","rp"],["image/vnd.wap.wbmp","wbmp"],["image/vnd.xiff","xif"],["image/webp","webp"],["image/x-cmu-raster","ras"],["image/x-cmx","cmx"],["image/x-dwg",["dwg","dxf","svf"]],["image/x-freehand","fh"],["image/x-icon","ico"],["image/x-jg","art"],["image/x-jps","jps"],["image/x-niff",["niff","nif"]],["image/x-pcx","pcx"],["image/x-pict",["pct","pic"]],["image/x-portable-anymap","pnm"],["image/x-portable-bitmap","pbm"],["image/x-portable-graymap","pgm"],["image/x-portable-greymap","pgm"],["image/x-portable-pixmap","ppm"],["image/x-quicktime",["qif","qti","qtif"]],["image/x-rgb","rgb"],["image/x-tiff",["tif","tiff"]],["image/x-windows-bmp","bmp"],["image/x-xbitmap","xbm"],["image/x-xbm","xbm"],["image/x-xpixmap",["xpm","pm"]],["image/x-xwd","xwd"],["image/x-xwindowdump","xwd"],["image/xbm","xbm"],["image/xpm","xpm"],["message/rfc822",["eml","mht","mhtml","nws","mime"]],["model/iges",["iges","igs"]],["model/mesh","msh"],["model/vnd.collada+xml","dae"],["model/vnd.dwf","dwf"],["model/vnd.gdl","gdl"],["model/vnd.gtw","gtw"],["model/vnd.mts","mts"],["model/vnd.vtu","vtu"],["model/vrml",["vrml","wrl","wrz"]],["model/x-pov","pov"],["multipart/x-gzip","gzip"],["multipart/x-ustar","ustar"],["multipart/x-zip","zip"],["music/crescendo",["mid","midi"]],["music/x-karaoke","kar"],["paleovu/x-pv","pvu"],["text/asp","asp"],["text/calendar","ics"],["text/css","css"],["text/csv","csv"],["text/ecmascript","js"],["text/h323","323"],["text/html",["html","htm","stm","acgi","htmls","htx","shtml"]],["text/iuls","uls"],["text/javascript","js"],["text/mcf","mcf"],["text/n3","n3"],["text/pascal","pas"],["text/plain",["txt","bas","c","h","c++","cc","com","conf","cxx","def","f","f90","for","g","hh","idc","jav","java","list","log","lst","m","mar","pl","sdml","text"]],["text/plain-bas","par"],["text/prs.lines.tag","dsc"],["text/richtext",["rtx","rt","rtf"]],["text/scriplet","wsc"],["text/scriptlet","sct"],["text/sgml",["sgm","sgml"]],["text/tab-separated-values","tsv"],["text/troff","t"],["text/turtle","ttl"],["text/uri-list",["uni","unis","uri","uris"]],["text/vnd.abc","abc"],["text/vnd.curl","curl"],["text/vnd.curl.dcurl","dcurl"],["text/vnd.curl.mcurl","mcurl"],["text/vnd.curl.scurl","scurl"],["text/vnd.fly","fly"],["text/vnd.fmi.flexstor","flx"],["text/vnd.graphviz","gv"],["text/vnd.in3d.3dml","3dml"],["text/vnd.in3d.spot","spot"],["text/vnd.rn-realtext","rt"],["text/vnd.sun.j2me.app-descriptor","jad"],["text/vnd.wap.wml","wml"],["text/vnd.wap.wmlscript","wmls"],["text/webviewhtml","htt"],["text/x-asm",["asm","s"]],["text/x-audiosoft-intra","aip"],["text/x-c",["c","cc","cpp"]],["text/x-component","htc"],["text/x-fortran",["for","f","f77","f90"]],["text/x-h",["h","hh"]],["text/x-java-source",["java","jav"]],["text/x-java-source,java","java"],["text/x-la-asf","lsx"],["text/x-m","m"],["text/x-pascal","p"],["text/x-script","hlb"],["text/x-script.csh","csh"],["text/x-script.elisp","el"],["text/x-script.guile","scm"],["text/x-script.ksh","ksh"],["text/x-script.lisp","lsp"],["text/x-script.perl","pl"],["text/x-script.perl-module","pm"],["text/x-script.phyton","py"],["text/x-script.rexx","rexx"],["text/x-script.scheme","scm"],["text/x-script.sh","sh"],["text/x-script.tcl","tcl"],["text/x-script.tcsh","tcsh"],["text/x-script.zsh","zsh"],["text/x-server-parsed-html",["shtml","ssi"]],["text/x-setext","etx"],["text/x-sgml",["sgm","sgml"]],["text/x-speech",["spc","talk"]],["text/x-uil","uil"],["text/x-uuencode",["uu","uue"]],["text/x-vcalendar","vcs"],["text/x-vcard","vcf"],["text/xml","xml"],["video/3gpp","3gp"],["video/3gpp2","3g2"],["video/animaflex","afl"],["video/avi","avi"],["video/avs-video","avs"],["video/dl","dl"],["video/fli","fli"],["video/gl","gl"],["video/h261","h261"],["video/h263","h263"],["video/h264","h264"],["video/jpeg","jpgv"],["video/jpm","jpm"],["video/mj2","mj2"],["video/mp4","mp4"],["video/mpeg",["mpeg","mp2","mpa","mpe","mpg","mpv2","m1v","m2v","mp3"]],["video/msvideo","avi"],["video/ogg","ogv"],["video/quicktime",["mov","qt","moov"]],["video/vdo","vdo"],["video/vivo",["viv","vivo"]],["video/vnd.dece.hd","uvh"],["video/vnd.dece.mobile","uvm"],["video/vnd.dece.pd","uvp"],["video/vnd.dece.sd","uvs"],["video/vnd.dece.video","uvv"],["video/vnd.fvt","fvt"],["video/vnd.mpegurl","mxu"],["video/vnd.ms-playready.media.pyv","pyv"],["video/vnd.rn-realvideo","rv"],["video/vnd.uvvu.mp4","uvu"],["video/vnd.vivo",["viv","vivo"]],["video/vosaic","vos"],["video/webm","webm"],["video/x-amt-demorun","xdr"],["video/x-amt-showrun","xsr"],["video/x-atomic3d-feature","fmf"],["video/x-dl","dl"],["video/x-dv",["dif","dv"]],["video/x-f4v","f4v"],["video/x-fli","fli"],["video/x-flv","flv"],["video/x-gl","gl"],["video/x-isvideo","isu"],["video/x-la-asf",["lsf","lsx"]],["video/x-m4v","m4v"],["video/x-motion-jpeg","mjpg"],["video/x-mpeg",["mp3","mp2"]],["video/x-mpeq2a","mp2"],["video/x-ms-asf",["asf","asr","asx"]],["video/x-ms-asf-plugin","asx"],["video/x-ms-wm","wm"],["video/x-ms-wmv","wmv"],["video/x-ms-wmx","wmx"],["video/x-ms-wvx","wvx"],["video/x-msvideo","avi"],["video/x-qtc","qtc"],["video/x-scm","scm"],["video/x-sgi-movie",["movie","mv"]],["windows/metafile","wmf"],["www/mime","mime"],["x-conference/x-cooltalk","ice"],["x-music/x-midi",["mid","midi"]],["x-world/x-3dmf",["3dm","3dmf","qd3","qd3d"]],["x-world/x-svr","svr"],["x-world/x-vrml",["flr","vrml","wrl","wrz","xaf","xof"]],["x-world/x-vrt","vrt"],["xgl/drawing","xgz"],["xgl/movie","xmz"]]),extensions=new Map([["123","application/vnd.lotus-1-2-3"],["323","text/h323"],["*","application/octet-stream"],["3dm","x-world/x-3dmf"],["3dmf","x-world/x-3dmf"],["3dml","text/vnd.in3d.3dml"],["3g2","video/3gpp2"],["3gp","video/3gpp"],["7z","application/x-7z-compressed"],["a","application/octet-stream"],["aab","application/x-authorware-bin"],["aac","audio/x-aac"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abc","text/vnd.abc"],["abw","application/x-abiword"],["ac","application/pkix-attr-cert"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acgi","text/html"],["acu","application/vnd.acucobol"],["acx","application/internet-property-stream"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afl","video/animaflex"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/postscript"],["aif",["audio/aiff","audio/x-aiff"]],["aifc",["audio/aiff","audio/x-aiff"]],["aiff",["audio/aiff","audio/x-aiff"]],["aim","application/x-aim"],["aip","text/x-audiosoft-intra"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["ani","application/x-navi-animation"],["aos","application/x-nokia-9000-communicator-add-on-software"],["apk","application/vnd.android.package-archive"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["aps","application/mime"],["arc","application/octet-stream"],["arj",["application/arj","application/octet-stream"]],["art","image/x-jg"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asp","text/asp"],["asr","video/x-ms-asf"],["asx",["video/x-ms-asf","application/x-mplayer2","video/x-ms-asf-plugin"]],["atc","application/vnd.acucorp"],["atomcat","application/atomcat+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au",["audio/basic","audio/x-au"]],["avi",["video/avi","video/msvideo","application/x-troff-msvideo","video/x-msvideo"]],["avs","video/avs-video"],["aw","application/applixware"],["axs","application/olescript"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azw","application/vnd.amazon.ebook"],["bas","text/plain"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bed","application/vnd.realvnc.bed"],["bh2","application/vnd.fujitsu.oasysprs"],["bin",["application/octet-stream","application/mac-binary","application/macbinary","application/x-macbinary","application/x-binary"]],["bm","image/bmp"],["bmi","application/vnd.bmi"],["bmp",["image/bmp","image/x-windows-bmp"]],["boo","application/book"],["book","application/book"],["box","application/vnd.previewsystems.box"],["boz","application/x-bzip2"],["bsh","application/x-bsh"],["btif","image/prs.btif"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["c",["text/plain","text/x-c"]],["c++","text/plain"],["c11amc","application/vnd.cluetrust.cartomobile-config"],["c11amz","application/vnd.cluetrust.cartomobile-config-pkg"],["c4g","application/vnd.clonk.c4group"],["cab","application/vnd.ms-cab-compressed"],["car","application/vnd.curl.car"],["cat",["application/vnd.ms-pkiseccat","application/vnd.ms-pki.seccat"]],["cc",["text/plain","text/x-c"]],["ccad","application/clariscad"],["cco","application/x-cocoa"],["ccxml","application/ccxml+xml,"],["cdbcmsg","application/vnd.contact.cmsg"],["cdf",["application/cdf","application/x-cdf","application/x-netcdf"]],["cdkey","application/vnd.mediastation.cdkey"],["cdmia","application/cdmi-capability"],["cdmic","application/cdmi-container"],["cdmid","application/cdmi-domain"],["cdmio","application/cdmi-object"],["cdmiq","application/cdmi-queue"],["cdx","chemical/x-cdx"],["cdxml","application/vnd.chemdraw+xml"],["cdy","application/vnd.cinderella"],["cer",["application/pkix-cert","application/x-x509-ca-cert"]],["cgm","image/cgm"],["cha","application/x-chat"],["chat","application/x-chat"],["chm","application/vnd.ms-htmlhelp"],["chrt","application/vnd.kde.kchart"],["cif","chemical/x-cif"],["cii","application/vnd.anser-web-certificate-issue-initiation"],["cil","application/vnd.ms-artgalry"],["cla","application/vnd.claymore"],["class",["application/octet-stream","application/java","application/java-byte-code","application/java-vm","application/x-java-class"]],["clkk","application/vnd.crick.clicker.keyboard"],["clkp","application/vnd.crick.clicker.palette"],["clkt","application/vnd.crick.clicker.template"],["clkw","application/vnd.crick.clicker.wordbank"],["clkx","application/vnd.crick.clicker"],["clp","application/x-msclip"],["cmc","application/vnd.cosmocaller"],["cmdf","chemical/x-cmdf"],["cml","chemical/x-cml"],["cmp","application/vnd.yellowriver-custom-menu"],["cmx","image/x-cmx"],["cod",["image/cis-cod","application/vnd.rim.cod"]],["com",["application/octet-stream","text/plain"]],["conf","text/plain"],["cpio","application/x-cpio"],["cpp","text/x-c"],["cpt",["application/mac-compactpro","application/x-compactpro","application/x-cpt"]],["crd","application/x-mscardfile"],["crl",["application/pkix-crl","application/pkcs-crl"]],["crt",["application/pkix-cert","application/x-x509-user-cert","application/x-x509-ca-cert"]],["cryptonote","application/vnd.rig.cryptonote"],["csh",["text/x-script.csh","application/x-csh"]],["csml","chemical/x-csml"],["csp","application/vnd.commonspace"],["css",["text/css","application/x-pointplus"]],["csv","text/csv"],["cu","application/cu-seeme"],["curl","text/vnd.curl"],["cww","application/prs.cww"],["cxx","text/plain"],["dae","model/vnd.collada+xml"],["daf","application/vnd.mobius.daf"],["davmount","application/davmount+xml"],["dcr","application/x-director"],["dcurl","text/vnd.curl.dcurl"],["dd2","application/vnd.oma.dd2+xml"],["ddd","application/vnd.fujixerox.ddd"],["deb","application/x-debian-package"],["deepv","application/x-deepv"],["def","text/plain"],["der","application/x-x509-ca-cert"],["dfac","application/vnd.dreamfactory"],["dif","video/x-dv"],["dir","application/x-director"],["dis","application/vnd.mobius.dis"],["djvu","image/vnd.djvu"],["dl",["video/dl","video/x-dl"]],["dll","application/x-msdownload"],["dms","application/octet-stream"],["dna","application/vnd.dna"],["doc","application/msword"],["docm","application/vnd.ms-word.document.macroenabled.12"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["dot","application/msword"],["dotm","application/vnd.ms-word.template.macroenabled.12"],["dotx","application/vnd.openxmlformats-officedocument.wordprocessingml.template"],["dp",["application/commonground","application/vnd.osgi.dp"]],["dpg","application/vnd.dpgraph"],["dra","audio/vnd.dra"],["drw","application/drafting"],["dsc","text/prs.lines.tag"],["dssc","application/dssc+der"],["dtb","application/x-dtbook+xml"],["dtd","application/xml-dtd"],["dts","audio/vnd.dts"],["dtshd","audio/vnd.dts.hd"],["dump","application/octet-stream"],["dv","video/x-dv"],["dvi","application/x-dvi"],["dwf",["model/vnd.dwf","drawing/x-dwf"]],["dwg",["application/acad","image/vnd.dwg","image/x-dwg"]],["dxf",["application/dxf","image/vnd.dwg","image/vnd.dxf","image/x-dwg"]],["dxp","application/vnd.spotfire.dxp"],["dxr","application/x-director"],["ecelp4800","audio/vnd.nuera.ecelp4800"],["ecelp7470","audio/vnd.nuera.ecelp7470"],["ecelp9600","audio/vnd.nuera.ecelp9600"],["edm","application/vnd.novadigm.edm"],["edx","application/vnd.novadigm.edx"],["efif","application/vnd.picsel"],["ei6","application/vnd.pg.osasli"],["el","text/x-script.elisp"],["elc",["application/x-elc","application/x-bytecode.elisp"]],["eml","message/rfc822"],["emma","application/emma+xml"],["env","application/x-envoy"],["eol","audio/vnd.digital-winds"],["eot","application/vnd.ms-fontobject"],["eps","application/postscript"],["epub","application/epub+zip"],["es",["application/ecmascript","application/x-esrehber"]],["es3","application/vnd.eszigno3+xml"],["esf","application/vnd.epson.esf"],["etx","text/x-setext"],["evy",["application/envoy","application/x-envoy"]],["exe",["application/octet-stream","application/x-msdownload"]],["exi","application/exi"],["ext","application/vnd.novadigm.ext"],["ez2","application/vnd.ezpix-album"],["ez3","application/vnd.ezpix-package"],["f",["text/plain","text/x-fortran"]],["f4v","video/x-f4v"],["f77","text/x-fortran"],["f90",["text/plain","text/x-fortran"]],["fbs","image/vnd.fastbidsheet"],["fcs","application/vnd.isac.fcs"],["fdf","application/vnd.fdf"],["fe_launch","application/vnd.denovo.fcselayout-link"],["fg5","application/vnd.fujitsu.oasysgp"],["fh","image/x-freehand"],["fif",["application/fractals","image/fif"]],["fig","application/x-xfig"],["fli",["video/fli","video/x-fli"]],["flo",["image/florian","application/vnd.micrografx.flo"]],["flr","x-world/x-vrml"],["flv","video/x-flv"],["flw","application/vnd.kde.kivio"],["flx","text/vnd.fmi.flexstor"],["fly","text/vnd.fly"],["fm","application/vnd.framemaker"],["fmf","video/x-atomic3d-feature"],["fnc","application/vnd.frogans.fnc"],["for",["text/plain","text/x-fortran"]],["fpx",["image/vnd.fpx","image/vnd.net-fpx"]],["frl","application/freeloader"],["fsc","application/vnd.fsc.weblaunch"],["fst","image/vnd.fst"],["ftc","application/vnd.fluxtime.clip"],["fti","application/vnd.anser-web-funds-transfer-initiation"],["funk","audio/make"],["fvt","video/vnd.fvt"],["fxp","application/vnd.adobe.fxp"],["fzs","application/vnd.fuzzysheet"],["g","text/plain"],["g2w","application/vnd.geoplan"],["g3","image/g3fax"],["g3w","application/vnd.geospace"],["gac","application/vnd.groove-account"],["gdl","model/vnd.gdl"],["geo","application/vnd.dynageo"],["geojson","application/geo+json"],["gex","application/vnd.geometry-explorer"],["ggb","application/vnd.geogebra.file"],["ggt","application/vnd.geogebra.tool"],["ghf","application/vnd.groove-help"],["gif","image/gif"],["gim","application/vnd.groove-identity-message"],["gl",["video/gl","video/x-gl"]],["gmx","application/vnd.gmx"],["gnumeric","application/x-gnumeric"],["gph","application/vnd.flographit"],["gqf","application/vnd.grafeq"],["gram","application/srgs"],["grv","application/vnd.groove-injector"],["grxml","application/srgs+xml"],["gsd","audio/x-gsm"],["gsf","application/x-font-ghostscript"],["gsm","audio/x-gsm"],["gsp","application/x-gsp"],["gss","application/x-gss"],["gtar","application/x-gtar"],["gtm","application/vnd.groove-tool-message"],["gtw","model/vnd.gtw"],["gv","text/vnd.graphviz"],["gxt","application/vnd.geonext"],["gz",["application/x-gzip","application/x-compressed"]],["gzip",["multipart/x-gzip","application/x-gzip"]],["h",["text/plain","text/x-h"]],["h261","video/h261"],["h263","video/h263"],["h264","video/h264"],["hal","application/vnd.hal+xml"],["hbci","application/vnd.hbci"],["hdf","application/x-hdf"],["help","application/x-helpfile"],["hgl","application/vnd.hp-hpgl"],["hh",["text/plain","text/x-h"]],["hlb","text/x-script"],["hlp",["application/winhlp","application/hlp","application/x-helpfile","application/x-winhelp"]],["hpg","application/vnd.hp-hpgl"],["hpgl","application/vnd.hp-hpgl"],["hpid","application/vnd.hp-hpid"],["hps","application/vnd.hp-hps"],["hqx",["application/mac-binhex40","application/binhex","application/binhex4","application/mac-binhex","application/x-binhex40","application/x-mac-binhex40"]],["hta","application/hta"],["htc","text/x-component"],["htke","application/vnd.kenameaapp"],["htm","text/html"],["html","text/html"],["htmls","text/html"],["htt","text/webviewhtml"],["htx","text/html"],["hvd","application/vnd.yamaha.hv-dic"],["hvp","application/vnd.yamaha.hv-voice"],["hvs","application/vnd.yamaha.hv-script"],["i2g","application/vnd.intergeo"],["icc","application/vnd.iccprofile"],["ice","x-conference/x-cooltalk"],["ico","image/x-icon"],["ics","text/calendar"],["idc","text/plain"],["ief","image/ief"],["iefs","image/ief"],["ifm","application/vnd.shana.informed.formdata"],["iges",["application/iges","model/iges"]],["igl","application/vnd.igloader"],["igm","application/vnd.insors.igm"],["igs",["application/iges","model/iges"]],["igx","application/vnd.micrografx.igx"],["iif","application/vnd.shana.informed.interchange"],["iii","application/x-iphone"],["ima","application/x-ima"],["imap","application/x-httpd-imap"],["imp","application/vnd.accpac.simply.imp"],["ims","application/vnd.ms-ims"],["inf","application/inf"],["ins",["application/x-internet-signup","application/x-internett-signup"]],["ip","application/x-ip2"],["ipfix","application/ipfix"],["ipk","application/vnd.shana.informed.package"],["irm","application/vnd.ibm.rights-management"],["irp","application/vnd.irepository.package+xml"],["isp","application/x-internet-signup"],["isu","video/x-isvideo"],["it","audio/it"],["itp","application/vnd.shana.informed.formtemplate"],["iv","application/x-inventor"],["ivp","application/vnd.immervision-ivp"],["ivr","i-world/i-vrml"],["ivu","application/vnd.immervision-ivu"],["ivy","application/x-livescreen"],["jad","text/vnd.sun.j2me.app-descriptor"],["jam",["application/vnd.jam","audio/x-jam"]],["jar","application/java-archive"],["jav",["text/plain","text/x-java-source"]],["java",["text/plain","text/x-java-source,java","text/x-java-source"]],["jcm","application/x-java-commerce"],["jfif",["image/pipeg","image/jpeg","image/pjpeg"]],["jfif-tbnl","image/jpeg"],["jisp","application/vnd.jisp"],["jlt","application/vnd.hp-jlyt"],["jnlp","application/x-java-jnlp-file"],["joda","application/vnd.joost.joda-archive"],["jpe",["image/jpeg","image/pjpeg"]],["jpeg",["image/jpeg","image/pjpeg"]],["jpg",["image/jpeg","image/pjpeg"]],["jpgv","video/jpeg"],["jpm","video/jpm"],["jps","image/x-jps"],["js",["application/javascript","application/ecmascript","text/javascript","text/ecmascript","application/x-javascript"]],["json","application/json"],["jut","image/jutvision"],["kar",["audio/midi","music/x-karaoke"]],["karbon","application/vnd.kde.karbon"],["kfo","application/vnd.kde.kformula"],["kia","application/vnd.kidspiration"],["kml","application/vnd.google-earth.kml+xml"],["kmz","application/vnd.google-earth.kmz"],["kne","application/vnd.kinar"],["kon","application/vnd.kde.kontour"],["kpr","application/vnd.kde.kpresenter"],["ksh",["application/x-ksh","text/x-script.ksh"]],["ksp","application/vnd.kde.kspread"],["ktx","image/ktx"],["ktz","application/vnd.kahootz"],["kwd","application/vnd.kde.kword"],["la",["audio/nspaudio","audio/x-nspaudio"]],["lam","audio/x-liveaudio"],["lasxml","application/vnd.las.las+xml"],["latex","application/x-latex"],["lbd","application/vnd.llamagraphics.life-balance.desktop"],["lbe","application/vnd.llamagraphics.life-balance.exchange+xml"],["les","application/vnd.hhe.lesson-player"],["lha",["application/octet-stream","application/lha","application/x-lha"]],["lhx","application/octet-stream"],["link66","application/vnd.route66.link66+xml"],["list","text/plain"],["lma",["audio/nspaudio","audio/x-nspaudio"]],["log","text/plain"],["lrm","application/vnd.ms-lrm"],["lsf","video/x-la-asf"],["lsp",["application/x-lisp","text/x-script.lisp"]],["lst","text/plain"],["lsx",["video/x-la-asf","text/x-la-asf"]],["ltf","application/vnd.frogans.ltf"],["ltx","application/x-latex"],["lvp","audio/vnd.lucent.voice"],["lwp","application/vnd.lotus-wordpro"],["lzh",["application/octet-stream","application/x-lzh"]],["lzx",["application/lzx","application/octet-stream","application/x-lzx"]],["m",["text/plain","text/x-m"]],["m13","application/x-msmediaview"],["m14","application/x-msmediaview"],["m1v","video/mpeg"],["m21","application/mp21"],["m2a","audio/mpeg"],["m2v","video/mpeg"],["m3u",["audio/x-mpegurl","audio/x-mpequrl"]],["m3u8","application/vnd.apple.mpegurl"],["m4v","video/x-m4v"],["ma","application/mathematica"],["mads","application/mads+xml"],["mag","application/vnd.ecowin.chart"],["man","application/x-troff-man"],["map","application/x-navimap"],["mar","text/plain"],["mathml","application/mathml+xml"],["mbd","application/mbedlet"],["mbk","application/vnd.mobius.mbk"],["mbox","application/mbox"],["mc$","application/x-magic-cap-package-1.0"],["mc1","application/vnd.medcalcdata"],["mcd",["application/mcad","application/vnd.mcd","application/x-mathcad"]],["mcf",["image/vasa","text/mcf"]],["mcp","application/netmc"],["mcurl","text/vnd.curl.mcurl"],["mdb","application/x-msaccess"],["mdi","image/vnd.ms-modi"],["me","application/x-troff-me"],["meta4","application/metalink4+xml"],["mets","application/mets+xml"],["mfm","application/vnd.mfmp"],["mgp","application/vnd.osgeo.mapguide.package"],["mgz","application/vnd.proteus.magazine"],["mht","message/rfc822"],["mhtml","message/rfc822"],["mid",["audio/mid","audio/midi","music/crescendo","x-music/x-midi","audio/x-midi","application/x-midi","audio/x-mid"]],["midi",["audio/midi","music/crescendo","x-music/x-midi","audio/x-midi","application/x-midi","audio/x-mid"]],["mif",["application/vnd.mif","application/x-mif","application/x-frame"]],["mime",["message/rfc822","www/mime"]],["mj2","video/mj2"],["mjf","audio/x-vnd.audioexplosion.mjuicemediafile"],["mjpg","video/x-motion-jpeg"],["mlp","application/vnd.dolby.mlp"],["mm",["application/base64","application/x-meme"]],["mmd","application/vnd.chipnuts.karaoke-mmd"],["mme","application/base64"],["mmf","application/vnd.smaf"],["mmr","image/vnd.fujixerox.edmics-mmr"],["mny","application/x-msmoney"],["mod",["audio/mod","audio/x-mod"]],["mods","application/mods+xml"],["moov","video/quicktime"],["mov","video/quicktime"],["movie","video/x-sgi-movie"],["mp2",["video/mpeg","audio/mpeg","video/x-mpeg","audio/x-mpeg","video/x-mpeq2a"]],["mp3",["audio/mpeg","audio/mpeg3","video/mpeg","audio/x-mpeg-3","video/x-mpeg"]],["mp4",["video/mp4","application/mp4"]],["mp4a","audio/mp4"],["mpa",["video/mpeg","audio/mpeg"]],["mpc",["application/vnd.mophun.certificate","application/x-project"]],["mpe","video/mpeg"],["mpeg","video/mpeg"],["mpg",["video/mpeg","audio/mpeg"]],["mpga","audio/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["mpm","application/vnd.blueice.multipass"],["mpn","application/vnd.mophun.application"],["mpp","application/vnd.ms-project"],["mpt","application/x-project"],["mpv","application/x-project"],["mpv2","video/mpeg"],["mpx","application/x-project"],["mpy","application/vnd.ibm.minipay"],["mqy","application/vnd.mobius.mqy"],["mrc","application/marc"],["mrcx","application/marcxml+xml"],["ms","application/x-troff-ms"],["mscml","application/mediaservercontrol+xml"],["mseq","application/vnd.mseq"],["msf","application/vnd.epson.msf"],["msg","application/vnd.ms-outlook"],["msh","model/mesh"],["msl","application/vnd.mobius.msl"],["msty","application/vnd.muvee.style"],["mts","model/vnd.mts"],["mus","application/vnd.musician"],["musicxml","application/vnd.recordare.musicxml+xml"],["mv","video/x-sgi-movie"],["mvb","application/x-msmediaview"],["mwf","application/vnd.mfer"],["mxf","application/mxf"],["mxl","application/vnd.recordare.musicxml"],["mxml","application/xv+xml"],["mxs","application/vnd.triscape.mxs"],["mxu","video/vnd.mpegurl"],["my","audio/make"],["mzz","application/x-vnd.audioexplosion.mzz"],["n-gage","application/vnd.nokia.n-gage.symbian.install"],["n3","text/n3"],["nap","image/naplps"],["naplps","image/naplps"],["nbp","application/vnd.wolfram.player"],["nc","application/x-netcdf"],["ncm","application/vnd.nokia.configuration-message"],["ncx","application/x-dtbncx+xml"],["ngdat","application/vnd.nokia.n-gage.data"],["nif","image/x-niff"],["niff","image/x-niff"],["nix","application/x-mix-transfer"],["nlu","application/vnd.neurolanguage.nlu"],["nml","application/vnd.enliven"],["nnd","application/vnd.noblenet-directory"],["nns","application/vnd.noblenet-sealer"],["nnw","application/vnd.noblenet-web"],["npx","image/vnd.net-fpx"],["nsc","application/x-conference"],["nsf","application/vnd.lotus-notes"],["nvd","application/x-navidoc"],["nws","message/rfc822"],["o","application/octet-stream"],["oa2","application/vnd.fujitsu.oasys2"],["oa3","application/vnd.fujitsu.oasys3"],["oas","application/vnd.fujitsu.oasys"],["obd","application/x-msbinder"],["oda","application/oda"],["odb","application/vnd.oasis.opendocument.database"],["odc","application/vnd.oasis.opendocument.chart"],["odf","application/vnd.oasis.opendocument.formula"],["odft","application/vnd.oasis.opendocument.formula-template"],["odg","application/vnd.oasis.opendocument.graphics"],["odi","application/vnd.oasis.opendocument.image"],["odm","application/vnd.oasis.opendocument.text-master"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["omc","application/x-omc"],["omcd","application/x-omcdatamaker"],["omcr","application/x-omcregerator"],["onetoc","application/onenote"],["opf","application/oebps-package+xml"],["org","application/vnd.lotus-organizer"],["osf","application/vnd.yamaha.openscoreformat"],["osfpvg","application/vnd.yamaha.openscoreformat.osfpvg+xml"],["otc","application/vnd.oasis.opendocument.chart-template"],["otf","application/x-font-otf"],["otg","application/vnd.oasis.opendocument.graphics-template"],["oth","application/vnd.oasis.opendocument.text-web"],["oti","application/vnd.oasis.opendocument.image-template"],["otp","application/vnd.oasis.opendocument.presentation-template"],["ots","application/vnd.oasis.opendocument.spreadsheet-template"],["ott","application/vnd.oasis.opendocument.text-template"],["oxt","application/vnd.openofficeorg.extension"],["p","text/x-pascal"],["p10",["application/pkcs10","application/x-pkcs10"]],["p12",["application/pkcs-12","application/x-pkcs12"]],["p7a","application/x-pkcs7-signature"],["p7b","application/x-pkcs7-certificates"],["p7c",["application/pkcs7-mime","application/x-pkcs7-mime"]],["p7m",["application/pkcs7-mime","application/x-pkcs7-mime"]],["p7r","application/x-pkcs7-certreqresp"],["p7s",["application/pkcs7-signature","application/x-pkcs7-signature"]],["p8","application/pkcs8"],["par","text/plain-bas"],["part","application/pro_eng"],["pas","text/pascal"],["paw","application/vnd.pawaafile"],["pbd","application/vnd.powerbuilder6"],["pbm","image/x-portable-bitmap"],["pcf","application/x-font-pcf"],["pcl",["application/vnd.hp-pcl","application/x-pcl"]],["pclxl","application/vnd.hp-pclxl"],["pct","image/x-pict"],["pcurl","application/vnd.curl.pcurl"],["pcx","image/x-pcx"],["pdb",["application/vnd.palm","chemical/x-pdb"]],["pdf","application/pdf"],["pfa","application/x-font-type1"],["pfr","application/font-tdpfr"],["pfunk",["audio/make","audio/make.my.funk"]],["pfx","application/x-pkcs12"],["pgm",["image/x-portable-graymap","image/x-portable-greymap"]],["pgn","application/x-chess-pgn"],["pgp","application/pgp-signature"],["pic",["image/pict","image/x-pict"]],["pict","image/pict"],["pkg","application/x-newton-compatible-pkg"],["pki","application/pkixcmp"],["pkipath","application/pkix-pkipath"],["pko",["application/ynd.ms-pkipko","application/vnd.ms-pki.pko"]],["pl",["text/plain","text/x-script.perl"]],["plb","application/vnd.3gpp.pic-bw-large"],["plc","application/vnd.mobius.plc"],["plf","application/vnd.pocketlearn"],["pls","application/pls+xml"],["plx","application/x-pixclscript"],["pm",["text/x-script.perl-module","image/x-xpixmap"]],["pm4","application/x-pagemaker"],["pm5","application/x-pagemaker"],["pma","application/x-perfmon"],["pmc","application/x-perfmon"],["pml",["application/vnd.ctc-posml","application/x-perfmon"]],["pmr","application/x-perfmon"],["pmw","application/x-perfmon"],["png","image/png"],["pnm",["application/x-portable-anymap","image/x-portable-anymap"]],["portpkg","application/vnd.macports.portpkg"],["pot",["application/vnd.ms-powerpoint","application/mspowerpoint"]],["potm","application/vnd.ms-powerpoint.template.macroenabled.12"],["potx","application/vnd.openxmlformats-officedocument.presentationml.template"],["pov","model/x-pov"],["ppa","application/vnd.ms-powerpoint"],["ppam","application/vnd.ms-powerpoint.addin.macroenabled.12"],["ppd","application/vnd.cups-ppd"],["ppm","image/x-portable-pixmap"],["pps",["application/vnd.ms-powerpoint","application/mspowerpoint"]],["ppsm","application/vnd.ms-powerpoint.slideshow.macroenabled.12"],["ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"],["ppt",["application/vnd.ms-powerpoint","application/mspowerpoint","application/powerpoint","application/x-mspowerpoint"]],["pptm","application/vnd.ms-powerpoint.presentation.macroenabled.12"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["ppz","application/mspowerpoint"],["prc","application/x-mobipocket-ebook"],["pre",["application/vnd.lotus-freelance","application/x-freelance"]],["prf","application/pics-rules"],["prt","application/pro_eng"],["ps","application/postscript"],["psb","application/vnd.3gpp.pic-bw-small"],["psd",["application/octet-stream","image/vnd.adobe.photoshop"]],["psf","application/x-font-linux-psf"],["pskcxml","application/pskc+xml"],["ptid","application/vnd.pvi.ptid1"],["pub","application/x-mspublisher"],["pvb","application/vnd.3gpp.pic-bw-var"],["pvu","paleovu/x-pv"],["pwn","application/vnd.3m.post-it-notes"],["pwz","application/vnd.ms-powerpoint"],["py","text/x-script.phyton"],["pya","audio/vnd.ms-playready.media.pya"],["pyc","application/x-bytecode.python"],["pyv","video/vnd.ms-playready.media.pyv"],["qam","application/vnd.epson.quickanime"],["qbo","application/vnd.intu.qbo"],["qcp","audio/vnd.qcelp"],["qd3","x-world/x-3dmf"],["qd3d","x-world/x-3dmf"],["qfx","application/vnd.intu.qfx"],["qif","image/x-quicktime"],["qps","application/vnd.publishare-delta-tree"],["qt","video/quicktime"],["qtc","video/x-qtc"],["qti","image/x-quicktime"],["qtif","image/x-quicktime"],["qxd","application/vnd.quark.quarkxpress"],["ra",["audio/x-realaudio","audio/x-pn-realaudio","audio/x-pn-realaudio-plugin"]],["ram","audio/x-pn-realaudio"],["rar","application/x-rar-compressed"],["ras",["image/cmu-raster","application/x-cmu-raster","image/x-cmu-raster"]],["rast","image/cmu-raster"],["rcprofile","application/vnd.ipunplugged.rcprofile"],["rdf","application/rdf+xml"],["rdz","application/vnd.data-vision.rdz"],["rep","application/vnd.businessobjects"],["res","application/x-dtbresource+xml"],["rexx","text/x-script.rexx"],["rf","image/vnd.rn-realflash"],["rgb","image/x-rgb"],["rif","application/reginfo+xml"],["rip","audio/vnd.rip"],["rl","application/resource-lists+xml"],["rlc","image/vnd.fujixerox.edmics-rlc"],["rld","application/resource-lists-diff+xml"],["rm",["application/vnd.rn-realmedia","audio/x-pn-realaudio"]],["rmi","audio/mid"],["rmm","audio/x-pn-realaudio"],["rmp",["audio/x-pn-realaudio-plugin","audio/x-pn-realaudio"]],["rms","application/vnd.jcp.javame.midlet-rms"],["rnc","application/relax-ng-compact-syntax"],["rng",["application/ringing-tones","application/vnd.nokia.ringing-tone"]],["rnx","application/vnd.rn-realplayer"],["roff","application/x-troff"],["rp","image/vnd.rn-realpix"],["rp9","application/vnd.cloanto.rp9"],["rpm","audio/x-pn-realaudio-plugin"],["rpss","application/vnd.nokia.radio-presets"],["rpst","application/vnd.nokia.radio-preset"],["rq","application/sparql-query"],["rs","application/rls-services+xml"],["rsd","application/rsd+xml"],["rt",["text/richtext","text/vnd.rn-realtext"]],["rtf",["application/rtf","text/richtext","application/x-rtf"]],["rtx",["text/richtext","application/rtf"]],["rv","video/vnd.rn-realvideo"],["s","text/x-asm"],["s3m","audio/s3m"],["saf","application/vnd.yamaha.smaf-audio"],["saveme","application/octet-stream"],["sbk","application/x-tbook"],["sbml","application/sbml+xml"],["sc","application/vnd.ibm.secure-container"],["scd","application/x-msschedule"],["scm",["application/vnd.lotus-screencam","video/x-scm","text/x-script.guile","application/x-lotusscreencam","text/x-script.scheme"]],["scq","application/scvp-cv-request"],["scs","application/scvp-cv-response"],["sct","text/scriptlet"],["scurl","text/vnd.curl.scurl"],["sda","application/vnd.stardivision.draw"],["sdc","application/vnd.stardivision.calc"],["sdd","application/vnd.stardivision.impress"],["sdkm","application/vnd.solent.sdkm+xml"],["sdml","text/plain"],["sdp",["application/sdp","application/x-sdp"]],["sdr","application/sounder"],["sdw","application/vnd.stardivision.writer"],["sea",["application/sea","application/x-sea"]],["see","application/vnd.seemail"],["seed","application/vnd.fdsn.seed"],["sema","application/vnd.sema"],["semd","application/vnd.semd"],["semf","application/vnd.semf"],["ser","application/java-serialized-object"],["set","application/set"],["setpay","application/set-payment-initiation"],["setreg","application/set-registration-initiation"],["sfd-hdstx","application/vnd.hydrostatix.sof-data"],["sfs","application/vnd.spotfire.sfs"],["sgl","application/vnd.stardivision.writer-global"],["sgm",["text/sgml","text/x-sgml"]],["sgml",["text/sgml","text/x-sgml"]],["sh",["application/x-shar","application/x-bsh","application/x-sh","text/x-script.sh"]],["shar",["application/x-bsh","application/x-shar"]],["shf","application/shf+xml"],["shtml",["text/html","text/x-server-parsed-html"]],["sid","audio/x-psid"],["sis","application/vnd.symbian.install"],["sit",["application/x-stuffit","application/x-sit"]],["sitx","application/x-stuffitx"],["skd","application/x-koan"],["skm","application/x-koan"],["skp",["application/vnd.koan","application/x-koan"]],["skt","application/x-koan"],["sl","application/x-seelogo"],["sldm","application/vnd.ms-powerpoint.slide.macroenabled.12"],["sldx","application/vnd.openxmlformats-officedocument.presentationml.slide"],["slt","application/vnd.epson.salt"],["sm","application/vnd.stepmania.stepchart"],["smf","application/vnd.stardivision.math"],["smi",["application/smil","application/smil+xml"]],["smil","application/smil"],["snd",["audio/basic","audio/x-adpcm"]],["snf","application/x-font-snf"],["sol","application/solids"],["spc",["text/x-speech","application/x-pkcs7-certificates"]],["spf","application/vnd.yamaha.smaf-phrase"],["spl",["application/futuresplash","application/x-futuresplash"]],["spot","text/vnd.in3d.spot"],["spp","application/scvp-vp-response"],["spq","application/scvp-vp-request"],["spr","application/x-sprite"],["sprite","application/x-sprite"],["src","application/x-wais-source"],["sru","application/sru+xml"],["srx","application/sparql-results+xml"],["sse","application/vnd.kodak-descriptor"],["ssf","application/vnd.epson.ssf"],["ssi","text/x-server-parsed-html"],["ssm","application/streamingmedia"],["ssml","application/ssml+xml"],["sst",["application/vnd.ms-pkicertstore","application/vnd.ms-pki.certstore"]],["st","application/vnd.sailingtracker.track"],["stc","application/vnd.sun.xml.calc.template"],["std","application/vnd.sun.xml.draw.template"],["step","application/step"],["stf","application/vnd.wt.stf"],["sti","application/vnd.sun.xml.impress.template"],["stk","application/hyperstudio"],["stl",["application/vnd.ms-pkistl","application/sla","application/vnd.ms-pki.stl","application/x-navistyle"]],["stm","text/html"],["stp","application/step"],["str","application/vnd.pg.format"],["stw","application/vnd.sun.xml.writer.template"],["sub","image/vnd.dvb.subtitle"],["sus","application/vnd.sus-calendar"],["sv4cpio","application/x-sv4cpio"],["sv4crc","application/x-sv4crc"],["svc","application/vnd.dvb.service"],["svd","application/vnd.svd"],["svf",["image/vnd.dwg","image/x-dwg"]],["svg","image/svg+xml"],["svr",["x-world/x-svr","application/x-world"]],["swf","application/x-shockwave-flash"],["swi","application/vnd.aristanetworks.swi"],["sxc","application/vnd.sun.xml.calc"],["sxd","application/vnd.sun.xml.draw"],["sxg","application/vnd.sun.xml.writer.global"],["sxi","application/vnd.sun.xml.impress"],["sxm","application/vnd.sun.xml.math"],["sxw","application/vnd.sun.xml.writer"],["t",["text/troff","application/x-troff"]],["talk","text/x-speech"],["tao","application/vnd.tao.intent-module-archive"],["tar","application/x-tar"],["tbk",["application/toolbook","application/x-tbook"]],["tcap","application/vnd.3gpp2.tcap"],["tcl",["text/x-script.tcl","application/x-tcl"]],["tcsh","text/x-script.tcsh"],["teacher","application/vnd.smart.teacher"],["tei","application/tei+xml"],["tex","application/x-tex"],["texi","application/x-texinfo"],["texinfo","application/x-texinfo"],["text",["application/plain","text/plain"]],["tfi","application/thraud+xml"],["tfm","application/x-tex-tfm"],["tgz",["application/gnutar","application/x-compressed"]],["thmx","application/vnd.ms-officetheme"],["tif",["image/tiff","image/x-tiff"]],["tiff",["image/tiff","image/x-tiff"]],["tmo","application/vnd.tmobile-livetv"],["torrent","application/x-bittorrent"],["tpl","application/vnd.groove-tool-template"],["tpt","application/vnd.trid.tpt"],["tr","application/x-troff"],["tra","application/vnd.trueapp"],["trm","application/x-msterminal"],["tsd","application/timestamped-data"],["tsi","audio/tsp-audio"],["tsp",["application/dsptype","audio/tsplayer"]],["tsv","text/tab-separated-values"],["ttf","application/x-font-ttf"],["ttl","text/turtle"],["turbot","image/florian"],["twd","application/vnd.simtech-mindmapper"],["txd","application/vnd.genomatix.tuxedo"],["txf","application/vnd.mobius.txf"],["txt","text/plain"],["ufd","application/vnd.ufdl"],["uil","text/x-uil"],["uls","text/iuls"],["umj","application/vnd.umajin"],["uni","text/uri-list"],["unis","text/uri-list"],["unityweb","application/vnd.unity"],["unv","application/i-deas"],["uoml","application/vnd.uoml+xml"],["uri","text/uri-list"],["uris","text/uri-list"],["ustar",["application/x-ustar","multipart/x-ustar"]],["utz","application/vnd.uiq.theme"],["uu",["application/octet-stream","text/x-uuencode"]],["uue","text/x-uuencode"],["uva","audio/vnd.dece.audio"],["uvh","video/vnd.dece.hd"],["uvi","image/vnd.dece.graphic"],["uvm","video/vnd.dece.mobile"],["uvp","video/vnd.dece.pd"],["uvs","video/vnd.dece.sd"],["uvu","video/vnd.uvvu.mp4"],["uvv","video/vnd.dece.video"],["vcd","application/x-cdlink"],["vcf","text/x-vcard"],["vcg","application/vnd.groove-vcard"],["vcs","text/x-vcalendar"],["vcx","application/vnd.vcx"],["vda","application/vda"],["vdo","video/vdo"],["vew","application/groupwise"],["vis","application/vnd.visionary"],["viv",["video/vivo","video/vnd.vivo"]],["vivo",["video/vivo","video/vnd.vivo"]],["vmd","application/vocaltec-media-desc"],["vmf","application/vocaltec-media-file"],["voc",["audio/voc","audio/x-voc"]],["vos","video/vosaic"],["vox","audio/voxware"],["vqe","audio/x-twinvq-plugin"],["vqf","audio/x-twinvq"],["vql","audio/x-twinvq-plugin"],["vrml",["model/vrml","x-world/x-vrml","application/x-vrml"]],["vrt","x-world/x-vrt"],["vsd",["application/vnd.visio","application/x-visio"]],["vsf","application/vnd.vsf"],["vst","application/x-visio"],["vsw","application/x-visio"],["vtu","model/vnd.vtu"],["vxml","application/voicexml+xml"],["w60","application/wordperfect6.0"],["w61","application/wordperfect6.1"],["w6w","application/msword"],["wad","application/x-doom"],["wav",["audio/wav","audio/x-wav"]],["wax","audio/x-ms-wax"],["wb1","application/x-qpro"],["wbmp","image/vnd.wap.wbmp"],["wbs","application/vnd.criticaltools.wbs+xml"],["wbxml","application/vnd.wap.wbxml"],["wcm","application/vnd.ms-works"],["wdb","application/vnd.ms-works"],["web","application/vnd.xara"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["wg","application/vnd.pmi.widget"],["wgt","application/widget"],["wiz","application/msword"],["wk1","application/x-123"],["wks","application/vnd.ms-works"],["wm","video/x-ms-wm"],["wma","audio/x-ms-wma"],["wmd","application/x-ms-wmd"],["wmf",["windows/metafile","application/x-msmetafile"]],["wml","text/vnd.wap.wml"],["wmlc","application/vnd.wap.wmlc"],["wmls","text/vnd.wap.wmlscript"],["wmlsc","application/vnd.wap.wmlscriptc"],["wmv","video/x-ms-wmv"],["wmx","video/x-ms-wmx"],["wmz","application/x-ms-wmz"],["woff","application/x-font-woff"],["word","application/msword"],["wp","application/wordperfect"],["wp5",["application/wordperfect","application/wordperfect6.0"]],["wp6","application/wordperfect"],["wpd",["application/wordperfect","application/vnd.wordperfect","application/x-wpwin"]],["wpl","application/vnd.ms-wpl"],["wps","application/vnd.ms-works"],["wq1","application/x-lotus"],["wqd","application/vnd.wqd"],["wri",["application/mswrite","application/x-wri","application/x-mswrite"]],["wrl",["model/vrml","x-world/x-vrml","application/x-world"]],["wrz",["model/vrml","x-world/x-vrml"]],["wsc","text/scriplet"],["wsdl","application/wsdl+xml"],["wspolicy","application/wspolicy+xml"],["wsrc","application/x-wais-source"],["wtb","application/vnd.webturbo"],["wtk","application/x-wintalk"],["wvx","video/x-ms-wvx"],["x-png","image/png"],["x3d","application/vnd.hzn-3d-crossword"],["xaf","x-world/x-vrml"],["xap","application/x-silverlight-app"],["xar","application/vnd.xara"],["xbap","application/x-ms-xbap"],["xbd","application/vnd.fujixerox.docuworks.binder"],["xbm",["image/xbm","image/x-xbm","image/x-xbitmap"]],["xdf","application/xcap-diff+xml"],["xdm","application/vnd.syncml.dm+xml"],["xdp","application/vnd.adobe.xdp+xml"],["xdr","video/x-amt-demorun"],["xdssc","application/dssc+xml"],["xdw","application/vnd.fujixerox.docuworks"],["xenc","application/xenc+xml"],["xer","application/patch-ops-error+xml"],["xfdf","application/vnd.adobe.xfdf"],["xfdl","application/vnd.xfdl"],["xgz","xgl/drawing"],["xhtml","application/xhtml+xml"],["xif","image/vnd.xiff"],["xl","application/excel"],["xla",["application/vnd.ms-excel","application/excel","application/x-msexcel","application/x-excel"]],["xlam","application/vnd.ms-excel.addin.macroenabled.12"],["xlb",["application/excel","application/vnd.ms-excel","application/x-excel"]],["xlc",["application/vnd.ms-excel","application/excel","application/x-excel"]],["xld",["application/excel","application/x-excel"]],["xlk",["application/excel","application/x-excel"]],["xll",["application/excel","application/vnd.ms-excel","application/x-excel"]],["xlm",["application/vnd.ms-excel","application/excel","application/x-excel"]],["xls",["application/vnd.ms-excel","application/excel","application/x-msexcel","application/x-excel"]],["xlsb","application/vnd.ms-excel.sheet.binary.macroenabled.12"],["xlsm","application/vnd.ms-excel.sheet.macroenabled.12"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xlt",["application/vnd.ms-excel","application/excel","application/x-excel"]],["xltm","application/vnd.ms-excel.template.macroenabled.12"],["xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"],["xlv",["application/excel","application/x-excel"]],["xlw",["application/vnd.ms-excel","application/excel","application/x-msexcel","application/x-excel"]],["xm","audio/xm"],["xml",["application/xml","text/xml","application/atom+xml","application/rss+xml"]],["xmz","xgl/movie"],["xo","application/vnd.olpc-sugar"],["xof","x-world/x-vrml"],["xop","application/xop+xml"],["xpi","application/x-xpinstall"],["xpix","application/x-vnd.ls-xpix"],["xpm",["image/xpm","image/x-xpixmap"]],["xpr","application/vnd.is-xpr"],["xps","application/vnd.ms-xpsdocument"],["xpw","application/vnd.intercon.formnet"],["xslt","application/xslt+xml"],["xsm","application/vnd.syncml+xml"],["xspf","application/xspf+xml"],["xsr","video/x-amt-showrun"],["xul","application/vnd.mozilla.xul+xml"],["xwd",["image/x-xwd","image/x-xwindowdump"]],["xyz",["chemical/x-xyz","chemical/x-pdb"]],["yang","application/yang"],["yin","application/yin+xml"],["z",["application/x-compressed","application/x-compress"]],["zaz","application/vnd.zzazz.deck+xml"],["zip",["application/zip","multipart/x-zip","application/x-zip-compressed","application/x-compressed"]],["zir","application/vnd.zul"],["zmm","application/vnd.handheld-entertainment+xml"],["zoo","application/octet-stream"],["zsh","text/x-script.zsh"]]);return mimeTypes_1={detectMimeType(filename){if(!filename)return"application/octet-stream";let parsed=path.parse(filename),extension=(parsed.ext.substr(1)||parsed.name||"").split("?").shift().trim().toLowerCase(),value="application/octet-stream";return extensions.has(extension)&&(value=extensions.get(extension)),Array.isArray(value)?value[0]:value},detectExtension(mimeType){if(!mimeType)return"bin";let parts=(mimeType||"").toLowerCase().trim().split("/"),rootType=parts.shift().trim(),subType=parts.join("/").trim();if(mimeTypes.has(rootType+"/"+subType)){let value=mimeTypes.get(rootType+"/"+subType);return Array.isArray(value)?value[0]:value}return"text"===rootType?"txt":"bin"}}}function requirePunycode(){if(hasRequiredPunycode)return punycode_1;hasRequiredPunycode=1;const maxInt=2147483647,regexPunycode=/^xn--/,regexNonASCII=/[^\0-\x7F]/,regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},floor=Math.floor,stringFromCharCode=String.fromCharCode;function error(type){throw new RangeError(errors[type])}function mapDomain(domain,callback){const parts=domain.split("@");let result="";parts.length>1&&(result=parts[0]+"@",domain=parts[1]);const encoded=function map(array,callback){const result=[];let length=array.length;for(;length--;)result[length]=callback(array[length]);return result}((domain=domain.replace(regexSeparators,".")).split("."),callback).join(".");return result+encoded}function ucs2decode(string){const output=[];let counter=0;const length=string.length;for(;counter<length;){const value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){const extra=string.charCodeAt(counter++);56320==(64512&extra)?output.push(((1023&value)<<10)+(1023&extra)+65536):(output.push(value),counter--)}else output.push(value)}return output}const basicToDigit=function(codePoint){return codePoint>=48&&codePoint<58?codePoint-48+26:codePoint>=65&&codePoint<91?codePoint-65:codePoint>=97&&codePoint<123?codePoint-97:36},digitToBasic=function(digit,flag){return digit+22+75*(digit<26)-((0!=flag)<<5)},adapt=function(delta,numPoints,firstTime){let k=0;for(delta=firstTime?floor(delta/700):delta>>1,delta+=floor(delta/numPoints);delta>455;k+=36)delta=floor(delta/35);return floor(k+36*delta/(delta+38))},decode=function(input){const output=[],inputLength=input.length;let i=0,n=128,bias=72,basic=input.lastIndexOf("-");basic<0&&(basic=0);for(let j=0;j<basic;++j)input.charCodeAt(j)>=128&&error("not-basic"),output.push(input.charCodeAt(j));for(let index=basic>0?basic+1:0;index<inputLength;){const oldi=i;for(let w=1,k=36;;k+=36){index>=inputLength&&error("invalid-input");const digit=basicToDigit(input.charCodeAt(index++));digit>=36&&error("invalid-input"),digit>floor((maxInt-i)/w)&&error("overflow"),i+=digit*w;const t=k<=bias?1:k>=bias+26?26:k-bias;if(digit<t)break;const baseMinusT=36-t;w>floor(maxInt/baseMinusT)&&error("overflow"),w*=baseMinusT}const out=output.length+1;bias=adapt(i-oldi,out,0==oldi),floor(i/out)>maxInt-n&&error("overflow"),n+=floor(i/out),i%=out,output.splice(i++,0,n)}return String.fromCodePoint(...output)},encode=function(input){const output=[],inputLength=(input=ucs2decode(input)).length;let n=128,delta=0,bias=72;for(const currentValue of input)currentValue<128&&output.push(stringFromCharCode(currentValue));const basicLength=output.length;let handledCPCount=basicLength;for(basicLength&&output.push("-");handledCPCount<inputLength;){let m=maxInt;for(const currentValue of input)currentValue>=n&¤tValue<m&&(m=currentValue);const handledCPCountPlusOne=handledCPCount+1;m-n>floor((maxInt-delta)/handledCPCountPlusOne)&&error("overflow"),delta+=(m-n)*handledCPCountPlusOne,n=m;for(const currentValue of input)if(currentValue<n&&++delta>maxInt&&error("overflow"),currentValue===n){let q=delta;for(let k=36;;k+=36){const t=k<=bias?1:k>=bias+26?26:k-bias;if(q<t)break;const qMinusT=q-t,baseMinusT=36-t;output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0))),q=floor(qMinusT/baseMinusT)}output.push(stringFromCharCode(digitToBasic(q,0))),bias=adapt(delta,handledCPCountPlusOne,handledCPCount===basicLength),delta=0,++handledCPCount}++delta,++n}return output.join("")};return punycode_1={version:"2.3.1",ucs2:{decode:ucs2decode,encode:codePoints=>String.fromCodePoint(...codePoints)},decode:decode,encode:encode,toASCII:function(input){return mapDomain(input,function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string})},toUnicode:function(input){return mapDomain(input,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string})}}}function requireBase64(){if(hasRequiredBase64)return base64;hasRequiredBase64=1;const Transform=require$$0__default$4.default.Transform;function encode(buffer){return"string"==typeof buffer&&(buffer=Buffer.from(buffer,"utf-8")),buffer.toString("base64")}function wrap(str,lineLength){if(lineLength=lineLength||76,(str=(str||"").toString()).length<=lineLength)return str;let result=[],pos=0,chunkLength=1024*lineLength;for(;pos<str.length;){let wrappedLines=str.substr(pos,chunkLength).replace(new RegExp(".{"+lineLength+"}","g"),"$&\r\n").trim();result.push(wrappedLines),pos+=chunkLength}return result.join("\r\n").trim()}return base64={encode:encode,wrap:wrap,Encoder:class Encoder extends Transform{constructor(options){super(),this.options=options||{},!1!==this.options.lineLength&&(this.options.lineLength=this.options.lineLength||76),this._curLine="",this._remainingBytes=!1,this.inputBytes=0,this.outputBytes=0}_transform(chunk,encoding,done){if("buffer"!==encoding&&(chunk=Buffer.from(chunk,encoding)),!chunk||!chunk.length)return setImmediate(done);this.inputBytes+=chunk.length,this._remainingBytes&&this._remainingBytes.length&&(chunk=Buffer.concat([this._remainingBytes,chunk],this._remainingBytes.length+chunk.length),this._remainingBytes=!1),chunk.length%3?(this._remainingBytes=chunk.slice(chunk.length-chunk.length%3),chunk=chunk.slice(0,chunk.length-chunk.length%3)):this._remainingBytes=!1;let b64=this._curLine+encode(chunk);if(this.options.lineLength){b64=wrap(b64,this.options.lineLength);let lastLF=b64.lastIndexOf("\n");lastLF<0?(this._curLine=b64,b64=""):lastLF===b64.length-1?this._curLine="":(this._curLine=b64.substr(lastLF+1),b64=b64.substr(0,lastLF+1))}b64&&(this.outputBytes+=b64.length,this.push(Buffer.from(b64,"ascii"))),setImmediate(done)}_flush(done){this._remainingBytes&&this._remainingBytes.length&&(this._curLine+=encode(this._remainingBytes)),this._curLine&&(this._curLine=wrap(this._curLine,this.options.lineLength),this.outputBytes+=this._curLine.length,this.push(this._curLine,"ascii"),this._curLine=""),done()}}}}function requireQp(){if(hasRequiredQp)return qp;hasRequiredQp=1;const Transform=require$$0__default$4.default.Transform;function encode(buffer){"string"==typeof buffer&&(buffer=Buffer.from(buffer,"utf-8"));let ord,ranges=[[9],[10],[13],[32,60],[62,126]],result="";for(let i=0,len=buffer.length;i<len;i++)ord=buffer[i],checkRanges(ord,ranges)&&(32!==ord&&9!==ord||i!==len-1&&10!==buffer[i+1]&&13!==buffer[i+1])?result+=String.fromCharCode(ord):result+="="+(ord<16?"0":"")+ord.toString(16).toUpperCase();return result}function wrap(str,lineLength){if(lineLength=lineLength||76,(str=(str||"").toString()).length<=lineLength)return str;let match,code,line,pos=0,len=str.length,lineMargin=Math.floor(lineLength/3),result="";for(;pos<len;)if(line=str.substr(pos,lineLength),match=line.match(/\r\n/))line=line.substr(0,match.index+match[0].length),result+=line,pos+=line.length;else if("\n"!==line.substr(-1))if(match=line.substr(-lineMargin).match(/\n.*?$/))line=line.substr(0,line.length-(match[0].length-1)),result+=line,pos+=line.length;else{if(line.length>lineLength-lineMargin&&(match=line.substr(-lineMargin).match(/[ \t.,!?][^ \t.,!?]*$/)))line=line.substr(0,line.length-(match[0].length-1));else if(line.match(/[=][\da-f]{0,2}$/i))for((match=line.match(/[=][\da-f]{0,1}$/i))&&(line=line.substr(0,line.length-match[0].length));line.length>3&&line.length<len-pos&&!line.match(/^(?:=[\da-f]{2}){1,4}$/i)&&(match=line.match(/[=][\da-f]{2}$/gi))&&(code=parseInt(match[0].substr(1,2),16),!(code<128))&&(line=line.substr(0,line.length-3),!(code>=192)););pos+line.length<len&&"\n"!==line.substr(-1)?(line.length===lineLength&&line.match(/[=][\da-f]{2}$/i)?line=line.substr(0,line.length-3):line.length===lineLength&&(line=line.substr(0,line.length-1)),pos+=line.length,line+="=\r\n"):pos+=line.length,result+=line}else result+=line,pos+=line.length;return result}function checkRanges(nr,ranges){for(let i=ranges.length-1;i>=0;i--)if(ranges[i].length){if(1===ranges[i].length&&nr===ranges[i][0])return!0;if(2===ranges[i].length&&nr>=ranges[i][0]&&nr<=ranges[i][1])return!0}return!1}return qp={encode:encode,wrap:wrap,Encoder:class Encoder extends Transform{constructor(options){super(),this.options=options||{},!1!==this.options.lineLength&&(this.options.lineLength=this.options.lineLength||76),this._curLine="",this.inputBytes=0,this.outputBytes=0}_transform(chunk,encoding,done){let qp;if("buffer"!==encoding&&(chunk=Buffer.from(chunk,encoding)),!chunk||!chunk.length)return done();this.inputBytes+=chunk.length,this.options.lineLength?(qp=this._curLine+encode(chunk),qp=wrap(qp,this.options.lineLength),qp=qp.replace(/(^|\n)([^\n]*)$/,(match,lineBreak,lastLine)=>(this._curLine=lastLine,lineBreak)),qp&&(this.outputBytes+=qp.length,this.push(qp))):(qp=encode(chunk),this.outputBytes+=qp.length,this.push(qp,"ascii")),done()}_flush(done){this._curLine&&(this.outputBytes+=this._curLine.length,this.push(this._curLine,"ascii")),done()}}}}function requireMimeFuncs(){if(hasRequiredMimeFuncs)return mimeFuncs;hasRequiredMimeFuncs=1;const base64=requireBase64(),qp=requireQp(),mimeTypes=requireMimeTypes();return mimeFuncs={isPlainText:(value,isParam)=>"string"==typeof value&&!(isParam?/[\x00-\x08\x0b\x0c\x0e-\x1f"\u0080-\uFFFF]/:/[\x00-\x08\x0b\x0c\x0e-\x1f\u0080-\uFFFF]/).test(value),hasLongerLines:(str,lineLength)=>str.length>131072||new RegExp("^.{"+(lineLength+1)+",}","m").test(str),encodeWord(data,mimeWordEncoding,maxLength){let encodedStr;if((maxLength=maxLength||0)&&maxLength>12&&(maxLength-=12),"Q"===(mimeWordEncoding=(mimeWordEncoding||"Q").toString().toUpperCase().trim().charAt(0))?encodedStr=qp.encode(data).replace(/[^a-z0-9!*+\-/=]/gi,chr=>{let ord=chr.charCodeAt(0).toString(16).toUpperCase();return" "===chr?"_":"="+(1===ord.length?"0"+ord:ord)}):"B"===mimeWordEncoding&&(encodedStr="string"==typeof data?data:base64.encode(data),maxLength=maxLength?Math.max(3,(maxLength-maxLength%4)/4*3):0),maxLength&&("B"!==mimeWordEncoding?encodedStr:base64.encode(data)).length>maxLength)if("Q"===mimeWordEncoding)encodedStr=this.splitMimeEncodedString(encodedStr,maxLength).join("?= =?UTF-8?"+mimeWordEncoding+"?");else{let parts=[],lpart="";for(let i=0,len=encodedStr.length;i<len;i++){let chr=encodedStr.charAt(i);/[\ud83c\ud83d\ud83e]/.test(chr)&&i<len-1&&(chr+=encodedStr.charAt(++i)),Buffer.byteLength(lpart+chr)<=maxLength||0===i?lpart+=chr:(parts.push(base64.encode(lpart)),lpart=chr)}lpart&&parts.push(base64.encode(lpart)),encodedStr=parts.length>1?parts.join("?= =?UTF-8?"+mimeWordEncoding+"?"):parts.join("")}else"B"===mimeWordEncoding&&(encodedStr=base64.encode(data));return"=?UTF-8?"+mimeWordEncoding+"?"+encodedStr+("?="===encodedStr.substr(-2)?"":"?=")},encodeWords(value,mimeWordEncoding,maxLength,encodeAll){let encodedValue;maxLength=maxLength||0;let firstMatch=value.match(/(?:^|\s)([^\s]*["\u0080-\uFFFF])/);if(!firstMatch)return value;if(encodeAll)return this.encodeWord(value,mimeWordEncoding,maxLength);let lastMatch=value.match(/(["\u0080-\uFFFF][^\s]*)[^"\u0080-\uFFFF]*$/);if(!lastMatch)return value;let startIndex=firstMatch.index+(firstMatch[0].match(/[^\s]/)||{index:0}).index,endIndex=lastMatch.index+(lastMatch[1]||"").length;return encodedValue=(startIndex?value.substr(0,startIndex):"")+this.encodeWord(value.substring(startIndex,endIndex),mimeWordEncoding||"Q",maxLength)+(endIndex<value.length?value.substr(endIndex):""),encodedValue},buildHeaderValue(structured){let paramsArray=[];return Object.keys(structured.params||{}).forEach(param=>{let value=structured.params[param];!this.isPlainText(value,!0)||value.length>=75?this.buildHeaderParam(param,value,50).forEach(encodedParam=>{/[\s"\\;:/=(),<>@[\]?]|^[-']|'$/.test(encodedParam.value)&&"*"!==encodedParam.key.substr(-1)?paramsArray.push(encodedParam.key+"="+JSON.stringify(encodedParam.value)):paramsArray.push(encodedParam.key+"="+encodedParam.value)}):/[\s'"\\;:/=(),<>@[\]?]|^-/.test(value)?paramsArray.push(param+"="+JSON.stringify(value)):paramsArray.push(param+"="+value)}),structured.value+(paramsArray.length?"; "+paramsArray.join("; "):"")},buildHeaderParam(key,data,maxLength){let encodedStrArr,chr,ord,line,i,len,list=[],encodedStr="string"==typeof data?data:(data||"").toString(),startPos=0;if(maxLength=maxLength||50,this.isPlainText(data,!0)){if(encodedStr.length<=maxLength)return[{key:key,value:encodedStr}];encodedStr=encodedStr.replace(new RegExp(".{"+maxLength+"}","g"),str=>(list.push({line:str}),"")),encodedStr&&list.push({line:encodedStr})}else{if(/[\uD800-\uDBFF]/.test(encodedStr)){for(encodedStrArr=[],i=0,len=encodedStr.length;i<len;i++)chr=encodedStr.charAt(i),ord=chr.charCodeAt(0),ord>=55296&&ord<=56319&&i<len-1?(chr+=encodedStr.charAt(i+1),encodedStrArr.push(chr),i++):encodedStrArr.push(chr);encodedStr=encodedStrArr}line="utf-8''";let encoded=!0;for(startPos=0,i=0,len=encodedStr.length;i<len;i++){if(chr=encodedStr[i],encoded)chr=this.safeEncodeURIComponent(chr);else if(chr=" "===chr?chr:this.safeEncodeURIComponent(chr),chr!==encodedStr[i]){if(!((this.safeEncodeURIComponent(line)+chr).length>=maxLength)){encoded=!0,i=startPos,line="";continue}list.push({line:line,encoded:encoded}),line="",startPos=i-1}(line+chr).length>=maxLength?(list.push({line:line,encoded:encoded}),line=chr=" "===encodedStr[i]?" ":this.safeEncodeURIComponent(encodedStr[i]),chr===encodedStr[i]?(encoded=!1,startPos=i-1):encoded=!0):line+=chr}line&&list.push({line:line,encoded:encoded})}return list.map((item,i)=>({key:key+"*"+i+(item.encoded?"*":""),value:item.line}))},parseHeaderValue(str){let chr,response={value:!1,params:{}},key=!1,value="",type="value",quote=!1,escaped=!1;for(let i=0,len=str.length;i<len;i++)if(chr=str.charAt(i),"key"===type){if("="===chr){key=value.trim().toLowerCase(),type="value",value="";continue}value+=chr}else{if(escaped)value+=chr;else{if("\\"===chr){escaped=!0;continue}quote&&chr===quote?quote=!1:quote||'"'!==chr?quote||";"!==chr?value+=chr:(!1===key?response.value=value.trim():response.params[key]=value.trim(),type="key",value=""):quote=chr}escaped=!1}return"value"===type?!1===key?response.value=value.trim():response.params[key]=value.trim():value.trim()&&(response.params[value.trim().toLowerCase()]=""),Object.keys(response.params).forEach(key=>{let actualKey,nr,match,value;(match=key.match(/(\*(\d+)|\*(\d+)\*|\*)$/))&&(actualKey=key.substr(0,match.index),nr=Number(match[2]||match[3])||0,response.params[actualKey]&&"object"==typeof response.params[actualKey]||(response.params[actualKey]={charset:!1,values:[]}),value=response.params[key],0===nr&&"*"===match[0].substr(-1)&&(match=value.match(/^([^']*)'[^']*'(.*)$/))&&(response.params[actualKey].charset=match[1]||"iso-8859-1",value=match[2]),response.params[actualKey].values[nr]=value,delete response.params[key])}),Object.keys(response.params).forEach(key=>{let value;response.params[key]&&Array.isArray(response.params[key].values)&&(value=response.params[key].values.map(val=>val||"").join(""),response.params[key].charset?response.params[key]="=?"+response.params[key].charset+"?Q?"+value.replace(/[=?_\s]/g,s=>{let c=s.charCodeAt(0).toString(16);return" "===s?"_":"%"+(c.length<2?"0":"")+c}).replace(/%/g,"=")+"?=":response.params[key]=value)}),response},detectExtension:mimeType=>mimeTypes.detectExtension(mimeType),detectMimeType:extension=>mimeTypes.detectMimeType(extension),foldLines(str,lineLength,afterSpace){lineLength=lineLength||76;let line,match,pos=0,len=(str=(str||"").toString()).length,result="";for(;pos<len;){if(line=str.substr(pos,lineLength),line.length<lineLength){result+=line;break}(match=line.match(/^[^\n\r]*(\r?\n|\r)/))?(line=match[0],result+=line,pos+=line.length):((match=line.match(/(\s+)[^\s]*$/))&&match[0].length-(afterSpace?(match[1]||"").length:0)<line.length?line=line.substr(0,line.length-(match[0].length-(afterSpace?(match[1]||"").length:0))):(match=str.substr(pos+line.length).match(/^[^\s]+(\s*)/))&&(line+=match[0].substr(0,match[0].length-(afterSpace?0:(match[1]||"").length))),result+=line,pos+=line.length,pos<len&&(result+="\r\n"))}return result},splitMimeEncodedString:(str,maxlen)=>{let curLine,match,chr,done,lines=[];for(maxlen=Math.max(maxlen||0,12);str.length;){for(curLine=str.substr(0,maxlen),(match=curLine.match(/[=][0-9A-F]?$/i))&&(curLine=curLine.substr(0,match.index)),done=!1;!done;)done=!0,(match=str.substr(curLine.length).match(/^[=]([0-9A-F]{2})/i))&&(chr=parseInt(match[1],16),chr<194&&chr>127&&(curLine=curLine.substr(0,curLine.length-3),done=!1));curLine.length&&lines.push(curLine),str=str.substr(curLine.length)}return lines},encodeURICharComponent:chr=>{let res="",ord=chr.charCodeAt(0).toString(16).toUpperCase();if(ord.length%2&&(ord="0"+ord),ord.length>2)for(let i=0,len=ord.length/2;i<len;i++)res+="%"+ord.substr(i,2);else res+="%"+ord;return res},safeEncodeURIComponent(str){str=(str||"").toString();try{str=encodeURIComponent(str)}catch(E){return str.replace(/[^\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]+/g,"")}return str.replace(/[\x00-\x1F *'()<>@,;:\\"[\]?=\u007F-\uFFFF]/g,chr=>this.encodeURICharComponent(chr))}},mimeFuncs}function requireAddressparser(){if(hasRequiredAddressparser)return addressparser_1;hasRequiredAddressparser=1;class Tokenizer{constructor(str){this.str=(str||"").toString(),this.operatorCurrent="",this.operatorExpecting="",this.node=null,this.escaped=!1,this.list=[],this.operators={'"':'"',"(":")","<":">",",":"",":":";",";":""}}tokenize(){let list=[];for(let i=0,len=this.str.length;i<len;i++){let chr=this.str.charAt(i),nextChr=i<len-1?this.str.charAt(i+1):null;this.checkChar(chr,nextChr)}return this.list.forEach(node=>{node.value=(node.value||"").toString().trim(),node.value&&list.push(node)}),list}checkChar(chr,nextChr){if(this.escaped);else{if(chr===this.operatorExpecting)return this.node={type:"operator",value:chr},nextChr&&![" ","\t","\r","\n",",",";"].includes(nextChr)&&(this.node.noBreak=!0),this.list.push(this.node),this.node=null,this.operatorExpecting="",void(this.escaped=!1);if(!this.operatorExpecting&&chr in this.operators)return this.node={type:"operator",value:chr},this.list.push(this.node),this.node=null,this.operatorExpecting=this.operators[chr],void(this.escaped=!1);if(['"',"'"].includes(this.operatorExpecting)&&"\\"===chr)return void(this.escaped=!0)}this.node||(this.node={type:"text",value:""},this.list.push(this.node)),"\n"===chr&&(chr=" "),(chr.charCodeAt(0)>=33||[" ","\t"].includes(chr))&&(this.node.value+=chr),this.escaped=!1}}function addressparser(str,options){options=options||{};let tokens=new Tokenizer(str).tokenize(),addresses=[],address=[],parsedAddresses=[];if(tokens.forEach(token=>{"operator"!==token.type||","!==token.value&&";"!==token.value?address.push(token):(address.length&&addresses.push(address),address=[])}),address.length&&addresses.push(address),addresses.forEach(address=>{address=function _handleAddress(tokens){let address,i,len,isGroup=!1,state="text",addresses=[],data={address:[],comment:[],group:[],text:[]};for(i=0,len=tokens.length;i<len;i++){let token=tokens[i],prevToken=i?tokens[i-1]:null;if("operator"===token.type)switch(token.value){case"<":state="address";break;case"(":state="comment";break;case":":state="group",isGroup=!0;break;default:state="text"}else token.value&&("address"===state&&(token.value=token.value.replace(/^[^<]*<\s*/,"")),prevToken&&prevToken.noBreak&&data[state].length?data[state][data[state].length-1]+=token.value:data[state].push(token.value))}if(!data.text.length&&data.comment.length&&(data.text=data.comment,data.comment=[]),isGroup)data.text=data.text.join(" "),addresses.push({name:data.text||address&&address.name,group:data.group.length?addressparser(data.group.join(",")):[]});else{if(!data.address.length&&data.text.length){for(i=data.text.length-1;i>=0;i--)if(data.text[i].match(/^[^@\s]+@[^@\s]+$/)){data.address=data.text.splice(i,1);break}let _regexHandler=function(address){return data.address.length?address:(data.address=[address.trim()]," ")};if(!data.address.length)for(i=data.text.length-1;i>=0&&(data.text[i]=data.text[i].replace(/\s*\b[^@\s]+@[^\s]+\b\s*/,_regexHandler).trim(),!data.address.length);i--);}if(!data.text.length&&data.comment.length&&(data.text=data.comment,data.comment=[]),data.address.length>1&&(data.text=data.text.concat(data.address.splice(1))),data.text=data.text.join(" "),data.address=data.address.join(" "),!data.address&&isGroup)return[];address={address:data.address||data.text||"",name:data.text||data.address||""},address.address===address.name&&((address.address||"").match(/@/)?address.name="":address.address=""),addresses.push(address)}return addresses}(address),address.length&&(parsedAddresses=parsedAddresses.concat(address))}),options.flatten){let addresses=[],walkAddressList=list=>{list.forEach(address=>{if(address.group)return walkAddressList(address.group);addresses.push(address)})};return walkAddressList(parsedAddresses),addresses}return parsedAddresses}return addressparser_1=addressparser}function requireLeWindows(){if(hasRequiredLeWindows)return leWindows;hasRequiredLeWindows=1;const Transform=require$$0__default$4.default.Transform;return leWindows=class LeWindows extends Transform{constructor(options){super(options),this.options=options||{},this.lastByte=!1}_transform(chunk,encoding,done){let buf,lastPos=0;for(let i=0,len=chunk.length;i<len;i++)10===chunk[i]&&(i&&13!==chunk[i-1]||!i&&13!==this.lastByte)&&(i>lastPos&&(buf=chunk.slice(lastPos,i),this.push(buf)),this.push(Buffer.from("\r\n")),lastPos=i+1);lastPos&&lastPos<chunk.length?(buf=chunk.slice(lastPos),this.push(buf)):lastPos||this.push(chunk),this.lastByte=chunk[chunk.length-1],done()}}}function requireMimeNode(){if(hasRequiredMimeNode)return mimeNode;hasRequiredMimeNode=1;const crypto=require$$0__default$1.default,fs=fs__default.default,punycode=requirePunycode(),PassThrough=require$$0__default$4.default.PassThrough,shared=requireShared(),mimeFuncs=requireMimeFuncs(),qp=requireQp(),base64=requireBase64(),addressparser=requireAddressparser(),nmfetch=requireFetch(),LastNewline=function requireLastNewline(){if(hasRequiredLastNewline)return lastNewline;hasRequiredLastNewline=1;const Transform=require$$0__default$4.default.Transform;return lastNewline=class LastNewline extends Transform{constructor(){super(),this.lastByte=!1}_transform(chunk,encoding,done){chunk.length&&(this.lastByte=chunk[chunk.length-1]),this.push(chunk),done()}_flush(done){return 10===this.lastByte?done():13===this.lastByte?(this.push(Buffer.from("\n")),done()):(this.push(Buffer.from("\r\n")),done())}}}(),LeWindows=requireLeWindows(),LeUnix=function requireLeUnix(){if(hasRequiredLeUnix)return leUnix;hasRequiredLeUnix=1;const Transform=require$$0__default$4.default.Transform;return leUnix=class LeWindows extends Transform{constructor(options){super(options),this.options=options||{}}_transform(chunk,encoding,done){let buf,lastPos=0;for(let i=0,len=chunk.length;i<len;i++)13===chunk[i]&&(buf=chunk.slice(lastPos,i),lastPos=i+1,this.push(buf));lastPos&&lastPos<chunk.length?(buf=chunk.slice(lastPos),this.push(buf)):lastPos||this.push(chunk),done()}}}();class MimeNode{constructor(contentType,options){this.nodeCounter=0,options=options||{},this.baseBoundary=options.baseBoundary||crypto.randomBytes(8).toString("hex"),this.boundaryPrefix=options.boundaryPrefix||"--_NmP",this.disableFileAccess=!!options.disableFileAccess,this.disableUrlAccess=!!options.disableUrlAccess,this.normalizeHeaderKey=options.normalizeHeaderKey,this.date=new Date,this.rootNode=options.rootNode||this,this.keepBcc=!!options.keepBcc,options.filename&&(this.filename=options.filename,contentType||(contentType=mimeFuncs.detectMimeType(this.filename.split(".").pop()))),this.textEncoding=(options.textEncoding||"").toString().trim().charAt(0).toUpperCase(),this.parentNode=options.parentNode,this.hostname=options.hostname,this.newline=options.newline,this.childNodes=[],this._nodeId=++this.rootNode.nodeCounter,this._headers=[],this._isPlainText=!1,this._hasLongLines=!1,this._envelope=!1,this._raw=!1,this._transforms=[],this._processFuncs=[],contentType&&this.setHeader("Content-Type",contentType)}createChild(contentType,options){options||"object"!=typeof contentType||(options=contentType,contentType=void 0);let node=new MimeNode(contentType,options);return this.appendChild(node),node}appendChild(childNode){return childNode.rootNode!==this.rootNode&&(childNode.rootNode=this.rootNode,childNode._nodeId=++this.rootNode.nodeCounter),childNode.parentNode=this,this.childNodes.push(childNode),childNode}replace(node){return node===this?this:(this.parentNode.childNodes.forEach((childNode,i)=>{childNode===this&&(node.rootNode=this.rootNode,node.parentNode=this.parentNode,node._nodeId=this._nodeId,this.rootNode=this,this.parentNode=void 0,node.parentNode.childNodes[i]=node)}),node)}remove(){if(!this.parentNode)return this;for(let i=this.parentNode.childNodes.length-1;i>=0;i--)if(this.parentNode.childNodes[i]===this)return this.parentNode.childNodes.splice(i,1),this.parentNode=void 0,this.rootNode=this,this}setHeader(key,value){let headerValue,added=!1;if(!value&&key&&"object"==typeof key)return key.key&&"value"in key?this.setHeader(key.key,key.value):Array.isArray(key)?key.forEach(i=>{this.setHeader(i.key,i.value)}):Object.keys(key).forEach(i=>{this.setHeader(i,key[i])}),this;headerValue={key:key=this._normalizeHeaderKey(key),value:value};for(let i=0,len=this._headers.length;i<len;i++)this._headers[i].key===key&&(added?(this._headers.splice(i,1),i--,len--):(this._headers[i]=headerValue,added=!0));return added||this._headers.push(headerValue),this}addHeader(key,value){return!value&&key&&"object"==typeof key?(key.key&&key.value?this.addHeader(key.key,key.value):Array.isArray(key)?key.forEach(i=>{this.addHeader(i.key,i.value)}):Object.keys(key).forEach(i=>{this.addHeader(i,key[i])}),this):Array.isArray(value)?(value.forEach(val=>{this.addHeader(key,val)}),this):(this._headers.push({key:this._normalizeHeaderKey(key),value:value}),this)}getHeader(key){key=this._normalizeHeaderKey(key);for(let i=0,len=this._headers.length;i<len;i++)if(this._headers[i].key===key)return this._headers[i].value}setContent(content){return this.content=content,"function"==typeof this.content.pipe?(this._contentErrorHandler=err=>{this.content.removeListener("error",this._contentErrorHandler),this.content=err},this.content.once("error",this._contentErrorHandler)):"string"==typeof this.content&&(this._isPlainText=mimeFuncs.isPlainText(this.content),this._isPlainText&&mimeFuncs.hasLongerLines(this.content,76)&&(this._hasLongLines=!0)),this}build(callback){let promise;callback||(promise=new Promise((resolve,reject)=>{callback=shared.callbackPromise(resolve,reject)}));let stream=this.createReadStream(),buf=[],buflen=0,returned=!1;return stream.on("readable",()=>{let chunk;for(;null!==(chunk=stream.read());)buf.push(chunk),buflen+=chunk.length}),stream.once("error",err=>{if(!returned)return returned=!0,callback(err)}),stream.once("end",chunk=>{if(!returned)return returned=!0,chunk&&chunk.length&&(buf.push(chunk),buflen+=chunk.length),callback(null,Buffer.concat(buf,buflen))}),promise}getTransferEncoding(){let transferEncoding=!1,contentType=(this.getHeader("Content-Type")||"").toString().toLowerCase().trim();return this.content&&(transferEncoding=(this.getHeader("Content-Transfer-Encoding")||"").toString().toLowerCase().trim(),transferEncoding&&["base64","quoted-printable"].includes(transferEncoding)||(/^text\//i.test(contentType)?transferEncoding=this._isPlainText&&!this._hasLongLines?"7bit":"string"==typeof this.content||this.content instanceof Buffer?"Q"===this._getTextEncoding(this.content)?"quoted-printable":"base64":"B"===this.textEncoding?"base64":"quoted-printable":/^(multipart|message)\//i.test(contentType)||(transferEncoding=transferEncoding||"base64"))),transferEncoding}buildHeaders(){let transferEncoding=this.getTransferEncoding(),headers=[];if(transferEncoding&&this.setHeader("Content-Transfer-Encoding",transferEncoding),this.filename&&!this.getHeader("Content-Disposition")&&this.setHeader("Content-Disposition","attachment"),this.rootNode===this){this.getHeader("Date")||this.setHeader("Date",this.date.toUTCString().replace(/GMT/,"+0000")),this.messageId(),this.getHeader("MIME-Version")||this.setHeader("MIME-Version","1.0");for(let i=this._headers.length-2;i>=0;i--){let header=this._headers[i];"Content-Type"===header.key&&(this._headers.splice(i,1),this._headers.push(header))}}return this._headers.forEach(header=>{let structured,param,key=header.key,value=header.value,options={};if(!value||"object"!=typeof value||["From","Sender","To","Cc","Bcc","Reply-To","Date","References"].includes(key)||(Object.keys(value).forEach(key=>{"value"!==key&&(options[key]=value[key])}),value=(value.value||"").toString(),value.trim()))if(options.prepared)options.foldLines?headers.push(mimeFuncs.foldLines(key+": "+value)):headers.push(key+": "+value);else{switch(header.key){case"Content-Disposition":structured=mimeFuncs.parseHeaderValue(value),this.filename&&(structured.params.filename=this.filename),value=mimeFuncs.buildHeaderValue(structured);break;case"Content-Type":structured=mimeFuncs.parseHeaderValue(value),this._handleContentType(structured),structured.value.match(/^text\/plain\b/)&&"string"==typeof this.content&&/[\u0080-\uFFFF]/.test(this.content)&&(structured.params.charset="utf-8"),value=mimeFuncs.buildHeaderValue(structured),this.filename&&(param=this._encodeWords(this.filename),(param!==this.filename||/[\s'"\\;:/=(),<>@[\]?]|^-/.test(param))&&(param='"'+param+'"'),value+="; name="+param);break;case"Bcc":if(!this.keepBcc)return}if(value=this._encodeHeaderValue(key,value),(value||"").toString().trim()){if("function"==typeof this.normalizeHeaderKey){let normalized=this.normalizeHeaderKey(key,value);normalized&&"string"==typeof normalized&&normalized.length&&(key=normalized)}headers.push(mimeFuncs.foldLines(key+": "+value,76))}}}),headers.join("\r\n")}createReadStream(options){let transform,stream=new PassThrough(options=options||{}),outputStream=stream;this.stream(stream,options,err=>{err?outputStream.emit("error",err):stream.end()});for(let i=0,len=this._transforms.length;i<len;i++)transform="function"==typeof this._transforms[i]?this._transforms[i]():this._transforms[i],outputStream.once("error",err=>{transform.emit("error",err)}),outputStream=outputStream.pipe(transform);transform=new LastNewline,outputStream.once("error",err=>{transform.emit("error",err)}),outputStream=outputStream.pipe(transform);for(let i=0,len=this._processFuncs.length;i<len;i++)transform=this._processFuncs[i],outputStream=transform(outputStream);if(this.newline){const newlineTransform=["win","windows","dos","\r\n"].includes(this.newline.toString().toLowerCase())?new LeWindows:new LeUnix,stream=outputStream.pipe(newlineTransform);return outputStream.on("error",err=>stream.emit("error",err)),stream}return outputStream}transform(transform){this._transforms.push(transform)}processFunc(processFunc){this._processFuncs.push(processFunc)}stream(outputStream,options,done){let contentStream,localStream,transferEncoding=this.getTransferEncoding(),returned=!1,callback=err=>{returned||(returned=!0,done(err))},finalize=()=>{let childId=0,processChildNode=()=>{if(childId>=this.childNodes.length)return outputStream.write("\r\n--"+this.boundary+"--\r\n"),callback();let child=this.childNodes[childId++];outputStream.write((childId>1?"\r\n":"")+"--"+this.boundary+"\r\n"),child.stream(outputStream,options,err=>{if(err)return callback(err);setImmediate(processChildNode)})};if(!this.multipart)return callback();setImmediate(processChildNode)},sendContent=()=>{if(this.content){if("[object Error]"===Object.prototype.toString.call(this.content))return callback(this.content);"function"==typeof this.content.pipe&&(this.content.removeListener("error",this._contentErrorHandler),this._contentErrorHandler=err=>callback(err),this.content.once("error",this._contentErrorHandler));let createStream=()=>{["quoted-printable","base64"].includes(transferEncoding)?(contentStream=new("base64"===transferEncoding?base64:qp).Encoder(options),contentStream.pipe(outputStream,{end:!1}),contentStream.once("end",finalize),contentStream.once("error",err=>callback(err)),localStream=this._getStream(this.content),localStream.pipe(contentStream)):(localStream=this._getStream(this.content),localStream.pipe(outputStream,{end:!1}),localStream.once("end",finalize)),localStream.once("error",err=>callback(err))};if(this.content._resolve){let chunks=[],chunklen=0,returned=!1,sourceStream=this._getStream(this.content);sourceStream.on("error",err=>{returned||(returned=!0,callback(err))}),sourceStream.on("readable",()=>{let chunk;for(;null!==(chunk=sourceStream.read());)chunks.push(chunk),chunklen+=chunk.length}),sourceStream.on("end",()=>{returned||(returned=!0,this.content._resolve=!1,this.content._resolvedValue=Buffer.concat(chunks,chunklen),setImmediate(createStream))})}else setImmediate(createStream);return}return setImmediate(finalize)};this._raw?setImmediate(()=>{if("[object Error]"===Object.prototype.toString.call(this._raw))return callback(this._raw);"function"==typeof this._raw.pipe&&this._raw.removeListener("error",this._contentErrorHandler);let raw=this._getStream(this._raw);raw.pipe(outputStream,{end:!1}),raw.on("error",err=>outputStream.emit("error",err)),raw.on("end",finalize)}):(outputStream.write(this.buildHeaders()+"\r\n\r\n"),setImmediate(sendContent))}setEnvelope(envelope){let list;this._envelope={from:!1,to:[]},envelope.from&&(list=[],this._convertAddresses(this._parseAddresses(envelope.from),list),list=list.filter(address=>address&&address.address),list.length&&list[0]&&(this._envelope.from=list[0].address)),["to","cc","bcc"].forEach(key=>{envelope[key]&&this._convertAddresses(this._parseAddresses(envelope[key]),this._envelope.to)}),this._envelope.to=this._envelope.to.map(to=>to.address).filter(address=>address);let standardFields=["to","cc","bcc","from"];return Object.keys(envelope).forEach(key=>{standardFields.includes(key)||(this._envelope[key]=envelope[key])}),this}getAddresses(){let addresses={};return this._headers.forEach(header=>{let key=header.key.toLowerCase();["from","sender","reply-to","to","cc","bcc"].includes(key)&&(Array.isArray(addresses[key])||(addresses[key]=[]),this._convertAddresses(this._parseAddresses(header.value),addresses[key]))}),addresses}getEnvelope(){if(this._envelope)return this._envelope;let envelope={from:!1,to:[]};return this._headers.forEach(header=>{let list=[];"From"===header.key||!envelope.from&&["Reply-To","Sender"].includes(header.key)?(this._convertAddresses(this._parseAddresses(header.value),list),list.length&&list[0]&&(envelope.from=list[0].address)):["To","Cc","Bcc"].includes(header.key)&&this._convertAddresses(this._parseAddresses(header.value),envelope.to)}),envelope.to=envelope.to.map(to=>to.address),envelope}messageId(){let messageId=this.getHeader("Message-ID");return messageId||(messageId=this._generateMessageId(),this.setHeader("Message-ID",messageId)),messageId}setRaw(raw){return this._raw=raw,this._raw&&"function"==typeof this._raw.pipe&&(this._contentErrorHandler=err=>{this._raw.removeListener("error",this._contentErrorHandler),this._raw=err},this._raw.once("error",this._contentErrorHandler)),this}_getStream(content){let contentStream;return content._resolvedValue?(contentStream=new PassThrough,setImmediate(()=>{try{contentStream.end(content._resolvedValue)}catch(err){contentStream.emit("error",err)}}),contentStream):"function"==typeof content.pipe?content:content&&"string"==typeof content.path&&!content.href?this.disableFileAccess?(contentStream=new PassThrough,setImmediate(()=>contentStream.emit("error",new Error("File access rejected for "+content.path))),contentStream):fs.createReadStream(content.path):content&&"string"==typeof content.href?this.disableUrlAccess?(contentStream=new PassThrough,setImmediate(()=>contentStream.emit("error",new Error("Url access rejected for "+content.href))),contentStream):nmfetch(content.href,{headers:content.httpHeaders}):(contentStream=new PassThrough,setImmediate(()=>{try{contentStream.end(content||"")}catch(err){contentStream.emit("error",err)}}),contentStream)}_parseAddresses(addresses){return[].concat.apply([],[].concat(addresses).map(address=>address&&address.address?(address.address=this._normalizeAddress(address.address),address.name=address.name||"",[address]):addressparser(address)))}_normalizeHeaderKey(key){return key=(key||"").toString().replace(/\r?\n|\r/g," ").trim().toLowerCase().replace(/^X-SMTPAPI$|^(MIME|DKIM|ARC|BIMI)\b|^[a-z]|-(SPF|FBL|ID|MD5)$|-[a-z]/gi,c=>c.toUpperCase()).replace(/^Content-Features$/i,"Content-features")}_handleContentType(structured){this.contentType=structured.value.trim().toLowerCase(),this.multipart=!!/^multipart\//i.test(this.contentType)&&this.contentType.substr(this.contentType.indexOf("/")+1),this.multipart?this.boundary=structured.params.boundary=structured.params.boundary||this.boundary||this._generateBoundary():this.boundary=!1}_generateBoundary(){return this.rootNode.boundaryPrefix+"-"+this.rootNode.baseBoundary+"-Part_"+this._nodeId}_encodeHeaderValue(key,value){switch(key=this._normalizeHeaderKey(key)){case"From":case"Sender":case"To":case"Cc":case"Bcc":case"Reply-To":return this._convertAddresses(this._parseAddresses(value));case"Message-ID":case"In-Reply-To":case"Content-Id":return"<"!==(value=(value||"").toString().replace(/\r?\n|\r/g," ")).charAt(0)&&(value="<"+value),">"!==value.charAt(value.length-1)&&(value+=">"),value;case"References":return(value=[].concat.apply([],[].concat(value||"").map(elm=>(elm=(elm||"").toString().replace(/\r?\n|\r/g," ").trim()).replace(/<[^>]*>/g,str=>str.replace(/\s/g,"")).split(/\s+/))).map(elm=>("<"!==elm.charAt(0)&&(elm="<"+elm),">"!==elm.charAt(elm.length-1)&&(elm+=">"),elm))).join(" ").trim();case"Date":return"[object Date]"===Object.prototype.toString.call(value)?value.toUTCString().replace(/GMT/,"+0000"):(value=(value||"").toString().replace(/\r?\n|\r/g," "),this._encodeWords(value));case"Content-Type":case"Content-Disposition":return(value||"").toString().replace(/\r?\n|\r/g," ");default:return value=(value||"").toString().replace(/\r?\n|\r/g," "),this._encodeWords(value)}}_convertAddresses(addresses,uniqueList){let values=[];return uniqueList=uniqueList||[],[].concat(addresses||[]).forEach(address=>{if(address.address)address.address=this._normalizeAddress(address.address),address.name?address.name&&values.push(`${this._encodeAddressName(address.name)} <${address.address}>`):values.push(address.address.indexOf(" ")>=0?`<${address.address}>`:`${address.address}`),address.address&&(uniqueList.filter(a=>a.address===address.address).length||uniqueList.push(address));else if(address.group){let groupListAddresses=(address.group.length?this._convertAddresses(address.group,uniqueList):"").trim();values.push(`${this._encodeAddressName(address.name)}:${groupListAddresses};`)}}),values.join(", ")}_normalizeAddress(address){let lastAt=(address=(address||"").toString().replace(/[\x00-\x1F<>]+/g," ").trim()).lastIndexOf("@");if(lastAt<0)return address;let encodedDomain,user=address.substr(0,lastAt),domain=address.substr(lastAt+1);try{encodedDomain=punycode.toASCII(domain.toLowerCase())}catch(err){}return user.indexOf(" ")>=0&&('"'!==user.charAt(0)&&(user='"'+user),'"'!==user.substr(-1)&&(user+='"')),`${user}@${encodedDomain}`}_encodeAddressName(name){return/^[\w ]*$/.test(name)?name:/^[\x20-\x7e]*$/.test(name)?'"'+name.replace(/([\\"])/g,"\\$1")+'"':mimeFuncs.encodeWord(name,this._getTextEncoding(name),52)}_encodeWords(value){return mimeFuncs.encodeWords(value,this._getTextEncoding(value),52,!0)}_getTextEncoding(value){value=(value||"").toString();let latinLen,nonLatinLen,encoding=this.textEncoding;return encoding||(nonLatinLen=(value.match(/[\x00-\x08\x0B\x0C\x0E-\x1F\u0080-\uFFFF]/g)||[]).length,latinLen=(value.match(/[a-z]/gi)||[]).length,encoding=nonLatinLen<latinLen?"Q":"B"),encoding}_generateMessageId(){return"<"+[2,2,2,6].reduce((prev,len)=>prev+"-"+crypto.randomBytes(len).toString("hex"),crypto.randomBytes(4).toString("hex"))+"@"+(this.getEnvelope().from||this.hostname||"localhost").split("@").pop()+">"}}return mimeNode=MimeNode}var hasRequiredSign,dkim,hasRequiredDkim,httpProxyClient_1,hasRequiredHttpProxyClient,mailMessage,hasRequiredMailMessage,mailer,hasRequiredMailer,dataStream,hasRequiredDataStream,smtpConnection,hasRequiredSmtpConnection,xoauth2,hasRequiredXoauth2,poolResource,hasRequiredPoolResource,sign={exports:{}};function requireSign(){if(hasRequiredSign)return sign.exports;hasRequiredSign=1;const punycode=requirePunycode(),mimeFuncs=requireMimeFuncs(),crypto=require$$0__default$1.default;function relaxedHeaders(headers,fieldNames,skipFields){let includedFields=new Set,skip=new Set,headerFields=new Map;(skipFields||"").toLowerCase().split(":").forEach(field=>{skip.add(field.trim())}),(fieldNames||"").toLowerCase().split(":").filter(field=>!skip.has(field.trim())).forEach(field=>{includedFields.add(field.trim())});for(let i=headers.length-1;i>=0;i--){let line=headers[i];includedFields.has(line.key)&&!headerFields.has(line.key)&&headerFields.set(line.key,relaxedHeaderLine(line.line))}let headersList=[],fields=[];return includedFields.forEach(field=>{headerFields.has(field)&&(fields.push(field),headersList.push(field+":"+headerFields.get(field)))}),{headers:headersList.join("\r\n")+"\r\n",fieldNames:fields.join(":")}}function relaxedHeaderLine(line){return line.substr(line.indexOf(":")+1).replace(/\r?\n/g,"").replace(/\s+/g," ").trim()}return sign.exports=(headers,hashAlgo,bodyHash,options)=>{let signer,signature,canonicalizedHeaderData=relaxedHeaders(headers,(options=options||{}).headerFieldNames||"From:Sender:Reply-To:Subject:Date:Message-ID:To:Cc:MIME-Version:Content-Type:Content-Transfer-Encoding:Content-ID:Content-Description:Resent-Date:Resent-From:Resent-Sender:Resent-To:Resent-Cc:Resent-Message-ID:In-Reply-To:References:List-Id:List-Help:List-Unsubscribe:List-Subscribe:List-Post:List-Owner:List-Archive",options.skipFields),dkimHeader=function generateDKIMHeader(domainName,keySelector,fieldNames,hashAlgo,bodyHash){let dkim=["v=1","a=rsa-"+hashAlgo,"c=relaxed/relaxed","d="+punycode.toASCII(domainName),"q=dns/txt","s="+keySelector,"bh="+bodyHash,"h="+fieldNames].join("; ");return mimeFuncs.foldLines("DKIM-Signature: "+dkim,76)+";\r\n b="}(options.domainName,options.keySelector,canonicalizedHeaderData.fieldNames,hashAlgo,bodyHash);canonicalizedHeaderData.headers+="dkim-signature:"+relaxedHeaderLine(dkimHeader),signer=crypto.createSign(("rsa-"+hashAlgo).toUpperCase()),signer.update(canonicalizedHeaderData.headers);try{signature=signer.sign(options.privateKey,"base64")}catch(E){return!1}return dkimHeader+signature.replace(/(^.{73}|.{75}(?!\r?\n|\r))/g,"$&\r\n ").trim()},sign.exports.relaxedHeaders=relaxedHeaders,sign.exports}function requireDkim(){if(hasRequiredDkim)return dkim;hasRequiredDkim=1;const MessageParser=function requireMessageParser(){if(hasRequiredMessageParser)return messageParser;hasRequiredMessageParser=1;const Transform=require$$0__default$4.default.Transform;return messageParser=class MessageParser extends Transform{constructor(options){super(options),this.lastBytes=Buffer.alloc(4),this.headersParsed=!1,this.headerBytes=0,this.headerChunks=[],this.rawHeaders=!1,this.bodySize=0}updateLastBytes(data){let lblen=this.lastBytes.length,nblen=Math.min(data.length,lblen);for(let i=0,len=lblen-nblen;i<len;i++)this.lastBytes[i]=this.lastBytes[i+nblen];for(let i=1;i<=nblen;i++)this.lastBytes[lblen-i]=data[data.length-i]}checkHeaders(data){if(this.headersParsed)return!0;let lblen=this.lastBytes.length,headerPos=0;this.curLinePos=0;for(let i=0,len=this.lastBytes.length+data.length;i<len;i++){let chr;if(chr=i<lblen?this.lastBytes[i]:data[i-lblen],10===chr&&i){let pr1=i-1<lblen?this.lastBytes[i-1]:data[i-1-lblen],pr2=i>1&&(i-2<lblen?this.lastBytes[i-2]:data[i-2-lblen]);if(10===pr1){this.headersParsed=!0,headerPos=i-lblen+1,this.headerBytes+=headerPos;break}if(13===pr1&&10===pr2){this.headersParsed=!0,headerPos=i-lblen+1,this.headerBytes+=headerPos;break}}}if(this.headersParsed){if(this.headerChunks.push(data.slice(0,headerPos)),this.rawHeaders=Buffer.concat(this.headerChunks,this.headerBytes),this.headerChunks=null,this.emit("headers",this.parseHeaders()),data.length-1>headerPos){let chunk=data.slice(headerPos);this.bodySize+=chunk.length,setImmediate(()=>this.push(chunk))}return!1}return this.headerBytes+=data.length,this.headerChunks.push(data),this.updateLastBytes(data),!1}_transform(chunk,encoding,callback){if(!chunk||!chunk.length)return callback();let headersFound;"string"==typeof chunk&&(chunk=Buffer.from(chunk,encoding));try{headersFound=this.checkHeaders(chunk)}catch(E){return callback(E)}headersFound&&(this.bodySize+=chunk.length,this.push(chunk)),setImmediate(callback)}_flush(callback){if(this.headerChunks){let chunk=Buffer.concat(this.headerChunks,this.headerBytes);this.bodySize+=chunk.length,this.push(chunk),this.headerChunks=null}callback()}parseHeaders(){let lines=(this.rawHeaders||"").toString().split(/\r?\n/);for(let i=lines.length-1;i>0;i--)/^\s/.test(lines[i])&&(lines[i-1]+="\n"+lines[i],lines.splice(i,1));return lines.filter(line=>line.trim()).map(line=>({key:line.substr(0,line.indexOf(":")).trim().toLowerCase(),line:line}))}}}(),RelaxedBody=function requireRelaxedBody(){if(hasRequiredRelaxedBody)return relaxedBody;hasRequiredRelaxedBody=1;const Transform=require$$0__default$4.default.Transform,crypto=require$$0__default$1.default;return relaxedBody=class RelaxedBody extends Transform{constructor(options){super(),options=options||{},this.chunkBuffer=[],this.chunkBufferLen=0,this.bodyHash=crypto.createHash(options.hashAlgo||"sha1"),this.remainder="",this.byteLength=0,this.debug=options.debug,this._debugBody=!!options.debug&&[]}updateHash(chunk){let bodyStr,nextRemainder="",state="file";for(let i=chunk.length-1;i>=0;i--){let c=chunk[i];if("file"!==state||10!==c&&13!==c)if("file"!==state||9!==c&&32!==c){if(("line"!==state||9!==c&&32!==c)&&("file"===state||"line"===state)&&(state="body",i===chunk.length-1))break}else state="line";if(0===i){if("file"===state&&(!this.remainder||/[\r\n]$/.test(this.remainder))||"line"===state&&(!this.remainder||/[ \t]$/.test(this.remainder)))return void(this.remainder+=chunk.toString("binary"));if("line"===state||"file"===state){nextRemainder=chunk.toString("binary"),chunk=!1;break}}if("body"===state){nextRemainder=chunk.slice(i+1).toString("binary"),chunk=chunk.slice(0,i+1);break}}let needsFixing=!!this.remainder;if(chunk&&!needsFixing)for(let i=0,len=chunk.length;i<len;i++){if(i&&10===chunk[i]&&13!==chunk[i-1]){needsFixing=!0;break}if(i&&13===chunk[i]&&32===chunk[i-1]){needsFixing=!0;break}if(i&&32===chunk[i]&&32===chunk[i-1]){needsFixing=!0;break}if(9===chunk[i]){needsFixing=!0;break}}needsFixing?(bodyStr=this.remainder+(chunk?chunk.toString("binary"):""),this.remainder=nextRemainder,bodyStr=bodyStr.replace(/\r?\n/g,"\n").replace(/[ \t]*$/gm,"").replace(/[ \t]+/gm," ").replace(/\n/g,"\r\n"),chunk=Buffer.from(bodyStr,"binary")):nextRemainder&&(this.remainder=nextRemainder),this.debug&&this._debugBody.push(chunk),this.bodyHash.update(chunk)}_transform(chunk,encoding,callback){if(!chunk||!chunk.length)return callback();"string"==typeof chunk&&(chunk=Buffer.from(chunk,encoding)),this.updateHash(chunk),this.byteLength+=chunk.length,this.push(chunk),callback()}_flush(callback){/[\r\n]$/.test(this.remainder)&&this.byteLength>2&&this.bodyHash.update(Buffer.from("\r\n")),this.byteLength||this.push(Buffer.from("\r\n")),this.emit("hash",this.bodyHash.digest("base64"),!!this.debug&&Buffer.concat(this._debugBody)),callback()}},relaxedBody}(),sign=requireSign(),PassThrough=require$$0__default$4.default.PassThrough,fs=fs__default.default,path=path__default.default,crypto=require$$0__default$1.default;class DKIMSigner{constructor(options,keys,input,output){this.options=options||{},this.keys=keys,this.cacheTreshold=Number(this.options.cacheTreshold)||131072,this.hashAlgo=this.options.hashAlgo||"sha256",this.cacheDir=this.options.cacheDir||!1,this.chunks=[],this.chunklen=0,this.readPos=0,this.cachePath=!!this.cacheDir&&path.join(this.cacheDir,"message."+Date.now()+"-"+crypto.randomBytes(14).toString("hex")),this.cache=!1,this.headers=!1,this.bodyHash=!1,this.parser=!1,this.relaxedBody=!1,this.input=input,this.output=output,this.output.usingCache=!1,this.hasErrored=!1,this.input.on("error",err=>{this.hasErrored=!0,this.cleanup(),output.emit("error",err)})}cleanup(){this.cache&&this.cachePath&&fs.unlink(this.cachePath,()=>!1)}createReadCache(){this.cache=fs.createReadStream(this.cachePath),this.cache.once("error",err=>{this.cleanup(),this.output.emit("error",err)}),this.cache.once("close",()=>{this.cleanup()}),this.cache.pipe(this.output)}sendNextChunk(){if(this.hasErrored)return;if(this.readPos>=this.chunks.length)return this.cache?this.createReadCache():this.output.end();let chunk=this.chunks[this.readPos++];if(!1===this.output.write(chunk))return this.output.once("drain",()=>{this.sendNextChunk()});setImmediate(()=>this.sendNextChunk())}sendSignedOutput(){let keyPos=0,signNextKey=()=>{if(keyPos>=this.keys.length)return this.output.write(this.parser.rawHeaders),setImmediate(()=>this.sendNextChunk());let key=this.keys[keyPos++],dkimField=sign(this.headers,this.hashAlgo,this.bodyHash,{domainName:key.domainName,keySelector:key.keySelector,privateKey:key.privateKey,headerFieldNames:this.options.headerFieldNames,skipFields:this.options.skipFields});return dkimField&&this.output.write(Buffer.from(dkimField+"\r\n")),setImmediate(signNextKey)};if(this.bodyHash&&this.headers)return signNextKey();this.output.write(this.parser.rawHeaders),this.sendNextChunk()}createWriteCache(){this.output.usingCache=!0,this.cache=fs.createWriteStream(this.cachePath),this.cache.once("error",err=>{this.cleanup(),this.relaxedBody.unpipe(this.cache),this.relaxedBody.on("readable",()=>{for(;null!==this.relaxedBody.read(););}),this.hasErrored=!0,this.output.emit("error",err)}),this.cache.once("close",()=>{this.sendSignedOutput()}),this.relaxedBody.removeAllListeners("readable"),this.relaxedBody.pipe(this.cache)}signStream(){this.parser=new MessageParser,this.relaxedBody=new RelaxedBody({hashAlgo:this.hashAlgo}),this.parser.on("headers",value=>{this.headers=value}),this.relaxedBody.on("hash",value=>{this.bodyHash=value}),this.relaxedBody.on("readable",()=>{let chunk;if(!this.cache)for(;null!==(chunk=this.relaxedBody.read());)if(this.chunks.push(chunk),this.chunklen+=chunk.length,this.chunklen>=this.cacheTreshold&&this.cachePath)return this.createWriteCache()}),this.relaxedBody.on("end",()=>{this.cache||this.sendSignedOutput()}),this.parser.pipe(this.relaxedBody),setImmediate(()=>this.input.pipe(this.parser))}}return dkim=class DKIM{constructor(options){this.options=options||{},this.keys=[].concat(this.options.keys||{domainName:options.domainName,keySelector:options.keySelector,privateKey:options.privateKey})}sign(input,extraOptions){let output=new PassThrough,inputStream=input,writeValue=!1;Buffer.isBuffer(input)?(writeValue=input,inputStream=new PassThrough):"string"==typeof input&&(writeValue=Buffer.from(input),inputStream=new PassThrough);let options=this.options;extraOptions&&Object.keys(extraOptions).length&&(options={},Object.keys(this.options||{}).forEach(key=>{options[key]=this.options[key]}),Object.keys(extraOptions||{}).forEach(key=>{key in options||(options[key]=extraOptions[key])}));let signer=new DKIMSigner(options,this.keys,inputStream,output);return setImmediate(()=>{signer.signStream(),writeValue&&setImmediate(()=>{inputStream.end(writeValue)})}),output}}}function requireMailer(){if(hasRequiredMailer)return mailer;hasRequiredMailer=1;const EventEmitter=require$$0__default.default,shared=requireShared(),mimeTypes=requireMimeTypes(),MailComposer=function requireMailComposer(){if(hasRequiredMailComposer)return mailComposer;hasRequiredMailComposer=1;const MimeNode=requireMimeNode(),mimeFuncs=requireMimeFuncs(),parseDataURI=requireShared().parseDataURI;return mailComposer=class MailComposer{constructor(mail){this.mail=mail||{},this.message=!1}compile(){return this._alternatives=this.getAlternatives(),this._htmlNode=this._alternatives.filter(alternative=>/^text\/html\b/i.test(alternative.contentType)).pop(),this._attachments=this.getAttachments(!!this._htmlNode),this._useRelated=!(!this._htmlNode||!this._attachments.related.length),this._useAlternative=this._alternatives.length>1,this._useMixed=this._attachments.attached.length>1||this._alternatives.length&&1===this._attachments.attached.length,this.mail.raw?this.message=new MimeNode("message/rfc822",{newline:this.mail.newline}).setRaw(this.mail.raw):this._useMixed?this.message=this._createMixed():this._useAlternative?this.message=this._createAlternative():this._useRelated?this.message=this._createRelated():this.message=this._createContentNode(!1,[].concat(this._alternatives||[]).concat(this._attachments.attached||[]).shift()||{contentType:"text/plain",content:""}),this.mail.headers&&this.message.addHeader(this.mail.headers),["from","sender","to","cc","bcc","reply-to","in-reply-to","references","subject","message-id","date"].forEach(header=>{let key=header.replace(/-(\w)/g,(o,c)=>c.toUpperCase());this.mail[key]&&this.message.setHeader(header,this.mail[key])}),this.mail.envelope&&this.message.setEnvelope(this.mail.envelope),this.message.messageId(),this.message}getAttachments(findRelated){let icalEvent,eventObject,attachments=[].concat(this.mail.attachments||[]).map((attachment,i)=>{let data,isMessageNode=/^message\//i.test(attachment.contentType);/^data:/i.test(attachment.path||attachment.href)&&(attachment=this._processDataUrl(attachment));let contentType=attachment.contentType||mimeFuncs.detectMimeType(attachment.filename||attachment.path||attachment.href||"bin"),isImage=/^image\//i.test(contentType);return data={contentType:contentType,contentDisposition:attachment.contentDisposition||(isMessageNode||isImage&&attachment.cid?"inline":"attachment"),contentTransferEncoding:"contentTransferEncoding"in attachment?attachment.contentTransferEncoding:"base64"},attachment.filename?data.filename=attachment.filename:isMessageNode||!1===attachment.filename||(data.filename=(attachment.path||attachment.href||"").split("/").pop().split("?").shift()||"attachment-"+(i+1),data.filename.indexOf(".")<0&&(data.filename+="."+mimeFuncs.detectExtension(data.contentType))),/^https?:\/\//i.test(attachment.path)&&(attachment.href=attachment.path,attachment.path=void 0),attachment.cid&&(data.cid=attachment.cid),attachment.raw?data.raw=attachment.raw:attachment.path?data.content={path:attachment.path}:attachment.href?data.content={href:attachment.href,httpHeaders:attachment.httpHeaders}:data.content=attachment.content||"",attachment.encoding&&(data.encoding=attachment.encoding),attachment.headers&&(data.headers=attachment.headers),data});return this.mail.icalEvent&&(icalEvent="object"==typeof this.mail.icalEvent&&(this.mail.icalEvent.content||this.mail.icalEvent.path||this.mail.icalEvent.href||this.mail.icalEvent.raw)?this.mail.icalEvent:{content:this.mail.icalEvent},eventObject={},Object.keys(icalEvent).forEach(key=>{eventObject[key]=icalEvent[key]}),eventObject.contentType="application/ics",eventObject.headers||(eventObject.headers={}),eventObject.filename=eventObject.filename||"invite.ics",eventObject.headers["Content-Disposition"]="attachment",eventObject.headers["Content-Transfer-Encoding"]="base64"),findRelated?{attached:attachments.filter(attachment=>!attachment.cid).concat(eventObject||[]),related:attachments.filter(attachment=>!!attachment.cid)}:{attached:attachments.concat(eventObject||[]),related:[]}}getAlternatives(){let text,html,watchHtml,amp,icalEvent,eventObject,alternatives=[];return this.mail.text&&(text="object"==typeof this.mail.text&&(this.mail.text.content||this.mail.text.path||this.mail.text.href||this.mail.text.raw)?this.mail.text:{content:this.mail.text},text.contentType="text/plain; charset=utf-8"),this.mail.watchHtml&&(watchHtml="object"==typeof this.mail.watchHtml&&(this.mail.watchHtml.content||this.mail.watchHtml.path||this.mail.watchHtml.href||this.mail.watchHtml.raw)?this.mail.watchHtml:{content:this.mail.watchHtml},watchHtml.contentType="text/watch-html; charset=utf-8"),this.mail.amp&&(amp="object"==typeof this.mail.amp&&(this.mail.amp.content||this.mail.amp.path||this.mail.amp.href||this.mail.amp.raw)?this.mail.amp:{content:this.mail.amp},amp.contentType="text/x-amp-html; charset=utf-8"),this.mail.icalEvent&&(icalEvent="object"==typeof this.mail.icalEvent&&(this.mail.icalEvent.content||this.mail.icalEvent.path||this.mail.icalEvent.href||this.mail.icalEvent.raw)?this.mail.icalEvent:{content:this.mail.icalEvent},eventObject={},Object.keys(icalEvent).forEach(key=>{eventObject[key]=icalEvent[key]}),eventObject.content&&"object"==typeof eventObject.content&&(eventObject.content._resolve=!0),eventObject.filename=!1,eventObject.contentType="text/calendar; charset=utf-8; method="+(eventObject.method||"PUBLISH").toString().trim().toUpperCase(),eventObject.headers||(eventObject.headers={})),this.mail.html&&(html="object"==typeof this.mail.html&&(this.mail.html.content||this.mail.html.path||this.mail.html.href||this.mail.html.raw)?this.mail.html:{content:this.mail.html},html.contentType="text/html; charset=utf-8"),[].concat(text||[]).concat(watchHtml||[]).concat(amp||[]).concat(html||[]).concat(eventObject||[]).concat(this.mail.alternatives||[]).forEach(alternative=>{let data;/^data:/i.test(alternative.path||alternative.href)&&(alternative=this._processDataUrl(alternative)),data={contentType:alternative.contentType||mimeFuncs.detectMimeType(alternative.filename||alternative.path||alternative.href||"txt"),contentTransferEncoding:alternative.contentTransferEncoding},alternative.filename&&(data.filename=alternative.filename),/^https?:\/\//i.test(alternative.path)&&(alternative.href=alternative.path,alternative.path=void 0),alternative.raw?data.raw=alternative.raw:alternative.path?data.content={path:alternative.path}:alternative.href?data.content={href:alternative.href}:data.content=alternative.content||"",alternative.encoding&&(data.encoding=alternative.encoding),alternative.headers&&(data.headers=alternative.headers),alternatives.push(data)}),alternatives}_createMixed(parentNode){let node;return node=parentNode?parentNode.createChild("multipart/mixed",{disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new MimeNode("multipart/mixed",{baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}),this._useAlternative?this._createAlternative(node):this._useRelated&&this._createRelated(node),[].concat(!this._useAlternative&&this._alternatives||[]).concat(this._attachments.attached||[]).forEach(element=>{this._useRelated&&element===this._htmlNode||this._createContentNode(node,element)}),node}_createAlternative(parentNode){let node;return node=parentNode?parentNode.createChild("multipart/alternative",{disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new MimeNode("multipart/alternative",{baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}),this._alternatives.forEach(alternative=>{this._useRelated&&this._htmlNode===alternative?this._createRelated(node):this._createContentNode(node,alternative)}),node}_createRelated(parentNode){let node;return node=parentNode?parentNode.createChild('multipart/related; type="text/html"',{disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new MimeNode('multipart/related; type="text/html"',{baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}),this._createContentNode(node,this._htmlNode),this._attachments.related.forEach(alternative=>this._createContentNode(node,alternative)),node}_createContentNode(parentNode,element){let node;(element=element||{}).content=element.content||"";let encoding=(element.encoding||"utf8").toString().toLowerCase().replace(/[-_\s]/g,"");return node=parentNode?parentNode.createChild(element.contentType,{filename:element.filename,textEncoding:this.mail.textEncoding,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}):new MimeNode(element.contentType,{filename:element.filename,baseBoundary:this.mail.baseBoundary,textEncoding:this.mail.textEncoding,boundaryPrefix:this.mail.boundaryPrefix,disableUrlAccess:this.mail.disableUrlAccess,disableFileAccess:this.mail.disableFileAccess,normalizeHeaderKey:this.mail.normalizeHeaderKey,newline:this.mail.newline}),element.headers&&node.addHeader(element.headers),element.cid&&node.setHeader("Content-Id","<"+element.cid.replace(/[<>]/g,"")+">"),element.contentTransferEncoding?node.setHeader("Content-Transfer-Encoding",element.contentTransferEncoding):this.mail.encoding&&/^text\//i.test(element.contentType)&&node.setHeader("Content-Transfer-Encoding",this.mail.encoding),/^text\//i.test(element.contentType)&&!element.contentDisposition||node.setHeader("Content-Disposition",element.contentDisposition||(element.cid&&/^image\//i.test(element.contentType)?"inline":"attachment")),"string"!=typeof element.content||["utf8","usascii","ascii"].includes(encoding)||(element.content=Buffer.from(element.content,encoding)),element.raw?node.setRaw(element.raw):node.setContent(element.content),node}_processDataUrl(element){let parsedDataUri;return(element.path||element.href).match(/^data:/)&&(parsedDataUri=parseDataURI(element.path||element.href)),parsedDataUri?(element.content=parsedDataUri.data,element.contentType=element.contentType||parsedDataUri.contentType,"path"in element&&(element.path=!1),"href"in element&&(element.href=!1),element):element}},mailComposer}(),DKIM=requireDkim(),httpProxyClient=function requireHttpProxyClient(){if(hasRequiredHttpProxyClient)return httpProxyClient_1;hasRequiredHttpProxyClient=1;const net=require$$7__default.default,tls=require$$1__default$2.default,urllib=require$$0__default$6.default;return httpProxyClient_1=function httpProxyClient(proxyUrl,destinationPort,destinationHost,callback){let options,connect,socket,proxy=urllib.parse(proxyUrl);options={host:proxy.hostname,port:Number(proxy.port)?Number(proxy.port):"https:"===proxy.protocol?443:80},"https:"===proxy.protocol?(options.rejectUnauthorized=!1,connect=tls.connect.bind(tls)):connect=net.connect.bind(net);let finished=!1,tempSocketErr=err=>{if(!finished){finished=!0;try{socket.destroy()}catch(E){}callback(err)}},timeoutErr=()=>{let err=new Error("Proxy socket timed out");err.code="ETIMEDOUT",tempSocketErr(err)};socket=connect(options,()=>{if(finished)return;let reqHeaders={Host:destinationHost+":"+destinationPort,Connection:"close"};proxy.auth&&(reqHeaders["Proxy-Authorization"]="Basic "+Buffer.from(proxy.auth).toString("base64")),socket.write("CONNECT "+destinationHost+":"+destinationPort+" HTTP/1.1\r\n"+Object.keys(reqHeaders).map(key=>key+": "+reqHeaders[key]).join("\r\n")+"\r\n\r\n");let headers="",onSocketData=chunk=>{let match,remainder;if(!finished&&(headers+=chunk.toString("binary"),match=headers.match(/\r\n\r\n/))){if(socket.removeListener("data",onSocketData),remainder=headers.substr(match.index+match[0].length),headers=headers.substr(0,match.index),remainder&&socket.unshift(Buffer.from(remainder,"binary")),finished=!0,match=headers.match(/^HTTP\/\d+\.\d+ (\d+)/i),!match||"2"!==(match[1]||"").charAt(0)){try{socket.destroy()}catch(E){}return callback(new Error("Invalid response from proxy"+(match&&": "+match[1]||"")))}return socket.removeListener("error",tempSocketErr),socket.removeListener("timeout",timeoutErr),socket.setTimeout(0),callback(null,socket)}};socket.on("data",onSocketData)}),socket.setTimeout(httpProxyClient.timeout||3e4),socket.on("timeout",timeoutErr),socket.once("error",tempSocketErr)},httpProxyClient_1}(),util=require$$0__default$2.default,urllib=require$$0__default$6.default,packageData=require$$9,MailMessage=function requireMailMessage(){if(hasRequiredMailMessage)return mailMessage;hasRequiredMailMessage=1;const shared=requireShared(),MimeNode=requireMimeNode(),mimeFuncs=requireMimeFuncs();return mailMessage=class MailMessage{constructor(mailer,data){this.mailer=mailer,this.data={},this.message=null,data=data||{};let options=mailer.options||{},defaults=mailer._defaults||{};Object.keys(data).forEach(key=>{this.data[key]=data[key]}),this.data.headers=this.data.headers||{},Object.keys(defaults).forEach(key=>{key in this.data?"headers"===key&&Object.keys(defaults.headers).forEach(key=>{key in this.data.headers||(this.data.headers[key]=defaults.headers[key])}):this.data[key]=defaults[key]}),["disableFileAccess","disableUrlAccess","normalizeHeaderKey"].forEach(key=>{key in options&&(this.data[key]=options[key])})}resolveContent(...args){return shared.resolveContent(...args)}resolveAll(callback){let keys=[[this.data,"html"],[this.data,"text"],[this.data,"watchHtml"],[this.data,"amp"],[this.data,"icalEvent"]];this.data.alternatives&&this.data.alternatives.length&&this.data.alternatives.forEach((alternative,i)=>{keys.push([this.data.alternatives,i])}),this.data.attachments&&this.data.attachments.length&&this.data.attachments.forEach((attachment,i)=>{attachment.filename||(attachment.filename=(attachment.path||attachment.href||"").split("/").pop().split("?").shift()||"attachment-"+(i+1),attachment.filename.indexOf(".")<0&&(attachment.filename+="."+mimeFuncs.detectExtension(attachment.contentType))),attachment.contentType||(attachment.contentType=mimeFuncs.detectMimeType(attachment.filename||attachment.path||attachment.href||"bin")),keys.push([this.data.attachments,i])});let mimeNode=new MimeNode;["from","to","cc","bcc","sender","replyTo"].forEach(address=>{let value;this.message?value=[].concat(mimeNode._parseAddresses(this.message.getHeader("replyTo"===address?"reply-to":address))||[]):this.data[address]&&(value=[].concat(mimeNode._parseAddresses(this.data[address])||[])),value&&value.length?this.data[address]=value:address in this.data&&(this.data[address]=null)}),["from","sender"].forEach(address=>{this.data[address]&&(this.data[address]=this.data[address].shift())});let pos=0,resolveNext=()=>{if(pos>=keys.length)return callback(null,this.data);let args=keys[pos++];if(!args[0]||!args[0][args[1]])return resolveNext();shared.resolveContent(...args,(err,value)=>{if(err)return callback(err);let node={content:value};args[0][args[1]]&&"object"==typeof args[0][args[1]]&&!Buffer.isBuffer(args[0][args[1]])&&Object.keys(args[0][args[1]]).forEach(key=>{key in node||["content","path","href","raw"].includes(key)||(node[key]=args[0][args[1]][key])}),args[0][args[1]]=node,resolveNext()})};setImmediate(()=>resolveNext())}normalize(callback){let envelope=this.data.envelope||this.message.getEnvelope(),messageId=this.message.messageId();this.resolveAll((err,data)=>err?callback(err):(data.envelope=envelope,data.messageId=messageId,["html","text","watchHtml","amp"].forEach(key=>{data[key]&&data[key].content&&("string"==typeof data[key].content?data[key]=data[key].content:Buffer.isBuffer(data[key].content)&&(data[key]=data[key].content.toString()))}),data.icalEvent&&Buffer.isBuffer(data.icalEvent.content)&&(data.icalEvent.content=data.icalEvent.content.toString("base64"),data.icalEvent.encoding="base64"),data.alternatives&&data.alternatives.length&&data.alternatives.forEach(alternative=>{alternative&&alternative.content&&Buffer.isBuffer(alternative.content)&&(alternative.content=alternative.content.toString("base64"),alternative.encoding="base64")}),data.attachments&&data.attachments.length&&data.attachments.forEach(attachment=>{attachment&&attachment.content&&Buffer.isBuffer(attachment.content)&&(attachment.content=attachment.content.toString("base64"),attachment.encoding="base64")}),data.normalizedHeaders={},Object.keys(data.headers||{}).forEach(key=>{let value=[].concat(data.headers[key]||[]).shift();value=value&&value.value||value,value&&(["references","in-reply-to","message-id","content-id"].includes(key)&&(value=this.message._encodeHeaderValue(key,value)),data.normalizedHeaders[key]=value)}),data.list&&"object"==typeof data.list&&this._getListHeaders(data.list).forEach(entry=>{data.normalizedHeaders[entry.key]=entry.value.map(val=>val&&val.value||val).join(", ")}),data.references&&(data.normalizedHeaders.references=this.message._encodeHeaderValue("references",data.references)),data.inReplyTo&&(data.normalizedHeaders["in-reply-to"]=this.message._encodeHeaderValue("in-reply-to",data.inReplyTo)),callback(null,data)))}setMailerHeader(){this.message&&this.data.xMailer&&this.message.setHeader("X-Mailer",this.data.xMailer)}setPriorityHeaders(){if(this.message&&this.data.priority)switch((this.data.priority||"").toString().toLowerCase()){case"high":this.message.setHeader("X-Priority","1 (Highest)"),this.message.setHeader("X-MSMail-Priority","High"),this.message.setHeader("Importance","High");break;case"low":this.message.setHeader("X-Priority","5 (Lowest)"),this.message.setHeader("X-MSMail-Priority","Low"),this.message.setHeader("Importance","Low")}}setListHeaders(){this.message&&this.data.list&&"object"==typeof this.data.list&&this.data.list&&"object"==typeof this.data.list&&this._getListHeaders(this.data.list).forEach(listHeader=>{listHeader.value.forEach(value=>{this.message.addHeader(listHeader.key,value)})})}_getListHeaders(listData){return Object.keys(listData).map(key=>({key:"list-"+key.toLowerCase().trim(),value:[].concat(listData[key]||[]).map(value=>({prepared:!0,foldLines:!0,value:[].concat(value||[]).map(value=>{if("string"==typeof value&&(value={url:value}),value&&value.url){if("id"===key.toLowerCase().trim()){let comment=value.comment||"";return comment=mimeFuncs.isPlainText(comment)?'"'+comment+'"':mimeFuncs.encodeWord(comment),(value.comment?comment+" ":"")+this._formatListUrl(value.url).replace(/^<[^:]+\/{,2}/,"")}let comment=value.comment||"";return mimeFuncs.isPlainText(comment)||(comment=mimeFuncs.encodeWord(comment)),this._formatListUrl(value.url)+(value.comment?" ("+comment+")":"")}return""}).filter(value=>value).join(", ")}))}))}_formatListUrl(url){return url=url.replace(/[\s<]+|[\s>]+/g,""),/^(https?|mailto|ftp):/.test(url)?"<"+url+">":/^[^@]+@[^@]+$/.test(url)?"<mailto:"+url+">":"<http://"+url+">"}},mailMessage}(),net=require$$7__default.default,dns=require$$4__default$2.default,crypto=require$$0__default$1.default;return mailer=class Mail extends EventEmitter{constructor(transporter,options,defaults){super(),this.options=options||{},this._defaults=defaults||{},this._defaultPlugins={compile:[(...args)=>this._convertDataImages(...args)],stream:[]},this._userPlugins={compile:[],stream:[]},this.meta=new Map,this.dkim=!!this.options.dkim&&new DKIM(this.options.dkim),this.transporter=transporter,this.transporter.mailer=this,this.logger=shared.getLogger(this.options,{component:this.options.component||"mail"}),this.logger.debug({tnx:"create"},"Creating transport: %s",this.getVersionString()),"function"==typeof this.transporter.on&&(this.transporter.on("log",log=>{this.logger.debug({tnx:"transport"},"%s: %s",log.type,log.message)}),this.transporter.on("error",err=>{this.logger.error({err:err,tnx:"transport"},"Transport Error: %s",err.message),this.emit("error",err)}),this.transporter.on("idle",(...args)=>{this.emit("idle",...args)})),["close","isIdle","verify"].forEach(method=>{this[method]=(...args)=>"function"==typeof this.transporter[method]?("verify"===method&&"function"==typeof this.getSocket&&(this.transporter.getSocket=this.getSocket,this.getSocket=!1),this.transporter[method](...args)):(this.logger.warn({tnx:"transport",methodName:method},"Non existing method %s called for transport",method),!1)}),this.options.proxy&&"string"==typeof this.options.proxy&&this.setupProxy(this.options.proxy)}use(step,plugin){return step=(step||"").toString(),this._userPlugins.hasOwnProperty(step)?this._userPlugins[step].push(plugin):this._userPlugins[step]=[plugin],this}sendMail(data,callback=null){let promise;callback||(promise=new Promise((resolve,reject)=>{callback=shared.callbackPromise(resolve,reject)})),"function"==typeof this.getSocket&&(this.transporter.getSocket=this.getSocket,this.getSocket=!1);let mail=new MailMessage(this,data);return this.logger.debug({tnx:"transport",name:this.transporter.name,version:this.transporter.version,action:"send"},"Sending mail using %s/%s",this.transporter.name,this.transporter.version),this._processPlugins("compile",mail,err=>{if(err)return this.logger.error({err:err,tnx:"plugin",action:"compile"},"PluginCompile Error: %s",err.message),callback(err);mail.message=new MailComposer(mail.data).compile(),mail.setMailerHeader(),mail.setPriorityHeaders(),mail.setListHeaders(),this._processPlugins("stream",mail,err=>{if(err)return this.logger.error({err:err,tnx:"plugin",action:"stream"},"PluginStream Error: %s",err.message),callback(err);(mail.data.dkim||this.dkim)&&mail.message.processFunc(input=>{let dkim=mail.data.dkim?new DKIM(mail.data.dkim):this.dkim;return this.logger.debug({tnx:"DKIM",messageId:mail.message.messageId(),dkimDomains:dkim.keys.map(key=>key.keySelector+"."+key.domainName).join(", ")},"Signing outgoing message with %s keys",dkim.keys.length),dkim.sign(input,mail.data._dkim)}),this.transporter.send(mail,(...args)=>{args[0]&&this.logger.error({err:args[0],tnx:"transport",action:"send"},"Send Error: %s",args[0].message),callback(...args)})})}),promise}getVersionString(){return util.format("%s (%s; +%s; %s/%s)",packageData.name,packageData.version,packageData.homepage,this.transporter.name,this.transporter.version)}_processPlugins(step,mail,callback){if(step=(step||"").toString(),!this._userPlugins.hasOwnProperty(step))return callback();let userPlugins=this._userPlugins[step]||[],defaultPlugins=this._defaultPlugins[step]||[];if(userPlugins.length&&this.logger.debug({tnx:"transaction",pluginCount:userPlugins.length,step:step},"Using %s plugins for %s",userPlugins.length,step),userPlugins.length+defaultPlugins.length===0)return callback();let pos=0,block="default",processPlugins=()=>{let curplugins="default"===block?defaultPlugins:userPlugins;if(pos>=curplugins.length){if("default"!==block||!userPlugins.length)return callback();block="user",pos=0,curplugins=userPlugins}(0,curplugins[pos++])(mail,err=>{if(err)return callback(err);processPlugins()})};processPlugins()}setupProxy(proxyUrl){let proxy=urllib.parse(proxyUrl);this.getSocket=(options,callback)=>{let protocol=proxy.protocol.replace(/:$/,"").toLowerCase();if(this.meta.has("proxy_handler_"+protocol))return this.meta.get("proxy_handler_"+protocol)(proxy,options,callback);switch(protocol){case"http":case"https":return void httpProxyClient(proxy.href,options.port,options.host,(err,socket)=>err?callback(err):callback(null,{connection:socket}));case"socks":case"socks5":case"socks4":case"socks4a":{if(!this.meta.has("proxy_socks_module"))return callback(new Error("Socks module not loaded"));let connect=ipaddress=>{let proxyV2=!!this.meta.get("proxy_socks_module").SocksClient,socksClient=proxyV2?this.meta.get("proxy_socks_module").SocksClient:this.meta.get("proxy_socks_module"),proxyType=Number(proxy.protocol.replace(/\D/g,""))||5,connectionOpts={proxy:{ipaddress:ipaddress,port:Number(proxy.port),type:proxyType},[proxyV2?"destination":"target"]:{host:options.host,port:options.port},command:"connect"};if(proxy.auth){let username=decodeURIComponent(proxy.auth.split(":").shift()),password=decodeURIComponent(proxy.auth.split(":").pop());proxyV2?(connectionOpts.proxy.userId=username,connectionOpts.proxy.password=password):4===proxyType?connectionOpts.userid=username:connectionOpts.authentication={username:username,password:password}}socksClient.createConnection(connectionOpts,(err,info)=>err?callback(err):callback(null,{connection:info.socket||info}))};return net.isIP(proxy.hostname)?connect(proxy.hostname):dns.resolve(proxy.hostname,(err,address)=>{if(err)return callback(err);connect(Array.isArray(address)?address[0]:address)})}}callback(new Error("Unknown proxy configuration"))}}_convertDataImages(mail,callback){if(!this.options.attachDataUrls&&!mail.data.attachDataUrls||!mail.data.html)return callback();mail.resolveContent(mail.data,"html",(err,html)=>{if(err)return callback(err);let cidCounter=0;html=(html||"").toString().replace(/(<img\b[^<>]{0,1024} src\s{0,20}=[\s"']{0,20})(data:([^;]+);[^"'>\s]+)/gi,(match,prefix,dataUri,mimeType)=>{let cid=crypto.randomBytes(10).toString("hex")+"@localhost";return mail.data.attachments||(mail.data.attachments=[]),Array.isArray(mail.data.attachments)||(mail.data.attachments=[].concat(mail.data.attachments||[])),mail.data.attachments.push({path:dataUri,cid:cid,filename:"image-"+ ++cidCounter+"."+mimeTypes.detectExtension(mimeType)}),prefix+"cid:"+cid}),mail.data.html=html,callback()})}set(key,value){return this.meta.set(key,value)}get(key){return this.meta.get(key)}},mailer}function requireSmtpConnection(){if(hasRequiredSmtpConnection)return smtpConnection;hasRequiredSmtpConnection=1;const packageInfo=require$$9,EventEmitter=require$$0__default.default.EventEmitter,net=require$$7__default.default,tls=require$$1__default$2.default,os=require$$0__default$3.default,crypto=require$$0__default$1.default,DataStream=function requireDataStream(){if(hasRequiredDataStream)return dataStream;hasRequiredDataStream=1;const Transform=require$$0__default$4.default.Transform;return dataStream=class DataStream extends Transform{constructor(options){super(options),this.options=options||{},this._curLine="",this.inByteCount=0,this.outByteCount=0,this.lastByte=!1}_transform(chunk,encoding,done){let i,len,buf,chunks=[],chunklen=0,lastPos=0;if(!chunk||!chunk.length)return done();for("string"==typeof chunk&&(chunk=Buffer.from(chunk)),this.inByteCount+=chunk.length,i=0,len=chunk.length;i<len;i++)46===chunk[i]?(i&&10===chunk[i-1]||!i&&(!this.lastByte||10===this.lastByte))&&(buf=chunk.slice(lastPos,i+1),chunks.push(buf),chunks.push(Buffer.from(".")),chunklen+=buf.length+1,lastPos=i+1):10===chunk[i]&&(i&&13!==chunk[i-1]||!i&&13!==this.lastByte)&&(i>lastPos?(buf=chunk.slice(lastPos,i),chunks.push(buf),chunklen+=buf.length+2):chunklen+=2,chunks.push(Buffer.from("\r\n")),lastPos=i+1);chunklen?(lastPos<chunk.length&&(buf=chunk.slice(lastPos),chunks.push(buf),chunklen+=buf.length),this.outByteCount+=chunklen,this.push(Buffer.concat(chunks,chunklen))):(this.outByteCount+=chunk.length,this.push(chunk)),this.lastByte=chunk[chunk.length-1],done()}_flush(done){let buf;buf=10===this.lastByte?Buffer.from(".\r\n"):13===this.lastByte?Buffer.from("\n.\r\n"):Buffer.from("\r\n.\r\n"),this.outByteCount+=buf.length,this.push(buf),done()}}}(),PassThrough=require$$0__default$4.default.PassThrough,shared=requireShared();return smtpConnection=class SMTPConnection extends EventEmitter{constructor(options){super(options),this.id=crypto.randomBytes(8).toString("base64").replace(/\W/g,""),this.stage="init",this.options=options||{},this.secureConnection=!!this.options.secure,this.alreadySecured=!!this.options.secured,this.port=Number(this.options.port)||(this.secureConnection?465:587),this.host=this.options.host||"localhost",this.servername=this.options.servername?this.options.servername:!net.isIP(this.host)&&this.host,this.allowInternalNetworkInterfaces=this.options.allowInternalNetworkInterfaces||!1,void 0===this.options.secure&&465===this.port&&(this.secureConnection=!0),this.name=this.options.name||this._getHostname(),this.logger=shared.getLogger(this.options,{component:this.options.component||"smtp-connection",sid:this.id}),this.customAuth=new Map,Object.keys(this.options.customAuth||{}).forEach(key=>{let mapKey=(key||"").toString().trim().toUpperCase();mapKey&&this.customAuth.set(mapKey,this.options.customAuth[key])}),this.version=packageInfo.version,this.authenticated=!1,this.destroyed=!1,this.secure=!!this.secureConnection,this._remainder="",this._responseQueue=[],this.lastServerResponse=!1,this._socket=!1,this._supportedAuth=[],this.allowsAuth=!1,this._envelope=!1,this._supportedExtensions=[],this._maxAllowedSize=0,this._responseActions=[],this._recipientQueue=[],this._greetingTimeout=!1,this._connectionTimeout=!1,this._destroyed=!1,this._closing=!1,this._onSocketData=chunk=>this._onData(chunk),this._onSocketError=error=>this._onError(error,"ESOCKET",!1,"CONN"),this._onSocketClose=()=>this._onClose(),this._onSocketEnd=()=>this._onEnd(),this._onSocketTimeout=()=>this._onTimeout()}connect(connectCallback){if("function"==typeof connectCallback){this.once("connect",()=>{this.logger.debug({tnx:"smtp"},"SMTP handshake finished"),connectCallback()});const isDestroyedMessage=this._isDestroyedMessage("connect");if(isDestroyedMessage)return connectCallback(this._formatError(isDestroyedMessage,"ECONNECTION",!1,"CONN"))}let opts={port:this.port,host:this.host,allowInternalNetworkInterfaces:this.allowInternalNetworkInterfaces,timeout:this.options.dnsTimeout||3e4};this.options.localAddress&&(opts.localAddress=this.options.localAddress);let setupConnectionHandlers=()=>{this._connectionTimeout=setTimeout(()=>{this._onError("Connection timeout","ETIMEDOUT",!1,"CONN")},this.options.connectionTimeout||12e4),this._socket.on("error",this._onSocketError)};return this.options.connection?(this._socket=this.options.connection,setupConnectionHandlers(),void(this.secureConnection&&!this.alreadySecured?setImmediate(()=>this._upgradeConnection(err=>{err?this._onError(new Error("Error initiating TLS - "+(err.message||err)),"ETLS",!1,"CONN"):this._onConnect()})):setImmediate(()=>this._onConnect()))):this.options.socket?(this._socket=this.options.socket,shared.resolveHostname(opts,(err,resolved)=>{if(err)return setImmediate(()=>this._onError(err,"EDNS",!1,"CONN"));this.logger.debug({tnx:"dns",source:opts.host,resolved:resolved.host,cached:!!resolved.cached},"Resolved %s as %s [cache %s]",opts.host,resolved.host,resolved.cached?"hit":"miss"),Object.keys(resolved).forEach(key=>{"_"!==key.charAt(0)&&resolved[key]&&(opts[key]=resolved[key])});try{this._socket.connect(this.port,this.host,()=>{this._socket.setKeepAlive(!0),this._onConnect()}),setupConnectionHandlers()}catch(E){return setImmediate(()=>this._onError(E,"ECONNECTION",!1,"CONN"))}})):this.secureConnection?(this.options.tls&&Object.keys(this.options.tls).forEach(key=>{opts[key]=this.options.tls[key]}),this.servername&&!opts.servername&&(opts.servername=this.servername),shared.resolveHostname(opts,(err,resolved)=>{if(err)return setImmediate(()=>this._onError(err,"EDNS",!1,"CONN"));this.logger.debug({tnx:"dns",source:opts.host,resolved:resolved.host,cached:!!resolved.cached},"Resolved %s as %s [cache %s]",opts.host,resolved.host,resolved.cached?"hit":"miss"),Object.keys(resolved).forEach(key=>{"_"!==key.charAt(0)&&resolved[key]&&(opts[key]=resolved[key])});try{this._socket=tls.connect(opts,()=>{this._socket.setKeepAlive(!0),this._onConnect()}),setupConnectionHandlers()}catch(E){return setImmediate(()=>this._onError(E,"ECONNECTION",!1,"CONN"))}})):shared.resolveHostname(opts,(err,resolved)=>{if(err)return setImmediate(()=>this._onError(err,"EDNS",!1,"CONN"));this.logger.debug({tnx:"dns",source:opts.host,resolved:resolved.host,cached:!!resolved.cached},"Resolved %s as %s [cache %s]",opts.host,resolved.host,resolved.cached?"hit":"miss"),Object.keys(resolved).forEach(key=>{"_"!==key.charAt(0)&&resolved[key]&&(opts[key]=resolved[key])});try{this._socket=net.connect(opts,()=>{this._socket.setKeepAlive(!0),this._onConnect()}),setupConnectionHandlers()}catch(E){return setImmediate(()=>this._onError(E,"ECONNECTION",!1,"CONN"))}})}quit(){this._sendCommand("QUIT"),this._responseActions.push(this.close)}close(){if(clearTimeout(this._connectionTimeout),clearTimeout(this._greetingTimeout),this._responseActions=[],this._closing)return;this._closing=!0;let closeMethod="end";"init"===this.stage&&(closeMethod="destroy"),this.logger.debug({tnx:"smtp"},'Closing connection to the server using "%s"',closeMethod);let socket=this._socket&&this._socket.socket||this._socket;if(socket&&!socket.destroyed)try{socket[closeMethod]()}catch(E){}this._destroy()}login(authData,callback){const isDestroyedMessage=this._isDestroyedMessage("login");if(isDestroyedMessage)return callback(this._formatError(isDestroyedMessage,"ECONNECTION",!1,"API"));if(this._auth=authData||{},this._authMethod=(this._auth.method||"").toString().trim().toUpperCase()||!1,this._authMethod||!this._auth.oauth2||this._auth.credentials?this._authMethod&&("XOAUTH2"!==this._authMethod||this._auth.oauth2)||(this._authMethod=(this._supportedAuth[0]||"PLAIN").toUpperCase().trim()):this._authMethod="XOAUTH2",!("XOAUTH2"===this._authMethod||this._auth.credentials&&this._auth.credentials.user&&this._auth.credentials.pass)){if(!(this._auth.user&&this._auth.pass||this.customAuth.has(this._authMethod)))return callback(this._formatError('Missing credentials for "'+this._authMethod+'"',"EAUTH",!1,"API"));this._auth.credentials={user:this._auth.user,pass:this._auth.pass,options:this._auth.options}}if(this.customAuth.has(this._authMethod)){let lastResponse,handler=this.customAuth.get(this._authMethod),returned=!1,resolve=()=>{returned||(returned=!0,this.logger.info({tnx:"smtp",username:this._auth.user,action:"authenticated",method:this._authMethod},"User %s authenticated",JSON.stringify(this._auth.user)),this.authenticated=!0,callback(null,!0))},reject=err=>{returned||(returned=!0,callback(this._formatError(err,"EAUTH",lastResponse,"AUTH "+this._authMethod)))},handlerResponse=handler({auth:this._auth,method:this._authMethod,extensions:[].concat(this._supportedExtensions),authMethods:[].concat(this._supportedAuth),maxAllowedSize:this._maxAllowedSize||!1,sendCommand:(cmd,done)=>{let promise;return done||(promise=new Promise((resolve,reject)=>{done=shared.callbackPromise(resolve,reject)})),this._responseActions.push(str=>{lastResponse=str;let codes=str.match(/^(\d+)(?:\s(\d+\.\d+\.\d+))?\s/),data={command:cmd,response:str};codes?(data.status=Number(codes[1])||0,codes[2]&&(data.code=codes[2]),data.text=str.substr(codes[0].length)):(data.text=str,data.status=0),done(null,data)}),setImmediate(()=>this._sendCommand(cmd)),promise},resolve:resolve,reject:reject});return void(handlerResponse&&"function"==typeof handlerResponse.catch&&handlerResponse.then(resolve).catch(reject))}switch(this._authMethod){case"XOAUTH2":return void this._handleXOauth2Token(!1,callback);case"LOGIN":return this._responseActions.push(str=>{this._actionAUTH_LOGIN_USER(str,callback)}),void this._sendCommand("AUTH LOGIN");case"PLAIN":return this._responseActions.push(str=>{this._actionAUTHComplete(str,callback)}),void this._sendCommand("AUTH PLAIN "+Buffer.from("\0"+this._auth.credentials.user+"\0"+this._auth.credentials.pass,"utf-8").toString("base64"),"AUTH PLAIN "+Buffer.from("\0"+this._auth.credentials.user+"\0/* secret */","utf-8").toString("base64"));case"CRAM-MD5":return this._responseActions.push(str=>{this._actionAUTH_CRAM_MD5(str,callback)}),void this._sendCommand("AUTH CRAM-MD5")}return callback(this._formatError('Unknown authentication method "'+this._authMethod+'"',"EAUTH",!1,"API"))}send(envelope,message,done){if(!message)return done(this._formatError("Empty message","EMESSAGE",!1,"API"));const isDestroyedMessage=this._isDestroyedMessage("send message");if(isDestroyedMessage)return done(this._formatError(isDestroyedMessage,"ECONNECTION",!1,"API"));if(this._maxAllowedSize&&envelope.size>this._maxAllowedSize)return setImmediate(()=>{done(this._formatError("Message size larger than allowed "+this._maxAllowedSize,"EMESSAGE",!1,"MAIL FROM"))});let returned=!1,callback=function(){returned||(returned=!0,done(...arguments))};"function"==typeof message.on&&message.on("error",err=>callback(this._formatError(err,"ESTREAM",!1,"API")));let startTime=Date.now();this._setEnvelope(envelope,(err,info)=>{if(err){let stream=new PassThrough;return"function"==typeof message.pipe?message.pipe(stream):(stream.write(message),stream.end()),callback(err)}let envelopeTime=Date.now(),stream=this._createSendStream((err,str)=>err?callback(err):(info.envelopeTime=envelopeTime-startTime,info.messageTime=Date.now()-envelopeTime,info.messageSize=stream.outByteCount,info.response=str,callback(null,info)));"function"==typeof message.pipe?message.pipe(stream):(stream.write(message),stream.end())})}reset(callback){this._sendCommand("RSET"),this._responseActions.push(str=>"2"!==str.charAt(0)?callback(this._formatError("Could not reset session state. response="+str,"EPROTOCOL",str,"RSET")):(this._envelope=!1,callback(null,!0)))}_onConnect(){clearTimeout(this._connectionTimeout),this.logger.info({tnx:"network",localAddress:this._socket.localAddress,localPort:this._socket.localPort,remoteAddress:this._socket.remoteAddress,remotePort:this._socket.remotePort},"%s established to %s:%s",this.secure?"Secure connection":"Connection",this._socket.remoteAddress,this._socket.remotePort),this._destroyed?this.close():(this.stage="connected",this._socket.removeListener("data",this._onSocketData),this._socket.removeListener("timeout",this._onSocketTimeout),this._socket.removeListener("close",this._onSocketClose),this._socket.removeListener("end",this._onSocketEnd),this._socket.on("data",this._onSocketData),this._socket.once("close",this._onSocketClose),this._socket.once("end",this._onSocketEnd),this._socket.setTimeout(this.options.socketTimeout||6e5),this._socket.on("timeout",this._onSocketTimeout),this._greetingTimeout=setTimeout(()=>{this._socket&&!this._destroyed&&this._responseActions[0]===this._actionGreeting&&this._onError("Greeting never received","ETIMEDOUT",!1,"CONN")},this.options.greetingTimeout||3e4),this._responseActions.push(this._actionGreeting),this._socket.resume())}_onData(chunk){if(this._destroyed||!chunk||!chunk.length)return;let lastline,data=(chunk||"").toString("binary"),lines=(this._remainder+data).split(/\r?\n/);this._remainder=lines.pop();for(let i=0,len=lines.length;i<len;i++)this._responseQueue.length&&(lastline=this._responseQueue[this._responseQueue.length-1],/^\d+-/.test(lastline.split("\n").pop()))?this._responseQueue[this._responseQueue.length-1]+="\n"+lines[i]:this._responseQueue.push(lines[i]);this._responseQueue.length&&(lastline=this._responseQueue[this._responseQueue.length-1],/^\d+-/.test(lastline.split("\n").pop()))||this._processResponse()}_onError(err,type,data,command){clearTimeout(this._connectionTimeout),clearTimeout(this._greetingTimeout),this._destroyed||(err=this._formatError(err,type,data,command),this.logger.error(data,err.message),this.emit("error",err),this.close())}_formatError(message,type,response,command){let err;err=/Error\]$/i.test(Object.prototype.toString.call(message))?message:new Error(message),type&&"Error"!==type&&(err.code=type),response&&(err.response=response,err.message+=": "+response);let responseCode="string"==typeof response&&Number((response.match(/^\d+/)||[])[0])||!1;return responseCode&&(err.responseCode=responseCode),command&&(err.command=command),err}_onClose(){let serverResponse=!1;return this._remainder&&this._remainder.trim()&&((this.options.debug||this.options.transactionLog)&&this.logger.debug({tnx:"server"},this._remainder.replace(/\r?\n$/,"")),this.lastServerResponse=serverResponse=this._remainder.trim()),this.logger.info({tnx:"network"},"Connection closed"),this.upgrading&&!this._destroyed?this._onError(new Error("Connection closed unexpectedly"),"ETLS",serverResponse,"CONN"):[this._actionGreeting,this.close].includes(this._responseActions[0])||this._destroyed?/^[45]\d{2}\b/.test(serverResponse)?this._onError(new Error("Connection closed unexpectedly"),"ECONNECTION",serverResponse,"CONN"):void this._destroy():this._onError(new Error("Connection closed unexpectedly"),"ECONNECTION",serverResponse,"CONN")}_onEnd(){this._socket&&!this._socket.destroyed&&this._socket.destroy()}_onTimeout(){return this._onError(new Error("Timeout"),"ETIMEDOUT",!1,"CONN")}_destroy(){this._destroyed||(this._destroyed=!0,this.emit("end"))}_upgradeConnection(callback){this._socket.removeListener("data",this._onSocketData),this._socket.removeListener("timeout",this._onSocketTimeout);let socketPlain=this._socket,opts={socket:this._socket,host:this.host};Object.keys(this.options.tls||{}).forEach(key=>{opts[key]=this.options.tls[key]}),this.servername&&!opts.servername&&(opts.servername=this.servername),this.upgrading=!0;try{this._socket=tls.connect(opts,()=>(this.secure=!0,this.upgrading=!1,this._socket.on("data",this._onSocketData),socketPlain.removeListener("close",this._onSocketClose),socketPlain.removeListener("end",this._onSocketEnd),callback(null,!0)))}catch(err){return callback(err)}this._socket.on("error",this._onSocketError),this._socket.once("close",this._onSocketClose),this._socket.once("end",this._onSocketEnd),this._socket.setTimeout(this.options.socketTimeout||6e5),this._socket.on("timeout",this._onSocketTimeout),socketPlain.resume()}_processResponse(){if(!this._responseQueue.length)return!1;let str=this.lastServerResponse=(this._responseQueue.shift()||"").toString();if(/^\d+-/.test(str.split("\n").pop()))return;(this.options.debug||this.options.transactionLog)&&this.logger.debug({tnx:"server"},str.replace(/\r?\n$/,"")),str.trim()||setImmediate(()=>this._processResponse());let action=this._responseActions.shift();if("function"!=typeof action)return this._onError(new Error("Unexpected Response"),"EPROTOCOL",str,"CONN");action.call(this,str),setImmediate(()=>this._processResponse())}_sendCommand(str,logStr){if(!this._destroyed){if(this._socket.destroyed)return this.close();(this.options.debug||this.options.transactionLog)&&this.logger.debug({tnx:"client"},(logStr||str||"").toString().replace(/\r?\n$/,"")),this._socket.write(Buffer.from(str+"\r\n","utf-8"))}}_setEnvelope(envelope,callback){let args=[],useSmtpUtf8=!1;if(this._envelope=envelope||{},this._envelope.from=(this._envelope.from&&this._envelope.from.address||this._envelope.from||"").toString().trim(),this._envelope.to=[].concat(this._envelope.to||[]).map(to=>(to&&to.address||to||"").toString().trim()),!this._envelope.to.length)return callback(this._formatError("No recipients defined","EENVELOPE",!1,"API"));if(this._envelope.from&&/[\r\n<>]/.test(this._envelope.from))return callback(this._formatError("Invalid sender "+JSON.stringify(this._envelope.from),"EENVELOPE",!1,"API"));/[\x80-\uFFFF]/.test(this._envelope.from)&&(useSmtpUtf8=!0);for(let i=0,len=this._envelope.to.length;i<len;i++){if(!this._envelope.to[i]||/[\r\n<>]/.test(this._envelope.to[i]))return callback(this._formatError("Invalid recipient "+JSON.stringify(this._envelope.to[i]),"EENVELOPE",!1,"API"));/[\x80-\uFFFF]/.test(this._envelope.to[i])&&(useSmtpUtf8=!0)}if(this._envelope.rcptQueue=JSON.parse(JSON.stringify(this._envelope.to||[])),this._envelope.rejected=[],this._envelope.rejectedErrors=[],this._envelope.accepted=[],this._envelope.dsn)try{this._envelope.dsn=this._setDsnEnvelope(this._envelope.dsn)}catch(err){return callback(this._formatError("Invalid DSN "+err.message,"EENVELOPE",!1,"API"))}this._responseActions.push(str=>{this._actionMAIL(str,callback)}),useSmtpUtf8&&this._supportedExtensions.includes("SMTPUTF8")&&(args.push("SMTPUTF8"),this._usingSmtpUtf8=!0),this._envelope.use8BitMime&&this._supportedExtensions.includes("8BITMIME")&&(args.push("BODY=8BITMIME"),this._using8BitMime=!0),this._envelope.size&&this._supportedExtensions.includes("SIZE")&&args.push("SIZE="+this._envelope.size),this._envelope.dsn&&this._supportedExtensions.includes("DSN")&&(this._envelope.dsn.ret&&args.push("RET="+shared.encodeXText(this._envelope.dsn.ret)),this._envelope.dsn.envid&&args.push("ENVID="+shared.encodeXText(this._envelope.dsn.envid))),this._sendCommand("MAIL FROM:<"+this._envelope.from+">"+(args.length?" "+args.join(" "):""))}_setDsnEnvelope(params){let ret=(params.ret||params.return||"").toString().toUpperCase()||null;if(ret)switch(ret){case"HDRS":case"HEADERS":ret="HDRS";break;case"FULL":case"BODY":ret="FULL"}if(ret&&!["FULL","HDRS"].includes(ret))throw new Error("ret: "+JSON.stringify(ret));let envid=(params.envid||params.id||"").toString()||null,notify=params.notify||null;if(notify){"string"==typeof notify&&(notify=notify.split(",")),notify=notify.map(n=>n.trim().toUpperCase());let validNotify=["NEVER","SUCCESS","FAILURE","DELAY"];if(notify.filter(n=>!validNotify.includes(n)).length||notify.length>1&¬ify.includes("NEVER"))throw new Error("notify: "+JSON.stringify(notify.join(",")));notify=notify.join(",")}let orcpt=(params.recipient||params.orcpt||"").toString()||null;return orcpt&&orcpt.indexOf(";")<0&&(orcpt="rfc822;"+orcpt),{ret:ret,envid:envid,notify:notify,orcpt:orcpt}}_getDsnRcptToArgs(){let args=[];return this._envelope.dsn&&this._supportedExtensions.includes("DSN")&&(this._envelope.dsn.notify&&args.push("NOTIFY="+shared.encodeXText(this._envelope.dsn.notify)),this._envelope.dsn.orcpt&&args.push("ORCPT="+shared.encodeXText(this._envelope.dsn.orcpt))),args.length?" "+args.join(" "):""}_createSendStream(callback){let logStream,dataStream=new DataStream;return this.options.lmtp?this._envelope.accepted.forEach((recipient,i)=>{let final=i===this._envelope.accepted.length-1;this._responseActions.push(str=>{this._actionLMTPStream(recipient,final,str,callback)})}):this._responseActions.push(str=>{this._actionSMTPStream(str,callback)}),dataStream.pipe(this._socket,{end:!1}),this.options.debug&&(logStream=new PassThrough,logStream.on("readable",()=>{let chunk;for(;chunk=logStream.read();)this.logger.debug({tnx:"message"},chunk.toString("binary").replace(/\r?\n$/,""))}),dataStream.pipe(logStream)),dataStream.once("end",()=>{this.logger.info({tnx:"message",inByteCount:dataStream.inByteCount,outByteCount:dataStream.outByteCount},"<%s bytes encoded mime message (source size %s bytes)>",dataStream.outByteCount,dataStream.inByteCount)}),dataStream}_actionGreeting(str){clearTimeout(this._greetingTimeout),"220"===str.substr(0,3)?this.options.lmtp?(this._responseActions.push(this._actionLHLO),this._sendCommand("LHLO "+this.name)):(this._responseActions.push(this._actionEHLO),this._sendCommand("EHLO "+this.name)):this._onError(new Error("Invalid greeting. response="+str),"EPROTOCOL",str,"CONN")}_actionLHLO(str){"2"===str.charAt(0)?this._actionEHLO(str):this._onError(new Error("Invalid LHLO. response="+str),"EPROTOCOL",str,"LHLO")}_actionEHLO(str){let match;if("421"!==str.substr(0,3)){if("2"!==str.charAt(0))return this.options.requireTLS?void this._onError(new Error("EHLO failed but HELO does not support required STARTTLS. response="+str),"ECONNECTION",str,"EHLO"):(this._responseActions.push(this._actionHELO),void this._sendCommand("HELO "+this.name));if(this._ehloLines=str.split(/\r?\n/).map(line=>line.replace(/^\d+[ -]/,"").trim()).filter(line=>line).slice(1),!this.secure&&!this.options.ignoreTLS&&(/[ -]STARTTLS\b/im.test(str)||this.options.requireTLS))return this._sendCommand("STARTTLS"),void this._responseActions.push(this._actionSTARTTLS);/[ -]SMTPUTF8\b/im.test(str)&&this._supportedExtensions.push("SMTPUTF8"),/[ -]DSN\b/im.test(str)&&this._supportedExtensions.push("DSN"),/[ -]8BITMIME\b/im.test(str)&&this._supportedExtensions.push("8BITMIME"),/[ -]PIPELINING\b/im.test(str)&&this._supportedExtensions.push("PIPELINING"),/[ -]AUTH\b/i.test(str)&&(this.allowsAuth=!0),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)PLAIN/i.test(str)&&this._supportedAuth.push("PLAIN"),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)LOGIN/i.test(str)&&this._supportedAuth.push("LOGIN"),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)CRAM-MD5/i.test(str)&&this._supportedAuth.push("CRAM-MD5"),/[ -]AUTH(?:(\s+|=)[^\n]*\s+|\s+|=)XOAUTH2/i.test(str)&&this._supportedAuth.push("XOAUTH2"),(match=str.match(/[ -]SIZE(?:[ \t]+(\d+))?/im))&&(this._supportedExtensions.push("SIZE"),this._maxAllowedSize=Number(match[1])||0),this.emit("connect")}else this._onError(new Error("Server terminates connection. response="+str),"ECONNECTION",str,"EHLO")}_actionHELO(str){"2"===str.charAt(0)?(this.allowsAuth=!0,this.emit("connect")):this._onError(new Error("Invalid HELO. response="+str),"EPROTOCOL",str,"HELO")}_actionSTARTTLS(str){if("2"!==str.charAt(0))return this.options.opportunisticTLS?(this.logger.info({tnx:"smtp"},"Failed STARTTLS upgrade, continuing unencrypted"),this.emit("connect")):void this._onError(new Error("Error upgrading connection with STARTTLS"),"ETLS",str,"STARTTLS");this._upgradeConnection((err,secured)=>{err?this._onError(new Error("Error initiating TLS - "+(err.message||err)),"ETLS",!1,"STARTTLS"):(this.logger.info({tnx:"smtp"},"Connection upgraded with STARTTLS"),secured?this.options.lmtp?(this._responseActions.push(this._actionLHLO),this._sendCommand("LHLO "+this.name)):(this._responseActions.push(this._actionEHLO),this._sendCommand("EHLO "+this.name)):this.emit("connect"))})}_actionAUTH_LOGIN_USER(str,callback){/^334[ -]/.test(str)?(this._responseActions.push(str=>{this._actionAUTH_LOGIN_PASS(str,callback)}),this._sendCommand(Buffer.from(this._auth.credentials.user+"","utf-8").toString("base64"))):callback(this._formatError('Invalid login sequence while waiting for "334 VXNlcm5hbWU6"',"EAUTH",str,"AUTH LOGIN"))}_actionAUTH_CRAM_MD5(str,callback){let challengeMatch=str.match(/^334\s+(.+)$/),challengeString="";if(!challengeMatch)return callback(this._formatError("Invalid login sequence while waiting for server challenge string","EAUTH",str,"AUTH CRAM-MD5"));challengeString=challengeMatch[1];let base64decoded=Buffer.from(challengeString,"base64").toString("ascii"),hmacMD5=crypto.createHmac("md5",this._auth.credentials.pass);hmacMD5.update(base64decoded);let prepended=this._auth.credentials.user+" "+hmacMD5.digest("hex");this._responseActions.push(str=>{this._actionAUTH_CRAM_MD5_PASS(str,callback)}),this._sendCommand(Buffer.from(prepended).toString("base64"),Buffer.from(this._auth.credentials.user+" /* secret */").toString("base64"))}_actionAUTH_CRAM_MD5_PASS(str,callback){if(!str.match(/^235\s+/))return callback(this._formatError('Invalid login sequence while waiting for "235"',"EAUTH",str,"AUTH CRAM-MD5"));this.logger.info({tnx:"smtp",username:this._auth.user,action:"authenticated",method:this._authMethod},"User %s authenticated",JSON.stringify(this._auth.user)),this.authenticated=!0,callback(null,!0)}_actionAUTH_LOGIN_PASS(str,callback){if(!/^334[ -]/.test(str))return callback(this._formatError('Invalid login sequence while waiting for "334 UGFzc3dvcmQ6"',"EAUTH",str,"AUTH LOGIN"));this._responseActions.push(str=>{this._actionAUTHComplete(str,callback)}),this._sendCommand(Buffer.from((this._auth.credentials.pass||"").toString(),"utf-8").toString("base64"),Buffer.from("/* secret */","utf-8").toString("base64"))}_actionAUTHComplete(str,isRetry,callback){return callback||"function"!=typeof isRetry||(callback=isRetry,isRetry=!1),"334"===str.substr(0,3)?(this._responseActions.push(str=>{isRetry||"XOAUTH2"!==this._authMethod?this._actionAUTHComplete(str,!0,callback):setImmediate(()=>this._handleXOauth2Token(!0,callback))}),void this._sendCommand("")):"2"!==str.charAt(0)?(this.logger.info({tnx:"smtp",username:this._auth.user,action:"authfail",method:this._authMethod},"User %s failed to authenticate",JSON.stringify(this._auth.user)),callback(this._formatError("Invalid login","EAUTH",str,"AUTH "+this._authMethod))):(this.logger.info({tnx:"smtp",username:this._auth.user,action:"authenticated",method:this._authMethod},"User %s authenticated",JSON.stringify(this._auth.user)),this.authenticated=!0,void callback(null,!0))}_actionMAIL(str,callback){let message,curRecipient;if(2!==Number(str.charAt(0)))return message=this._usingSmtpUtf8&&/^550 /.test(str)&&/[\x80-\uFFFF]/.test(this._envelope.from)?"Internationalized mailbox name not allowed":"Mail command failed",callback(this._formatError(message,"EENVELOPE",str,"MAIL FROM"));if(!this._envelope.rcptQueue.length)return callback(this._formatError("Can't send mail - no recipients defined","EENVELOPE",!1,"API"));if(this._recipientQueue=[],this._supportedExtensions.includes("PIPELINING"))for(;this._envelope.rcptQueue.length;)curRecipient=this._envelope.rcptQueue.shift(),this._recipientQueue.push(curRecipient),this._responseActions.push(str=>{this._actionRCPT(str,callback)}),this._sendCommand("RCPT TO:<"+curRecipient+">"+this._getDsnRcptToArgs());else curRecipient=this._envelope.rcptQueue.shift(),this._recipientQueue.push(curRecipient),this._responseActions.push(str=>{this._actionRCPT(str,callback)}),this._sendCommand("RCPT TO:<"+curRecipient+">"+this._getDsnRcptToArgs())}_actionRCPT(str,callback){let message,err,curRecipient=this._recipientQueue.shift();if(2!==Number(str.charAt(0))?(message=this._usingSmtpUtf8&&/^553 /.test(str)&&/[\x80-\uFFFF]/.test(curRecipient)?"Internationalized mailbox name not allowed":"Recipient command failed",this._envelope.rejected.push(curRecipient),err=this._formatError(message,"EENVELOPE",str,"RCPT TO"),err.recipient=curRecipient,this._envelope.rejectedErrors.push(err)):this._envelope.accepted.push(curRecipient),this._envelope.rcptQueue.length||this._recipientQueue.length)this._envelope.rcptQueue.length&&(curRecipient=this._envelope.rcptQueue.shift(),this._recipientQueue.push(curRecipient),this._responseActions.push(str=>{this._actionRCPT(str,callback)}),this._sendCommand("RCPT TO:<"+curRecipient+">"+this._getDsnRcptToArgs()));else{if(!(this._envelope.rejected.length<this._envelope.to.length))return err=this._formatError("Can't send mail - all recipients were rejected","EENVELOPE",str,"RCPT TO"),err.rejected=this._envelope.rejected,err.rejectedErrors=this._envelope.rejectedErrors,callback(err);this._responseActions.push(str=>{this._actionDATA(str,callback)}),this._sendCommand("DATA")}}_actionDATA(str,callback){if(!/^[23]/.test(str))return callback(this._formatError("Data command failed","EENVELOPE",str,"DATA"));let response={accepted:this._envelope.accepted,rejected:this._envelope.rejected};this._ehloLines&&this._ehloLines.length&&(response.ehlo=this._ehloLines),this._envelope.rejectedErrors.length&&(response.rejectedErrors=this._envelope.rejectedErrors),callback(null,response)}_actionSMTPStream(str,callback){return 2!==Number(str.charAt(0))?callback(this._formatError("Message failed","EMESSAGE",str,"DATA")):callback(null,str)}_actionLMTPStream(recipient,final,str,callback){let err;if(2!==Number(str.charAt(0))){err=this._formatError("Message failed for recipient "+recipient,"EMESSAGE",str,"DATA"),err.recipient=recipient,this._envelope.rejected.push(recipient),this._envelope.rejectedErrors.push(err);for(let i=0,len=this._envelope.accepted.length;i<len;i++)this._envelope.accepted[i]===recipient&&this._envelope.accepted.splice(i,1)}if(final)return callback(null,str)}_handleXOauth2Token(isRetry,callback){this._auth.oauth2.getToken(isRetry,(err,accessToken)=>{if(err)return this.logger.info({tnx:"smtp",username:this._auth.user,action:"authfail",method:this._authMethod},"User %s failed to authenticate",JSON.stringify(this._auth.user)),callback(this._formatError(err,"EAUTH",!1,"AUTH XOAUTH2"));this._responseActions.push(str=>{this._actionAUTHComplete(str,isRetry,callback)}),this._sendCommand("AUTH XOAUTH2 "+this._auth.oauth2.buildXOAuth2Token(accessToken),"AUTH XOAUTH2 "+this._auth.oauth2.buildXOAuth2Token("/* secret */"))})}_isDestroyedMessage(command){if(this._destroyed)return"Cannot "+command+" - smtp connection is already destroyed.";if(this._socket){if(this._socket.destroyed)return"Cannot "+command+" - smtp connection socket is already destroyed.";if(!this._socket.writable)return"Cannot "+command+" - smtp connection socket is already half-closed."}}_getHostname(){let defaultHostname;try{defaultHostname=os.hostname()||""}catch(err){defaultHostname="localhost"}return(!defaultHostname||defaultHostname.indexOf(".")<0)&&(defaultHostname="[127.0.0.1]"),defaultHostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)&&(defaultHostname="["+defaultHostname+"]"),defaultHostname}},smtpConnection}function requireXoauth2(){if(hasRequiredXoauth2)return xoauth2;hasRequiredXoauth2=1;const Stream=require$$0__default$4.default.Stream,nmfetch=requireFetch(),crypto=require$$0__default$1.default,shared=requireShared();return xoauth2=class XOAuth2 extends Stream{constructor(options,logger){if(super(),this.options=options||{},options&&options.serviceClient){if(!options.privateKey||!options.user)return void setImmediate(()=>this.emit("error",new Error('Options "privateKey" and "user" are required for service account!')));let serviceRequestTimeout=Math.min(Math.max(Number(this.options.serviceRequestTimeout)||0,0),3600);this.options.serviceRequestTimeout=serviceRequestTimeout||300}if(this.logger=shared.getLogger({logger:logger},{component:this.options.component||"OAuth2"}),this.provisionCallback="function"==typeof this.options.provisionCallback&&this.options.provisionCallback,this.options.accessUrl=this.options.accessUrl||"https://accounts.google.com/o/oauth2/token",this.options.customHeaders=this.options.customHeaders||{},this.options.customParams=this.options.customParams||{},this.accessToken=this.options.accessToken||!1,this.options.expires&&Number(this.options.expires))this.expires=this.options.expires;else{let timeout=Math.max(Number(this.options.timeout)||0,0);this.expires=timeout&&Date.now()+1e3*timeout||0}}getToken(renew,callback){if(!renew&&this.accessToken&&(!this.expires||this.expires>Date.now()))return callback(null,this.accessToken);let generateCallback=(...args)=>{args[0]?this.logger.error({err:args[0],tnx:"OAUTH2",user:this.options.user,action:"renew"},"Failed generating new Access Token for %s",this.options.user):this.logger.info({tnx:"OAUTH2",user:this.options.user,action:"renew"},"Generated new Access Token for %s",this.options.user),callback(...args)};this.provisionCallback?this.provisionCallback(this.options.user,!!renew,(err,accessToken,expires)=>{!err&&accessToken&&(this.accessToken=accessToken,this.expires=expires||0),generateCallback(err,accessToken)}):this.generateToken(generateCallback)}updateToken(accessToken,timeout){this.accessToken=accessToken,timeout=Math.max(Number(timeout)||0,0),this.expires=timeout&&Date.now()+1e3*timeout||0,this.emit("token",{user:this.options.user,accessToken:accessToken||"",expires:this.expires})}generateToken(callback){let urlOptions,loggedUrlOptions;if(this.options.serviceClient){let token,iat=Math.floor(Date.now()/1e3),tokenData={iss:this.options.serviceClient,scope:this.options.scope||"https://mail.google.com/",sub:this.options.user,aud:this.options.accessUrl,iat:iat,exp:iat+this.options.serviceRequestTimeout};try{token=this.jwtSignRS256(tokenData)}catch(err){return callback(new Error("Can't generate token. Check your auth options"))}urlOptions={grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:token},loggedUrlOptions={grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:tokenData}}else{if(!this.options.refreshToken)return callback(new Error("Can't create new access token for user"));urlOptions={client_id:this.options.clientId||"",client_secret:this.options.clientSecret||"",refresh_token:this.options.refreshToken,grant_type:"refresh_token"},loggedUrlOptions={client_id:this.options.clientId||"",client_secret:(this.options.clientSecret||"").substr(0,6)+"...",refresh_token:(this.options.refreshToken||"").substr(0,6)+"...",grant_type:"refresh_token"}}Object.keys(this.options.customParams).forEach(key=>{urlOptions[key]=this.options.customParams[key],loggedUrlOptions[key]=this.options.customParams[key]}),this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"generate"},"Requesting token using: %s",JSON.stringify(loggedUrlOptions)),this.postRequest(this.options.accessUrl,urlOptions,this.options,(error,body)=>{let data;if(error)return callback(error);try{data=JSON.parse(body.toString())}catch(E){return callback(E)}if(!data||"object"!=typeof data)return this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"post"},"Response: %s",(body||"").toString()),callback(new Error("Invalid authentication response"));let logData={};if(Object.keys(data).forEach(key=>{logData[key]="access_token"!==key?data[key]:(data[key]||"").toString().substr(0,6)+"..."}),this.logger.debug({tnx:"OAUTH2",user:this.options.user,action:"post"},"Response: %s",JSON.stringify(logData)),data.error){let errorMessage=data.error;return data.error_description&&(errorMessage+=": "+data.error_description),data.error_uri&&(errorMessage+=" ("+data.error_uri+")"),callback(new Error(errorMessage))}return data.access_token?(this.updateToken(data.access_token,data.expires_in),callback(null,this.accessToken)):callback(new Error("No access token"))})}buildXOAuth2Token(accessToken){let authData=["user="+(this.options.user||""),"auth=Bearer "+(accessToken||this.accessToken),"",""];return Buffer.from(authData.join(""),"utf-8").toString("base64")}postRequest(url,payload,params,callback){let returned=!1,chunks=[],chunklen=0,req=nmfetch(url,{method:"post",headers:params.customHeaders,body:payload,allowErrorResponse:!0});req.on("readable",()=>{let chunk;for(;null!==(chunk=req.read());)chunks.push(chunk),chunklen+=chunk.length}),req.once("error",err=>{if(!returned)return returned=!0,callback(err)}),req.once("end",()=>{if(!returned)return returned=!0,callback(null,Buffer.concat(chunks,chunklen))})}toBase64URL(data){return"string"==typeof data&&(data=Buffer.from(data)),data.toString("base64").replace(/[=]+/g,"").replace(/\+/g,"-").replace(/\//g,"_")}jwtSignRS256(payload){payload=['{"alg":"RS256","typ":"JWT"}',JSON.stringify(payload)].map(val=>this.toBase64URL(val)).join(".");let signature=crypto.createSign("RSA-SHA256").update(payload).sign(this.options.privateKey);return payload+"."+this.toBase64URL(signature)}},xoauth2}var wellKnown,hasRequiredWellKnown,smtpPool,hasRequiredSmtpPool,smtpTransport,hasRequiredSmtpTransport,sendmailTransport,hasRequiredSendmailTransport,streamTransport,hasRequiredStreamTransport,jsonTransport,hasRequiredJsonTransport,sesTransport,hasRequiredSesTransport,hasRequiredNodemailer,require$$0={126:{host:"smtp.126.com",port:465,secure:!0},163:{host:"smtp.163.com",port:465,secure:!0},"1und1":{host:"smtp.1und1.de",port:465,secure:!0,authMethod:"LOGIN"},Aliyun:{domains:["aliyun.com"],host:"smtp.aliyun.com",port:465,secure:!0},AOL:{domains:["aol.com"],host:"smtp.aol.com",port:587},Bluewin:{host:"smtpauths.bluewin.ch",domains:["bluewin.ch"],port:465},DebugMail:{host:"debugmail.io",port:25},DynectEmail:{aliases:["Dynect"],host:"smtp.dynect.net",port:25},Ethereal:{aliases:["ethereal.email"],host:"smtp.ethereal.email",port:587},FastMail:{domains:["fastmail.fm"],host:"smtp.fastmail.com",port:465,secure:!0},"Forward Email":{aliases:["FE","ForwardEmail"],domains:["forwardemail.net"],host:"smtp.forwardemail.net",port:465,secure:!0},"Feishu Mail":{aliases:["Feishu","FeishuMail"],domains:["www.feishu.cn"],host:"smtp.feishu.cn",port:465,secure:!0},GandiMail:{aliases:["Gandi","Gandi Mail"],host:"mail.gandi.net",port:587},Gmail:{aliases:["Google Mail"],domains:["gmail.com","googlemail.com"],host:"smtp.gmail.com",port:465,secure:!0},Godaddy:{host:"smtpout.secureserver.net",port:25},GodaddyAsia:{host:"smtp.asia.secureserver.net",port:25},GodaddyEurope:{host:"smtp.europe.secureserver.net",port:25},"hot.ee":{host:"mail.hot.ee"},Hotmail:{aliases:["Outlook","Outlook.com","Hotmail.com"],domains:["hotmail.com","outlook.com"],host:"smtp-mail.outlook.com",port:587},iCloud:{aliases:["Me","Mac"],domains:["me.com","mac.com"],host:"smtp.mail.me.com",port:587},Infomaniak:{host:"mail.infomaniak.com",domains:["ik.me","ikmail.com","etik.com"],port:587},Loopia:{host:"mailcluster.loopia.se",port:465},"mail.ee":{host:"smtp.mail.ee"},"Mail.ru":{host:"smtp.mail.ru",port:465,secure:!0},"Mailcatch.app":{host:"sandbox-smtp.mailcatch.app",port:2525},Maildev:{port:1025,ignoreTLS:!0},Mailgun:{host:"smtp.mailgun.org",port:465,secure:!0},Mailjet:{host:"in.mailjet.com",port:587},Mailosaur:{host:"mailosaur.io",port:25},Mailtrap:{host:"live.smtp.mailtrap.io",port:587},Mandrill:{host:"smtp.mandrillapp.com",port:587},Naver:{host:"smtp.naver.com",port:587},One:{host:"send.one.com",port:465,secure:!0},OpenMailBox:{aliases:["OMB","openmailbox.org"],host:"smtp.openmailbox.org",port:465,secure:!0},Outlook365:{host:"smtp.office365.com",port:587,secure:!1},OhMySMTP:{host:"smtp.ohmysmtp.com",port:587,secure:!1},Postmark:{aliases:["PostmarkApp"],host:"smtp.postmarkapp.com",port:2525},Proton:{aliases:["ProtonMail","Proton.me","Protonmail.com","Protonmail.ch"],domains:["proton.me","protonmail.com","pm.me","protonmail.ch"],host:"smtp.protonmail.ch",port:587,requireTLS:!0},"qiye.aliyun":{host:"smtp.mxhichina.com",port:"465",secure:!0},QQ:{domains:["qq.com"],host:"smtp.qq.com",port:465,secure:!0},QQex:{aliases:["QQ Enterprise"],domains:["exmail.qq.com"],host:"smtp.exmail.qq.com",port:465,secure:!0},SendCloud:{host:"smtp.sendcloud.net",port:2525},SendGrid:{host:"smtp.sendgrid.net",port:587},SendinBlue:{aliases:["Brevo"],host:"smtp-relay.brevo.com",port:587},SendPulse:{host:"smtp-pulse.com",port:465,secure:!0},SES:{host:"email-smtp.us-east-1.amazonaws.com",port:465,secure:!0},"SES-US-EAST-1":{host:"email-smtp.us-east-1.amazonaws.com",port:465,secure:!0},"SES-US-WEST-2":{host:"email-smtp.us-west-2.amazonaws.com",port:465,secure:!0},"SES-EU-WEST-1":{host:"email-smtp.eu-west-1.amazonaws.com",port:465,secure:!0},"SES-AP-SOUTH-1":{host:"email-smtp.ap-south-1.amazonaws.com",port:465,secure:!0},"SES-AP-NORTHEAST-1":{host:"email-smtp.ap-northeast-1.amazonaws.com",port:465,secure:!0},"SES-AP-NORTHEAST-2":{host:"email-smtp.ap-northeast-2.amazonaws.com",port:465,secure:!0},"SES-AP-NORTHEAST-3":{host:"email-smtp.ap-northeast-3.amazonaws.com",port:465,secure:!0},"SES-AP-SOUTHEAST-1":{host:"email-smtp.ap-southeast-1.amazonaws.com",port:465,secure:!0},"SES-AP-SOUTHEAST-2":{host:"email-smtp.ap-southeast-2.amazonaws.com",port:465,secure:!0},Seznam:{aliases:["Seznam Email"],domains:["seznam.cz","email.cz","post.cz","spoluzaci.cz"],host:"smtp.seznam.cz",port:465,secure:!0},Sparkpost:{aliases:["SparkPost","SparkPost Mail"],domains:["sparkpost.com"],host:"smtp.sparkpostmail.com",port:587,secure:!1},Tipimail:{host:"smtp.tipimail.com",port:587},Yahoo:{domains:["yahoo.com"],host:"smtp.mail.yahoo.com",port:465,secure:!0},Yandex:{domains:["yandex.ru"],host:"smtp.yandex.ru",port:465,secure:!0},Zoho:{host:"smtp.zoho.com",port:465,secure:!0,authMethod:"LOGIN"}};function requireWellKnown(){if(hasRequiredWellKnown)return wellKnown;hasRequiredWellKnown=1;const services=require$$0,normalized={};function normalizeKey(key){return key.replace(/[^a-zA-Z0-9.-]/g,"").toLowerCase()}function normalizeService(service){let filter=["domains","aliases"],response={};return Object.keys(service).forEach(key=>{filter.indexOf(key)<0&&(response[key]=service[key])}),response}return Object.keys(services).forEach(key=>{let service=services[key];normalized[normalizeKey(key)]=normalizeService(service),[].concat(service.aliases||[]).forEach(alias=>{normalized[normalizeKey(alias)]=normalizeService(service)}),[].concat(service.domains||[]).forEach(domain=>{normalized[normalizeKey(domain)]=normalizeService(service)})}),wellKnown=function(key){return key=normalizeKey(key.split("@").pop()),normalized[key]||!1}}function requireSmtpPool(){if(hasRequiredSmtpPool)return smtpPool;hasRequiredSmtpPool=1;const EventEmitter=require$$0__default.default,PoolResource=function requirePoolResource(){if(hasRequiredPoolResource)return poolResource;hasRequiredPoolResource=1;const SMTPConnection=requireSmtpConnection(),assign=requireShared().assign,XOAuth2=requireXoauth2(),EventEmitter=require$$0__default.default;return poolResource=class PoolResource extends EventEmitter{constructor(pool){if(super(),this.pool=pool,this.options=pool.options,this.logger=this.pool.logger,this.options.auth)switch((this.options.auth.type||"").toString().toUpperCase()){case"OAUTH2":{let oauth2=new XOAuth2(this.options.auth,this.logger);oauth2.provisionCallback=this.pool.mailer&&this.pool.mailer.get("oauth2_provision_cb")||oauth2.provisionCallback,this.auth={type:"OAUTH2",user:this.options.auth.user,oauth2:oauth2,method:"XOAUTH2"},oauth2.on("token",token=>this.pool.mailer.emit("token",token)),oauth2.on("error",err=>this.emit("error",err));break}default:if(!this.options.auth.user&&!this.options.auth.pass)break;this.auth={type:(this.options.auth.type||"").toString().toUpperCase()||"LOGIN",user:this.options.auth.user,credentials:{user:this.options.auth.user||"",pass:this.options.auth.pass,options:this.options.auth.options},method:(this.options.auth.method||"").trim().toUpperCase()||this.options.authMethod||!1}}this._connection=!1,this._connected=!1,this.messages=0,this.available=!0}connect(callback){this.pool.getSocket(this.options,(err,socketOptions)=>{if(err)return callback(err);let returned=!1,options=this.options;socketOptions&&socketOptions.connection&&(this.logger.info({tnx:"proxy",remoteAddress:socketOptions.connection.remoteAddress,remotePort:socketOptions.connection.remotePort,destHost:options.host||"",destPort:options.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",socketOptions.connection.remoteAddress,socketOptions.connection.remotePort,options.host||"",options.port||""),options=assign(!1,options),Object.keys(socketOptions).forEach(key=>{options[key]=socketOptions[key]})),this.connection=new SMTPConnection(options),this.connection.once("error",err=>{if(this.emit("error",err),!returned)return returned=!0,callback(err)}),this.connection.once("end",()=>{if(this.close(),returned)return;returned=!0;let timer=setTimeout(()=>{if(returned)return;let err=new Error("Unexpected socket close");this.connection&&this.connection._socket&&this.connection._socket.upgrading&&(err.code="ETLS"),callback(err)},1e3);try{timer.unref()}catch(E){}}),this.connection.connect(()=>{if(!returned)return this.auth&&(this.connection.allowsAuth||options.forceAuth)?void this.connection.login(this.auth,err=>{if(!returned){if(returned=!0,err)return this.connection.close(),this.emit("error",err),callback(err);this._connected=!0,callback(null,!0)}}):(returned=!0,this._connected=!0,callback(null,!0))})})}send(mail,callback){if(!this._connected)return this.connect(err=>err?callback(err):this.send(mail,callback));let envelope=mail.message.getEnvelope(),messageId=mail.message.messageId(),recipients=[].concat(envelope.to||[]);recipients.length>3&&recipients.push("...and "+recipients.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:messageId,cid:this.id},"Sending message %s using #%s to <%s>",messageId,this.id,recipients.join(", ")),mail.data.dsn&&(envelope.dsn=mail.data.dsn),this.connection.send(envelope,mail.message.createReadStream(),(err,info)=>{if(this.messages++,err)return this.connection.close(),this.emit("error",err),callback(err);info.envelope={from:envelope.from,to:envelope.to},info.messageId=messageId,setImmediate(()=>{let err;this.messages>=this.options.maxMessages?(err=new Error("Resource exhausted"),err.code="EMAXLIMIT",this.connection.close(),this.emit("error",err)):this.pool._checkRateLimit(()=>{this.available=!0,this.emit("available")})}),callback(null,info)})}close(){this._connected=!1,this.auth&&this.auth.oauth2&&this.auth.oauth2.removeAllListeners(),this.connection&&this.connection.close(),this.emit("close")}},poolResource}(),SMTPConnection=requireSmtpConnection(),wellKnown=requireWellKnown(),shared=requireShared(),packageData=require$$9;return smtpPool=class SMTPPool extends EventEmitter{constructor(options){let urlData;super(),"string"==typeof(options=options||{})&&(options={url:options});let service=options.service;"function"==typeof options.getSocket&&(this.getSocket=options.getSocket),options.url&&(urlData=shared.parseConnectionUrl(options.url),service=service||urlData.service),this.options=shared.assign(!1,options,urlData,service&&wellKnown(service)),this.options.maxConnections=this.options.maxConnections||5,this.options.maxMessages=this.options.maxMessages||100,this.logger=shared.getLogger(this.options,{component:this.options.component||"smtp-pool"});let connection=new SMTPConnection(this.options);this.name="SMTP (pool)",this.version=packageData.version+"[client:"+connection.version+"]",this._rateLimit={counter:0,timeout:null,waiting:[],checkpoint:!1,delta:Number(this.options.rateDelta)||1e3,limit:Number(this.options.rateLimit)||0},this._closed=!1,this._queue=[],this._connections=[],this._connectionCounter=0,this.idling=!0,setImmediate(()=>{this.idling&&this.emit("idle")})}getSocket(options,callback){return setImmediate(()=>callback(null,!1))}send(mail,callback){return!this._closed&&(this._queue.push({mail:mail,requeueAttempts:0,callback:callback}),this.idling&&this._queue.length>=this.options.maxConnections&&(this.idling=!1),setImmediate(()=>this._processMessages()),!0)}close(){let connection,len=this._connections.length;if(this._closed=!0,clearTimeout(this._rateLimit.timeout),!len&&!this._queue.length)return;for(let i=len-1;i>=0;i--)this._connections[i]&&this._connections[i].available&&(connection=this._connections[i],connection.close(),this.logger.info({tnx:"connection",cid:connection.id,action:"removed"},"Connection #%s removed",connection.id));if(len&&!this._connections.length&&this.logger.debug({tnx:"connection"},"All connections removed"),!this._queue.length)return;let invokeCallbacks=()=>{if(!this._queue.length)return void this.logger.debug({tnx:"connection"},"Pending queue entries cleared");let entry=this._queue.shift();if(entry&&"function"==typeof entry.callback)try{entry.callback(new Error("Connection pool was closed"))}catch(E){this.logger.error({err:E,tnx:"callback",cid:connection.id},"Callback error for #%s: %s",connection.id,E.message)}setImmediate(invokeCallbacks)};setImmediate(invokeCallbacks)}_processMessages(){let connection,i,len;if(this._closed)return;if(!this._queue.length)return void(this.idling||(this.idling=!0,this.emit("idle")));for(i=0,len=this._connections.length;i<len;i++)if(this._connections[i].available){connection=this._connections[i];break}if(!connection&&this._connections.length<this.options.maxConnections&&(connection=this._createConnection()),!connection)return void(this.idling=!1);!this.idling&&this._queue.length<this.options.maxConnections&&(this.idling=!0,this.emit("idle"));let entry=connection.queueEntry=this._queue.shift();entry.messageId=(connection.queueEntry.mail.message.getHeader("message-id")||"").replace(/[<>\s]/g,""),connection.available=!1,this.logger.debug({tnx:"pool",cid:connection.id,messageId:entry.messageId,action:"assign"},"Assigned message <%s> to #%s (%s)",entry.messageId,connection.id,connection.messages+1),this._rateLimit.limit&&(this._rateLimit.counter++,this._rateLimit.checkpoint||(this._rateLimit.checkpoint=Date.now())),connection.send(entry.mail,(err,info)=>{if(entry===connection.queueEntry){try{entry.callback(err,info)}catch(E){this.logger.error({err:E,tnx:"callback",cid:connection.id},"Callback error for #%s: %s",connection.id,E.message)}connection.queueEntry=!1}})}_createConnection(){let connection=new PoolResource(this);return connection.id=++this._connectionCounter,this.logger.info({tnx:"pool",cid:connection.id,action:"conection"},"Created new pool resource #%s",connection.id),connection.on("available",()=>{this.logger.debug({tnx:"connection",cid:connection.id,action:"available"},"Connection #%s became available",connection.id),this._closed?this.close():this._processMessages()}),connection.once("error",err=>{if("EMAXLIMIT"!==err.code?this.logger.error({err:err,tnx:"pool",cid:connection.id},"Pool Error for #%s: %s",connection.id,err.message):this.logger.debug({tnx:"pool",cid:connection.id,action:"maxlimit"},"Max messages limit exchausted for #%s",connection.id),connection.queueEntry){try{connection.queueEntry.callback(err)}catch(E){this.logger.error({err:E,tnx:"callback",cid:connection.id},"Callback error for #%s: %s",connection.id,E.message)}connection.queueEntry=!1}this._removeConnection(connection),this._continueProcessing()}),connection.once("close",()=>{this.logger.info({tnx:"connection",cid:connection.id,action:"closed"},"Connection #%s was closed",connection.id),this._removeConnection(connection),connection.queueEntry?setTimeout(()=>{connection.queueEntry&&(this._shouldRequeuOnConnectionClose(connection.queueEntry)?this._requeueEntryOnConnectionClose(connection):this._failDeliveryOnConnectionClose(connection)),this._continueProcessing()},50):this._continueProcessing()}),this._connections.push(connection),connection}_shouldRequeuOnConnectionClose(queueEntry){return void 0===this.options.maxRequeues||this.options.maxRequeues<0||queueEntry.requeueAttempts<this.options.maxRequeues}_failDeliveryOnConnectionClose(connection){if(connection.queueEntry&&connection.queueEntry.callback){try{connection.queueEntry.callback(new Error("Reached maximum number of retries after connection was closed"))}catch(E){this.logger.error({err:E,tnx:"callback",messageId:connection.queueEntry.messageId,cid:connection.id},"Callback error for #%s: %s",connection.id,E.message)}connection.queueEntry=!1}}_requeueEntryOnConnectionClose(connection){connection.queueEntry.requeueAttempts=connection.queueEntry.requeueAttempts+1,this.logger.debug({tnx:"pool",cid:connection.id,messageId:connection.queueEntry.messageId,action:"requeue"},"Re-queued message <%s> for #%s. Attempt: #%s",connection.queueEntry.messageId,connection.id,connection.queueEntry.requeueAttempts),this._queue.unshift(connection.queueEntry),connection.queueEntry=!1}_continueProcessing(){this._closed?this.close():setTimeout(()=>this._processMessages(),100)}_removeConnection(connection){let index=this._connections.indexOf(connection);-1!==index&&this._connections.splice(index,1)}_checkRateLimit(callback){if(!this._rateLimit.limit)return callback();let now=Date.now();return this._rateLimit.counter<this._rateLimit.limit?callback():(this._rateLimit.waiting.push(callback),this._rateLimit.checkpoint<=now-this._rateLimit.delta?this._clearRateLimit():void(this._rateLimit.timeout||(this._rateLimit.timeout=setTimeout(()=>this._clearRateLimit(),this._rateLimit.delta-(now-this._rateLimit.checkpoint)),this._rateLimit.checkpoint=now)))}_clearRateLimit(){for(clearTimeout(this._rateLimit.timeout),this._rateLimit.timeout=null,this._rateLimit.counter=0,this._rateLimit.checkpoint=!1;this._rateLimit.waiting.length;){let cb=this._rateLimit.waiting.shift();setImmediate(cb)}}isIdle(){return this.idling}verify(callback){let promise;callback||(promise=new Promise((resolve,reject)=>{callback=shared.callbackPromise(resolve,reject)}));let auth=new PoolResource(this).auth;return this.getSocket(this.options,(err,socketOptions)=>{if(err)return callback(err);let options=this.options;socketOptions&&socketOptions.connection&&(this.logger.info({tnx:"proxy",remoteAddress:socketOptions.connection.remoteAddress,remotePort:socketOptions.connection.remotePort,destHost:options.host||"",destPort:options.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",socketOptions.connection.remoteAddress,socketOptions.connection.remotePort,options.host||"",options.port||""),options=shared.assign(!1,options),Object.keys(socketOptions).forEach(key=>{options[key]=socketOptions[key]}));let connection=new SMTPConnection(options),returned=!1;connection.once("error",err=>{if(!returned)return returned=!0,connection.close(),callback(err)}),connection.once("end",()=>{if(!returned)return returned=!0,callback(new Error("Connection closed"))});let finalize=()=>{if(!returned)return returned=!0,connection.quit(),callback(null,!0)};connection.connect(()=>{if(!returned)if(auth&&(connection.allowsAuth||options.forceAuth))connection.login(auth,err=>{if(!returned)return err?(returned=!0,connection.close(),callback(err)):void finalize()});else{if(!auth&&connection.allowsAuth&&options.forceAuth){let err=new Error("Authentication info was not provided");return err.code="NoAuth",returned=!0,connection.close(),callback(err)}finalize()}})}),promise}},smtpPool}function requireSesTransport(){if(hasRequiredSesTransport)return sesTransport;hasRequiredSesTransport=1;const EventEmitter=require$$0__default.default,packageData=require$$9,shared=requireShared(),LeWindows=requireLeWindows();return sesTransport=class SESTransport extends EventEmitter{constructor(options){super(),options=options||{},this.options=options||{},this.ses=this.options.SES,this.name="SESTransport",this.version=packageData.version,this.logger=shared.getLogger(this.options,{component:this.options.component||"ses-transport"}),this.maxConnections=Number(this.options.maxConnections)||1/0,this.connections=0,this.sendingRate=Number(this.options.sendingRate)||1/0,this.sendingRateTTL=null,this.rateInterval=1e3,this.rateMessages=[],this.pending=[],this.idling=!0,setImmediate(()=>{this.idling&&this.emit("idle")})}send(mail,callback){return this.connections>=this.maxConnections?(this.idling=!1,this.pending.push({mail:mail,callback:callback})):this._checkSendingRate()?void this._send(mail,(...args)=>{setImmediate(()=>callback(...args)),this._sent()}):(this.idling=!1,this.pending.push({mail:mail,callback:callback}))}_checkRatedQueue(){if(this.connections>=this.maxConnections||!this._checkSendingRate())return;if(!this.pending.length)return void(this.idling||(this.idling=!0,this.emit("idle")));let next=this.pending.shift();this._send(next.mail,(...args)=>{setImmediate(()=>next.callback(...args)),this._sent()})}_checkSendingRate(){clearTimeout(this.sendingRateTTL);let now=Date.now(),oldest=!1;for(let i=this.rateMessages.length-1;i>=0;i--)this.rateMessages[i].ts>=now-this.rateInterval&&(!oldest||this.rateMessages[i].ts<oldest)&&(oldest=this.rateMessages[i].ts),this.rateMessages[i].ts<now-this.rateInterval&&!this.rateMessages[i].pending&&this.rateMessages.splice(i,1);if(this.rateMessages.length<this.sendingRate)return!0;let delay=Math.max(oldest+1001,now+20);this.sendingRateTTL=setTimeout(()=>this._checkRatedQueue(),now-delay);try{this.sendingRateTTL.unref()}catch(E){}return!1}_sent(){this.connections--,this._checkRatedQueue()}isIdle(){return this.idling}_send(mail,callback){let statObject={ts:Date.now(),pending:!0};this.connections++,this.rateMessages.push(statObject);let envelope=mail.data.envelope||mail.message.getEnvelope(),messageId=mail.message.messageId(),recipients=[].concat(envelope.to||[]);recipients.length>3&&recipients.push("...and "+recipients.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:messageId},"Sending message %s to <%s>",messageId,recipients.join(", "));setImmediate(()=>(next=>{mail.data._dkim||(mail.data._dkim={}),mail.data._dkim.skipFields&&"string"==typeof mail.data._dkim.skipFields?mail.data._dkim.skipFields+=":date:message-id":mail.data._dkim.skipFields="date:message-id";let sourceStream=mail.message.createReadStream(),stream=sourceStream.pipe(new LeWindows),chunks=[],chunklen=0;stream.on("readable",()=>{let chunk;for(;null!==(chunk=stream.read());)chunks.push(chunk),chunklen+=chunk.length}),sourceStream.once("error",err=>stream.emit("error",err)),stream.once("error",err=>{next(err)}),stream.once("end",()=>next(null,Buffer.concat(chunks,chunklen)))})((err,raw)=>{if(err)return this.logger.error({err:err,tnx:"send",messageId:messageId},"Failed creating message for %s. %s",messageId,err.message),statObject.pending=!1,callback(err);let sesMessage={RawMessage:{Data:raw},Source:envelope.from,Destinations:envelope.to};Object.keys(mail.data.ses||{}).forEach(key=>{sesMessage[key]=mail.data.ses[key]});let ses=(this.ses.aws?this.ses.ses:this.ses)||{},aws=this.ses.aws||{};var cb;cb=(err,region)=>{let sendPromise;!err&®ion||(region="us-east-1"),sendPromise="function"==typeof ses.send&&aws.SendRawEmailCommand?ses.send(new aws.SendRawEmailCommand(sesMessage)):ses.sendRawEmail(sesMessage).promise(),sendPromise.then(data=>{"us-east-1"===region&&(region="email"),statObject.pending=!1,callback(null,{envelope:{from:envelope.from,to:envelope.to},messageId:"<"+data.MessageId+(/@/.test(data.MessageId)?"":"@"+region+".amazonses.com")+">",response:data.MessageId,raw:raw})}).catch(err=>{this.logger.error({err:err,tnx:"send"},"Send error for %s: %s",messageId,err.message),statObject.pending=!1,callback(err)})},ses.config&&"function"==typeof ses.config.region?ses.config.region().then(region=>cb(null,region)).catch(err=>cb(err)):cb(null,ses.config&&ses.config.region||"us-east-1")}))}verify(callback){let promise,ses=(this.ses.aws?this.ses.ses:this.ses)||{},aws=this.ses.aws||{};const sesMessage={RawMessage:{Data:"From: invalid@invalid\r\nTo: invalid@invalid\r\n Subject: Invalid\r\n\r\nInvalid"},Source:"invalid@invalid",Destinations:["invalid@invalid"]};callback||(promise=new Promise((resolve,reject)=>{callback=shared.callbackPromise(resolve,reject)}));const cb=err=>err&&"InvalidParameterValue"!==(err.code||err.Code)?callback(err):callback(null,!0);return"function"==typeof ses.send&&aws.SendRawEmailCommand?(sesMessage.RawMessage.Data=Buffer.from(sesMessage.RawMessage.Data),ses.send(new aws.SendRawEmailCommand(sesMessage),cb)):ses.sendRawEmail(sesMessage,cb),promise}},sesTransport}var nodemailerExports=function requireNodemailer(){if(hasRequiredNodemailer)return nodemailer$1;hasRequiredNodemailer=1;const Mailer=requireMailer(),shared=requireShared(),SMTPPool=requireSmtpPool(),SMTPTransport=function requireSmtpTransport(){if(hasRequiredSmtpTransport)return smtpTransport;hasRequiredSmtpTransport=1;const EventEmitter=require$$0__default.default,SMTPConnection=requireSmtpConnection(),wellKnown=requireWellKnown(),shared=requireShared(),XOAuth2=requireXoauth2(),packageData=require$$9;return smtpTransport=class SMTPTransport extends EventEmitter{constructor(options){let urlData;super(),"string"==typeof(options=options||{})&&(options={url:options});let service=options.service;"function"==typeof options.getSocket&&(this.getSocket=options.getSocket),options.url&&(urlData=shared.parseConnectionUrl(options.url),service=service||urlData.service),this.options=shared.assign(!1,options,urlData,service&&wellKnown(service)),this.logger=shared.getLogger(this.options,{component:this.options.component||"smtp-transport"});let connection=new SMTPConnection(this.options);this.name="SMTP",this.version=packageData.version+"[client:"+connection.version+"]",this.options.auth&&(this.auth=this.getAuth({}))}getSocket(options,callback){return setImmediate(()=>callback(null,!1))}getAuth(authOpts){if(!authOpts)return this.auth;let hasAuth=!1,authData={};if(this.options.auth&&"object"==typeof this.options.auth&&Object.keys(this.options.auth).forEach(key=>{hasAuth=!0,authData[key]=this.options.auth[key]}),authOpts&&"object"==typeof authOpts&&Object.keys(authOpts).forEach(key=>{hasAuth=!0,authData[key]=authOpts[key]}),!hasAuth)return!1;if("OAUTH2"===(authData.type||"").toString().toUpperCase()){if(!authData.service&&!authData.user)return!1;let oauth2=new XOAuth2(authData,this.logger);return oauth2.provisionCallback=this.mailer&&this.mailer.get("oauth2_provision_cb")||oauth2.provisionCallback,oauth2.on("token",token=>this.mailer.emit("token",token)),oauth2.on("error",err=>this.emit("error",err)),{type:"OAUTH2",user:authData.user,oauth2:oauth2,method:"XOAUTH2"}}return{type:(authData.type||"").toString().toUpperCase()||"LOGIN",user:authData.user,credentials:{user:authData.user||"",pass:authData.pass,options:authData.options},method:(authData.method||"").trim().toUpperCase()||this.options.authMethod||!1}}send(mail,callback){this.getSocket(this.options,(err,socketOptions)=>{if(err)return callback(err);let returned=!1,options=this.options;socketOptions&&socketOptions.connection&&(this.logger.info({tnx:"proxy",remoteAddress:socketOptions.connection.remoteAddress,remotePort:socketOptions.connection.remotePort,destHost:options.host||"",destPort:options.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",socketOptions.connection.remoteAddress,socketOptions.connection.remotePort,options.host||"",options.port||""),options=shared.assign(!1,options),Object.keys(socketOptions).forEach(key=>{options[key]=socketOptions[key]}));let connection=new SMTPConnection(options);connection.once("error",err=>{if(!returned)return returned=!0,connection.close(),callback(err)}),connection.once("end",()=>{if(returned)return;let timer=setTimeout(()=>{if(returned)return;returned=!0;let err=new Error("Unexpected socket close");connection&&connection._socket&&connection._socket.upgrading&&(err.code="ETLS"),callback(err)},1e3);try{timer.unref()}catch(E){}});let sendMessage=()=>{let envelope=mail.message.getEnvelope(),messageId=mail.message.messageId(),recipients=[].concat(envelope.to||[]);recipients.length>3&&recipients.push("...and "+recipients.splice(2).length+" more"),mail.data.dsn&&(envelope.dsn=mail.data.dsn),this.logger.info({tnx:"send",messageId:messageId},"Sending message %s to <%s>",messageId,recipients.join(", ")),connection.send(envelope,mail.message.createReadStream(),(err,info)=>{if(returned=!0,connection.close(),err)return this.logger.error({err:err,tnx:"send"},"Send error for %s: %s",messageId,err.message),callback(err);info.envelope={from:envelope.from,to:envelope.to},info.messageId=messageId;try{return callback(null,info)}catch(E){this.logger.error({err:E,tnx:"callback"},"Callback error for %s: %s",messageId,E.message)}})};connection.connect(()=>{if(returned)return;let auth=this.getAuth(mail.data.auth);auth&&(connection.allowsAuth||options.forceAuth)?connection.login(auth,err=>{if(auth&&auth!==this.auth&&auth.oauth2&&auth.oauth2.removeAllListeners(),!returned)return err?(returned=!0,connection.close(),callback(err)):void sendMessage()}):sendMessage()})})}verify(callback){let promise;return callback||(promise=new Promise((resolve,reject)=>{callback=shared.callbackPromise(resolve,reject)})),this.getSocket(this.options,(err,socketOptions)=>{if(err)return callback(err);let options=this.options;socketOptions&&socketOptions.connection&&(this.logger.info({tnx:"proxy",remoteAddress:socketOptions.connection.remoteAddress,remotePort:socketOptions.connection.remotePort,destHost:options.host||"",destPort:options.port||"",action:"connected"},"Using proxied socket from %s:%s to %s:%s",socketOptions.connection.remoteAddress,socketOptions.connection.remotePort,options.host||"",options.port||""),options=shared.assign(!1,options),Object.keys(socketOptions).forEach(key=>{options[key]=socketOptions[key]}));let connection=new SMTPConnection(options),returned=!1;connection.once("error",err=>{if(!returned)return returned=!0,connection.close(),callback(err)}),connection.once("end",()=>{if(!returned)return returned=!0,callback(new Error("Connection closed"))});let finalize=()=>{if(!returned)return returned=!0,connection.quit(),callback(null,!0)};connection.connect(()=>{if(returned)return;let authData=this.getAuth({});if(authData&&(connection.allowsAuth||options.forceAuth))connection.login(authData,err=>{if(!returned)return err?(returned=!0,connection.close(),callback(err)):void finalize()});else{if(!authData&&connection.allowsAuth&&options.forceAuth){let err=new Error("Authentication info was not provided");return err.code="NoAuth",returned=!0,connection.close(),callback(err)}finalize()}})}),promise}close(){this.auth&&this.auth.oauth2&&this.auth.oauth2.removeAllListeners(),this.emit("close")}},smtpTransport}(),SendmailTransport=function requireSendmailTransport(){if(hasRequiredSendmailTransport)return sendmailTransport;hasRequiredSendmailTransport=1;const spawn=require$$0__default$7.default.spawn,packageData=require$$9,shared=requireShared();return sendmailTransport=class SendmailTransport{constructor(options){options=options||{},this._spawn=spawn,this.options=options||{},this.name="Sendmail",this.version=packageData.version,this.path="sendmail",this.args=!1,this.winbreak=!1,this.logger=shared.getLogger(this.options,{component:this.options.component||"sendmail"}),options&&("string"==typeof options?this.path=options:"object"==typeof options&&(options.path&&(this.path=options.path),Array.isArray(options.args)&&(this.args=options.args),this.winbreak=["win","windows","dos","\r\n"].includes((options.newline||"").toString().toLowerCase())))}send(mail,done){mail.message.keepBcc=!0;let args,sendmail,returned,envelope=mail.data.envelope||mail.message.getEnvelope(),messageId=mail.message.messageId();if([].concat(envelope.from||[]).concat(envelope.to||[]).some(addr=>/^-/.test(addr)))return done(new Error("Can not send mail. Invalid envelope addresses."));args=this.args?["-i"].concat(this.args).concat(envelope.to):["-i"].concat(envelope.from?["-f",envelope.from]:[]).concat(envelope.to);let callback=err=>{if(!returned)return returned=!0,"function"==typeof done?err?done(err):done(null,{envelope:mail.data.envelope||mail.message.getEnvelope(),messageId:messageId,response:"Messages queued for delivery"}):void 0};try{sendmail=this._spawn(this.path,args)}catch(E){return this.logger.error({err:E,tnx:"spawn",messageId:messageId},"Error occurred while spawning sendmail. %s",E.message),callback(E)}if(!sendmail)return callback(new Error("sendmail was not found"));{sendmail.on("error",err=>{this.logger.error({err:err,tnx:"spawn",messageId:messageId},"Error occurred when sending message %s. %s",messageId,err.message),callback(err)}),sendmail.once("exit",code=>{if(!code)return callback();let err;err=127===code?new Error("Sendmail command not found, process exited with code "+code):new Error("Sendmail exited with code "+code),this.logger.error({err:err,tnx:"stdin",messageId:messageId},"Error sending message %s to sendmail. %s",messageId,err.message),callback(err)}),sendmail.once("close",callback),sendmail.stdin.on("error",err=>{this.logger.error({err:err,tnx:"stdin",messageId:messageId},"Error occurred when piping message %s to sendmail. %s",messageId,err.message),callback(err)});let recipients=[].concat(envelope.to||[]);recipients.length>3&&recipients.push("...and "+recipients.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:messageId},"Sending message %s to <%s>",messageId,recipients.join(", "));let sourceStream=mail.message.createReadStream();sourceStream.once("error",err=>{this.logger.error({err:err,tnx:"stdin",messageId:messageId},"Error occurred when generating message %s. %s",messageId,err.message),sendmail.kill("SIGINT"),callback(err)}),sourceStream.pipe(sendmail.stdin)}}},sendmailTransport}(),StreamTransport=function requireStreamTransport(){if(hasRequiredStreamTransport)return streamTransport;hasRequiredStreamTransport=1;const packageData=require$$9,shared=requireShared();return streamTransport=class StreamTransport{constructor(options){options=options||{},this.options=options||{},this.name="StreamTransport",this.version=packageData.version,this.logger=shared.getLogger(this.options,{component:this.options.component||"stream-transport"}),this.winbreak=["win","windows","dos","\r\n"].includes((options.newline||"").toString().toLowerCase())}send(mail,done){mail.message.keepBcc=!0;let envelope=mail.data.envelope||mail.message.getEnvelope(),messageId=mail.message.messageId(),recipients=[].concat(envelope.to||[]);recipients.length>3&&recipients.push("...and "+recipients.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:messageId},"Sending message %s to <%s> using %s line breaks",messageId,recipients.join(", "),this.winbreak?"<CR><LF>":"<LF>"),setImmediate(()=>{let stream;try{stream=mail.message.createReadStream()}catch(E){return this.logger.error({err:E,tnx:"send",messageId:messageId},"Creating send stream failed for %s. %s",messageId,E.message),done(E)}if(!this.options.buffer)return stream.once("error",err=>{this.logger.error({err:err,tnx:"send",messageId:messageId},"Failed creating message for %s. %s",messageId,err.message)}),done(null,{envelope:mail.data.envelope||mail.message.getEnvelope(),messageId:messageId,message:stream});let chunks=[],chunklen=0;stream.on("readable",()=>{let chunk;for(;null!==(chunk=stream.read());)chunks.push(chunk),chunklen+=chunk.length}),stream.once("error",err=>(this.logger.error({err:err,tnx:"send",messageId:messageId},"Failed creating message for %s. %s",messageId,err.message),done(err))),stream.on("end",()=>done(null,{envelope:mail.data.envelope||mail.message.getEnvelope(),messageId:messageId,message:Buffer.concat(chunks,chunklen)}))})}},streamTransport}(),JSONTransport=function requireJsonTransport(){if(hasRequiredJsonTransport)return jsonTransport;hasRequiredJsonTransport=1;const packageData=require$$9,shared=requireShared();return jsonTransport=class JSONTransport{constructor(options){options=options||{},this.options=options||{},this.name="JSONTransport",this.version=packageData.version,this.logger=shared.getLogger(this.options,{component:this.options.component||"json-transport"})}send(mail,done){mail.message.keepBcc=!0;let envelope=mail.data.envelope||mail.message.getEnvelope(),messageId=mail.message.messageId(),recipients=[].concat(envelope.to||[]);recipients.length>3&&recipients.push("...and "+recipients.splice(2).length+" more"),this.logger.info({tnx:"send",messageId:messageId},"Composing JSON structure of %s to <%s>",messageId,recipients.join(", ")),setImmediate(()=>{mail.normalize((err,data)=>err?(this.logger.error({err:err,tnx:"send",messageId:messageId},"Failed building JSON structure for %s. %s",messageId,err.message),done(err)):(delete data.envelope,delete data.normalizedHeaders,done(null,{envelope:envelope,messageId:messageId,message:this.options.skipEncoding?data:JSON.stringify(data)})))})}},jsonTransport}(),SESTransport=requireSesTransport(),nmfetch=requireFetch(),packageData=require$$9,ETHEREAL_API=(process.env.ETHEREAL_API||"https://api.nodemailer.com").replace(/\/+$/,""),ETHEREAL_WEB=(process.env.ETHEREAL_WEB||"https://ethereal.email").replace(/\/+$/,""),ETHEREAL_API_KEY=(process.env.ETHEREAL_API_KEY||"").replace(/\s*/g,"")||null,ETHEREAL_CACHE=["true","yes","y","1"].includes((process.env.ETHEREAL_CACHE||"yes").toString().trim().toLowerCase());let testAccount=!1;return nodemailer$1.createTransport=function(transporter,defaults){let urlConfig,options,mailer;return("object"==typeof transporter&&"function"!=typeof transporter.send||"string"==typeof transporter&&/^(smtps?|direct):/i.test(transporter))&&(options=(urlConfig="string"==typeof transporter?transporter:transporter.url)?shared.parseConnectionUrl(urlConfig):transporter,transporter=options.pool?new SMTPPool(options):options.sendmail?new SendmailTransport(options):options.streamTransport?new StreamTransport(options):options.jsonTransport?new JSONTransport(options):options.SES?new SESTransport(options):new SMTPTransport(options)),mailer=new Mailer(transporter,options,defaults),mailer},nodemailer$1.createTestAccount=function(apiUrl,callback){let promise;if(callback||"function"!=typeof apiUrl||(callback=apiUrl,apiUrl=!1),callback||(promise=new Promise((resolve,reject)=>{callback=shared.callbackPromise(resolve,reject)})),ETHEREAL_CACHE&&testAccount)return setImmediate(()=>callback(null,testAccount)),promise;apiUrl=apiUrl||ETHEREAL_API;let chunks=[],chunklen=0,requestHeaders={},requestBody={requestor:packageData.name,version:packageData.version};ETHEREAL_API_KEY&&(requestHeaders.Authorization="Bearer "+ETHEREAL_API_KEY);let req=nmfetch(apiUrl+"/user",{contentType:"application/json",method:"POST",headers:requestHeaders,body:Buffer.from(JSON.stringify(requestBody))});return req.on("readable",()=>{let chunk;for(;null!==(chunk=req.read());)chunks.push(chunk),chunklen+=chunk.length}),req.once("error",err=>callback(err)),req.once("end",()=>{let data,err,res=Buffer.concat(chunks,chunklen);try{data=JSON.parse(res.toString())}catch(E){err=E}return err?callback(err):"success"!==data.status||data.error?callback(new Error(data.error||"Request failed")):(delete data.status,testAccount=data,void callback(null,testAccount))}),promise},nodemailer$1.getTestMessageUrl=function(info){if(!info||!info.response)return!1;let infoProps=new Map;return info.response.replace(/\[([^\]]+)\]$/,(m,props)=>{props.replace(/\b([A-Z0-9]+)=([^\s]+)/g,(m,key,value)=>{infoProps.set(key,value)})}),!(!infoProps.has("STATUS")||!infoProps.has("MSGID"))&&(testAccount.web||ETHEREAL_WEB)+"/message/"+infoProps.get("MSGID")},nodemailer$1}(),nodemailer=getDefaultExportFromCjs(nodemailerExports);class MailController{environment;constructor(environment){this.environment=environment}createTransporter(email){const{host:host,port:port,secure:secure,auth:{user:user,pass:pass}}=email;return nodemailer.createTransport({host:host,port:port,secure:secure,auth:{user:user,pass:pass}})}mountMail(email,mailParams){const{emailParams:{from:from,to:to}}=email,{message:message,subject:subject,attachments:attachments}=mailParams,attachmentsWithVerifiedFileName=attachments?.map(attachment=>(attachment.filename||(attachment.filename=!1),attachment));return{from:from,to:to,subject:subject,html:message,attachments:attachmentsWithVerifiedFileName}}sendEmail(mailParams){try{const{email:email}=this.environment.getConfig();if(!email)throw new Error('Email não configurado. Para utilizar o envio de e-mail certifique-se de passar as configurações corretas para o método "NFE_LoadEnvironment".');const transporter=this.createTransporter(email),mailOptions=this.mountMail(email,mailParams);transporter.sendMail(mailOptions,(error,info)=>{if(error)throw console.log(error),new Error(error)})}catch(error){throw new Error(`Erro ao enviar e-mail: ${error.message}`)}}}var canPromise,hasRequiredCanPromise,server={};function requireCanPromise(){return hasRequiredCanPromise?canPromise:(hasRequiredCanPromise=1,canPromise=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then})}var hasRequiredUtils$1,qrcode={},utils$1={};function requireUtils$1(){if(hasRequiredUtils$1)return utils$1;let toSJISFunction;hasRequiredUtils$1=1;const CODEWORDS_COUNT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return utils$1.getSymbolSize=function getSymbolSize(version){if(!version)throw new Error('"version" cannot be null or undefined');if(version<1||version>40)throw new Error('"version" should be in range from 1 to 40');return 4*version+17},utils$1.getSymbolTotalCodewords=function getSymbolTotalCodewords(version){return CODEWORDS_COUNT[version]},utils$1.getBCHDigit=function(data){let digit=0;for(;0!==data;)digit++,data>>>=1;return digit},utils$1.setToSJISFunction=function setToSJISFunction(f){if("function"!=typeof f)throw new Error('"toSJISFunc" is not a valid function.');toSJISFunction=f},utils$1.isKanjiModeEnabled=function(){return void 0!==toSJISFunction},utils$1.toSJIS=function toSJIS(kanji){return toSJISFunction(kanji)},utils$1}var hasRequiredErrorCorrectionLevel,bitBuffer,hasRequiredBitBuffer,bitMatrix,hasRequiredBitMatrix,errorCorrectionLevel={};function requireErrorCorrectionLevel(){return hasRequiredErrorCorrectionLevel||(hasRequiredErrorCorrectionLevel=1,function(exports){exports.L={bit:1},exports.M={bit:0},exports.Q={bit:3},exports.H={bit:2},exports.isValid=function isValid(level){return level&&void 0!==level.bit&&level.bit>=0&&level.bit<4},exports.from=function from(value,defaultValue){if(exports.isValid(value))return value;try{return function fromString(string){if("string"!=typeof string)throw new Error("Param is not a string");switch(string.toLowerCase()){case"l":case"low":return exports.L;case"m":case"medium":return exports.M;case"q":case"quartile":return exports.Q;case"h":case"high":return exports.H;default:throw new Error("Unknown EC Level: "+string)}}(value)}catch(e){return defaultValue}}}(errorCorrectionLevel)),errorCorrectionLevel}var hasRequiredAlignmentPattern,alignmentPattern={};var hasRequiredFinderPattern,finderPattern={};var hasRequiredMaskPattern,maskPattern={};var hasRequiredErrorCorrectionCode,errorCorrectionCode={};function requireErrorCorrectionCode(){if(hasRequiredErrorCorrectionCode)return errorCorrectionCode;hasRequiredErrorCorrectionCode=1;const ECLevel=requireErrorCorrectionLevel(),EC_BLOCKS_TABLE=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],EC_CODEWORDS_TABLE=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return errorCorrectionCode.getBlocksCount=function getBlocksCount(version,errorCorrectionLevel){switch(errorCorrectionLevel){case ECLevel.L:return EC_BLOCKS_TABLE[4*(version-1)+0];case ECLevel.M:return EC_BLOCKS_TABLE[4*(version-1)+1];case ECLevel.Q:return EC_BLOCKS_TABLE[4*(version-1)+2];case ECLevel.H:return EC_BLOCKS_TABLE[4*(version-1)+3];default:return}},errorCorrectionCode.getTotalCodewordsCount=function getTotalCodewordsCount(version,errorCorrectionLevel){switch(errorCorrectionLevel){case ECLevel.L:return EC_CODEWORDS_TABLE[4*(version-1)+0];case ECLevel.M:return EC_CODEWORDS_TABLE[4*(version-1)+1];case ECLevel.Q:return EC_CODEWORDS_TABLE[4*(version-1)+2];case ECLevel.H:return EC_CODEWORDS_TABLE[4*(version-1)+3];default:return}},errorCorrectionCode}var hasRequiredGaloisField,hasRequiredPolynomial,reedSolomonEncoder,hasRequiredReedSolomonEncoder,polynomial={},galoisField={};function requirePolynomial(){return hasRequiredPolynomial||(hasRequiredPolynomial=1,function(exports){const GF=function requireGaloisField(){if(hasRequiredGaloisField)return galoisField;hasRequiredGaloisField=1;const EXP_TABLE=new Uint8Array(512),LOG_TABLE=new Uint8Array(256);return function initTables(){let x=1;for(let i=0;i<255;i++)EXP_TABLE[i]=x,LOG_TABLE[x]=i,x<<=1,256&x&&(x^=285);for(let i=255;i<512;i++)EXP_TABLE[i]=EXP_TABLE[i-255]}(),galoisField.log=function log(n){if(n<1)throw new Error("log("+n+")");return LOG_TABLE[n]},galoisField.exp=function exp(n){return EXP_TABLE[n]},galoisField.mul=function mul(x,y){return 0===x||0===y?0:EXP_TABLE[LOG_TABLE[x]+LOG_TABLE[y]]},galoisField}();exports.mul=function mul(p1,p2){const coeff=new Uint8Array(p1.length+p2.length-1);for(let i=0;i<p1.length;i++)for(let j=0;j<p2.length;j++)coeff[i+j]^=GF.mul(p1[i],p2[j]);return coeff},exports.mod=function mod(divident,divisor){let result=new Uint8Array(divident);for(;result.length-divisor.length>=0;){const coeff=result[0];for(let i=0;i<divisor.length;i++)result[i]^=GF.mul(divisor[i],coeff);let offset=0;for(;offset<result.length&&0===result[offset];)offset++;result=result.slice(offset)}return result},exports.generateECPolynomial=function generateECPolynomial(degree){let poly=new Uint8Array([1]);for(let i=0;i<degree;i++)poly=exports.mul(poly,new Uint8Array([1,GF.exp(i)]));return poly}}(polynomial)),polynomial}var hasRequiredVersionCheck,version={},mode={},versionCheck={};function requireVersionCheck(){return hasRequiredVersionCheck||(hasRequiredVersionCheck=1,versionCheck.isValid=function isValid(version){return!isNaN(version)&&version>=1&&version<=40}),versionCheck}var hasRequiredRegex,hasRequiredMode,hasRequiredVersion,regex={};function requireRegex(){if(hasRequiredRegex)return regex;hasRequiredRegex=1;let kanji="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";kanji=kanji.replace(/u/g,"\\u");const byte="(?:(?![A-Z0-9 $%*+\\-./:]|"+kanji+")(?:.|[\r\n]))+";regex.KANJI=new RegExp(kanji,"g"),regex.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),regex.BYTE=new RegExp(byte,"g"),regex.NUMERIC=new RegExp("[0-9]+","g"),regex.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");const TEST_KANJI=new RegExp("^"+kanji+"$"),TEST_NUMERIC=new RegExp("^[0-9]+$"),TEST_ALPHANUMERIC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return regex.testKanji=function testKanji(str){return TEST_KANJI.test(str)},regex.testNumeric=function testNumeric(str){return TEST_NUMERIC.test(str)},regex.testAlphanumeric=function testAlphanumeric(str){return TEST_ALPHANUMERIC.test(str)},regex}function requireMode(){return hasRequiredMode||(hasRequiredMode=1,function(exports){const VersionCheck=requireVersionCheck(),Regex=requireRegex();exports.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},exports.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},exports.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},exports.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},exports.MIXED={bit:-1},exports.getCharCountIndicator=function getCharCountIndicator(mode,version){if(!mode.ccBits)throw new Error("Invalid mode: "+mode);if(!VersionCheck.isValid(version))throw new Error("Invalid version: "+version);return version>=1&&version<10?mode.ccBits[0]:version<27?mode.ccBits[1]:mode.ccBits[2]},exports.getBestModeForData=function getBestModeForData(dataStr){return Regex.testNumeric(dataStr)?exports.NUMERIC:Regex.testAlphanumeric(dataStr)?exports.ALPHANUMERIC:Regex.testKanji(dataStr)?exports.KANJI:exports.BYTE},exports.toString=function toString(mode){if(mode&&mode.id)return mode.id;throw new Error("Invalid mode")},exports.isValid=function isValid(mode){return mode&&mode.bit&&mode.ccBits},exports.from=function from(value,defaultValue){if(exports.isValid(value))return value;try{return function fromString(string){if("string"!=typeof string)throw new Error("Param is not a string");switch(string.toLowerCase()){case"numeric":return exports.NUMERIC;case"alphanumeric":return exports.ALPHANUMERIC;case"kanji":return exports.KANJI;case"byte":return exports.BYTE;default:throw new Error("Unknown mode: "+string)}}(value)}catch(e){return defaultValue}}}(mode)),mode}function requireVersion(){return hasRequiredVersion||(hasRequiredVersion=1,function(exports){const Utils=requireUtils$1(),ECCode=requireErrorCorrectionCode(),ECLevel=requireErrorCorrectionLevel(),Mode=requireMode(),VersionCheck=requireVersionCheck(),G18_BCH=Utils.getBCHDigit(7973);function getReservedBitsCount(mode,version){return Mode.getCharCountIndicator(mode,version)+4}function getTotalBitsFromDataArray(segments,version){let totalBits=0;return segments.forEach(function(data){const reservedBits=getReservedBitsCount(data.mode,version);totalBits+=reservedBits+data.getBitsLength()}),totalBits}exports.from=function from(value,defaultValue){return VersionCheck.isValid(value)?parseInt(value,10):defaultValue},exports.getCapacity=function getCapacity(version,errorCorrectionLevel,mode){if(!VersionCheck.isValid(version))throw new Error("Invalid QR Code version");void 0===mode&&(mode=Mode.BYTE);const dataTotalCodewordsBits=8*(Utils.getSymbolTotalCodewords(version)-ECCode.getTotalCodewordsCount(version,errorCorrectionLevel));if(mode===Mode.MIXED)return dataTotalCodewordsBits;const usableBits=dataTotalCodewordsBits-getReservedBitsCount(mode,version);switch(mode){case Mode.NUMERIC:return Math.floor(usableBits/10*3);case Mode.ALPHANUMERIC:return Math.floor(usableBits/11*2);case Mode.KANJI:return Math.floor(usableBits/13);case Mode.BYTE:default:return Math.floor(usableBits/8)}},exports.getBestVersionForData=function getBestVersionForData(data,errorCorrectionLevel){let seg;const ecl=ECLevel.from(errorCorrectionLevel,ECLevel.M);if(Array.isArray(data)){if(data.length>1)return function getBestVersionForMixedData(segments,errorCorrectionLevel){for(let currentVersion=1;currentVersion<=40;currentVersion++)if(getTotalBitsFromDataArray(segments,currentVersion)<=exports.getCapacity(currentVersion,errorCorrectionLevel,Mode.MIXED))return currentVersion}(data,ecl);if(0===data.length)return 1;seg=data[0]}else seg=data;return function getBestVersionForDataLength(mode,length,errorCorrectionLevel){for(let currentVersion=1;currentVersion<=40;currentVersion++)if(length<=exports.getCapacity(currentVersion,errorCorrectionLevel,mode))return currentVersion}(seg.mode,seg.getLength(),ecl)},exports.getEncodedBits=function getEncodedBits(version){if(!VersionCheck.isValid(version)||version<7)throw new Error("Invalid QR Code version");let d=version<<12;for(;Utils.getBCHDigit(d)-G18_BCH>=0;)d^=7973<<Utils.getBCHDigit(d)-G18_BCH;return version<<12|d}}(version)),version}var hasRequiredFormatInfo,formatInfo={};var numericData,hasRequiredNumericData,alphanumericData,hasRequiredAlphanumericData,byteData,hasRequiredByteData,kanjiData,hasRequiredKanjiData,segments={};var hasRequiredDijkstra,hasRequiredSegments,hasRequiredQrcode,dijkstra={exports:{}};function requireDijkstra(){return hasRequiredDijkstra||(hasRequiredDijkstra=1,function(module){var dijkstra={single_source_shortest_paths:function(graph,s,d){var predecessors={},costs={};costs[s]=0;var closest,u,v,cost_of_s_to_u,adjacent_nodes,cost_of_s_to_u_plus_cost_of_e,cost_of_s_to_v,open=dijkstra.PriorityQueue.make();for(open.push(s,0);!open.empty();)for(v in u=(closest=open.pop()).value,cost_of_s_to_u=closest.cost,adjacent_nodes=graph[u]||{})adjacent_nodes.hasOwnProperty(v)&&(cost_of_s_to_u_plus_cost_of_e=cost_of_s_to_u+adjacent_nodes[v],cost_of_s_to_v=costs[v],(void 0===costs[v]||cost_of_s_to_v>cost_of_s_to_u_plus_cost_of_e)&&(costs[v]=cost_of_s_to_u_plus_cost_of_e,open.push(v,cost_of_s_to_u_plus_cost_of_e),predecessors[v]=u));if(void 0!==d&&void 0===costs[d]){var msg=["Could not find a path from ",s," to ",d,"."].join("");throw new Error(msg)}return predecessors},extract_shortest_path_from_predecessor_list:function(predecessors,d){for(var nodes=[],u=d;u;)nodes.push(u),predecessors[u],u=predecessors[u];return nodes.reverse(),nodes},find_path:function(graph,s,d){var predecessors=dijkstra.single_source_shortest_paths(graph,s,d);return dijkstra.extract_shortest_path_from_predecessor_list(predecessors,d)},PriorityQueue:{make:function(opts){var key,T=dijkstra.PriorityQueue,t={};for(key in opts=opts||{},T)T.hasOwnProperty(key)&&(t[key]=T[key]);return t.queue=[],t.sorter=opts.sorter||T.default_sorter,t},default_sorter:function(a,b){return a.cost-b.cost},push:function(value,cost){var item={value:value,cost:cost};this.queue.push(item),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};module.exports=dijkstra}(dijkstra)),dijkstra.exports}function requireSegments(){return hasRequiredSegments||(hasRequiredSegments=1,function(exports){const Mode=requireMode(),NumericData=function requireNumericData(){if(hasRequiredNumericData)return numericData;hasRequiredNumericData=1;const Mode=requireMode();function NumericData(data){this.mode=Mode.NUMERIC,this.data=data.toString()}return NumericData.getBitsLength=function getBitsLength(length){return 10*Math.floor(length/3)+(length%3?length%3*3+1:0)},NumericData.prototype.getLength=function getLength(){return this.data.length},NumericData.prototype.getBitsLength=function getBitsLength(){return NumericData.getBitsLength(this.data.length)},NumericData.prototype.write=function write(bitBuffer){let i,group,value;for(i=0;i+3<=this.data.length;i+=3)group=this.data.substr(i,3),value=parseInt(group,10),bitBuffer.put(value,10);const remainingNum=this.data.length-i;remainingNum>0&&(group=this.data.substr(i),value=parseInt(group,10),bitBuffer.put(value,3*remainingNum+1))},numericData=NumericData}(),AlphanumericData=function requireAlphanumericData(){if(hasRequiredAlphanumericData)return alphanumericData;hasRequiredAlphanumericData=1;const Mode=requireMode(),ALPHA_NUM_CHARS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function AlphanumericData(data){this.mode=Mode.ALPHANUMERIC,this.data=data}return AlphanumericData.getBitsLength=function getBitsLength(length){return 11*Math.floor(length/2)+length%2*6},AlphanumericData.prototype.getLength=function getLength(){return this.data.length},AlphanumericData.prototype.getBitsLength=function getBitsLength(){return AlphanumericData.getBitsLength(this.data.length)},AlphanumericData.prototype.write=function write(bitBuffer){let i;for(i=0;i+2<=this.data.length;i+=2){let value=45*ALPHA_NUM_CHARS.indexOf(this.data[i]);value+=ALPHA_NUM_CHARS.indexOf(this.data[i+1]),bitBuffer.put(value,11)}this.data.length%2&&bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]),6)},alphanumericData=AlphanumericData}(),ByteData=function requireByteData(){if(hasRequiredByteData)return byteData;hasRequiredByteData=1;const Mode=requireMode();function ByteData(data){this.mode=Mode.BYTE,this.data="string"==typeof data?(new TextEncoder).encode(data):new Uint8Array(data)}return ByteData.getBitsLength=function getBitsLength(length){return 8*length},ByteData.prototype.getLength=function getLength(){return this.data.length},ByteData.prototype.getBitsLength=function getBitsLength(){return ByteData.getBitsLength(this.data.length)},ByteData.prototype.write=function(bitBuffer){for(let i=0,l=this.data.length;i<l;i++)bitBuffer.put(this.data[i],8)},byteData=ByteData}(),KanjiData=function requireKanjiData(){if(hasRequiredKanjiData)return kanjiData;hasRequiredKanjiData=1;const Mode=requireMode(),Utils=requireUtils$1();function KanjiData(data){this.mode=Mode.KANJI,this.data=data}return KanjiData.getBitsLength=function getBitsLength(length){return 13*length},KanjiData.prototype.getLength=function getLength(){return this.data.length},KanjiData.prototype.getBitsLength=function getBitsLength(){return KanjiData.getBitsLength(this.data.length)},KanjiData.prototype.write=function(bitBuffer){let i;for(i=0;i<this.data.length;i++){let value=Utils.toSJIS(this.data[i]);if(value>=33088&&value<=40956)value-=33088;else{if(!(value>=57408&&value<=60351))throw new Error("Invalid SJIS character: "+this.data[i]+"\nMake sure your charset is UTF-8");value-=49472}value=192*(value>>>8&255)+(255&value),bitBuffer.put(value,13)}},kanjiData=KanjiData}(),Regex=requireRegex(),Utils=requireUtils$1(),dijkstra=requireDijkstra();function getStringByteLength(str){return unescape(encodeURIComponent(str)).length}function getSegments(regex,mode,str){const segments=[];let result;for(;null!==(result=regex.exec(str));)segments.push({data:result[0],index:result.index,mode:mode,length:result[0].length});return segments}function getSegmentsFromString(dataStr){const numSegs=getSegments(Regex.NUMERIC,Mode.NUMERIC,dataStr),alphaNumSegs=getSegments(Regex.ALPHANUMERIC,Mode.ALPHANUMERIC,dataStr);let byteSegs,kanjiSegs;Utils.isKanjiModeEnabled()?(byteSegs=getSegments(Regex.BYTE,Mode.BYTE,dataStr),kanjiSegs=getSegments(Regex.KANJI,Mode.KANJI,dataStr)):(byteSegs=getSegments(Regex.BYTE_KANJI,Mode.BYTE,dataStr),kanjiSegs=[]);return numSegs.concat(alphaNumSegs,byteSegs,kanjiSegs).sort(function(s1,s2){return s1.index-s2.index}).map(function(obj){return{data:obj.data,mode:obj.mode,length:obj.length}})}function getSegmentBitsLength(length,mode){switch(mode){case Mode.NUMERIC:return NumericData.getBitsLength(length);case Mode.ALPHANUMERIC:return AlphanumericData.getBitsLength(length);case Mode.KANJI:return KanjiData.getBitsLength(length);case Mode.BYTE:return ByteData.getBitsLength(length)}}function buildSingleSegment(data,modesHint){let mode;const bestMode=Mode.getBestModeForData(data);if(mode=Mode.from(modesHint,bestMode),mode!==Mode.BYTE&&mode.bit<bestMode.bit)throw new Error('"'+data+'" cannot be encoded with mode '+Mode.toString(mode)+".\n Suggested mode is: "+Mode.toString(bestMode));switch(mode!==Mode.KANJI||Utils.isKanjiModeEnabled()||(mode=Mode.BYTE),mode){case Mode.NUMERIC:return new NumericData(data);case Mode.ALPHANUMERIC:return new AlphanumericData(data);case Mode.KANJI:return new KanjiData(data);case Mode.BYTE:return new ByteData(data)}}exports.fromArray=function fromArray(array){return array.reduce(function(acc,seg){return"string"==typeof seg?acc.push(buildSingleSegment(seg,null)):seg.data&&acc.push(buildSingleSegment(seg.data,seg.mode)),acc},[])},exports.fromString=function fromString(data,version){const nodes=function buildNodes(segs){const nodes=[];for(let i=0;i<segs.length;i++){const seg=segs[i];switch(seg.mode){case Mode.NUMERIC:nodes.push([seg,{data:seg.data,mode:Mode.ALPHANUMERIC,length:seg.length},{data:seg.data,mode:Mode.BYTE,length:seg.length}]);break;case Mode.ALPHANUMERIC:nodes.push([seg,{data:seg.data,mode:Mode.BYTE,length:seg.length}]);break;case Mode.KANJI:nodes.push([seg,{data:seg.data,mode:Mode.BYTE,length:getStringByteLength(seg.data)}]);break;case Mode.BYTE:nodes.push([{data:seg.data,mode:Mode.BYTE,length:getStringByteLength(seg.data)}])}}return nodes}(getSegmentsFromString(data,Utils.isKanjiModeEnabled())),graph=function buildGraph(nodes,version){const table={},graph={start:{}};let prevNodeIds=["start"];for(let i=0;i<nodes.length;i++){const nodeGroup=nodes[i],currentNodeIds=[];for(let j=0;j<nodeGroup.length;j++){const node=nodeGroup[j],key=""+i+j;currentNodeIds.push(key),table[key]={node:node,lastCount:0},graph[key]={};for(let n=0;n<prevNodeIds.length;n++){const prevNodeId=prevNodeIds[n];table[prevNodeId]&&table[prevNodeId].node.mode===node.mode?(graph[prevNodeId][key]=getSegmentBitsLength(table[prevNodeId].lastCount+node.length,node.mode)-getSegmentBitsLength(table[prevNodeId].lastCount,node.mode),table[prevNodeId].lastCount+=node.length):(table[prevNodeId]&&(table[prevNodeId].lastCount=node.length),graph[prevNodeId][key]=getSegmentBitsLength(node.length,node.mode)+4+Mode.getCharCountIndicator(node.mode,version))}}prevNodeIds=currentNodeIds}for(let n=0;n<prevNodeIds.length;n++)graph[prevNodeIds[n]].end=0;return{map:graph,table:table}}(nodes,version),path=dijkstra.find_path(graph.map,"start","end"),optimizedSegs=[];for(let i=1;i<path.length-1;i++)optimizedSegs.push(graph.table[path[i]].node);return exports.fromArray(function mergeSegments(segs){return segs.reduce(function(acc,curr){const prevSeg=acc.length-1>=0?acc[acc.length-1]:null;return prevSeg&&prevSeg.mode===curr.mode?(acc[acc.length-1].data+=curr.data,acc):(acc.push(curr),acc)},[])}(optimizedSegs))},exports.rawSplit=function rawSplit(data){return exports.fromArray(getSegmentsFromString(data,Utils.isKanjiModeEnabled()))}}(segments)),segments}function requireQrcode(){if(hasRequiredQrcode)return qrcode;hasRequiredQrcode=1;const Utils=requireUtils$1(),ECLevel=requireErrorCorrectionLevel(),BitBuffer=function requireBitBuffer(){if(hasRequiredBitBuffer)return bitBuffer;function BitBuffer(){this.buffer=[],this.length=0}return hasRequiredBitBuffer=1,BitBuffer.prototype={get:function(index){const bufIndex=Math.floor(index/8);return 1==(this.buffer[bufIndex]>>>7-index%8&1)},put:function(num,length){for(let i=0;i<length;i++)this.putBit(1==(num>>>length-i-1&1))},getLengthInBits:function(){return this.length},putBit:function(bit){const bufIndex=Math.floor(this.length/8);this.buffer.length<=bufIndex&&this.buffer.push(0),bit&&(this.buffer[bufIndex]|=128>>>this.length%8),this.length++}},bitBuffer=BitBuffer}(),BitMatrix=function requireBitMatrix(){if(hasRequiredBitMatrix)return bitMatrix;function BitMatrix(size){if(!size||size<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=size,this.data=new Uint8Array(size*size),this.reservedBit=new Uint8Array(size*size)}return hasRequiredBitMatrix=1,BitMatrix.prototype.set=function(row,col,value,reserved){const index=row*this.size+col;this.data[index]=value,reserved&&(this.reservedBit[index]=!0)},BitMatrix.prototype.get=function(row,col){return this.data[row*this.size+col]},BitMatrix.prototype.xor=function(row,col,value){this.data[row*this.size+col]^=value},BitMatrix.prototype.isReserved=function(row,col){return this.reservedBit[row*this.size+col]},bitMatrix=BitMatrix}(),AlignmentPattern=function requireAlignmentPattern(){return hasRequiredAlignmentPattern||(hasRequiredAlignmentPattern=1,function(exports){const getSymbolSize=requireUtils$1().getSymbolSize;exports.getRowColCoords=function getRowColCoords(version){if(1===version)return[];const posCount=Math.floor(version/7)+2,size=getSymbolSize(version),intervals=145===size?26:2*Math.ceil((size-13)/(2*posCount-2)),positions=[size-7];for(let i=1;i<posCount-1;i++)positions[i]=positions[i-1]-intervals;return positions.push(6),positions.reverse()},exports.getPositions=function getPositions(version){const coords=[],pos=exports.getRowColCoords(version),posLength=pos.length;for(let i=0;i<posLength;i++)for(let j=0;j<posLength;j++)0===i&&0===j||0===i&&j===posLength-1||i===posLength-1&&0===j||coords.push([pos[i],pos[j]]);return coords}}(alignmentPattern)),alignmentPattern}(),FinderPattern=function requireFinderPattern(){if(hasRequiredFinderPattern)return finderPattern;hasRequiredFinderPattern=1;const getSymbolSize=requireUtils$1().getSymbolSize;return finderPattern.getPositions=function getPositions(version){const size=getSymbolSize(version);return[[0,0],[size-7,0],[0,size-7]]},finderPattern}(),MaskPattern=function requireMaskPattern(){return hasRequiredMaskPattern||(hasRequiredMaskPattern=1,function(exports){exports.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const PenaltyScores_N1=3,PenaltyScores_N2=3,PenaltyScores_N3=40,PenaltyScores_N4=10;function getMaskAt(maskPattern,i,j){switch(maskPattern){case exports.Patterns.PATTERN000:return(i+j)%2==0;case exports.Patterns.PATTERN001:return i%2==0;case exports.Patterns.PATTERN010:return j%3==0;case exports.Patterns.PATTERN011:return(i+j)%3==0;case exports.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(j/3))%2==0;case exports.Patterns.PATTERN101:return i*j%2+i*j%3==0;case exports.Patterns.PATTERN110:return(i*j%2+i*j%3)%2==0;case exports.Patterns.PATTERN111:return(i*j%3+(i+j)%2)%2==0;default:throw new Error("bad maskPattern:"+maskPattern)}}exports.isValid=function isValid(mask){return null!=mask&&""!==mask&&!isNaN(mask)&&mask>=0&&mask<=7},exports.from=function from(value){return exports.isValid(value)?parseInt(value,10):void 0},exports.getPenaltyN1=function getPenaltyN1(data){const size=data.size;let points=0,sameCountCol=0,sameCountRow=0,lastCol=null,lastRow=null;for(let row=0;row<size;row++){sameCountCol=sameCountRow=0,lastCol=lastRow=null;for(let col=0;col<size;col++){let module=data.get(row,col);module===lastCol?sameCountCol++:(sameCountCol>=5&&(points+=PenaltyScores_N1+(sameCountCol-5)),lastCol=module,sameCountCol=1),module=data.get(col,row),module===lastRow?sameCountRow++:(sameCountRow>=5&&(points+=PenaltyScores_N1+(sameCountRow-5)),lastRow=module,sameCountRow=1)}sameCountCol>=5&&(points+=PenaltyScores_N1+(sameCountCol-5)),sameCountRow>=5&&(points+=PenaltyScores_N1+(sameCountRow-5))}return points},exports.getPenaltyN2=function getPenaltyN2(data){const size=data.size;let points=0;for(let row=0;row<size-1;row++)for(let col=0;col<size-1;col++){const last=data.get(row,col)+data.get(row,col+1)+data.get(row+1,col)+data.get(row+1,col+1);4!==last&&0!==last||points++}return points*PenaltyScores_N2},exports.getPenaltyN3=function getPenaltyN3(data){const size=data.size;let points=0,bitsCol=0,bitsRow=0;for(let row=0;row<size;row++){bitsCol=bitsRow=0;for(let col=0;col<size;col++)bitsCol=bitsCol<<1&2047|data.get(row,col),col>=10&&(1488===bitsCol||93===bitsCol)&&points++,bitsRow=bitsRow<<1&2047|data.get(col,row),col>=10&&(1488===bitsRow||93===bitsRow)&&points++}return points*PenaltyScores_N3},exports.getPenaltyN4=function getPenaltyN4(data){let darkCount=0;const modulesCount=data.data.length;for(let i=0;i<modulesCount;i++)darkCount+=data.data[i];return Math.abs(Math.ceil(100*darkCount/modulesCount/5)-10)*PenaltyScores_N4},exports.applyMask=function applyMask(pattern,data){const size=data.size;for(let col=0;col<size;col++)for(let row=0;row<size;row++)data.isReserved(row,col)||data.xor(row,col,getMaskAt(pattern,row,col))},exports.getBestMask=function getBestMask(data,setupFormatFunc){const numPatterns=Object.keys(exports.Patterns).length;let bestPattern=0,lowerPenalty=1/0;for(let p=0;p<numPatterns;p++){setupFormatFunc(p),exports.applyMask(p,data);const penalty=exports.getPenaltyN1(data)+exports.getPenaltyN2(data)+exports.getPenaltyN3(data)+exports.getPenaltyN4(data);exports.applyMask(p,data),penalty<lowerPenalty&&(lowerPenalty=penalty,bestPattern=p)}return bestPattern}}(maskPattern)),maskPattern}(),ECCode=requireErrorCorrectionCode(),ReedSolomonEncoder=function requireReedSolomonEncoder(){if(hasRequiredReedSolomonEncoder)return reedSolomonEncoder;hasRequiredReedSolomonEncoder=1;const Polynomial=requirePolynomial();function ReedSolomonEncoder(degree){this.genPoly=void 0,this.degree=degree,this.degree&&this.initialize(this.degree)}return ReedSolomonEncoder.prototype.initialize=function initialize(degree){this.degree=degree,this.genPoly=Polynomial.generateECPolynomial(this.degree)},ReedSolomonEncoder.prototype.encode=function encode(data){if(!this.genPoly)throw new Error("Encoder not initialized");const paddedData=new Uint8Array(data.length+this.degree);paddedData.set(data);const remainder=Polynomial.mod(paddedData,this.genPoly),start=this.degree-remainder.length;if(start>0){const buff=new Uint8Array(this.degree);return buff.set(remainder,start),buff}return remainder},reedSolomonEncoder=ReedSolomonEncoder}(),Version=requireVersion(),FormatInfo=function requireFormatInfo(){if(hasRequiredFormatInfo)return formatInfo;hasRequiredFormatInfo=1;const Utils=requireUtils$1(),G15_BCH=Utils.getBCHDigit(1335);return formatInfo.getEncodedBits=function getEncodedBits(errorCorrectionLevel,mask){const data=errorCorrectionLevel.bit<<3|mask;let d=data<<10;for(;Utils.getBCHDigit(d)-G15_BCH>=0;)d^=1335<<Utils.getBCHDigit(d)-G15_BCH;return 21522^(data<<10|d)},formatInfo}(),Mode=requireMode(),Segments=requireSegments();function setupFormatInfo(matrix,errorCorrectionLevel,maskPattern){const size=matrix.size,bits=FormatInfo.getEncodedBits(errorCorrectionLevel,maskPattern);let i,mod;for(i=0;i<15;i++)mod=1==(bits>>i&1),i<6?matrix.set(i,8,mod,!0):i<8?matrix.set(i+1,8,mod,!0):matrix.set(size-15+i,8,mod,!0),i<8?matrix.set(8,size-i-1,mod,!0):i<9?matrix.set(8,15-i-1+1,mod,!0):matrix.set(8,15-i-1,mod,!0);matrix.set(size-8,8,1,!0)}function createData(version,errorCorrectionLevel,segments){const buffer=new BitBuffer;segments.forEach(function(data){buffer.put(data.mode.bit,4),buffer.put(data.getLength(),Mode.getCharCountIndicator(data.mode,version)),data.write(buffer)});const dataTotalCodewordsBits=8*(Utils.getSymbolTotalCodewords(version)-ECCode.getTotalCodewordsCount(version,errorCorrectionLevel));for(buffer.getLengthInBits()+4<=dataTotalCodewordsBits&&buffer.put(0,4);buffer.getLengthInBits()%8!=0;)buffer.putBit(0);const remainingByte=(dataTotalCodewordsBits-buffer.getLengthInBits())/8;for(let i=0;i<remainingByte;i++)buffer.put(i%2?17:236,8);return function createCodewords(bitBuffer,version,errorCorrectionLevel){const totalCodewords=Utils.getSymbolTotalCodewords(version),ecTotalCodewords=ECCode.getTotalCodewordsCount(version,errorCorrectionLevel),dataTotalCodewords=totalCodewords-ecTotalCodewords,ecTotalBlocks=ECCode.getBlocksCount(version,errorCorrectionLevel),blocksInGroup2=totalCodewords%ecTotalBlocks,blocksInGroup1=ecTotalBlocks-blocksInGroup2,totalCodewordsInGroup1=Math.floor(totalCodewords/ecTotalBlocks),dataCodewordsInGroup1=Math.floor(dataTotalCodewords/ecTotalBlocks),dataCodewordsInGroup2=dataCodewordsInGroup1+1,ecCount=totalCodewordsInGroup1-dataCodewordsInGroup1,rs=new ReedSolomonEncoder(ecCount);let offset=0;const dcData=new Array(ecTotalBlocks),ecData=new Array(ecTotalBlocks);let maxDataSize=0;const buffer=new Uint8Array(bitBuffer.buffer);for(let b=0;b<ecTotalBlocks;b++){const dataSize=b<blocksInGroup1?dataCodewordsInGroup1:dataCodewordsInGroup2;dcData[b]=buffer.slice(offset,offset+dataSize),ecData[b]=rs.encode(dcData[b]),offset+=dataSize,maxDataSize=Math.max(maxDataSize,dataSize)}const data=new Uint8Array(totalCodewords);let i,r,index=0;for(i=0;i<maxDataSize;i++)for(r=0;r<ecTotalBlocks;r++)i<dcData[r].length&&(data[index++]=dcData[r][i]);for(i=0;i<ecCount;i++)for(r=0;r<ecTotalBlocks;r++)data[index++]=ecData[r][i];return data}(buffer,version,errorCorrectionLevel)}function createSymbol(data,version,errorCorrectionLevel,maskPattern){let segments;if(Array.isArray(data))segments=Segments.fromArray(data);else{if("string"!=typeof data)throw new Error("Invalid data");{let estimatedVersion=version;if(!estimatedVersion){const rawSegments=Segments.rawSplit(data);estimatedVersion=Version.getBestVersionForData(rawSegments,errorCorrectionLevel)}segments=Segments.fromString(data,estimatedVersion||40)}}const bestVersion=Version.getBestVersionForData(segments,errorCorrectionLevel);if(!bestVersion)throw new Error("The amount of data is too big to be stored in a QR Code");if(version){if(version<bestVersion)throw new Error("\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: "+bestVersion+".\n")}else version=bestVersion;const dataBits=createData(version,errorCorrectionLevel,segments),moduleCount=Utils.getSymbolSize(version),modules=new BitMatrix(moduleCount);return function setupFinderPattern(matrix,version){const size=matrix.size,pos=FinderPattern.getPositions(version);for(let i=0;i<pos.length;i++){const row=pos[i][0],col=pos[i][1];for(let r=-1;r<=7;r++)if(!(row+r<=-1||size<=row+r))for(let c=-1;c<=7;c++)col+c<=-1||size<=col+c||(r>=0&&r<=6&&(0===c||6===c)||c>=0&&c<=6&&(0===r||6===r)||r>=2&&r<=4&&c>=2&&c<=4?matrix.set(row+r,col+c,!0,!0):matrix.set(row+r,col+c,!1,!0))}}(modules,version),function setupTimingPattern(matrix){const size=matrix.size;for(let r=8;r<size-8;r++){const value=r%2==0;matrix.set(r,6,value,!0),matrix.set(6,r,value,!0)}}(modules),function setupAlignmentPattern(matrix,version){const pos=AlignmentPattern.getPositions(version);for(let i=0;i<pos.length;i++){const row=pos[i][0],col=pos[i][1];for(let r=-2;r<=2;r++)for(let c=-2;c<=2;c++)-2===r||2===r||-2===c||2===c||0===r&&0===c?matrix.set(row+r,col+c,!0,!0):matrix.set(row+r,col+c,!1,!0)}}(modules,version),setupFormatInfo(modules,errorCorrectionLevel,0),version>=7&&function setupVersionInfo(matrix,version){const size=matrix.size,bits=Version.getEncodedBits(version);let row,col,mod;for(let i=0;i<18;i++)row=Math.floor(i/3),col=i%3+size-8-3,mod=1==(bits>>i&1),matrix.set(row,col,mod,!0),matrix.set(col,row,mod,!0)}(modules,version),function setupData(matrix,data){const size=matrix.size;let inc=-1,row=size-1,bitIndex=7,byteIndex=0;for(let col=size-1;col>0;col-=2)for(6===col&&col--;;){for(let c=0;c<2;c++)if(!matrix.isReserved(row,col-c)){let dark=!1;byteIndex<data.length&&(dark=1==(data[byteIndex]>>>bitIndex&1)),matrix.set(row,col-c,dark),bitIndex--,-1===bitIndex&&(byteIndex++,bitIndex=7)}if(row+=inc,row<0||size<=row){row-=inc,inc=-inc;break}}}(modules,dataBits),isNaN(maskPattern)&&(maskPattern=MaskPattern.getBestMask(modules,setupFormatInfo.bind(null,modules,errorCorrectionLevel))),MaskPattern.applyMask(maskPattern,modules),setupFormatInfo(modules,errorCorrectionLevel,maskPattern),{modules:modules,version:version,errorCorrectionLevel:errorCorrectionLevel,maskPattern:maskPattern,segments:segments}}return qrcode.create=function create(data,options){if(void 0===data||""===data)throw new Error("No input text");let version,mask,errorCorrectionLevel=ECLevel.M;return void 0!==options&&(errorCorrectionLevel=ECLevel.from(options.errorCorrectionLevel,ECLevel.M),version=Version.from(options.version),mask=MaskPattern.from(options.maskPattern),options.toSJISFunc&&Utils.setToSJISFunction(options.toSJISFunc)),createSymbol(data,version,errorCorrectionLevel,mask)},qrcode}var hasRequiredChunkstream,png$1={},png={},parserAsync={exports:{}},chunkstream={exports:{}};function requireChunkstream(){if(hasRequiredChunkstream)return chunkstream.exports;hasRequiredChunkstream=1;let util=require$$0__default$2.default,Stream=require$$0__default$4.default,ChunkStream=chunkstream.exports=function(){Stream.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};return util.inherits(ChunkStream,Stream),ChunkStream.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))},ChunkStream.prototype.write=function(data,encoding){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let dataBuffer;return dataBuffer=Buffer.isBuffer(data)?data:Buffer.from(data,encoding||this._encoding),this._buffers.push(dataBuffer),this._buffered+=dataBuffer.length,this._process(),this._reads&&0===this._reads.length&&(this._paused=!0),this.writable&&!this._paused},ChunkStream.prototype.end=function(data,encoding){data&&this.write(data,encoding),this.writable=!1,this._buffers&&(0===this._buffers.length?this._end():(this._buffers.push(null),this._process()))},ChunkStream.prototype.destroySoon=ChunkStream.prototype.end,ChunkStream.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()},ChunkStream.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))},ChunkStream.prototype._processReadAllowingLess=function(read){this._reads.shift();let smallerBuf=this._buffers[0];smallerBuf.length>read.length?(this._buffered-=read.length,this._buffers[0]=smallerBuf.slice(read.length),read.func.call(this,smallerBuf.slice(0,read.length))):(this._buffered-=smallerBuf.length,this._buffers.shift(),read.func.call(this,smallerBuf))},ChunkStream.prototype._processRead=function(read){this._reads.shift();let pos=0,count=0,data=Buffer.alloc(read.length);for(;pos<read.length;){let buf=this._buffers[count++],len=Math.min(buf.length,read.length-pos);buf.copy(data,pos,0,len),pos+=len,len!==buf.length&&(this._buffers[--count]=buf.slice(len))}count>0&&this._buffers.splice(0,count),this._buffered-=read.length,read.func.call(this,data)},ChunkStream.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let read=this._reads[0];if(read.allowLess)this._processReadAllowingLess(read);else{if(!(this._buffered>=read.length))break;this._processRead(read)}}this._buffers&&!this.writable&&this._end()}catch(ex){this.emit("error",ex)}},chunkstream.exports}var hasRequiredInterlace,paethPredictor,hasRequiredPaethPredictor,hasRequiredFilterParse,hasRequiredFilterParseAsync,filterParseAsync={exports:{}},filterParse={exports:{}},interlace={};function requireInterlace(){if(hasRequiredInterlace)return interlace;hasRequiredInterlace=1;let imagePasses=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];return interlace.getImagePasses=function(width,height){let images=[],xLeftOver=width%8,yLeftOver=height%8,xRepeats=(width-xLeftOver)/8,yRepeats=(height-yLeftOver)/8;for(let i=0;i<imagePasses.length;i++){let pass=imagePasses[i],passWidth=xRepeats*pass.x.length,passHeight=yRepeats*pass.y.length;for(let j=0;j<pass.x.length&&pass.x[j]<xLeftOver;j++)passWidth++;for(let j=0;j<pass.y.length&&pass.y[j]<yLeftOver;j++)passHeight++;passWidth>0&&passHeight>0&&images.push({width:passWidth,height:passHeight,index:i})}return images},interlace.getInterlaceIterator=function(width){return function(x,y,pass){let outerXLeftOver=x%imagePasses[pass].x.length,outerX=(x-outerXLeftOver)/imagePasses[pass].x.length*8+imagePasses[pass].x[outerXLeftOver],outerYLeftOver=y%imagePasses[pass].y.length;return 4*outerX+((y-outerYLeftOver)/imagePasses[pass].y.length*8+imagePasses[pass].y[outerYLeftOver])*width*4}},interlace}function requirePaethPredictor(){return hasRequiredPaethPredictor?paethPredictor:(hasRequiredPaethPredictor=1,paethPredictor=function paethPredictor(left,above,upLeft){let paeth=left+above-upLeft,pLeft=Math.abs(paeth-left),pAbove=Math.abs(paeth-above),pUpLeft=Math.abs(paeth-upLeft);return pLeft<=pAbove&&pLeft<=pUpLeft?left:pAbove<=pUpLeft?above:upLeft})}function requireFilterParse(){if(hasRequiredFilterParse)return filterParse.exports;hasRequiredFilterParse=1;let interlaceUtils=requireInterlace(),paethPredictor=requirePaethPredictor();function getByteWidth(width,bpp,depth){let byteWidth=width*bpp;return 8!==depth&&(byteWidth=Math.ceil(byteWidth/(8/depth))),byteWidth}let Filter=filterParse.exports=function(bitmapInfo,dependencies){let width=bitmapInfo.width,height=bitmapInfo.height,interlace=bitmapInfo.interlace,bpp=bitmapInfo.bpp,depth=bitmapInfo.depth;if(this.read=dependencies.read,this.write=dependencies.write,this.complete=dependencies.complete,this._imageIndex=0,this._images=[],interlace){let passes=interlaceUtils.getImagePasses(width,height);for(let i=0;i<passes.length;i++)this._images.push({byteWidth:getByteWidth(passes[i].width,bpp,depth),height:passes[i].height,lineIndex:0})}else this._images.push({byteWidth:getByteWidth(width,bpp,depth),height:height,lineIndex:0});this._xComparison=8===depth?bpp:16===depth?2*bpp:1};return Filter.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},Filter.prototype._unFilterType1=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f1Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;unfilteredLine[x]=rawByte+f1Left}},Filter.prototype._unFilterType2=function(rawData,unfilteredLine,byteWidth){let lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f2Up=lastLine?lastLine[x]:0;unfilteredLine[x]=rawByte+f2Up}},Filter.prototype._unFilterType3=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f3Up=lastLine?lastLine[x]:0,f3Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f3Add=Math.floor((f3Left+f3Up)/2);unfilteredLine[x]=rawByte+f3Add}},Filter.prototype._unFilterType4=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f4Up=lastLine?lastLine[x]:0,f4Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f4UpLeft=x>xBiggerThan&&lastLine?lastLine[x-xComparison]:0,f4Add=paethPredictor(f4Left,f4Up,f4UpLeft);unfilteredLine[x]=rawByte+f4Add}},Filter.prototype._reverseFilterLine=function(rawData){let unfilteredLine,filter=rawData[0],currentImage=this._images[this._imageIndex],byteWidth=currentImage.byteWidth;if(0===filter)unfilteredLine=rawData.slice(1,byteWidth+1);else switch(unfilteredLine=Buffer.alloc(byteWidth),filter){case 1:this._unFilterType1(rawData,unfilteredLine,byteWidth);break;case 2:this._unFilterType2(rawData,unfilteredLine,byteWidth);break;case 3:this._unFilterType3(rawData,unfilteredLine,byteWidth);break;case 4:this._unFilterType4(rawData,unfilteredLine,byteWidth);break;default:throw new Error("Unrecognised filter type - "+filter)}this.write(unfilteredLine),currentImage.lineIndex++,currentImage.lineIndex>=currentImage.height?(this._lastLine=null,this._imageIndex++,currentImage=this._images[this._imageIndex]):this._lastLine=unfilteredLine,currentImage?this.read(currentImage.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())},filterParse.exports}var constants$3,hasRequiredConstants,parser={exports:{}};function requireConstants(){return hasRequiredConstants?constants$3:(hasRequiredConstants=1,constants$3={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5})}var hasRequiredCrc,hasRequiredParser,crc={exports:{}};function requireCrc(){if(hasRequiredCrc)return crc.exports;hasRequiredCrc=1;let crcTable=[];!function(){for(let i=0;i<256;i++){let currentCrc=i;for(let j=0;j<8;j++)1¤tCrc?currentCrc=3988292384^currentCrc>>>1:currentCrc>>>=1;crcTable[i]=currentCrc}}();let CrcCalculator=crc.exports=function(){this._crc=-1};return CrcCalculator.prototype.write=function(data){for(let i=0;i<data.length;i++)this._crc=crcTable[255&(this._crc^data[i])]^this._crc>>>8;return!0},CrcCalculator.prototype.crc32=function(){return-1^this._crc},CrcCalculator.crc32=function(buf){let crc=-1;for(let i=0;i<buf.length;i++)crc=crcTable[255&(crc^buf[i])]^crc>>>8;return-1^crc},crc.exports}function requireParser(){if(hasRequiredParser)return parser.exports;hasRequiredParser=1;let constants=requireConstants(),CrcCalculator=requireCrc(),Parser=parser.exports=function(options,dependencies){this._options=options,options.checkCRC=!1!==options.checkCRC,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[constants.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[constants.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[constants.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[constants.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[constants.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[constants.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=dependencies.read,this.error=dependencies.error,this.metadata=dependencies.metadata,this.gamma=dependencies.gamma,this.transColor=dependencies.transColor,this.palette=dependencies.palette,this.parsed=dependencies.parsed,this.inflateData=dependencies.inflateData,this.finished=dependencies.finished,this.simpleTransparency=dependencies.simpleTransparency,this.headersFinished=dependencies.headersFinished||function(){}};return Parser.prototype.start=function(){this.read(constants.PNG_SIGNATURE.length,this._parseSignature.bind(this))},Parser.prototype._parseSignature=function(data){let signature=constants.PNG_SIGNATURE;for(let i=0;i<signature.length;i++)if(data[i]!==signature[i])return void this.error(new Error("Invalid file signature"));this.read(8,this._parseChunkBegin.bind(this))},Parser.prototype._parseChunkBegin=function(data){let length=data.readUInt32BE(0),type=data.readUInt32BE(4),name="";for(let i=4;i<8;i++)name+=String.fromCharCode(data[i]);let ancillary=Boolean(32&data[4]);if(this._hasIHDR||type===constants.TYPE_IHDR){if(this._crc=new CrcCalculator,this._crc.write(Buffer.from(name)),this._chunks[type])return this._chunks[type](length);ancillary?this.read(length+4,this._skipChunk.bind(this)):this.error(new Error("Unsupported critical chunk type "+name))}else this.error(new Error("Expected IHDR on beggining"))},Parser.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},Parser.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},Parser.prototype._parseChunkEnd=function(data){let fileCrc=data.readInt32BE(0),calcCrc=this._crc.crc32();this._options.checkCRC&&calcCrc!==fileCrc?this.error(new Error("Crc error - "+fileCrc+" - "+calcCrc)):this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},Parser.prototype._handleIHDR=function(length){this.read(length,this._parseIHDR.bind(this))},Parser.prototype._parseIHDR=function(data){this._crc.write(data);let width=data.readUInt32BE(0),height=data.readUInt32BE(4),depth=data[8],colorType=data[9],compr=data[10],filter=data[11],interlace=data[12];if(8!==depth&&4!==depth&&2!==depth&&1!==depth&&16!==depth)return void this.error(new Error("Unsupported bit depth "+depth));if(!(colorType in constants.COLORTYPE_TO_BPP_MAP))return void this.error(new Error("Unsupported color type"));if(0!==compr)return void this.error(new Error("Unsupported compression method"));if(0!==filter)return void this.error(new Error("Unsupported filter method"));if(0!==interlace&&1!==interlace)return void this.error(new Error("Unsupported interlace method"));this._colorType=colorType;let bpp=constants.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:width,height:height,depth:depth,interlace:Boolean(interlace),palette:Boolean(colorType&constants.COLORTYPE_PALETTE),color:Boolean(colorType&constants.COLORTYPE_COLOR),alpha:Boolean(colorType&constants.COLORTYPE_ALPHA),bpp:bpp,colorType:colorType}),this._handleChunkEnd()},Parser.prototype._handlePLTE=function(length){this.read(length,this._parsePLTE.bind(this))},Parser.prototype._parsePLTE=function(data){this._crc.write(data);let entries=Math.floor(data.length/3);for(let i=0;i<entries;i++)this._palette.push([data[3*i],data[3*i+1],data[3*i+2],255]);this.palette(this._palette),this._handleChunkEnd()},Parser.prototype._handleTRNS=function(length){this.simpleTransparency(),this.read(length,this._parseTRNS.bind(this))},Parser.prototype._parseTRNS=function(data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR){if(0===this._palette.length)return void this.error(new Error("Transparency chunk must be after palette"));if(data.length>this._palette.length)return void this.error(new Error("More transparent colors than palette size"));for(let i=0;i<data.length;i++)this._palette[i][3]=data[i];this.palette(this._palette)}this._colorType===constants.COLORTYPE_GRAYSCALE&&this.transColor([data.readUInt16BE(0)]),this._colorType===constants.COLORTYPE_COLOR&&this.transColor([data.readUInt16BE(0),data.readUInt16BE(2),data.readUInt16BE(4)]),this._handleChunkEnd()},Parser.prototype._handleGAMA=function(length){this.read(length,this._parseGAMA.bind(this))},Parser.prototype._parseGAMA=function(data){this._crc.write(data),this.gamma(data.readUInt32BE(0)/constants.GAMMA_DIVISION),this._handleChunkEnd()},Parser.prototype._handleIDAT=function(length){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-length,this._parseIDAT.bind(this,length))},Parser.prototype._parseIDAT=function(length,data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR&&0===this._palette.length)throw new Error("Expected palette not found");this.inflateData(data);let leftOverLength=length-data.length;leftOverLength>0?this._handleIDAT(leftOverLength):this._handleChunkEnd()},Parser.prototype._handleIEND=function(length){this.read(length,this._parseIEND.bind(this))},Parser.prototype._parseIEND=function(data){this._crc.write(data),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()},parser.exports}var hasRequiredBitmapper,formatNormaliser,hasRequiredFormatNormaliser,hasRequiredParserAsync,bitmapper={};function requireBitmapper(){if(hasRequiredBitmapper)return bitmapper;hasRequiredBitmapper=1;let interlaceUtils=requireInterlace(),pixelBppMapper=[function(){},function(pxData,data,pxPos,rawPos){if(rawPos===data.length)throw new Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+1>=data.length)throw new Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=data[rawPos+1]},function(pxData,data,pxPos,rawPos){if(rawPos+2>=data.length)throw new Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+3>=data.length)throw new Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=data[rawPos+3]}],pixelBppCustomMapper=[function(){},function(pxData,pixelData,pxPos,maxBit){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=pixelData[1]},function(pxData,pixelData,pxPos,maxBit){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=pixelData[3]}];function mapImage8Bit(image,pxData,getPxPos,bpp,data,rawPos){let imageWidth=image.width,imageHeight=image.height,imagePass=image.index;for(let y=0;y<imageHeight;y++)for(let x=0;x<imageWidth;x++){let pxPos=getPxPos(x,y,imagePass);pixelBppMapper[bpp](pxData,data,pxPos,rawPos),rawPos+=bpp}return rawPos}function mapImageCustomBit(image,pxData,getPxPos,bpp,bits,maxBit){let imageWidth=image.width,imageHeight=image.height,imagePass=image.index;for(let y=0;y<imageHeight;y++){for(let x=0;x<imageWidth;x++){let pixelData=bits.get(bpp),pxPos=getPxPos(x,y,imagePass);pixelBppCustomMapper[bpp](pxData,pixelData,pxPos,maxBit)}bits.resetAfterLine()}}return bitmapper.dataToBitMap=function(data,bitmapInfo){let bits,pxData,width=bitmapInfo.width,height=bitmapInfo.height,depth=bitmapInfo.depth,bpp=bitmapInfo.bpp,interlace=bitmapInfo.interlace;8!==depth&&(bits=function bitRetriever(data,depth){let leftOver=[],i=0;function split(){if(i===data.length)throw new Error("Ran out of data");let byte8,byte7,byte6,byte5,byte4,byte3,byte2,byte1,byte=data[i];switch(i++,depth){default:throw new Error("unrecognised depth");case 16:byte2=data[i],i++,leftOver.push((byte<<8)+byte2);break;case 4:byte2=15&byte,byte1=byte>>4,leftOver.push(byte1,byte2);break;case 2:byte4=3&byte,byte3=byte>>2&3,byte2=byte>>4&3,byte1=byte>>6&3,leftOver.push(byte1,byte2,byte3,byte4);break;case 1:byte8=1&byte,byte7=byte>>1&1,byte6=byte>>2&1,byte5=byte>>3&1,byte4=byte>>4&1,byte3=byte>>5&1,byte2=byte>>6&1,byte1=byte>>7&1,leftOver.push(byte1,byte2,byte3,byte4,byte5,byte6,byte7,byte8)}}return{get:function(count){for(;leftOver.length<count;)split();let returner=leftOver.slice(0,count);return leftOver=leftOver.slice(count),returner},resetAfterLine:function(){leftOver.length=0},end:function(){if(i!==data.length)throw new Error("extra data found")}}}(data,depth)),pxData=depth<=8?Buffer.alloc(width*height*4):new Uint16Array(width*height*4);let images,getPxPos,maxBit=Math.pow(2,depth)-1,rawPos=0;if(interlace)images=interlaceUtils.getImagePasses(width,height),getPxPos=interlaceUtils.getInterlaceIterator(width,height);else{let nonInterlacedPxPos=0;getPxPos=function(){let returner=nonInterlacedPxPos;return nonInterlacedPxPos+=4,returner},images=[{width:width,height:height}]}for(let imageIndex=0;imageIndex<images.length;imageIndex++)8===depth?rawPos=mapImage8Bit(images[imageIndex],pxData,getPxPos,bpp,data,rawPos):mapImageCustomBit(images[imageIndex],pxData,getPxPos,bpp,bits,maxBit);if(8===depth){if(rawPos!==data.length)throw new Error("extra data found")}else bits.end();return pxData},bitmapper}function requireFormatNormaliser(){if(hasRequiredFormatNormaliser)return formatNormaliser;return hasRequiredFormatNormaliser=1,formatNormaliser=function(indata,imageData){let depth=imageData.depth,width=imageData.width,height=imageData.height,colorType=imageData.colorType,transColor=imageData.transColor,palette=imageData.palette,outdata=indata;return 3===colorType?function dePalette(indata,outdata,width,height,palette){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let color=palette[indata[pxPos]];if(!color)throw new Error("index "+indata[pxPos]+" not in palette");for(let i=0;i<4;i++)outdata[pxPos+i]=color[i];pxPos+=4}}(indata,outdata,width,height,palette):(transColor&&function replaceTransparentColor(indata,outdata,width,height,transColor){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let makeTrans=!1;if(1===transColor.length?transColor[0]===indata[pxPos]&&(makeTrans=!0):transColor[0]===indata[pxPos]&&transColor[1]===indata[pxPos+1]&&transColor[2]===indata[pxPos+2]&&(makeTrans=!0),makeTrans)for(let i=0;i<4;i++)outdata[pxPos+i]=0;pxPos+=4}}(indata,outdata,width,height,transColor),8!==depth&&(16===depth&&(outdata=Buffer.alloc(width*height*4)),function scaleDepth(indata,outdata,width,height,depth){let maxInSample=Math.pow(2,depth)-1,pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){for(let i=0;i<4;i++)outdata[pxPos+i]=Math.floor(255*indata[pxPos+i]/maxInSample+.5);pxPos+=4}}(indata,outdata,width,height,depth))),outdata}}function requireParserAsync(){if(hasRequiredParserAsync)return parserAsync.exports;hasRequiredParserAsync=1;let util=require$$0__default$2.default,zlib=zlib__default.default,ChunkStream=requireChunkstream(),FilterAsync=function requireFilterParseAsync(){if(hasRequiredFilterParseAsync)return filterParseAsync.exports;hasRequiredFilterParseAsync=1;let util=require$$0__default$2.default,ChunkStream=requireChunkstream(),Filter=requireFilterParse(),FilterAsync=filterParseAsync.exports=function(bitmapInfo){ChunkStream.call(this);let buffers=[],that=this;this._filter=new Filter(bitmapInfo,{read:this.read.bind(this),write:function(buffer){buffers.push(buffer)},complete:function(){that.emit("complete",Buffer.concat(buffers))}}),this._filter.start()};return util.inherits(FilterAsync,ChunkStream),filterParseAsync.exports}(),Parser=requireParser(),bitmapper=requireBitmapper(),formatNormaliser=requireFormatNormaliser(),ParserAsync=parserAsync.exports=function(options){ChunkStream.call(this),this._parser=new Parser(options,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=options,this.writable=!0,this._parser.start()};return util.inherits(ParserAsync,ChunkStream),ParserAsync.prototype._handleError=function(err){this.emit("error",err),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0},ParserAsync.prototype._inflateData=function(data){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=zlib.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let imageSize=(1+(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3))*this._bitmapInfo.height,chunkSize=Math.max(imageSize,zlib.Z_MIN_CHUNK);this._inflate=zlib.createInflate({chunkSize:chunkSize});let leftToInflate=imageSize,emitError=this.emit.bind(this,"error");this._inflate.on("error",function(err){leftToInflate&&emitError(err)}),this._filter.on("complete",this._complete.bind(this));let filterWrite=this._filter.write.bind(this._filter);this._inflate.on("data",function(chunk){leftToInflate&&(chunk.length>leftToInflate&&(chunk=chunk.slice(0,leftToInflate)),leftToInflate-=chunk.length,filterWrite(chunk))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(data)},ParserAsync.prototype._handleMetaData=function(metaData){this._metaData=metaData,this._bitmapInfo=Object.create(metaData),this._filter=new FilterAsync(this._bitmapInfo)},ParserAsync.prototype._handleTransColor=function(transColor){this._bitmapInfo.transColor=transColor},ParserAsync.prototype._handlePalette=function(palette){this._bitmapInfo.palette=palette},ParserAsync.prototype._simpleTransparency=function(){this._metaData.alpha=!0},ParserAsync.prototype._headersFinished=function(){this.emit("metadata",this._metaData)},ParserAsync.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))},ParserAsync.prototype._complete=function(filteredData){if(this.errord)return;let normalisedBitmapData;try{let bitmapData=bitmapper.dataToBitMap(filteredData,this._bitmapInfo);normalisedBitmapData=formatNormaliser(bitmapData,this._bitmapInfo),bitmapData=null}catch(ex){return void this._handleError(ex)}this.emit("parsed",normalisedBitmapData)},parserAsync.exports}var bitpacker,hasRequiredBitpacker,filterPack,hasRequiredFilterPack,hasRequiredPacker,hasRequiredPackerAsync,packerAsync={exports:{}},packer={exports:{}};function requirePacker(){if(hasRequiredPacker)return packer.exports;hasRequiredPacker=1;let constants=requireConstants(),CrcStream=requireCrc(),bitPacker=function requireBitpacker(){if(hasRequiredBitpacker)return bitpacker;hasRequiredBitpacker=1;let constants=requireConstants();return bitpacker=function(dataIn,width,height,options){let outHasAlpha=-1!==[constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType);if(options.colorType===options.inputColorType){let bigEndian=function(){let buffer=new ArrayBuffer(2);return new DataView(buffer).setInt16(0,256,!0),256!==new Int16Array(buffer)[0]}();if(8===options.bitDepth||16===options.bitDepth&&bigEndian)return dataIn}let data=16!==options.bitDepth?dataIn:new Uint16Array(dataIn.buffer),maxValue=255,inBpp=constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];4!==inBpp||options.inputHasAlpha||(inBpp=3);let outBpp=constants.COLORTYPE_TO_BPP_MAP[options.colorType];16===options.bitDepth&&(maxValue=65535,outBpp*=2);let outData=Buffer.alloc(width*height*outBpp),inIndex=0,outIndex=0,bgColor=options.bgColor||{};function getRGBA(){let red,green,blue,alpha=maxValue;switch(options.inputColorType){case constants.COLORTYPE_COLOR_ALPHA:alpha=data[inIndex+3],red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_COLOR:red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_ALPHA:alpha=data[inIndex+1],red=data[inIndex],green=red,blue=red;break;case constants.COLORTYPE_GRAYSCALE:red=data[inIndex],green=red,blue=red;break;default:throw new Error("input color type:"+options.inputColorType+" is not supported at present")}return options.inputHasAlpha&&(outHasAlpha||(alpha/=maxValue,red=Math.min(Math.max(Math.round((1-alpha)*bgColor.red+alpha*red),0),maxValue),green=Math.min(Math.max(Math.round((1-alpha)*bgColor.green+alpha*green),0),maxValue),blue=Math.min(Math.max(Math.round((1-alpha)*bgColor.blue+alpha*blue),0),maxValue))),{red:red,green:green,blue:blue,alpha:alpha}}void 0===bgColor.red&&(bgColor.red=maxValue),void 0===bgColor.green&&(bgColor.green=maxValue),void 0===bgColor.blue&&(bgColor.blue=maxValue);for(let y=0;y<height;y++)for(let x=0;x<width;x++){let rgba=getRGBA();switch(options.colorType){case constants.COLORTYPE_COLOR_ALPHA:case constants.COLORTYPE_COLOR:8===options.bitDepth?(outData[outIndex]=rgba.red,outData[outIndex+1]=rgba.green,outData[outIndex+2]=rgba.blue,outHasAlpha&&(outData[outIndex+3]=rgba.alpha)):(outData.writeUInt16BE(rgba.red,outIndex),outData.writeUInt16BE(rgba.green,outIndex+2),outData.writeUInt16BE(rgba.blue,outIndex+4),outHasAlpha&&outData.writeUInt16BE(rgba.alpha,outIndex+6));break;case constants.COLORTYPE_ALPHA:case constants.COLORTYPE_GRAYSCALE:{let grayscale=(rgba.red+rgba.green+rgba.blue)/3;8===options.bitDepth?(outData[outIndex]=grayscale,outHasAlpha&&(outData[outIndex+1]=rgba.alpha)):(outData.writeUInt16BE(grayscale,outIndex),outHasAlpha&&outData.writeUInt16BE(rgba.alpha,outIndex+2));break}default:throw new Error("unrecognised color Type "+options.colorType)}inIndex+=inBpp,outIndex+=outBpp}return outData}}(),filter=function requireFilterPack(){if(hasRequiredFilterPack)return filterPack;hasRequiredFilterPack=1;let paethPredictor=requirePaethPredictor(),filters={0:function filterNone(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++)rawData[rawPos+x]=pxData[pxPos+x]},1:function filterSub(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;rawData[rawPos+x]=val}},2:function filterUp(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++){let up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-up;rawData[rawPos+x]=val}},3:function filterAvg(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);rawData[rawPos+x]=val}},4:function filterPaeth(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);rawData[rawPos+x]=val}}},filterSums={0:function filterSumNone(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let i=pxPos;i<length;i++)sum+=Math.abs(pxData[i]);return sum},1:function filterSumSub(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;sum+=Math.abs(val)}return sum},2:function filterSumUp(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let x=pxPos;x<length;x++){let up=pxPos>0?pxData[x-byteWidth]:0,val=pxData[x]-up;sum+=Math.abs(val)}return sum},3:function filterSumAvg(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);sum+=Math.abs(val)}return sum},4:function filterSumPaeth(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);sum+=Math.abs(val)}return sum}};return filterPack=function(pxData,width,height,options,bpp){let filterTypes;if("filterType"in options&&-1!==options.filterType){if("number"!=typeof options.filterType)throw new Error("unrecognised filter types");filterTypes=[options.filterType]}else filterTypes=[0,1,2,3,4];16===options.bitDepth&&(bpp*=2);let byteWidth=width*bpp,rawPos=0,pxPos=0,rawData=Buffer.alloc((byteWidth+1)*height),sel=filterTypes[0];for(let y=0;y<height;y++){if(filterTypes.length>1){let min=1/0;for(let i=0;i<filterTypes.length;i++){let sum=filterSums[filterTypes[i]](pxData,pxPos,byteWidth,bpp);sum<min&&(sel=filterTypes[i],min=sum)}}rawData[rawPos]=sel,rawPos++,filters[sel](pxData,pxPos,byteWidth,rawData,rawPos,bpp),rawPos+=byteWidth,pxPos+=byteWidth}return rawData},filterPack}(),zlib=zlib__default.default,Packer=packer.exports=function(options){if(this._options=options,options.deflateChunkSize=options.deflateChunkSize||32768,options.deflateLevel=null!=options.deflateLevel?options.deflateLevel:9,options.deflateStrategy=null!=options.deflateStrategy?options.deflateStrategy:3,options.inputHasAlpha=null==options.inputHasAlpha||options.inputHasAlpha,options.deflateFactory=options.deflateFactory||zlib.createDeflate,options.bitDepth=options.bitDepth||8,options.colorType="number"==typeof options.colorType?options.colorType:constants.COLORTYPE_COLOR_ALPHA,options.inputColorType="number"==typeof options.inputColorType?options.inputColorType:constants.COLORTYPE_COLOR_ALPHA,-1===[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType))throw new Error("option color type:"+options.colorType+" is not supported at present");if(-1===[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.inputColorType))throw new Error("option input color type:"+options.inputColorType+" is not supported at present");if(8!==options.bitDepth&&16!==options.bitDepth)throw new Error("option bit depth:"+options.bitDepth+" is not supported at present")};return Packer.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},Packer.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},Packer.prototype.filterData=function(data,width,height){let packedData=bitPacker(data,width,height,this._options),bpp=constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];return filter(packedData,width,height,this._options,bpp)},Packer.prototype._packChunk=function(type,data){let len=data?data.length:0,buf=Buffer.alloc(len+12);return buf.writeUInt32BE(len,0),buf.writeUInt32BE(type,4),data&&data.copy(buf,8),buf.writeInt32BE(CrcStream.crc32(buf.slice(4,buf.length-4)),buf.length-4),buf},Packer.prototype.packGAMA=function(gamma){let buf=Buffer.alloc(4);return buf.writeUInt32BE(Math.floor(gamma*constants.GAMMA_DIVISION),0),this._packChunk(constants.TYPE_gAMA,buf)},Packer.prototype.packIHDR=function(width,height){let buf=Buffer.alloc(13);return buf.writeUInt32BE(width,0),buf.writeUInt32BE(height,4),buf[8]=this._options.bitDepth,buf[9]=this._options.colorType,buf[10]=0,buf[11]=0,buf[12]=0,this._packChunk(constants.TYPE_IHDR,buf)},Packer.prototype.packIDAT=function(data){return this._packChunk(constants.TYPE_IDAT,data)},Packer.prototype.packIEND=function(){return this._packChunk(constants.TYPE_IEND,null)},packer.exports}var hasRequiredSyncInflate,pngSync={},syncInflate={exports:{}};function requireSyncInflate(){return hasRequiredSyncInflate||(hasRequiredSyncInflate=1,function(module,exports){let assert=require$$4__default$1.default.ok,zlib=zlib__default.default,util=require$$0__default$2.default,kMaxLength=require$$2__default.default.kMaxLength;function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);opts&&opts.chunkSize<zlib.Z_MIN_CHUNK&&(opts.chunkSize=zlib.Z_MIN_CHUNK),zlib.Inflate.call(this,opts),this._offset=void 0===this._offset?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,opts&&null!=opts.maxLength&&(this._maxLength=opts.maxLength)}function _close(engine,callback){callback&&process.nextTick(callback),engine._handle&&(engine._handle.close(),engine._handle=null)}function inflateSync(buffer,opts){return function zlibBufferSync(engine,buffer){if("string"==typeof buffer&&(buffer=Buffer.from(buffer)),!(buffer instanceof Buffer))throw new TypeError("Not a string or buffer");let flushFlag=engine._finishFlushFlag;return null==flushFlag&&(flushFlag=zlib.Z_FINISH),engine._processChunk(buffer,flushFlag)}(new Inflate(opts),buffer)}Inflate.prototype._processChunk=function(chunk,flushFlag,asyncCb){if("function"==typeof asyncCb)return zlib.Inflate._processChunk.call(this,chunk,flushFlag,asyncCb);let error,res,self=this,availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,leftToInflate=this._maxLength,inOff=0,buffers=[],nread=0;function handleChunk(availInAfter,availOutAfter){if(self._hadError)return;let have=availOutBefore-availOutAfter;if(assert(have>=0,"have should not go down"),have>0){let out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,out.length>leftToInflate&&(out=out.slice(0,leftToInflate)),buffers.push(out),nread+=out.length,leftToInflate-=out.length,0===leftToInflate)return!1}return(0===availOutAfter||self._offset>=self._chunkSize)&&(availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer.allocUnsafe(self._chunkSize)),0===availOutAfter&&(inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!0)}this.on("error",function(err){error=err}),assert(this._handle,"zlib binding closed");do{res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore),res=res||this._writeState}while(!this._hadError&&handleChunk(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)throw _close(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+kMaxLength.toString(16)+" bytes");let buf=Buffer.concat(buffers,nread);return _close(this),buf},util.inherits(Inflate,zlib.Inflate),module.exports=exports=inflateSync,exports.Inflate=Inflate,exports.createInflate=function createInflate(opts){return new Inflate(opts)},exports.inflateSync=inflateSync}(syncInflate,syncInflate.exports)),syncInflate.exports}var hasRequiredSyncReader,syncReader={exports:{}};function requireSyncReader(){if(hasRequiredSyncReader)return syncReader.exports;hasRequiredSyncReader=1;let SyncReader=syncReader.exports=function(buffer){this._buffer=buffer,this._reads=[]};return SyncReader.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback})},SyncReader.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let read=this._reads[0];if(!this._buffer.length||!(this._buffer.length>=read.length||read.allowLess))break;{this._reads.shift();let buf=this._buffer;this._buffer=buf.slice(read.length),read.func.call(this,buf.slice(0,read.length))}}return this._reads.length>0?new Error("There are some read requests waitng on finished stream"):this._buffer.length>0?new Error("unrecognised content at end of stream"):void 0},syncReader.exports}var hasRequiredFilterParseSync,parserSync,hasRequiredParserSync,packerSync,hasRequiredPackerSync,hasRequiredPngSync,hasRequiredPng$1,filterParseSync={};function requireParserSync(){if(hasRequiredParserSync)return parserSync;hasRequiredParserSync=1;let hasSyncZlib=!0,zlib=zlib__default.default,inflateSync=requireSyncInflate();zlib.deflateSync||(hasSyncZlib=!1);let SyncReader=requireSyncReader(),FilterSync=function requireFilterParseSync(){if(hasRequiredFilterParseSync)return filterParseSync;hasRequiredFilterParseSync=1;let SyncReader=requireSyncReader(),Filter=requireFilterParse();return filterParseSync.process=function(inBuffer,bitmapInfo){let outBuffers=[],reader=new SyncReader(inBuffer);return new Filter(bitmapInfo,{read:reader.read.bind(reader),write:function(bufferPart){outBuffers.push(bufferPart)},complete:function(){}}).start(),reader.process(),Buffer.concat(outBuffers)},filterParseSync}(),Parser=requireParser(),bitmapper=requireBitmapper(),formatNormaliser=requireFormatNormaliser();return parserSync=function(buffer,options){if(!hasSyncZlib)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let err,metaData,gamma;let inflateDataList=[];let reader=new SyncReader(buffer),parser=new Parser(options,{read:reader.read.bind(reader),error:function handleError(_err_){err=_err_},metadata:function handleMetaData(_metaData_){metaData=_metaData_},gamma:function handleGamma(_gamma_){gamma=_gamma_},palette:function handlePalette(palette){metaData.palette=palette},transColor:function handleTransColor(transColor){metaData.transColor=transColor},inflateData:function handleInflateData(inflatedData){inflateDataList.push(inflatedData)},simpleTransparency:function handleSimpleTransparency(){metaData.alpha=!0}});if(parser.start(),reader.process(),err)throw err;let inflatedData,inflateData=Buffer.concat(inflateDataList);if(inflateDataList.length=0,metaData.interlace)inflatedData=zlib.inflateSync(inflateData);else{let imageSize=(1+(metaData.width*metaData.bpp*metaData.depth+7>>3))*metaData.height;inflatedData=inflateSync(inflateData,{chunkSize:imageSize,maxLength:imageSize})}if(inflateData=null,!inflatedData||!inflatedData.length)throw new Error("bad png - invalid inflate data response");let unfilteredData=FilterSync.process(inflatedData,metaData);inflateData=null;let bitmapData=bitmapper.dataToBitMap(unfilteredData,metaData);unfilteredData=null;let normalisedBitmapData=formatNormaliser(bitmapData,metaData);return metaData.data=normalisedBitmapData,metaData.gamma=gamma||0,metaData},parserSync}function requirePngSync(){if(hasRequiredPngSync)return pngSync;hasRequiredPngSync=1;let parse=requireParserSync(),pack=function requirePackerSync(){if(hasRequiredPackerSync)return packerSync;hasRequiredPackerSync=1;let hasSyncZlib=!0,zlib=zlib__default.default;zlib.deflateSync||(hasSyncZlib=!1);let constants=requireConstants(),Packer=requirePacker();return packerSync=function(metaData,opt){if(!hasSyncZlib)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let packer=new Packer(opt||{}),chunks=[];chunks.push(Buffer.from(constants.PNG_SIGNATURE)),chunks.push(packer.packIHDR(metaData.width,metaData.height)),metaData.gamma&&chunks.push(packer.packGAMA(metaData.gamma));let filteredData=packer.filterData(metaData.data,metaData.width,metaData.height),compressedData=zlib.deflateSync(filteredData,packer.getDeflateOptions());if(filteredData=null,!compressedData||!compressedData.length)throw new Error("bad png - invalid compressed data response");return chunks.push(packer.packIDAT(compressedData)),chunks.push(packer.packIEND()),Buffer.concat(chunks)},packerSync}();return pngSync.read=function(buffer,options){return parse(buffer,options||{})},pngSync.write=function(png,options){return pack(png,options)},pngSync}function requirePng$1(){if(hasRequiredPng$1)return png;hasRequiredPng$1=1;let util=require$$0__default$2.default,Stream=require$$0__default$4.default,Parser=requireParserAsync(),Packer=function requirePackerAsync(){if(hasRequiredPackerAsync)return packerAsync.exports;hasRequiredPackerAsync=1;let util=require$$0__default$2.default,Stream=require$$0__default$4.default,constants=requireConstants(),Packer=requirePacker(),PackerAsync=packerAsync.exports=function(opt){Stream.call(this);let options=opt||{};this._packer=new Packer(options),this._deflate=this._packer.createDeflate(),this.readable=!0};return util.inherits(PackerAsync,Stream),PackerAsync.prototype.pack=function(data,width,height,gamma){this.emit("data",Buffer.from(constants.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(width,height)),gamma&&this.emit("data",this._packer.packGAMA(gamma));let filteredData=this._packer.filterData(data,width,height);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(compressedData){this.emit("data",this._packer.packIDAT(compressedData))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(filteredData)},packerAsync.exports}(),PNGSync=requirePngSync(),PNG=png.PNG=function(options){Stream.call(this),options=options||{},this.width=0|options.width,this.height=0|options.height,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,options.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Parser(options),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(data){this.data=data,this.emit("parsed",data)}.bind(this)),this._packer=new Packer(options),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};return util.inherits(PNG,Stream),PNG.sync=PNGSync,PNG.prototype.pack=function(){return this.data&&this.data.length?(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this):(this.emit("error","No data provided"),this)},PNG.prototype.parse=function(data,callback){if(callback){let onParsed,onError;onParsed=function(parsedData){this.removeListener("error",onError),this.data=parsedData,callback(null,this)}.bind(this),onError=function(err){this.removeListener("parsed",onParsed),callback(err,null)}.bind(this),this.once("parsed",onParsed),this.once("error",onError)}return this.end(data),this},PNG.prototype.write=function(data){return this._parser.write(data),!0},PNG.prototype.end=function(data){this._parser.end(data)},PNG.prototype._metadata=function(metadata){this.width=metadata.width,this.height=metadata.height,this.emit("metadata",metadata)},PNG.prototype._gamma=function(gamma){this.gamma=gamma},PNG.prototype._handleClose=function(){this._parser.writable||this._packer.readable||this.emit("close")},PNG.bitblt=function(src,dst,srcX,srcY,width,height,deltaX,deltaY){if(srcY|=0,width|=0,height|=0,deltaX|=0,deltaY|=0,(srcX|=0)>src.width||srcY>src.height||srcX+width>src.width||srcY+height>src.height)throw new Error("bitblt reading outside image");if(deltaX>dst.width||deltaY>dst.height||deltaX+width>dst.width||deltaY+height>dst.height)throw new Error("bitblt writing outside image");for(let y=0;y<height;y++)src.data.copy(dst.data,(deltaY+y)*dst.width+deltaX<<2,(srcY+y)*src.width+srcX<<2,(srcY+y)*src.width+srcX+width<<2)},PNG.prototype.bitblt=function(dst,srcX,srcY,width,height,deltaX,deltaY){return PNG.bitblt(this,dst,srcX,srcY,width,height,deltaX,deltaY),this},PNG.adjustGamma=function(src){if(src.gamma){for(let y=0;y<src.height;y++)for(let x=0;x<src.width;x++){let idx=src.width*y+x<<2;for(let i=0;i<3;i++){let sample=src.data[idx+i]/255;sample=Math.pow(sample,1/2.2/src.gamma),src.data[idx+i]=Math.round(255*sample)}}src.gamma=0}},PNG.prototype.adjustGamma=function(){PNG.adjustGamma(this)},png}var hasRequiredUtils,hasRequiredPng,utils={};function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,function(exports){function hex2rgba(hex){if("number"==typeof hex&&(hex=hex.toString()),"string"!=typeof hex)throw new Error("Color should be defined as hex string");let hexCode=hex.slice().replace("#","").split("");if(hexCode.length<3||5===hexCode.length||hexCode.length>8)throw new Error("Invalid hex color: "+hex);3!==hexCode.length&&4!==hexCode.length||(hexCode=Array.prototype.concat.apply([],hexCode.map(function(c){return[c,c]}))),6===hexCode.length&&hexCode.push("F","F");const hexValue=parseInt(hexCode.join(""),16);return{r:hexValue>>24&255,g:hexValue>>16&255,b:hexValue>>8&255,a:255&hexValue,hex:"#"+hexCode.slice(0,6).join("")}}exports.getOptions=function getOptions(options){options||(options={}),options.color||(options.color={});const margin=void 0===options.margin||null===options.margin||options.margin<0?4:options.margin,width=options.width&&options.width>=21?options.width:void 0,scale=options.scale||4;return{width:width,scale:width?4:scale,margin:margin,color:{dark:hex2rgba(options.color.dark||"#000000ff"),light:hex2rgba(options.color.light||"#ffffffff")},type:options.type,rendererOpts:options.rendererOpts||{}}},exports.getScale=function getScale(qrSize,opts){return opts.width&&opts.width>=qrSize+2*opts.margin?opts.width/(qrSize+2*opts.margin):opts.scale},exports.getImageWidth=function getImageWidth(qrSize,opts){const scale=exports.getScale(qrSize,opts);return Math.floor((qrSize+2*opts.margin)*scale)},exports.qrToImageData=function qrToImageData(imgData,qr,opts){const size=qr.modules.size,data=qr.modules.data,scale=exports.getScale(size,opts),symbolSize=Math.floor((size+2*opts.margin)*scale),scaledMargin=opts.margin*scale,palette=[opts.color.light,opts.color.dark];for(let i=0;i<symbolSize;i++)for(let j=0;j<symbolSize;j++){let posDst=4*(i*symbolSize+j),pxColor=opts.color.light;if(i>=scaledMargin&&j>=scaledMargin&&i<symbolSize-scaledMargin&&j<symbolSize-scaledMargin){pxColor=palette[data[Math.floor((i-scaledMargin)/scale)*size+Math.floor((j-scaledMargin)/scale)]?1:0]}imgData[posDst++]=pxColor.r,imgData[posDst++]=pxColor.g,imgData[posDst++]=pxColor.b,imgData[posDst]=pxColor.a}}}(utils)),utils}var hasRequiredUtf8,utf8={};var hasRequiredTerminal$1,terminal$1={},terminal={};var hasRequiredTerminalSmall,hasRequiredTerminal,terminalSmall={};function requireTerminal(){if(hasRequiredTerminal)return terminal$1;hasRequiredTerminal=1;const big=function requireTerminal$1(){return hasRequiredTerminal$1||(hasRequiredTerminal$1=1,terminal.render=function(qrData,options,cb){const size=qrData.modules.size,data=qrData.modules.data,white="[47m [0m";let output="";const hMargin=Array(size+3).join(white),vMargin=Array(2).join(white);output+=hMargin+"\n";for(let i=0;i<size;++i){output+=white;for(let j=0;j<size;j++)output+=data[i*size+j]?"[40m [0m":white;output+=vMargin+"\n"}return output+=hMargin+"\n","function"==typeof cb&&cb(null,output),output}),terminal}(),small=function requireTerminalSmall(){if(hasRequiredTerminalSmall)return terminalSmall;hasRequiredTerminalSmall=1;const mkCodePixel=function(modules,size,x,y){const sizePlus=size+1;return x>=sizePlus||y>=sizePlus||y<-1||x<-1?"0":x>=size||y>=size||y<0||x<0?"1":modules[y*size+x]?"2":"1"},mkCode=function(modules,size,x,y){return mkCodePixel(modules,size,x,y)+mkCodePixel(modules,size,x,y+1)};return terminalSmall.render=function(qrData,options,cb){const size=qrData.modules.size,data=qrData.modules.data,inverse=!(!options||!options.inverse),lineSetup=options&&options.inverse?"[40m[37m":"[47m[30m",palette=function(lineSetup,foregroundWhite,foregroundBlack){return{"00":"[0m "+lineSetup,"01":"[0m"+foregroundWhite+"▄"+lineSetup,"02":"[0m"+foregroundBlack+"▄"+lineSetup,10:"[0m"+foregroundWhite+"▀"+lineSetup,11:" ",12:"▄",20:"[0m"+foregroundBlack+"▀"+lineSetup,21:"▀",22:"█"}}(lineSetup,inverse?"[30m":"[37m",inverse?"[37m":"[30m"),newLine="[0m\n"+lineSetup;let output=lineSetup;for(let y=-1;y<size+1;y+=2){for(let x=-1;x<size;x++)output+=palette[mkCode(data,size,x,y)];output+=palette[mkCode(data,size,size,y)]+newLine}return output+="[0m","function"==typeof cb&&cb(null,output),output},terminalSmall}();return terminal$1.render=function(qrData,options,cb){return options&&options.small?small.render(qrData,options,cb):big.render(qrData,options,cb)},terminal$1}var hasRequiredSvgTag,hasRequiredSvg,svg={},svgTag={};function requireSvgTag(){if(hasRequiredSvgTag)return svgTag;hasRequiredSvgTag=1;const Utils=requireUtils();function getColorAttrib(color,attrib){const alpha=color.a/255,str=attrib+'="'+color.hex+'"';return alpha<1?str+" "+attrib+'-opacity="'+alpha.toFixed(2).slice(1)+'"':str}function svgCmd(cmd,x,y){let str=cmd+x;return void 0!==y&&(str+=" "+y),str}return svgTag.render=function render(qrData,options,cb){const opts=Utils.getOptions(options),size=qrData.modules.size,data=qrData.modules.data,qrcodesize=size+2*opts.margin,bg=opts.color.light.a?"<path "+getColorAttrib(opts.color.light,"fill")+' d="M0 0h'+qrcodesize+"v"+qrcodesize+'H0z"/>':"",path="<path "+getColorAttrib(opts.color.dark,"stroke")+' d="'+function qrToPath(data,size,margin){let path="",moveBy=0,newRow=!1,lineLength=0;for(let i=0;i<data.length;i++){const col=Math.floor(i%size),row=Math.floor(i/size);col||newRow||(newRow=!0),data[i]?(lineLength++,i>0&&col>0&&data[i-1]||(path+=newRow?svgCmd("M",col+margin,.5+row+margin):svgCmd("m",moveBy,0),moveBy=0,newRow=!1),col+1<size&&data[i+1]||(path+=svgCmd("h",lineLength),lineLength=0)):moveBy++}return path}(data,size,opts.margin)+'"/>',viewBox='viewBox="0 0 '+qrcodesize+" "+qrcodesize+'"',svgTag='<svg xmlns="http://www.w3.org/2000/svg" '+(opts.width?'width="'+opts.width+'" height="'+opts.width+'" ':"")+viewBox+' shape-rendering="crispEdges">'+bg+path+"</svg>\n";return"function"==typeof cb&&cb(null,svgTag),svgTag},svgTag}var hasRequiredCanvas,hasRequiredBrowser,hasRequiredServer,lib,hasRequiredLib,browser={},canvas={};function requireCanvas(){return hasRequiredCanvas||(hasRequiredCanvas=1,function(exports){const Utils=requireUtils();exports.render=function render(qrData,canvas,options){let opts=options,canvasEl=canvas;void 0!==opts||canvas&&canvas.getContext||(opts=canvas,canvas=void 0),canvas||(canvasEl=function getCanvasElement(){try{return document.createElement("canvas")}catch(e){throw new Error("You need to specify a canvas element")}}()),opts=Utils.getOptions(opts);const size=Utils.getImageWidth(qrData.modules.size,opts),ctx=canvasEl.getContext("2d"),image=ctx.createImageData(size,size);return Utils.qrToImageData(image.data,qrData,opts),function clearCanvas(ctx,canvas,size){ctx.clearRect(0,0,canvas.width,canvas.height),canvas.style||(canvas.style={}),canvas.height=size,canvas.width=size,canvas.style.height=size+"px",canvas.style.width=size+"px"}(ctx,canvasEl,size),ctx.putImageData(image,0,0),canvasEl},exports.renderToDataURL=function renderToDataURL(qrData,canvas,options){let opts=options;void 0!==opts||canvas&&canvas.getContext||(opts=canvas,canvas=void 0),opts||(opts={});const canvasEl=exports.render(qrData,canvas,opts),type=opts.type||"image/png",rendererOpts=opts.rendererOpts||{};return canvasEl.toDataURL(type,rendererOpts.quality)}}(canvas)),canvas}function requireServer(){if(hasRequiredServer)return server;hasRequiredServer=1;const canPromise=requireCanPromise(),QRCode=requireQrcode(),PngRenderer=function requirePng(){return hasRequiredPng||(hasRequiredPng=1,function(exports){const fs=fs__default.default,PNG=requirePng$1().PNG,Utils=requireUtils();exports.render=function render(qrData,options){const opts=Utils.getOptions(options),pngOpts=opts.rendererOpts,size=Utils.getImageWidth(qrData.modules.size,opts);pngOpts.width=size,pngOpts.height=size;const pngImage=new PNG(pngOpts);return Utils.qrToImageData(pngImage.data,qrData,opts),pngImage},exports.renderToDataURL=function renderToDataURL(qrData,options,cb){void 0===cb&&(cb=options,options=void 0),exports.renderToBuffer(qrData,options,function(err,output){err&&cb(err);let url="data:image/png;base64,";url+=output.toString("base64"),cb(null,url)})},exports.renderToBuffer=function renderToBuffer(qrData,options,cb){void 0===cb&&(cb=options,options=void 0);const png=exports.render(qrData,options),buffer=[];png.on("error",cb),png.on("data",function(data){buffer.push(data)}),png.on("end",function(){cb(null,Buffer.concat(buffer))}),png.pack()},exports.renderToFile=function renderToFile(path,qrData,options,cb){void 0===cb&&(cb=options,options=void 0);let called=!1;const done=(...args)=>{called||(called=!0,cb.apply(null,args))},stream=fs.createWriteStream(path);stream.on("error",done),stream.on("close",done),exports.renderToFileStream(stream,qrData,options)},exports.renderToFileStream=function renderToFileStream(stream,qrData,options){exports.render(qrData,options).pack().pipe(stream)}}(png$1)),png$1}(),Utf8Renderer=function requireUtf8(){return hasRequiredUtf8||(hasRequiredUtf8=1,function(exports){const Utils=requireUtils(),BLOCK_CHAR={WW:" ",WB:"▄",BB:"█",BW:"▀"},INVERTED_BLOCK_CHAR={BB:" ",BW:"▄",WW:"█",WB:"▀"};function getBlockChar(top,bottom,blocks){return top&&bottom?blocks.BB:top&&!bottom?blocks.BW:!top&&bottom?blocks.WB:blocks.WW}exports.render=function(qrData,options,cb){const opts=Utils.getOptions(options);let blocks=BLOCK_CHAR;"#ffffff"!==opts.color.dark.hex&&"#000000"!==opts.color.light.hex||(blocks=INVERTED_BLOCK_CHAR);const size=qrData.modules.size,data=qrData.modules.data;let output="",hMargin=Array(size+2*opts.margin+1).join(blocks.WW);hMargin=Array(opts.margin/2+1).join(hMargin+"\n");const vMargin=Array(opts.margin+1).join(blocks.WW);output+=hMargin;for(let i=0;i<size;i+=2){output+=vMargin;for(let j=0;j<size;j++)output+=getBlockChar(data[i*size+j],data[(i+1)*size+j],blocks);output+=vMargin+"\n"}return output+=hMargin.slice(0,-1),"function"==typeof cb&&cb(null,output),output},exports.renderToFile=function renderToFile(path,qrData,options,cb){void 0===cb&&(cb=options,options=void 0);const fs=fs__default.default,utf8=exports.render(qrData,options);fs.writeFile(path,utf8,cb)}}(utf8)),utf8}(),TerminalRenderer=requireTerminal(),SvgRenderer=function requireSvg(){return hasRequiredSvg||(hasRequiredSvg=1,function(exports){const svgTagRenderer=requireSvgTag();exports.render=svgTagRenderer.render,exports.renderToFile=function renderToFile(path,qrData,options,cb){void 0===cb&&(cb=options,options=void 0);const fs=fs__default.default,xmlStr='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+exports.render(qrData,options);fs.writeFile(path,xmlStr,cb)}}(svg)),svg}();function checkParams(text,opts,cb){if(void 0===text)throw new Error("String required as first argument");if(void 0===cb&&(cb=opts,opts={}),"function"!=typeof cb){if(!canPromise())throw new Error("Callback required as last argument");opts=cb||{},cb=null}return{opts:opts,cb:cb}}function getRendererFromType(type){switch(type){case"svg":return SvgRenderer;case"txt":case"utf8":return Utf8Renderer;default:return PngRenderer}}function render(renderFunc,text,params){if(!params.cb)return new Promise(function(resolve,reject){try{const data=QRCode.create(text,params.opts);return renderFunc(data,params.opts,function(err,data){return err?reject(err):resolve(data)})}catch(e){reject(e)}});try{const data=QRCode.create(text,params.opts);return renderFunc(data,params.opts,params.cb)}catch(e){params.cb(e)}}return server.create=QRCode.create,server.toCanvas=function requireBrowser(){if(hasRequiredBrowser)return browser;hasRequiredBrowser=1;const canPromise=requireCanPromise(),QRCode=requireQrcode(),CanvasRenderer=requireCanvas(),SvgRenderer=requireSvgTag();function renderCanvas(renderFunc,canvas,text,opts,cb){const args=[].slice.call(arguments,1),argsNum=args.length,isLastArgCb="function"==typeof args[argsNum-1];if(!isLastArgCb&&!canPromise())throw new Error("Callback required as last argument");if(!isLastArgCb){if(argsNum<1)throw new Error("Too few arguments provided");return 1===argsNum?(text=canvas,canvas=opts=void 0):2!==argsNum||canvas.getContext||(opts=text,text=canvas,canvas=void 0),new Promise(function(resolve,reject){try{const data=QRCode.create(text,opts);resolve(renderFunc(data,canvas,opts))}catch(e){reject(e)}})}if(argsNum<2)throw new Error("Too few arguments provided");2===argsNum?(cb=text,text=canvas,canvas=opts=void 0):3===argsNum&&(canvas.getContext&&void 0===cb?(cb=opts,opts=void 0):(cb=opts,opts=text,text=canvas,canvas=void 0));try{const data=QRCode.create(text,opts);cb(null,renderFunc(data,canvas,opts))}catch(e){cb(e)}}return browser.create=QRCode.create,browser.toCanvas=renderCanvas.bind(null,CanvasRenderer.render),browser.toDataURL=renderCanvas.bind(null,CanvasRenderer.renderToDataURL),browser.toString=renderCanvas.bind(null,function(data,_,opts){return SvgRenderer.render(data,opts)}),browser}().toCanvas,server.toString=function toString(text,opts,cb){const params=checkParams(text,opts,cb),renderer=function getStringRendererFromType(type){switch(type){case"svg":return SvgRenderer;case"terminal":return TerminalRenderer;default:return Utf8Renderer}}(params.opts?params.opts.type:void 0);return render(renderer.render,text,params)},server.toDataURL=function toDataURL(text,opts,cb){const params=checkParams(text,opts,cb);return render(getRendererFromType(params.opts.type).renderToDataURL,text,params)},server.toBuffer=function toBuffer(text,opts,cb){const params=checkParams(text,opts,cb);return render(getRendererFromType(params.opts.type).renderToBuffer,text,params)},server.toFile=function toFile(path,text,opts,cb){if("string"!=typeof path||"string"!=typeof text&&"object"!=typeof text)throw new Error("Invalid argument");if(arguments.length<3&&!canPromise())throw new Error("Too few arguments provided");const params=checkParams(text,opts,cb),type=params.opts.type||function getTypeFromFilename(path){return path.slice((path.lastIndexOf(".")-1>>>0)+2).toLowerCase()}(path);return render(getRendererFromType(type).renderToFile.bind(null,path),text,params)},server.toFileStream=function toFileStream(stream,text,opts){if(arguments.length<2)throw new Error("Too few arguments provided");const params=checkParams(text,opts,stream.emit.bind(stream,"error"));render(getRendererFromType("png").renderToFileStream.bind(null,stream),text,params)},server}var QRCode=getDefaultExportFromCjs(function requireLib(){return hasRequiredLib?lib:(hasRequiredLib=1,lib=requireServer())}());class ValidaCPFCNPJ{constructor(){}validarCpfCnpj(cpfCnpj){if(!cpfCnpj||"string"!=typeof cpfCnpj)return{documentoValido:!1,tipoDoDocumento:"Desconhecido"};const clean=cpfCnpj.replace(/[.\-\/\s]/g,"").toUpperCase(),isCpf=/^\d{11}$/.test(clean),isCnpj=/^[A-Z0-9]{12}[0-9]{2}$/.test(clean);return isCpf||isCnpj?isCpf?"00000000000"===clean?{documentoValido:!1,tipoDoDocumento:"CPF"}:this.documentoValidoateCpf(clean)?{documentoValido:!0,tipoDoDocumento:"CPF"}:{documentoValido:!1,tipoDoDocumento:"CPF"}:this.documentoValidoateCnpj(clean)?{documentoValido:!0,tipoDoDocumento:"CNPJ"}:{documentoValido:!1,tipoDoDocumento:"CNPJ"}:{documentoValido:!1,tipoDoDocumento:"Desconhecido"}}documentoValidoateCpf(cpf){let remainder,sum=0;for(let i=1;i<=9;i++)sum+=parseInt(cpf.substring(i-1,i),10)*(11-i);if(remainder=10*sum%11,10!==remainder&&11!==remainder||(remainder=0),remainder!==parseInt(cpf.substring(9,10),10))return!1;sum=0;for(let i=1;i<=10;i++)sum+=parseInt(cpf.substring(i-1,i),10)*(12-i);return remainder=10*sum%11,10!==remainder&&11!==remainder||(remainder=0),remainder===parseInt(cpf.substring(10,11),10)}documentoValidoateCnpj(cnpj){if(!/^[A-Z0-9]{12}[0-9]{2}$/.test(cnpj))return!1;if("00000000000000"===cnpj)return!1;const vals=[];for(let i=0;i<14;i++){const ch=cnpj.charAt(i);if(!/[0-9A-Z]/.test(ch))return!1;vals.push(cnpj.charCodeAt(i)-48)}const pesos1=[5,4,3,2,9,8,7,6,5,4,3,2],pesos2=[6,5,4,3,2,9,8,7,6,5,4,3,2];let soma1=0;for(let i=0;i<12;i++)soma1+=vals[i]*pesos1[i];const resto1=soma1%11,dv1=resto1<2?0:11-resto1;if(dv1!==vals[12])return!1;const valsParaDV2=vals.slice(0,12).concat([dv1]);let soma2=0;for(let i=0;i<13;i++)soma2+=valsParaDV2[i]*pesos2[i];const resto2=soma2%11;return(resto2<2?0:11-resto2)===vals[13]}mascaraCnpjCpf(cpfcnpj){if(!cpfcnpj||"string"!=typeof cpfcnpj)return cpfcnpj;let clean=cpfcnpj.replace(/[.\-\/\s]/g,"").toUpperCase();return 11===clean.length&&/^\d{11}$/.test(clean)?clean.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/,"$1.$2.$3-$4"):14===clean.length?clean.replace(/(.{2})(.{3})(.{3})(.{4})(.{2})/,"$1.$2.$3/$4-$5"):cpfcnpj}}const getDesTipoPag=tPag=>({"01":"Dinheiro","02":"Cheque","03":"Cartão de Crédito","04":"Cartão de Débito","05":"Cartão da Loja (Private Label), Crediário Digital, Outros Crediários",10:"Vale Alimentação",11:"Vale Refeição",12:"Vale Presente",13:"Vale Combustível",14:"Duplicata Mercantil",15:"Boleto Bancário",16:"Depósito Bancário",17:"Pagamento Instantâneo (PIX) - Dinâmico",18:"Transferência bancária, Carteira Digital",19:"Programa de fidelidade, Cashback, Crédito Virtual",20:"Pagamento Instantâneo (PIX) - Estático",21:"Crédito em Loja",22:"Pagamento Eletrônico não Informado - falha de hardware do sistema emissor",90:"Sem Pagamento",99:"Outros"}[tPag]||"Outros"),baseDir=path__default.default.dirname(require$$0$9.fileURLToPath("undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&"SCRIPT"===document.currentScript.tagName.toUpperCase()&&document.currentScript.src||new URL("index.cjs",document.baseURI).href));class NFCEGerarDanfe{data;chave;enviada;outputPath;qrcodePath;documento;protNFe;det;ide;dest;emit;total;transp;pag;infAdic;infNFeSupl;exibirMarcaDaguaDanfe;fontSize;larguraPadrao;documentWidth;itemHeight;doc;constructor(props){const{data:data,chave:chave,outputPath:outputPath,pageWidth:pageWidth}=props;this.data=data,this.chave=chave.trim(),this.outputPath=outputPath,this.enviada=!1,this.qrcodePath=outputPath,this.documento=new ValidaCPFCNPJ,this.protNFe=data.protNFe;const nfeData=Array.isArray(data.NFe)?data.NFe[0]:data.NFe,{det:det,ide:ide,emit:emit,dest:dest,total:total,transp:transp,pag:pag,infAdic:infAdic}=nfeData.infNFe,infNFeSupl=nfeData.infNFeSupl;this.det=det,this.ide=ide,this.emit=emit,this.total=total,this.transp=transp,this.pag=pag,this.infAdic=infAdic,this.infNFeSupl=infNFeSupl,dest&&(this.dest=dest),this.protNFe?.infProt.nProt&&(this.enviada=!0),this.larguraPadrao=226.772,this.documentWidth=pageWidth||226.772;let itensLength=1;this.det instanceof Array&&(itensLength=this.det.length);const fontSize=function calculateFontSize(width){return.02646*Math.min(width)}(this.documentWidth);this.fontSize=fontSize,this.itemHeight=1.116*fontSize;const pageHeight=function calculateHeight(itemsLength,itemHeight){return 204.22975675056+itemsLength*itemHeight+5}(itensLength,this.itemHeight),fontPath=path__default.default.resolve(baseDir,"../resources/fonts/ARIAL.TTF"),fontPathBold=path__default.default.resolve(baseDir,"../resources/fonts/ARIALBD.TTF");this.doc=new PDFDocument__default.default({margins:{top:5.67,right:5.67,bottom:5.67,left:5.67},size:[this.documentWidth,pageHeight],bufferPages:!0,layout:"portrait"}),this.doc.registerFont("Arial",fontPath),this.doc.registerFont("Arial-bold",fontPathBold)}saveQRCode=async text=>{const filePath=path__default.default.resolve(baseDir,this.qrcodePath);try{await QRCode.toFile(`${filePath}/qrcode.png`,text,{color:{dark:"#000000",light:"#FFFFFF"},width:300})}catch(error){console.error("Erro ao gerar o QR code:",error),console.error(error.stack)}};getQRCodeBuffer=async text=>{try{return await QRCode.toBuffer(text,{color:{dark:"#000000",light:"#FFFFFF"},width:300})}catch(error){throw console.error("Erro ao gerar o QR code:",error),console.error(error.stack),new Error(`Erro ao gerar o QR code: ${error.message}`)}};createDir(path){fs__default.default.existsSync(path)||fs__default.default.mkdirSync(path,{recursive:!0})}async generateBarcode(data){try{const barcode=(await bwipjs__default.default.toBuffer({bcid:"code128",text:data,scaleX:4,height:14,includetext:!1})).toString("base64"),buffer=Buffer.from(barcode,"base64"),barcodeDir=this.qrcodePath,barcodeFilePath=path__default.default.join(barcodeDir,"barcode.png");fs__default.default.writeFileSync(barcodeFilePath,buffer)}catch(err){return console.error("Erro ao gerar código de barras:",err),null}}centeredPos(texto){return(this.doc.page.width-this.doc.fontSize(this.fontSize).widthOfString(texto))/2}ajustarPosicao(posicaoOriginal,novaLargura){return posicaoOriginal*(novaLargura/this.larguraPadrao)}calculaPosicao(text){const{right:right,left:left}=this.doc.page.margins,[pageWidth]=this.doc.page.size,textWidth=this.doc.widthOfString(text);return Number(pageWidth)-textWidth-right-left}drawHeader(isFirstPage){this._buildHeader()}drawFooter(qrCodeBuffer){this._buildFooter(qrCodeBuffer)}_buildHeader(){const CNPJCPF=this.emit.CNPJCPF?.toString(),CNPJ=this.emit.CNPJ?.toString(),CPF=this.emit.CPF?.toString(),documento=this.documento.mascaraCnpjCpf(CNPJCPF||CNPJ||CPF||""),identificationJoined=`${this.emit.enderEmit.xLgr}, ${this.emit.enderEmit.nro}, ${this.emit.enderEmit.xBairro}, ${this.emit.enderEmit.UF}`;(()=>{const centeredPosEmit=this.centeredPos(`CNPJ: ${documento} ${this.emit.xNome}`),centeredPosEnd=this.centeredPos(identificationJoined),centeredPosText=this.centeredPos("Documento Auxiliar da Nota Fiscal de Consumidor Eletrônica");this.doc.font("Arial").fontSize(this.fontSize).text(`CNPJ: ${documento} `,centeredPosEmit,2,{lineBreak:!1}).font("Arial-bold").text(this.emit.xNome).fontSize(this.fontSize).font("Arial").text(identificationJoined,centeredPosEnd).text("Documento Auxiliar da Nota Fiscal de Consumidor Eletrônica",centeredPosText)})()}_buildProdutos(){const{right:right,left:left,top:top}=this.doc.page.margins,tableWidth=this.documentWidth-left-right,startX=left,tableTop=this.doc.y+top,columnWidths={codigo:tableWidth*.15,descricao:tableWidth*.4,qtdeUn:tableWidth*.15,unit:tableWidth*.15,total:tableWidth*.15},row=(top,item)=>{const quant=parseFloat(String(item.prod.qCom||item.prod.qTrib)).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3}),valUnit=parseFloat(String(item.prod.vUnCom||item.prod.vUnTrib||"0")).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2}),valLiq=parseFloat(String(item.prod.vProd||"0")).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});let x=startX;this.doc.font("Arial").fontSize(this.fontSize).text(item.prod.cProd,x,top,{width:columnWidths.codigo,align:"left"}),x+=columnWidths.codigo+0;const descricao=item.prod.xProd.slice(0,120),textWidth=this.doc.widthOfString(descricao),lineCount=Math.ceil(textWidth/columnWidths.descricao),descricaoOptions={width:columnWidths.descricao,align:"left",height:this.itemHeight*lineCount};return this.doc.text(descricao,x,top,descricaoOptions),x+=columnWidths.descricao+0,this.doc.text(`${quant} ${item.prod.uCom}`,x,top,{width:columnWidths.qtdeUn,align:"right"}),x+=columnWidths.qtdeUn+0,this.doc.text(valUnit,x,top,{width:columnWidths.unit,align:"right"}),x+=columnWidths.unit+0,this.doc.text(valLiq,x,top,{width:columnWidths.total,align:"right"}),descricaoOptions.height};(top=>{let x=startX;this.doc.font("Arial-bold").fontSize(this.fontSize).text("Código",x,top,{width:columnWidths.codigo}),x+=columnWidths.codigo+0,this.doc.text("Descrição",x,top,{width:columnWidths.descricao}),x+=columnWidths.descricao+0,this.doc.text("Qtde",x,top,{width:columnWidths.qtdeUn,align:"right"}),x+=columnWidths.qtdeUn+0,this.doc.text("Unit",x,top,{width:columnWidths.unit,align:"right"}),x+=columnWidths.unit+0,this.doc.text("Total",x,top,{width:columnWidths.total,align:"right"})})(tableTop);let y=tableTop+this.itemHeight;this.det instanceof Array?this.det.forEach(prod=>{row(y,prod),y+=this.itemHeight}):row(y,this.det)}_buildTotais(){let tableTop=this.doc.y+5;const quantidadeTotalDeItens=Array.isArray(this.det)?this.det.length:1;let valTotal=0,acrescimo=0,desconto=0;Array.isArray(this.det)?(valTotal=this.det.reduce((sum,item)=>sum+parseFloat(item.prod.vProd),0),acrescimo=this.det.reduce((sum,item)=>sum+(parseFloat(item.prod.vFrete||"0")+parseFloat(item.prod.vSeg||"0")+parseFloat(item.prod.vOutro||"0")),0),desconto=this.det.reduce((sum,item)=>sum+parseFloat(item.prod.vDesc||"0"),0)):(valTotal=parseFloat(this.det.prod.vProd),acrescimo=parseFloat(this.det.prod.vFrete||"0")+parseFloat(this.det.prod.vSeg||"0")+parseFloat(this.det.prod.vOutro||"0"),desconto=parseFloat(this.det.prod.vDesc||"0"));const valorTotal=valTotal.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3}),acrescimoTotal=acrescimo.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3}),descontoTotal=desconto.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3});if(this.doc.text("Qtd. total de itens",2,tableTop),this.doc.text(String(quantidadeTotalDeItens),this.calculaPosicao(String(quantidadeTotalDeItens)),tableTop,{align:"right"}),tableTop+=this.itemHeight,this.doc.text("Valor total R$",2,tableTop),this.doc.text(valorTotal,this.calculaPosicao(valorTotal),tableTop,{align:"right"}),tableTop+=this.itemHeight,desconto>0&&(this.doc.text("Desconto R$",2,tableTop),this.doc.text(descontoTotal,this.calculaPosicao(descontoTotal),tableTop,{align:"right"}),tableTop+=this.itemHeight),acrescimo>0&&(this.doc.text("Acréscimo R$",2,tableTop),this.doc.text(acrescimoTotal,this.calculaPosicao(acrescimoTotal),tableTop,{align:"right"}),tableTop+=this.itemHeight),desconto>0||acrescimo>0){const totalPagar=parseFloat(String(valTotal+acrescimo-desconto)).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3});this.doc.font("Arial-bold").text("Valor a Pagar R$",2,tableTop),this.doc.text(totalPagar,this.calculaPosicao(totalPagar),tableTop,{align:"right"})}tableTop+=this.itemHeight+2,this.doc.font("Arial").text("FORMA PAGAMENTO",2,tableTop);let topTiposPag=tableTop;if(Array.isArray(this.pag.detPag))for(let pagto of this.pag.detPag)pagto.xPag||(pagto.xPag=getDesTipoPag(pagto.tPag)),this.doc.text(pagto.xPag||"Não informado",2,topTiposPag+this.itemHeight),topTiposPag+=this.itemHeight;else this.pag.detPag.xPag||(this.pag.detPag.xPag=getDesTipoPag(this.pag.detPag.tPag)),this.doc.text(this.pag.detPag.xPag||"Não informado",2,topTiposPag+this.itemHeight);this.doc.text("VALOR PAGO R$",this.calculaPosicao("VALOR PAGO R$"),tableTop,{align:"right"});let topValPags=tableTop;if(Array.isArray(this.pag.detPag))for(let pagto of this.pag.detPag){const val=parseFloat(pagto.vPag).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3});this.doc.text(val,this.calculaPosicao(val),topValPags+this.itemHeight,{align:"right"}),topValPags+=this.itemHeight}else{const val=parseFloat(this.pag.detPag.vPag).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3});this.doc.text(val,this.calculaPosicao(val),topValPags+this.itemHeight,{align:"right"})}tableTop=topValPags,tableTop+=2*this.itemHeight;let valTroco=0;valTroco=Array.isArray(this.pag.detPag)?this.pag.detPag.reduce((sum,item)=>sum+parseFloat(item.vTroco||"0"),0):parseFloat(this.pag.detPag.vTroco||"0");const troco=valTroco.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3});this.doc.text("Troco R$",2,tableTop),this.doc.text(troco,this.calculaPosicao(troco),tableTop,{align:"right"})}_buildFooter(qrCodeBuffer){let tableTop=this.doc.y+5;this.doc.font("Arial-bold").text("Consulte pela Chave de Acesso em",0,tableTop,{align:"center"}),tableTop+=this.itemHeight,this.doc.font("Arial").text(this.infNFeSupl?.urlChave||"",0,tableTop,{align:"center"}),tableTop+=this.itemHeight,this.doc.text(this.protNFe?.infProt.chNFe||"",0,tableTop,{align:"center"}),tableTop+=this.itemHeight,this.doc.image(qrCodeBuffer,2,tableTop,{width:70.87,height:70.87}),tableTop+=4;let topBeforeQrCode=tableTop;const CNPJCPF=this.documento.mascaraCnpjCpf(this.dest?.CNPJCPF||this.dest?.CNPJ||this.dest?.CPF||this.dest?.idEstrangeiro||""),xNome=this.dest?.xNome??"Sem cliente identificado",xLgr=this.dest?.enderDest?.xLgr??"",nro=this.dest?.enderDest?.nro??"",xBairro=this.dest?.enderDest?.xBairro??null,xMun=this.dest?.enderDest?.xMun??"",UF=this.dest?.enderDest?.UF??"",enderecoStr=[xLgr&&`${xLgr}`,nro&&`${nro}`,xBairro&&`bairro: ${xBairro}`,xMun&&`${xMun}`,UF&&`${UF}`].filter(Boolean).join(", ");CNPJCPF&&""!==CNPJCPF?(this.doc.font("Arial-bold").text(`CONSUMIDOR - DOC ${CNPJCPF}`,75,tableTop,{align:"left",lineGap:1}).font("Arial").text(` - ${xNome}`,{lineGap:1}),tableTop=this.doc.y+4,this.doc.text(enderecoStr,75,tableTop),tableTop=this.doc.y+8):(this.doc.text("CONSUMIDOR NÃO IDENTIFICADO",75,tableTop,{align:"left"}),tableTop=this.doc.y+8);const dtaEmi=format(parseISO(this.ide.dhEmi),"dd/MM/yyyy HH:mm:ss");let dtaAut=format(new Date,"dd/MM/yyyy HH:mm:ss");if(this.protNFe?.infProt.dhRecbto){dtaAut=format(parseISO(this.protNFe?.infProt.dhRecbto),"dd/MM/yyyy HH:mm:ss")}this.doc.font("Arial-bold").text(`NFC-e nº ${this.ide.nNF} Série ${this.ide.serie} ${dtaEmi}`,75,tableTop,{align:"left",lineGap:1}).text("Protocolo de autorização: ",{continued:!0,lineGap:1}).font("Arial").text(this.protNFe?.infProt.nProt||"123").font("Arial-bold").text("Data de autorização ",{continued:!0,lineGap:1}).font("Arial").text(dtaAut),tableTop=this.doc.y+20,topBeforeQrCode+=70.87,this.doc.text(`Tributos Totais Incidentes (Lei Federal 12.741/2012): R$ ${parseFloat(this.total.ICMSTot.vTotTrib||"0").toFixed(2)}`,0,topBeforeQrCode,{align:"center"})}async generatePDF(exibirMarcaDaguaDanfe){try{this.exibirMarcaDaguaDanfe=exibirMarcaDaguaDanfe||!0;const qrCodeBuffer=await this.getQRCodeBuffer(this.infNFeSupl?.qrCode||"");return this.doc.pipe(fs__default.default.createWriteStream(this.outputPath)),this.drawHeader(!0),this._buildProdutos(),this._buildTotais(),this.drawFooter(qrCodeBuffer),this.doc.end(),{message:` DANFE Gerada em '${this.outputPath}'`,success:!0}}catch(error){throw new Error(`Erro ao gerar DANFE: ${error.message}`)}}}class NFEGerarDanfe{data;chave;enviada;outputPath;documento;protNFe;det;ide;dest;emit;total;transp;infAdic;exibirMarcaDaguaDanfe;doc;barcodeBuffer=null;constructor(props){const{data:data,chave:chave,outputPath:outputPath}=props;this.data=data,this.chave=chave.trim(),this.outputPath=outputPath,this.enviada=!1,this.documento=new ValidaCPFCNPJ,this.protNFe=data.protNFe;const nfeData=Array.isArray(data.NFe)?data.NFe[0]:data.NFe,{det:det,ide:ide,emit:emit,dest:dest,total:total,transp:transp,infAdic:infAdic}=nfeData.infNFe;this.det=det,this.ide=ide,this.emit=emit,this.total=total,this.transp=transp,this.infAdic=infAdic,dest&&(this.dest=dest),this.protNFe?.infProt.nProt&&(this.enviada=!0),this.doc=new PDFDocument__default.default({margins:{top:22,right:22.68,bottom:12,left:5.67},size:"a4",bufferPages:!0,layout:"portrait",font:"Times-Roman"})}async generateBarcode(data){try{const pngBuffer=await bwipjs__default.default.toBuffer({bcid:"code128",text:data,scaleX:4,height:14,includetext:!1});return this.barcodeBuffer=pngBuffer,pngBuffer}catch(err){return console.error("Erro ao gerar código de barras:",err),this.barcodeBuffer=null,null}}setLineStyle(lineWidth,strokeColor){this.doc.lineWidth(lineWidth).strokeColor(strokeColor).fill("black")}drawHeader(isFirstPage){isFirstPage?(this._buildGuia(),this._buildSeparator(),this._buildHeader(52)):this._buildHeader(0)}drawFooter(){this._buildFooter()}_buildGuia(){const{top:top,left:left}=this.doc.page.margins;this.setLineStyle(.75,"#1c1c1c"),this.doc.rect(left,top,470,21).stroke(),this.doc.fontSize(5).text(`RECEBEMOS DE ${this.emit.xNome} OS PRODUTOS / SERVIÇOS CONSTANTES DA NOTA FISCAL INDICADO AO LADO`,10,26,{characterSpacing:.5}),this.doc.fontSize(6).text(`EMISSÃO: ${format(new Date(this.ide.dhEmi),"dd-MM-yyyy")} - DEST. / REM.: ${this.dest?.xNome||""} - VALOR TOTAL: R$ ${parseFloat(String(this.total.ICMSTot.vNF)).toFixed(2)}`,10,33.5,{characterSpacing:.5}),this.doc.rect(left+470,top,96.93,42).stroke(),this.doc.fontSize(11).text("NF-e",480,27,{characterSpacing:1.5,align:"center"}),this.doc.fontSize(8.8).font("Times-Bold").text(`Nº ${String(this.ide.nNF).padStart(2,"0")}`,480,40.5,{characterSpacing:1.5,align:"center"}),this.doc.fontSize(8.5).font("Times-Roman").text(`SÉRIE ${this.ide.serie.padStart(3,"0")}`,480,53,{characterSpacing:1.5,align:"center"}),this.doc.rect(left,top+21,75,21).stroke(),this.doc.fontSize(5).text("DATA DE RECEBIMENTO",10,46.5,{characterSpacing:.5}),this.doc.rect(left+75,top+21,395,21).stroke(),this.doc.fontSize(5).text("IDENTIFICAÇÃO E ASSINATURA DO RECEBEDOR",85,46.5,{characterSpacing:.5})}_buildSeparator(){const{left:left,right:right}=this.doc.page.margins,lineWidth=595.28-left-right;this.doc.moveTo(left,69).lineTo(left+lineWidth,69).lineWidth(1).dash(1.5,{space:1.5}).strokeColor("black").stroke(),this.doc.undash()}_buildHeader(pos){const{top:top,left:left}=this.doc.page.margins,page=this.doc.bufferedPageRange(),CNPJCPF=this.emit.CNPJCPF?.toString(),CNPJ=this.emit.CNPJ?.toString(),CPF=this.emit.CPF?.toString(),documento=this.documento.mascaraCnpjCpf(CNPJCPF||CNPJ||CPF||"");this.setLineStyle(.75,"#1c1c1c");const topIdentificacao_1=top+pos,identificationJoined=`\nCEP: ${this.emit.enderEmit.CEP} - ${this.emit.enderEmit.xBairro} - ${this.emit.enderEmit.UF}\nTEL: ${this.emit.enderEmit.fone} - FAX: ${this.emit.enderEmit.fone}`;(()=>{this.doc.rect(left,topIdentificacao_1,197.5,98).stroke(),this.doc.fontSize(5).text("IDENTIFICAÇÃO DO EMITENTE",10,topIdentificacao_1+3.5,{characterSpacing:.5}),this.doc.fontSize(8).font("Times-Bold").text(this.emit.xNome,35,topIdentificacao_1+14,{characterSpacing:1,width:170,lineBreak:!0,lineGap:4}),this.doc.fontSize(7).font("Times-Roman").text(`${this.emit.enderEmit.xLgr}, ${this.emit.enderEmit.nro} ${this.emit.xFant?`- ${this.emit.xFant}`:""}`,10,topIdentificacao_1+44,{characterSpacing:1,width:181,lineBreak:!0,lineGap:2,continued:!0}).text(identificationJoined)})(),(()=>{this.doc.rect(left+197.5,topIdentificacao_1,112.7,98).stroke(),this.doc.fontSize(12).font("Times-Bold").text("DANFE",203,topIdentificacao_1+8,{characterSpacing:1.5,width:112.7,align:"center"}),this.doc.fontSize(6).text("DOCUMENTO AUXILIAR DA NOTA FISCAL ELETRÔNICA",215,topIdentificacao_1+20,{characterSpacing:.5,width:95,align:"left",lineGap:2}),this.doc.fontSize(8).font("Times-Roman").text("0 - ENTRADA",217,topIdentificacao_1+40,{characterSpacing:.5,align:"left"}),this.doc.fontSize(8).text("1 - SAÍDA",217,topIdentificacao_1+50,{characterSpacing:.5,align:"left"}),this.doc.rect(left+275,topIdentificacao_1+38,18,18).stroke(),this.doc.fontSize(14).font("Times-Bold").text(String(this.ide.tpNF),left+280,topIdentificacao_1+42.5),this.doc.fontSize(8.8).text(`Nº ${String(this.ide.nNF).padStart(2,"0")}`,208,topIdentificacao_1+65,{characterSpacing:1}),this.doc.fontSize(10).font("Times-Roman").text(`fl. ${page.start+1}/${page.count}`,240,topIdentificacao_1+65,{characterSpacing:1.5,width:112.7,align:"center"}),this.doc.fontSize(8.8).text(`SÉRIE ${this.ide.serie.padStart(3,"0")}`,208,topIdentificacao_1+78,{characterSpacing:1.5,width:112.7,align:"center"})})(),(()=>{if(this.doc.rect(left+310.2,topIdentificacao_1,256.73,35).stroke(),this.barcodeBuffer?this.doc.image(this.barcodeBuffer,left+323.5,topIdentificacao_1+3,{width:230,height:30}):this.doc.fontSize(8).fillColor("red").text("Erro ao carregar barcode",left+316,topIdentificacao_1+12,{width:256.73,align:"center"}),2===Number(this.ide.tpAmb)||this.enviada||this.data.forceTransmitida||this.doc.fontSize(14).font("Times-Bold").fillColor("red").text("NF-E NÃO ENVIADA PARA SEFAZ",left+316,topIdentificacao_1+12,{characterSpacing:1,width:256.73}),this.setLineStyle(.75,"#1c1c1c"),this.doc.rect(left+310.2,topIdentificacao_1+35,256.73,23).stroke(),this.doc.fontSize(5).font("Times-Roman").text("CHAVE DE ACESSO",left+314,topIdentificacao_1+38,{characterSpacing:.5}),this.doc.fontSize(6).text(this.chave,left+310.2,topIdentificacao_1+47,{characterSpacing:1,width:256.73,align:"center"}),this.doc.rect(left+310.2,topIdentificacao_1+58,256.73,40).stroke(),(2===Number(this.ide.tpAmb)||this.enviada)&&(this.doc.fontSize(6.5).text("Consulta de autenticidade no portal nacional da NF-e",left+310.2,topIdentificacao_1+65,{characterSpacing:.5,width:256.73,align:"center"}),this.doc.fontSize(6.5).text("www.nfe.fazenda.gov.br/portal",left+310.2,topIdentificacao_1+75,{characterSpacing:.5,width:256.73,align:"center"}),this.doc.fontSize(6.5).text("ou no site da Sefaz Autorizadora",left+310.2,topIdentificacao_1+85,{characterSpacing:.5,width:256.73,align:"center"})),this.doc.rect(left,topIdentificacao_1+98,310.2,23).stroke(),this.doc.fontSize(5).text("NATUREZA DE OPERAÇÃO",left+4,topIdentificacao_1+102,{characterSpacing:.5}),this.doc.fontSize(8).text(this.ide.natOp,left+4,topIdentificacao_1+112,{characterSpacing:1}),this.doc.rect(left+310.2,topIdentificacao_1+98,256.73,23).stroke(),2===Number(this.ide.tpAmb)||this.enviada){let dhRecbto="";this.protNFe?.infProt.dhRecbto&&(dhRecbto=format(new Date(this.protNFe?.infProt.dhRecbto),"dd/MM/yyyy HH:mm:ss"));const xProtNfe=`${String(this.protNFe?.infProt.nProt||"")} ${dhRecbto}`;this.doc.fontSize(5).text("PROTOCOLO DE AUTORIZAÇÃO DE USO",left+314.2,topIdentificacao_1+102,{characterSpacing:.5}),this.doc.fontSize(8).text(xProtNfe,left+314.2,topIdentificacao_1+112,{characterSpacing:1})}})(),(()=>{this.doc.rect(left,topIdentificacao_1+121,189.5,23).stroke(),this.doc.fontSize(5).text("INSCRIÇÃO ESTADUAL",left+4,topIdentificacao_1+125,{characterSpacing:.5}),this.doc.fontSize(8).text(this.emit.IE,left+5,topIdentificacao_1+135,{characterSpacing:1}),this.doc.rect(left+189.5,topIdentificacao_1+121,187.93,23).stroke(),this.doc.fontSize(5).text("INSCRIÇÃO ESTADUAL DO SUBST. TRIB.",left+193.5,topIdentificacao_1+125,{characterSpacing:.5}),this.doc.fontSize(8).text(String(this.emit.IEST||""),left+194.5,topIdentificacao_1+135,{characterSpacing:1}),this.doc.rect(left+377.43,topIdentificacao_1+121,189.5,23).stroke(),this.doc.fontSize(5).text("CNPJ / CPF",left+381.43,topIdentificacao_1+125,{characterSpacing:.5}),this.doc.fontSize(8).text(documento,left+386.43,topIdentificacao_1+135,{characterSpacing:1})})()}_buildDestinatario(){const{top:top,left:left}=this.doc.page.margins,docDest=this.documento.mascaraCnpjCpf(this.dest?.CNPJCPF||this.dest?.CNPJ||this.dest?.CPF||"");this.setLineStyle(.75,"#1c1c1c");const topDestinatario=top+90;this.doc.fontSize(6).font("Times-Bold").text("DESTINATÁRIO / REMETENTE",left,topDestinatario+114,{characterSpacing:.5}),(()=>{this.doc.rect(left,topDestinatario+120,398,23).stroke();let xNome="NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL";2!==Number(this.ide.tpAmb)&&(xNome=String(this.dest?.xNome||"")),this.doc.fontSize(5).font("Times-Roman").text("NOME / RAZÃO SOCIAL",left+4,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(xNome,left+5,topDestinatario+135,{characterSpacing:1}),this.doc.rect(left+398,topDestinatario+120,94,23).stroke(),this.doc.fontSize(5).text("CNPJ / CPF",left+402,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(docDest,left+403,topDestinatario+135,{characterSpacing:1}),this.doc.rect(left+492,topDestinatario+120,74.3,23).stroke(),this.doc.fontSize(5).text("DATA DA EMISSÃO",left+496,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(format(new Date(this.ide.dhEmi),"dd-MM-yyyy"),left+497,topDestinatario+135,{characterSpacing:1})})(),(()=>{this.doc.rect(left,topDestinatario+143,320,23).stroke(),this.doc.fontSize(5).text("ENDEREÇO",left+4,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(`${this.dest?.enderDest?.xLgr||""}, ${this.dest?.enderDest?.nro||""}`,left+5,topDestinatario+158,{characterSpacing:1}),this.doc.rect(left+320,topDestinatario+143,118.5,23).stroke(),this.doc.fontSize(5).text("BAIRRO / DISTRITO",left+324,topDestinatario+148,{characterSpacing:.5});const bairroText=String(this.dest?.enderDest?.xBairro||"");let fontSizeToUse=8,charSpacingToUse=1;bairroText.length>22&&(fontSizeToUse=5.5,charSpacingToUse=.25);const textLineHeight=this.doc.currentLineHeight(),cellContentYBase=topDestinatario+158;let yPosForBairro=cellContentYBase;textLineHeight<13&&(yPosForBairro=cellContentYBase-(13-textLineHeight)/2+.3*textLineHeight),yPosForBairro=topDestinatario+158,this.doc.font("Times-Roman").fontSize(fontSizeToUse),this.doc.text(bairroText,left+320+3,yPosForBairro,{characterSpacing:charSpacingToUse,width:110,lineBreak:!1,ellipsis:!0}),this.doc.font("Times-Roman").fontSize(8),this.doc.rect(left+438.5,topDestinatario+143,53.5,23).stroke(),this.doc.fontSize(5).text("CEP",left+442.5,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(String(this.dest?.enderDest?.CEP||""),left+443.5,topDestinatario+158,{characterSpacing:1}),this.doc.rect(left+492,topDestinatario+143,74.3,23).stroke(),this.doc.fontSize(5).text("DATA SAÍDA / ENTRADA",left+496,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(format(new Date,"dd-MM-yyyy"),left+497,topDestinatario+158,{characterSpacing:1})})(),(()=>{this.doc.rect(left,topDestinatario+166,246.5,23).stroke(),this.doc.fontSize(5).text("MUNICÍPIO",left+4,topDestinatario+171,{characterSpacing:.5}),this.doc.fontSize(8).text(String(this.dest?.enderDest?.xMun||""),left+5,topDestinatario+181,{characterSpacing:1}),this.doc.rect(left+246.5,topDestinatario+166,113,23).stroke(),this.doc.fontSize(5).text("FONE / FAX",left+250.5,topDestinatario+171,{characterSpacing:.5}),this.doc.fontSize(8).text(this.dest?.enderDest?.fone||"",left+250.5,topDestinatario+181,{characterSpacing:1}),this.doc.rect(left+359.5,topDestinatario+166,40,23).stroke(),this.doc.fontSize(5).text("UF",left+363.5,topDestinatario+171,{characterSpacing:.5}),this.doc.fontSize(8).text(String(this.dest?.enderDest?.UF||""),left+363.5,topDestinatario+181,{characterSpacing:1}),this.doc.rect(left+399.5,topDestinatario+166,92.5,23).stroke(),this.doc.fontSize(5).text("INSCRIÇÃO ESTADUAL",left+403.5,topDestinatario+171,{characterSpacing:.5}),this.doc.fontSize(8).text(String(this.dest?.indIEDest||""),left+403.5,topDestinatario+181,{characterSpacing:1}),this.doc.rect(left+492,topDestinatario+166,74.3,23).stroke(),this.doc.fontSize(5).text("HORA DA SAÍDA",left+496,topDestinatario+171,{characterSpacing:.5}),this.doc.fontSize(8).text(format(new Date,"HH:mm"),left+497,topDestinatario+181,{characterSpacing:1})})()}_builCalculoImposto(){const{top:top,left:left}=this.doc.page.margins;this.setLineStyle(.75,"#1c1c1c");const topDestinatario=top+173;this.doc.fontSize(6).font("Times-Bold").text("CÁLCULO DO IMPOSTO",left,topDestinatario+114,{characterSpacing:.5}),(()=>{this.doc.rect(left,topDestinatario+120,86,23).stroke(),this.doc.fontSize(5).font("Times-Roman").text("BASE DE CÁLCULO DO ICMS",left+4,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vBC)).toFixed(2),left-8,topDestinatario+135,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+86,topDestinatario+120,79,23).stroke(),this.doc.fontSize(5).text("VALOR DO ICMS",left+90,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vICMS)).toFixed(2),left+86-16,topDestinatario+135,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+165,topDestinatario+120,79,23).stroke(),this.doc.fontSize(5).text("BASE CÁLC. ICMS SUBST",left+169,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vBCST)).toFixed(2),left+165-16,topDestinatario+135,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+244,topDestinatario+120,79,23).stroke(),this.doc.fontSize(5).text("VALOR DO ICMS SUBST.",left+248,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vST)).toFixed(2),left+244-16,topDestinatario+135,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+323,topDestinatario+120,91,23).stroke(),this.doc.fontSize(5).text("VALOR APROX. DOS TRIBUTOS",left+327,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(this.total.ICMSTot.vTotTrib||"0").toFixed(2),left+323-6,topDestinatario+135,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+414,topDestinatario+120,152.93,23).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.fontSize(5).text("VALOR TOTAL DOS PRODUTOS",left+418,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vProd)).toFixed(2),left+480-8,topDestinatario+135,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left,topDestinatario+143,86,23).stroke(),this.doc.fontSize(5).text("VALOR DO FRETE",left+4,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vFrete)).toFixed(2),left-8,topDestinatario+158,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+86,topDestinatario+143,79,23).stroke(),this.doc.fontSize(5).text("VALOR DO SEGURO",left+90,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vSeg)).toFixed(2),left+86-16,topDestinatario+158,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+165,topDestinatario+143,79,23).stroke(),this.doc.fontSize(5).text("DESCONTO",left+169,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vDesc)).toFixed(2),left+165-16,topDestinatario+158,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+244,topDestinatario+143,79,23).stroke(),this.doc.fontSize(5).text("OUTRAS DESP. ACESS.",left+248,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vOutro)).toFixed(2),left+244-16,topDestinatario+158,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+323,topDestinatario+143,91,23).stroke(),this.doc.fontSize(5).text("VALOR DO IPI",left+327,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vIPI)).toFixed(2),left+323-6,topDestinatario+158,{characterSpacing:1,align:"right",width:86}),this.doc.rect(left+414,topDestinatario+143,152.93,23).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.fontSize(5).text("VALOR TOTAL DA NOTA",left+418,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(parseFloat(String(this.total.ICMSTot.vNF)).toFixed(2),left+480-8,topDestinatario+158,{characterSpacing:1,align:"right",width:86})})()}_builTransporte(){const{top:top,left:left}=this.doc.page.margins;this.setLineStyle(.75,"#1c1c1c");const topDestinatario=top+233,getModFrete=()=>{const modFrete=parseInt(String(this.transp.modFrete));switch(modFrete){case 0:case 3:return`${modFrete} - REMETENTE`;case 1:case 4:return`${modFrete} - DESTINATÁRIO`;case 2:return`${modFrete} - TERCEIROS`;case 9:return`${modFrete} - SEM FRETE`;default:return""}};this.doc.fontSize(6).font("Times-Bold").text("TRANSPORTADOR / VOLUMES TRANSPORTADOS",left,topDestinatario+114,{characterSpacing:.5}),(()=>{const documento=this.documento.mascaraCnpjCpf(this.transp.transporta?.CNPJCPF||this.transp.transporta?.CNPJ||this.transp.transporta?.CPF||"");this.doc.rect(left,topDestinatario+120,248.5,23).stroke(),this.doc.fontSize(5).font("Times-Roman").text("RAZÃO SOCIAL",left+4,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp.transporta?.xNome||"",left+5,topDestinatario+135,{characterSpacing:1,width:246}),this.doc.rect(left+248.5,topDestinatario+120,90,23).stroke(),this.doc.fontSize(5).text("FRETE POR CONTA",left+252.5,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(getModFrete(),left+253.5,topDestinatario+135,{characterSpacing:1}),this.doc.rect(left+338.5,topDestinatario+120,50,23).stroke(),this.doc.fontSize(5).text("CÓDIGO ANTT",left+342.5,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp?.veicTransp?.RNTC||"",left+343.5,topDestinatario+135,{characterSpacing:1}),this.doc.rect(left+388.5,topDestinatario+120,62,23).stroke(),this.doc.fontSize(5).text("PLACA DO VEÍCULO",left+391.5,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp?.veicTransp?.placa||"",left+393.5,topDestinatario+135,{characterSpacing:1}),this.doc.rect(left+450.5,topDestinatario+120,22,23).stroke(),this.doc.fontSize(5).text("UF",left+454.5,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp?.transporta?.UF||"",left+455.5,topDestinatario+135,{characterSpacing:1}),this.doc.rect(left+472.5,topDestinatario+120,94.43,23).stroke(),this.doc.fontSize(5).text("CNPJ / CPF",left+476.5,topDestinatario+125,{characterSpacing:.5}),this.doc.fontSize(8).text(documento,left+477.5,topDestinatario+135,{characterSpacing:1}),this.doc.rect(left,topDestinatario+143,338.5,23).stroke(),this.doc.fontSize(5).text("ENDEREÇO",left+4,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp.transporta?.xEnder||"",left+4,topDestinatario+158,{characterSpacing:1}),this.doc.rect(left+338.5,topDestinatario+143,112,23).stroke(),this.doc.fontSize(5).text("MUNICÍPIO",left+342.5,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp.transporta?.xMun||"",left+343.5,topDestinatario+158,{characterSpacing:1}),this.doc.rect(left+450.5,topDestinatario+143,22,23).stroke(),this.doc.fontSize(5).text("UF",left+454.5,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp?.transporta?.UF||"",left+455.5,topDestinatario+158,{characterSpacing:1}),this.doc.rect(left+472.5,topDestinatario+143,94.43,23).stroke(),this.doc.fontSize(5).text("INSCRIÇÃO ESTADUAL",left+476.5,topDestinatario+148,{characterSpacing:.5}),this.doc.fontSize(8).text(this.transp?.transporta?.IE||"",left+476.5,topDestinatario+158,{characterSpacing:1})})(),(()=>{if(this.transp.vol){let topTrnasport=topDestinatario+166,topTrnasportTitle=topDestinatario+171,topTrnasportValue=topDestinatario+181;const createVolume=vol=>{this.doc.rect(left,topTrnasport,68.5,23).stroke(),this.doc.fontSize(5).text("QUANTIDADE",left+4,topTrnasportTitle,{characterSpacing:.5}),this.doc.fontSize(8).text(String(vol?.qVol||""),left-8,topTrnasportValue,{characterSpacing:1,align:"right",width:68.5}),this.doc.rect(left+68.5,topTrnasport,100.5,23).stroke(),this.doc.fontSize(5).text("ESPÉCIE",left+72.5,topTrnasportTitle,{characterSpacing:.5}),this.doc.fontSize(8).text(String(vol?.esp||""),left+73.5,topTrnasportValue,{characterSpacing:1}),this.doc.rect(left+169,topTrnasport,100.5,23).stroke(),this.doc.fontSize(5).text("MARCA",left+173,topTrnasportTitle,{characterSpacing:.5}),this.doc.fontSize(8).text(String(vol?.marca||""),left+174,topTrnasportValue,{characterSpacing:1}),this.doc.rect(left+269.5,topTrnasport,100.5,23).stroke(),this.doc.fontSize(5).text("NUMERAÇÃO",left+273.5,topTrnasportTitle,{characterSpacing:.5}),this.doc.fontSize(8).text(String(vol?.nVol||""),left+274.5,topTrnasportValue,{characterSpacing:1}),this.doc.rect(left+370,topTrnasport,102.6,23).stroke(),this.doc.fontSize(5).text("PESO BRUTO",left+374,topTrnasportTitle,{characterSpacing:.5}),this.doc.fontSize(8).text(String(vol?.nVol||""),left+375,topTrnasportValue,{characterSpacing:1}),this.doc.rect(left+472.5,topTrnasport,94.43,23).stroke(),this.doc.fontSize(5).text("PESO LÍQUIDO",left+474.5,topTrnasportTitle,{characterSpacing:.5}),this.doc.fontSize(8).text(String(vol?.nVol||""),left+475.5,topTrnasportValue,{characterSpacing:1}),topTrnasport+=23,topTrnasportTitle+=23,topTrnasportValue+=23};if(this.transp.vol instanceof Array)for(let vol of this.transp.vol)createVolume(vol);else createVolume(this.transp.vol)}})()}_buildProdutos(){const{top:top,left:left}=this.doc.page.margins;this.setLineStyle(.75,"#1c1c1c"),this.doc.fontSize(6).font("Times-Bold").fillColor("black").text("DADOS DO PRODUTO / SERVIÇOS",left,452,{characterSpacing:.5});let y=458,currentPage=0;const header=top=>{this.doc.rect(left,top,40,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.font("Times-Roman").fontSize(5.7).text("CÓDIGO DO PROD. / SERV",left,top+2.8,{width:40,align:"center"}),this.doc.rect(left+40,top,138,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("DESCRIÇÃO DO PRODUTO / SERVIÇO",left+40,top+5.9,{width:138,align:"center"}),this.doc.rect(left+178,top,30,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("NCM / SH",left+178,top+5.9,{width:30,align:"center"}),this.doc.rect(left+208,top,17,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("CST",left+208,top+5.9,{width:17,align:"center"}),this.doc.rect(left+225,top,28,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("CFOP",left+225,top+5.9,{width:28,align:"center"}),this.doc.rect(left+253,top,23,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("UNID.",left+253,top+5.9,{width:23,align:"center"}),this.doc.rect(left+276,top,25,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("QUANT.",left+276,top+5.9,{width:25,align:"center"}),this.doc.rect(left+301,top,37.23,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("VALOR UNITÁRIO",left+301,top+2.9,{width:37.23,align:"center"}),this.doc.rect(left+338.23,top,39.23,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("VALOR DESCONTO",left+338.23,top+2.9,{width:39.23,align:"center"}),this.doc.rect(left+377.46,top,33.23,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("VALOR LIQUIDO",left+377.46,top+2.9,{width:33.23,align:"center"}),this.doc.rect(left+410.69,top,38,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("BASE CÁLC. ICMS",left+413.8,top+2.9,{width:32,align:"center"}),this.doc.rect(left+448.69,top,35,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("VALOR I.C.M.S.",left+448.69,top+2.9,{width:35,align:"center"}),this.doc.rect(left+483.69,top,38,15).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("VALOR I.P.I.",left+490.69,top+2.9,{width:25,align:"center"}),this.doc.rect(left+521.69,top,45.2,7.5).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("ALÍQUOTAS",left+521.69,top+2,{width:45,align:"center"}),this.doc.rect(left+521.69,top+7.5,22.5,7.5).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("ICMS",left+521.69,top+9.5,{width:22.5,align:"center"}),this.doc.rect(left+544.19,top+7.5,22.75,7.5).fillAndStroke("#DDDDDD","#1c1c1c"),this.setLineStyle(.75,"#1c1c1c"),this.doc.text("IPI",left+544.19,top+9.5,{width:22.5,align:"center"})},row=(top,item)=>{const CST=function getCST(ICMS){const chavesICMS=Object.keys(ICMS),icmsSemCST=["ICMSSN101","ICMSSN102","ICMSSN201","ICMSSN202","ICMSSN500","ICMSSN900"].includes(chavesICMS[0]);let CST="";if(chavesICMS.length>0){const tipoICMS=chavesICMS[0];icmsSemCST||(CST=ICMS[tipoICMS].CST)}return CST}(item.imposto.ICMS),{vIPI:vIPI,pIPI:pIPI}=function getValoresIPI(IPI){return IPI?{vIPI:parseFloat(String(IPI.IPITrib.vIPI)).toFixed(2),pIPI:parseFloat(String(IPI.IPITrib.pIPI)).toFixed(2)}:{vIPI:"0,00",pIPI:"0,00"}}(item.imposto.IPI),{vBC:vBC,vICMS:vICMS,pICMS:pICMS}=function getValoresItem(ICMS){const chavesICMS=Object.keys(ICMS),icmsSemvBC=["ICMS02","ICMS15","ICMS30","ICMS40","ICMS53","ICMS60","ICMS61","ICMSST","ICMSSN101","ICMSSN102","ICMSSN201","ICMSSN202","ICMSSN500"].includes(chavesICMS[0]);let vBC="0,00",vICMS="0,00",pICMS="0,00";if(chavesICMS.length>0){const tipoICMS=chavesICMS[0];if(!icmsSemvBC)return vBC=ICMS[tipoICMS].vBC,vICMS=ICMS[tipoICMS].vICMS,pICMS=ICMS[tipoICMS].pICMS,{vBC:parseFloat(vBC).toFixed(2),vICMS:parseFloat(vBC).toFixed(2),pICMS:parseFloat(pICMS).toFixed(2)}}return{vBC:vBC,vICMS:vICMS,pICMS:pICMS}}(item.imposto.ICMS),text=item.infAdProd?`${item.prod.xProd||""}\n${item.infAdProd}`:item.prod.xProd||"",textHeight=this.doc.heightOfString(text,{width:138,align:"center"}),itemHeight=Math.max(15,textHeight+10);this.setLineStyle(.75,"#1c1c1c"),this.doc.rect(left,top,40,itemHeight).stroke(),this.doc.font("Times-Roman").fontSize(6).text(item.prod.cProd||"",left+2,top+3,{width:40}),this.doc.rect(left+40,top,138,itemHeight).stroke(),this.doc.text(text,left+43,top+4,{width:137}),this.doc.rect(left+178,top,30,itemHeight).stroke(),this.doc.text(String(item.prod.NCM)||"",left+178,top+5.9,{width:30,align:"center"}),this.doc.rect(left+208,top,17,itemHeight).stroke(),this.doc.text(CST,left+208,top+5.9,{width:17,align:"center"}),this.doc.rect(left+225,top,28,itemHeight).stroke(),this.doc.text(String(item.prod.CFOP||""),left+225,top+5.9,{width:28,align:"center"}),this.doc.rect(left+253,top,23,itemHeight).stroke(),this.doc.text(item.prod.uCom||item.prod.uTrib||"",left+256,top+5.9,{width:23});const quant=parseFloat(String(item.prod.qCom||item.prod.qTrib)).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:3});this.doc.rect(left+276,top,25,itemHeight).stroke(),this.doc.text(String(quant||""),left+274.5,top+5.9,{width:25,align:"right"});const valUnit=parseFloat(String(item.prod.vUnCom||item.prod.vUnTrib||"0")).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});this.doc.rect(left+301,top,37.23,itemHeight).stroke(),this.doc.text(valUnit,left+299.5,top+5.9,{width:37.23,align:"right"});const valDesc=parseFloat(String(item.prod.vDesc||"0")).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});this.doc.rect(left+338.23,top,39.23,itemHeight).stroke(),this.doc.text(valDesc,left+336.73,top+5.9,{width:39.23,align:"right"});const valLiq=parseFloat(String(item.prod.vProd||"0")).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});return this.doc.rect(left+377.46,top,33.23,itemHeight).stroke(),this.doc.text(valLiq,left+375.96,top+5.9,{width:33.23,align:"right"}),this.doc.rect(left+410.69,top,38,itemHeight).stroke(),this.doc.text(vBC,left+409.19,top+5.9,{width:38,align:"right"}),this.doc.rect(left+448.69,top,35,itemHeight).stroke(),this.doc.text(vICMS,left+447.19,top+5.9,{width:35,align:"right"}),this.doc.rect(left+483.69,top,38,itemHeight).stroke(),this.doc.text(vIPI,left+482.19,top+5.9,{width:38,align:"right"}),this.doc.rect(left+521.69,top,22.5,itemHeight).stroke(),this.doc.text(pICMS,left+520.19,top+5.9,{width:22.5,align:"right"}),this.doc.rect(left+544.19,top,22.75,itemHeight).stroke(),this.doc.text(pIPI,left+542.69,top+5.9,{width:22.5,align:"right"}),itemHeight};header(458);const createTable=prod=>{y+15>this.doc.page.height-160&&(this.doc.addPage(),currentPage++,currentPage>0&&(y=185,this.doc.fontSize(6).font("Times-Bold").fillColor("black").text("DADOS DO PRODUTO / SERVIÇOS",left,175,{characterSpacing:.5}),header(185)));const itemHeight=row(y+15,prod);y+=itemHeight};if(this.det instanceof Array)for(let i=0;i<this.det.length;i++){createTable(this.det[i])}else createTable(this.det)}_buildFooter(){const{left:left}=this.doc.page.margins;this.setLineStyle(.75,"#1c1c1c");if(this.doc.fontSize(6).font("Times-Bold").text("DADOS ADICIONAIS",left,726.95,{characterSpacing:.5}),this.doc.rect(left,731.95,408,95).stroke(),this.doc.fontSize(5).font("Times-Roman").text("INFORMAÇÕES COMPLEMENTARES",10,736.45,{characterSpacing:.5}),this.doc.fontSize(8).text(this.infAdic?.infCpl||"",13,744.95,{characterSpacing:1,width:400}),this.doc.rect(left+408,731.95,158.93,95).stroke(),this.doc.fontSize(5).text("RESERVADO AO FISCO",418,736.45,{characterSpacing:.5}),this.doc.fontSize(8).text(String(this.infAdic?.infAdFisco||""),13,744.95,{characterSpacing:1,width:400}),this.exibirMarcaDaguaDanfe){const topPosition=2!==Number(Number(this.ide.tpAmb))?769.95:789.95,leftPosition=2!==Number(Number(this.ide.tpAmb))?left+150:left+100;this.doc.fontSize(26).font("Times-Bold").fillColor("#c7c7c7").text("NFeWizard-io",leftPosition,topPosition,{characterSpacing:.5})}2===Number(Number(this.ide.tpAmb))&&this.doc.fontSize(14).font("Times-Bold").fillColor("grey").text("AMBIENTE DE HOMOLOGAÇÃO - NF-E SEM VALOR FISCAL",left+100,776.95,{characterSpacing:1})}async generatePDF(exibirMarcaDaguaDanfe){try{this.exibirMarcaDaguaDanfe=exibirMarcaDaguaDanfe??!0;const chave=this.chave;return await this.generateBarcode(chave),this.doc.pipe(fs__default.default.createWriteStream(this.outputPath)),this.drawHeader(!0),this._buildDestinatario(),this._builCalculoImposto(),this._builTransporte(),this.doc.on("pageAdded",()=>{this.drawHeader(!1)}),this.drawFooter(),this.doc.on("pageAdded",()=>{this.drawFooter()}),this._buildProdutos(),this.doc.end(),{message:` DANFE Gerada em '${this.outputPath}'`,success:!0}}catch(error){throw new Error(`Erro ao gerar DANFE: ${error.message}`)}}}class NFCEAutorizacao{nfceAutorizacaoService;constructor(nfceAutorizacaoService){this.nfceAutorizacaoService=nfceAutorizacaoService}async Exec(data){return await this.nfceAutorizacaoService.Exec(data)}}class NFERecepcaoEvento$1{nfeDistribuicaoDFeService;constructor(nfeDistribuicaoDFeService){this.nfeDistribuicaoDFeService=nfeDistribuicaoDFeService}async Exec(data){return await this.nfeDistribuicaoDFeService.Exec(data)}}class NFEDistribuicaoDFePorChave{nfeDistribuicaoDFePorChaveService;constructor(nfeDistribuicaoDFePorChaveService){this.nfeDistribuicaoDFePorChaveService=nfeDistribuicaoDFePorChaveService}async Exec(data){return await this.nfeDistribuicaoDFePorChaveService.Exec(data)}}class NFEDistribuicaoDFePorNSU{nfeDistribuicaoDFePorNSUService;constructor(nfeDistribuicaoDFePorNSUService){this.nfeDistribuicaoDFePorNSUService=nfeDistribuicaoDFePorNSUService}async Exec(data){return await this.nfeDistribuicaoDFePorNSUService.Exec(data)}}class NFEDistribuicaoDFePorUltNSU{nfeDistribuicaoDFePorUltNSUService;constructor(nfeDistribuicaoDFePorUltNSUService){this.nfeDistribuicaoDFePorUltNSUService=nfeDistribuicaoDFePorUltNSUService}async Exec(data){return await this.nfeDistribuicaoDFePorUltNSUService.Exec(data)}}class CTEDistribuicaoDFe{cteDistribuicaoDFeService;constructor(cteDistribuicaoDFeService){this.cteDistribuicaoDFeService=cteDistribuicaoDFeService}async Exec(data){return await this.cteDistribuicaoDFeService.Exec(data)}}
|
|
9
|
-
/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */function zero$1(buf){let len=buf.length;for(;--len>=0;)buf[len]=0}const extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),static_ltree=new Array(576);zero$1(static_ltree);const static_dtree=new Array(60);zero$1(static_dtree);const _dist_code=new Array(512);zero$1(_dist_code);const _length_code=new Array(256);zero$1(_length_code);const base_length=new Array(29);zero$1(base_length);const base_dist=new Array(30);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}zero$1(base_dist);const d_code=dist=>dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)],put_short=(s,w)=>{s.pending_buf[s.pending++]=255&w,s.pending_buf[s.pending++]=w>>>8&255},send_bits=(s,value,length)=>{s.bi_valid>16-length?(s.bi_buf|=value<<s.bi_valid&65535,put_short(s,s.bi_buf),s.bi_buf=value>>16-s.bi_valid,s.bi_valid+=length-16):(s.bi_buf|=value<<s.bi_valid&65535,s.bi_valid+=length)},send_code=(s,c,tree)=>{send_bits(s,tree[2*c],tree[2*c+1])},bi_reverse=(code,len)=>{let res=0;do{res|=1&code,code>>>=1,res<<=1}while(--len>0);return res>>>1},gen_codes=(tree,max_code,bl_count)=>{const next_code=new Array(16);let bits,n,code=0;for(bits=1;bits<=15;bits++)code=code+bl_count[bits-1]<<1,next_code[bits]=code;for(n=0;n<=max_code;n++){let len=tree[2*n+1];0!==len&&(tree[2*n]=bi_reverse(next_code[len]++,len))}},init_block=s=>{let n;for(n=0;n<286;n++)s.dyn_ltree[2*n]=0;for(n=0;n<30;n++)s.dyn_dtree[2*n]=0;for(n=0;n<19;n++)s.bl_tree[2*n]=0;s.dyn_ltree[512]=1,s.opt_len=s.static_len=0,s.sym_next=s.matches=0},bi_windup=s=>{s.bi_valid>8?put_short(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},smaller=(tree,n,m,depth)=>{const _n2=2*n,_m2=2*m;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]},pqdownheap=(s,tree,k)=>{const v=s.heap[k];let j=k<<1;for(;j<=s.heap_len&&(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)&&j++,!smaller(tree,v,s.heap[j],s.depth));)s.heap[k]=s.heap[j],k=j,j<<=1;s.heap[k]=v},compress_block=(s,ltree,dtree)=>{let dist,lc,code,extra,sx=0;if(0!==s.sym_next)do{dist=255&s.pending_buf[s.sym_buf+sx++],dist+=(255&s.pending_buf[s.sym_buf+sx++])<<8,lc=s.pending_buf[s.sym_buf+sx++],0===dist?send_code(s,lc,ltree):(code=_length_code[lc],send_code(s,code+256+1,ltree),extra=extra_lbits[code],0!==extra&&(lc-=base_length[code],send_bits(s,lc,extra)),dist--,code=d_code(dist),send_code(s,code,dtree),extra=extra_dbits[code],0!==extra&&(dist-=base_dist[code],send_bits(s,dist,extra)))}while(sx<s.sym_next);send_code(s,256,ltree)},build_tree=(s,desc)=>{const tree=desc.dyn_tree,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,elems=desc.stat_desc.elems;let n,m,node,max_code=-1;for(s.heap_len=0,s.heap_max=573,n=0;n<elems;n++)0!==tree[2*n]?(s.heap[++s.heap_len]=max_code=n,s.depth[n]=0):tree[2*n+1]=0;for(;s.heap_len<2;)node=s.heap[++s.heap_len]=max_code<2?++max_code:0,tree[2*node]=1,s.depth[node]=0,s.opt_len--,has_stree&&(s.static_len-=stree[2*node+1]);for(desc.max_code=max_code,n=s.heap_len>>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do{n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[2*node]=tree[2*n]+tree[2*m],s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1,tree[2*n+1]=tree[2*m+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1)}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],((s,desc)=>{const tree=desc.dyn_tree,max_code=desc.max_code,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length;let h,n,m,bits,xbits,f,overflow=0;for(bits=0;bits<=15;bits++)s.bl_count[bits]=0;for(tree[2*s.heap[s.heap_max]+1]=0,h=s.heap_max+1;h<573;h++)n=s.heap[h],bits=tree[2*tree[2*n+1]+1]+1,bits>max_length&&(bits=max_length,overflow++),tree[2*n+1]=bits,n>max_code||(s.bl_count[bits]++,xbits=0,n>=base&&(xbits=extra[n-base]),f=tree[2*n],s.opt_len+=f*(bits+xbits),has_stree&&(s.static_len+=f*(stree[2*n+1]+xbits)));if(0!==overflow){do{for(bits=max_length-1;0===s.bl_count[bits];)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0);for(bits=max_length;0!==bits;bits--)for(n=s.bl_count[bits];0!==n;)m=s.heap[--h],m>max_code||(tree[2*m+1]!==bits&&(s.opt_len+=(bits-tree[2*m+1])*tree[2*m],tree[2*m+1]=bits),n--)}})(s,desc),gen_codes(tree,max_code,s.bl_count)},scan_tree=(s,tree,max_code)=>{let n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),tree[2*(max_code+1)+1]=65535,n=0;n<=max_code;n++)curlen=nextlen,nextlen=tree[2*(n+1)+1],++count<max_count&&curlen===nextlen||(count<min_count?s.bl_tree[2*curlen]+=count:0!==curlen?(curlen!==prevlen&&s.bl_tree[2*curlen]++,s.bl_tree[32]++):count<=10?s.bl_tree[34]++:s.bl_tree[36]++,count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4))},send_tree=(s,tree,max_code)=>{let n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),n=0;n<=max_code;n++)if(curlen=nextlen,nextlen=tree[2*(n+1)+1],!(++count<max_count&&curlen===nextlen)){if(count<min_count)do{send_code(s,curlen,s.bl_tree)}while(0!==--count);else 0!==curlen?(curlen!==prevlen&&(send_code(s,curlen,s.bl_tree),count--),send_code(s,16,s.bl_tree),send_bits(s,count-3,2)):count<=10?(send_code(s,17,s.bl_tree),send_bits(s,count-3,3)):(send_code(s,18,s.bl_tree),send_bits(s,count-11,7));count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4)}};let static_init_done=!1;const _tr_stored_block$1=(s,buf,stored_len,last)=>{send_bits(s,0+(last?1:0),3),bi_windup(s),put_short(s,stored_len),put_short(s,~stored_len),stored_len&&s.pending_buf.set(s.window.subarray(buf,buf+stored_len),s.pending),s.pending+=stored_len};var _tr_init_1=s=>{static_init_done||((()=>{let n,bits,length,code,dist;const bl_count=new Array(16);for(length=0,code=0;code<28;code++)for(base_length[code]=length,n=0;n<1<<extra_lbits[code];n++)_length_code[length++]=code;for(_length_code[length-1]=code,dist=0,code=0;code<16;code++)for(base_dist[code]=dist,n=0;n<1<<extra_dbits[code];n++)_dist_code[dist++]=code;for(dist>>=7;code<30;code++)for(base_dist[code]=dist<<7,n=0;n<1<<extra_dbits[code]-7;n++)_dist_code[256+dist++]=code;for(bits=0;bits<=15;bits++)bl_count[bits]=0;for(n=0;n<=143;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(;n<=255;)static_ltree[2*n+1]=9,n++,bl_count[9]++;for(;n<=279;)static_ltree[2*n+1]=7,n++,bl_count[7]++;for(;n<=287;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(gen_codes(static_ltree,287,bl_count),n=0;n<30;n++)static_dtree[2*n+1]=5,static_dtree[2*n]=bi_reverse(n,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,257,286,15),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,30,15),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,19,7)})(),static_init_done=!0),s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc),s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc),s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc),s.bi_buf=0,s.bi_valid=0,init_block(s)},_tr_flush_block_1=(s,buf,stored_len,last)=>{let opt_lenb,static_lenb,max_blindex=0;s.level>0?(2===s.strm.data_type&&(s.strm.data_type=(s=>{let n,block_mask=4093624447;for(n=0;n<=31;n++,block_mask>>>=1)if(1&block_mask&&0!==s.dyn_ltree[2*n])return 0;if(0!==s.dyn_ltree[18]||0!==s.dyn_ltree[20]||0!==s.dyn_ltree[26])return 1;for(n=32;n<256;n++)if(0!==s.dyn_ltree[2*n])return 1;return 0})(s)),build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=(s=>{let max_blindex;for(scan_tree(s,s.dyn_ltree,s.l_desc.max_code),scan_tree(s,s.dyn_dtree,s.d_desc.max_code),build_tree(s,s.bl_desc),max_blindex=18;max_blindex>=3&&0===s.bl_tree[2*bl_order[max_blindex]+1];max_blindex--);return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex})(s),opt_lenb=s.opt_len+3+7>>>3,static_lenb=s.static_len+3+7>>>3,static_lenb<=opt_lenb&&(opt_lenb=static_lenb)):opt_lenb=static_lenb=stored_len+5,stored_len+4<=opt_lenb&&-1!==buf?_tr_stored_block$1(s,buf,stored_len,last):4===s.strategy||static_lenb===opt_lenb?(send_bits(s,2+(last?1:0),3),compress_block(s,static_ltree,static_dtree)):(send_bits(s,4+(last?1:0),3),((s,lcodes,dcodes,blcodes)=>{let rank;for(send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4),rank=0;rank<blcodes;rank++)send_bits(s,s.bl_tree[2*bl_order[rank]+1],3);send_tree(s,s.dyn_ltree,lcodes-1),send_tree(s,s.dyn_dtree,dcodes-1)})(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree)),init_block(s),last&&bi_windup(s)},_tr_tally_1=(s,dist,lc)=>(s.pending_buf[s.sym_buf+s.sym_next++]=dist,s.pending_buf[s.sym_buf+s.sym_next++]=dist>>8,s.pending_buf[s.sym_buf+s.sym_next++]=lc,0===dist?s.dyn_ltree[2*lc]++:(s.matches++,dist--,s.dyn_ltree[2*(_length_code[lc]+256+1)]++,s.dyn_dtree[2*d_code(dist)]++),s.sym_next===s.sym_end),trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block$1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:s=>{send_bits(s,2,3),send_code(s,256,static_ltree),(s=>{16===s.bi_valid?(put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=255&s.bi_buf,s.bi_buf>>=8,s.bi_valid-=8)})(s)}};var adler32_1=(adler,buf,len,pos)=>{let s1=65535&adler,s2=adler>>>16&65535,n=0;for(;0!==len;){n=len>2e3?2e3:len,len-=n;do{s1=s1+buf[pos++]|0,s2=s2+s1|0}while(--n);s1%=65521,s2%=65521}return s1|s2<<16};const crcTable=new Uint32Array((()=>{let c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=1&c?3988292384^c>>>1:c>>>1;table[n]=c}return table})());var crc32_1=(crc,buf,len,pos)=>{const t=crcTable,end=pos+len;crc^=-1;for(let i=pos;i<end;i++)crc=crc>>>8^t[255&(crc^buf[i])];return-1^crc},messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:_tr_init,_tr_stored_block:_tr_stored_block,_tr_flush_block:_tr_flush_block,_tr_tally:_tr_tally,_tr_align:_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH:Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED:Z_FILTERED,Z_HUFFMAN_ONLY:Z_HUFFMAN_ONLY,Z_RLE:Z_RLE,Z_FIXED:Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN:Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,err=(strm,errorCode)=>(strm.msg=messages[errorCode],errorCode),rank=f=>2*f-(f>4?9:0),zero=buf=>{let len=buf.length;for(;--len>=0;)buf[len]=0},slide_hash=s=>{let n,m,p,wsize=s.w_size;n=s.hash_size,p=n;do{m=s.head[--p],s.head[p]=m>=wsize?m-wsize:0}while(--n);n=wsize,p=n;do{m=s.prev[--p],s.prev[p]=m>=wsize?m-wsize:0}while(--n)};let HASH=(s,prev,data)=>(prev<<s.hash_shift^data)&s.hash_mask;const flush_pending=strm=>{const s=strm.state;let len=s.pending;len>strm.avail_out&&(len=strm.avail_out),0!==len&&(strm.output.set(s.pending_buf.subarray(s.pending_out,s.pending_out+len),strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,0===s.pending&&(s.pending_out=0))},flush_block_only=(s,last)=>{_tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)},put_byte=(s,b)=>{s.pending_buf[s.pending++]=b},putShortMSB=(s,b)=>{s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=255&b},read_buf=(strm,buf,start,size)=>{let len=strm.avail_in;return len>size&&(len=size),0===len?0:(strm.avail_in-=len,buf.set(strm.input.subarray(strm.next_in,strm.next_in+len),start),1===strm.state.wrap?strm.adler=adler32_1(strm.adler,buf,len,start):2===strm.state.wrap&&(strm.adler=crc32_1(strm.adler,buf,len,start)),strm.next_in+=len,strm.total_in+=len,len)},longest_match=(s,cur_match)=>{let match,len,chain_length=s.max_chain_length,scan=s.strstart,best_len=s.prev_length,nice_match=s.nice_match;const limit=s.strstart>s.w_size-262?s.strstart-(s.w_size-262):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+258;let scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];s.prev_length>=s.good_match&&(chain_length>>=2),nice_match>s.lookahead&&(nice_match=s.lookahead);do{if(match=cur_match,_win[match+best_len]===scan_end&&_win[match+best_len-1]===scan_end1&&_win[match]===_win[scan]&&_win[++match]===_win[scan+1]){scan+=2,match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);if(len=258-(strend-scan),scan=strend-258,len>best_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}}while((cur_match=prev[cur_match&wmask])>limit&&0!==--chain_length);return best_len<=s.lookahead?best_len:s.lookahead},fill_window=s=>{const _w_size=s.w_size;let n,more,str;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-262)&&(s.window.set(s.window.subarray(_w_size,_w_size+_w_size-more),0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,s.insert>s.strstart&&(s.insert=s.strstart),slide_hash(s),more+=_w_size),0===s.strm.avail_in)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=3)for(str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=HASH(s,s.ins_h,s.window[str+1]);s.insert&&(s.ins_h=HASH(s,s.ins_h,s.window[str+3-1]),s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++,s.insert--,!(s.lookahead+s.insert<3)););}while(s.lookahead<262&&0!==s.strm.avail_in)},deflate_stored=(s,flush)=>{let len,left,have,min_block=s.pending_buf_size-5>s.w_size?s.w_size:s.pending_buf_size-5,last=0,used=s.strm.avail_in;do{if(len=65535,have=s.bi_valid+42>>3,s.strm.avail_out<have)break;if(have=s.strm.avail_out-have,left=s.strstart-s.block_start,len>left+s.strm.avail_in&&(len=left+s.strm.avail_in),len>have&&(len=have),len<min_block&&(0===len&&flush!==Z_FINISH$3||flush===Z_NO_FLUSH$2||len!==left+s.strm.avail_in))break;last=flush===Z_FINISH$3&&len===left+s.strm.avail_in?1:0,_tr_stored_block(s,0,0,last),s.pending_buf[s.pending-4]=len,s.pending_buf[s.pending-3]=len>>8,s.pending_buf[s.pending-2]=~len,s.pending_buf[s.pending-1]=~len>>8,flush_pending(s.strm),left&&(left>len&&(left=len),s.strm.output.set(s.window.subarray(s.block_start,s.block_start+left),s.strm.next_out),s.strm.next_out+=left,s.strm.avail_out-=left,s.strm.total_out+=left,s.block_start+=left,len-=left),len&&(read_buf(s.strm,s.strm.output,s.strm.next_out,len),s.strm.next_out+=len,s.strm.avail_out-=len,s.strm.total_out+=len)}while(0===last);return used-=s.strm.avail_in,used&&(used>=s.w_size?(s.matches=2,s.window.set(s.strm.input.subarray(s.strm.next_in-s.w_size,s.strm.next_in),0),s.strstart=s.w_size,s.insert=s.strstart):(s.window_size-s.strstart<=used&&(s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,s.insert>s.strstart&&(s.insert=s.strstart)),s.window.set(s.strm.input.subarray(s.strm.next_in-used,s.strm.next_in),s.strstart),s.strstart+=used,s.insert+=used>s.w_size-s.insert?s.w_size-s.insert:used),s.block_start=s.strstart),s.high_water<s.strstart&&(s.high_water=s.strstart),last?4:flush!==Z_NO_FLUSH$2&&flush!==Z_FINISH$3&&0===s.strm.avail_in&&s.strstart===s.block_start?2:(have=s.window_size-s.strstart,s.strm.avail_in>have&&s.block_start>=s.w_size&&(s.block_start-=s.w_size,s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,have+=s.w_size,s.insert>s.strstart&&(s.insert=s.strstart)),have>s.strm.avail_in&&(have=s.strm.avail_in),have&&(read_buf(s.strm,s.window,s.strstart,have),s.strstart+=have,s.insert+=have>s.w_size-s.insert?s.w_size-s.insert:have),s.high_water<s.strstart&&(s.high_water=s.strstart),have=s.bi_valid+42>>3,have=s.pending_buf_size-have>65535?65535:s.pending_buf_size-have,min_block=have>s.w_size?s.w_size:have,left=s.strstart-s.block_start,(left>=min_block||(left||flush===Z_FINISH$3)&&flush!==Z_NO_FLUSH$2&&0===s.strm.avail_in&&left<=have)&&(len=left>have?have:left,last=flush===Z_FINISH$3&&0===s.strm.avail_in&&len===left?1:0,_tr_stored_block(s,s.block_start,len,last),s.block_start+=len,flush_pending(s.strm)),last?3:1)},deflate_fast=(s,flush)=>{let hash_head,bflush;for(;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&flush===Z_NO_FLUSH$2)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),0!==hash_head&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head)),s.match_length>=3)if(bflush=_tr_tally(s,s.strstart-s.match_start,s.match_length-3),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=3){s.match_length--;do{s.strstart++,s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart}while(0!==--s.match_length);s.strstart++}else s.strstart+=s.match_length,s.match_length=0,s.ins_h=s.window[s.strstart],s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+1]);else bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=s.strstart<2?s.strstart:2,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2},deflate_slow=(s,flush)=>{let hash_head,bflush,max_insert;for(;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&flush===Z_NO_FLUSH$2)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),s.prev_length=s.match_length,s.prev_match=s.match_start,s.match_length=2,0!==hash_head&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head),s.match_length<=5&&(s.strategy===Z_FILTERED||3===s.match_length&&s.strstart-s.match_start>4096)&&(s.match_length=2)),s.prev_length>=3&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-3,bflush=_tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-3),s.lookahead-=s.prev_length-1,s.prev_length-=2;do{++s.strstart<=max_insert&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart)}while(0!==--s.prev_length);if(s.match_available=0,s.match_length=2,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}else if(s.match_available){if(bflush=_tr_tally(s,0,s.window[s.strstart-1]),bflush&&flush_block_only(s,!1),s.strstart++,s.lookahead--,0===s.strm.avail_out)return 1}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(bflush=_tr_tally(s,0,s.window[s.strstart-1]),s.match_available=0),s.insert=s.strstart<2?s.strstart:2,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2};function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const deflateStateCheck=strm=>{if(!strm)return 1;const s=strm.state;return!s||s.strm!==strm||42!==s.status&&57!==s.status&&69!==s.status&&73!==s.status&&91!==s.status&&103!==s.status&&113!==s.status&&666!==s.status?1:0},deflateResetKeep=strm=>{if(deflateStateCheck(strm))return err(strm,Z_STREAM_ERROR$2);strm.total_in=strm.total_out=0,strm.data_type=Z_UNKNOWN;const s=strm.state;return s.pending=0,s.pending_out=0,s.wrap<0&&(s.wrap=-s.wrap),s.status=2===s.wrap?57:s.wrap?42:113,strm.adler=2===s.wrap?0:1,s.last_flush=-2,_tr_init(s),Z_OK$3},deflateReset=strm=>{const ret=deflateResetKeep(strm);var s;return ret===Z_OK$3&&((s=strm.state).window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=2,s.match_available=0,s.ins_h=0),ret},deflateInit2=(strm,level,method,windowBits,memLevel,strategy)=>{if(!strm)return Z_STREAM_ERROR$2;let wrap=1;if(level===Z_DEFAULT_COMPRESSION$1&&(level=6),windowBits<0?(wrap=0,windowBits=-windowBits):windowBits>15&&(wrap=2,windowBits-=16),memLevel<1||memLevel>9||method!==Z_DEFLATED$2||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED||8===windowBits&&1!==wrap)return err(strm,Z_STREAM_ERROR$2);8===windowBits&&(windowBits=9);const s=new DeflateState;return strm.state=s,s.strm=strm,s.status=42,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=memLevel+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new Uint8Array(2*s.w_size),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<memLevel+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=3*(s.lit_bufsize-1),s.level=level,s.strategy=strategy,s.method=method,deflateReset(strm)};var deflate_1$2={deflateInit:(strm,level)=>deflateInit2(strm,level,Z_DEFLATED$2,15,8,Z_DEFAULT_STRATEGY$1),deflateInit2:deflateInit2,deflateReset:deflateReset,deflateResetKeep:deflateResetKeep,deflateSetHeader:(strm,head)=>deflateStateCheck(strm)||2!==strm.state.wrap?Z_STREAM_ERROR$2:(strm.state.gzhead=head,Z_OK$3),deflate:(strm,flush)=>{if(deflateStateCheck(strm)||flush>Z_BLOCK$1||flush<0)return strm?err(strm,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const s=strm.state;if(!strm.output||0!==strm.avail_in&&!strm.input||666===s.status&&flush!==Z_FINISH$3)return err(strm,0===strm.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const old_flush=s.last_flush;if(s.last_flush=flush,0!==s.pending){if(flush_pending(strm),0===strm.avail_out)return s.last_flush=-1,Z_OK$3}else if(0===strm.avail_in&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH$3)return err(strm,Z_BUF_ERROR$1);if(666===s.status&&0!==strm.avail_in)return err(strm,Z_BUF_ERROR$1);if(42===s.status&&0===s.wrap&&(s.status=113),42===s.status){let header=Z_DEFLATED$2+(s.w_bits-8<<4)<<8,level_flags=-1;if(level_flags=s.strategy>=Z_HUFFMAN_ONLY||s.level<2?0:s.level<6?1:6===s.level?2:3,header|=level_flags<<6,0!==s.strstart&&(header|=32),header+=31-header%31,putShortMSB(s,header),0!==s.strstart&&(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),strm.adler=1,s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3}if(57===s.status)if(strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),s.gzhead)put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),put_byte(s,255&s.gzhead.time),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,9===s.level?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0),put_byte(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(put_byte(s,255&s.gzhead.extra.length),put_byte(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69;else if(put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,9===s.level?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0),put_byte(s,3),s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;if(69===s.status){if(s.gzhead.extra){let beg=s.pending,left=(65535&s.gzhead.extra.length)-s.gzindex;for(;s.pending+left>s.pending_buf_size;){let copy=s.pending_buf_size-s.pending;if(s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex,s.gzindex+copy),s.pending),s.pending=s.pending_buf_size,s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex+=copy,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;beg=0,left-=copy}let gzhead_extra=new Uint8Array(s.gzhead.extra);s.pending_buf.set(gzhead_extra.subarray(s.gzindex,s.gzindex+left),s.pending),s.pending+=left,s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex=0}s.status=73}if(73===s.status){if(s.gzhead.name){let val,beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;beg=0}val=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val);s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex=0}s.status=91}if(91===s.status){if(s.gzhead.comment){let val,beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;beg=0}val=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val);s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg))}s.status=103}if(103===s.status){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size&&(flush_pending(strm),0!==s.pending))return s.last_flush=-1,Z_OK$3;put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),strm.adler=0}if(s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3}if(0!==strm.avail_in||0!==s.lookahead||flush!==Z_NO_FLUSH$2&&666!==s.status){let bstate=0===s.level?deflate_stored(s,flush):s.strategy===Z_HUFFMAN_ONLY?((s,flush)=>{let bflush;for(;;){if(0===s.lookahead&&(fill_window(s),0===s.lookahead)){if(flush===Z_NO_FLUSH$2)return 1;break}if(s.match_length=0,bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=0,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2})(s,flush):s.strategy===Z_RLE?((s,flush)=>{let bflush,prev,scan,strend;const _win=s.window;for(;;){if(s.lookahead<=258){if(fill_window(s),s.lookahead<=258&&flush===Z_NO_FLUSH$2)return 1;if(0===s.lookahead)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(scan=s.strstart-1,prev=_win[scan],prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan])){strend=s.strstart+258;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=258-(strend-scan),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(bflush=_tr_tally(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=0,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2})(s,flush):configuration_table[s.level].func(s,flush);if(3!==bstate&&4!==bstate||(s.status=666),1===bstate||3===bstate)return 0===strm.avail_out&&(s.last_flush=-1),Z_OK$3;if(2===bstate&&(flush===Z_PARTIAL_FLUSH?_tr_align(s):flush!==Z_BLOCK$1&&(_tr_stored_block(s,0,0,!1),flush===Z_FULL_FLUSH$1&&(zero(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),flush_pending(strm),0===strm.avail_out))return s.last_flush=-1,Z_OK$3}return flush!==Z_FINISH$3?Z_OK$3:s.wrap<=0?Z_STREAM_END$3:(2===s.wrap?(put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,255&strm.total_in),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255)):(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),flush_pending(strm),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?Z_OK$3:Z_STREAM_END$3)},deflateEnd:strm=>{if(deflateStateCheck(strm))return Z_STREAM_ERROR$2;const status=strm.state.status;return strm.state=null,113===status?err(strm,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary:(strm,dictionary)=>{let dictLength=dictionary.length;if(deflateStateCheck(strm))return Z_STREAM_ERROR$2;const s=strm.state,wrap=s.wrap;if(2===wrap||1===wrap&&42!==s.status||s.lookahead)return Z_STREAM_ERROR$2;if(1===wrap&&(strm.adler=adler32_1(strm.adler,dictionary,dictLength,0)),s.wrap=0,dictLength>=s.w_size){0===wrap&&(zero(s.head),s.strstart=0,s.block_start=0,s.insert=0);let tmpDict=new Uint8Array(s.w_size);tmpDict.set(dictionary.subarray(dictLength-s.w_size,dictLength),0),dictionary=tmpDict,dictLength=s.w_size}const avail=strm.avail_in,next=strm.next_in,input=strm.input;for(strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);s.lookahead>=3;){let str=s.strstart,n=s.lookahead-2;do{s.ins_h=HASH(s,s.ins_h,s.window[str+3-1]),s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++}while(--n);s.strstart=str,s.lookahead=2,fill_window(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,strm.next_in=next,strm.input=input,strm.avail_in=avail,s.wrap=wrap,Z_OK$3},deflateInfo:"pako deflate (from Nodeca project)"};const _has=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);var common_assign=function(obj){const sources=Array.prototype.slice.call(arguments,1);for(;sources.length;){const source=sources.shift();if(source){if("object"!=typeof source)throw new TypeError(source+"must be non-object");for(const p in source)_has(source,p)&&(obj[p]=source[p])}}return obj},common_flattenChunks=chunks=>{let len=0;for(let i=0,l=chunks.length;i<l;i++)len+=chunks[i].length;const result=new Uint8Array(len);for(let i=0,pos=0,l=chunks.length;i<l;i++){let chunk=chunks[i];result.set(chunk,pos),pos+=chunk.length}return result};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let q=0;q<256;q++)_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1;_utf8len[254]=_utf8len[254]=1;var strings_string2buf=str=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(str);let buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos<str_len;m_pos++)c=str.charCodeAt(m_pos),55296==(64512&c)&&m_pos+1<str_len&&(c2=str.charCodeAt(m_pos+1),56320==(64512&c2)&&(c=65536+(c-55296<<10)+(c2-56320),m_pos++)),buf_len+=c<128?1:c<2048?2:c<65536?3:4;for(buf=new Uint8Array(buf_len),i=0,m_pos=0;i<buf_len;m_pos++)c=str.charCodeAt(m_pos),55296==(64512&c)&&m_pos+1<str_len&&(c2=str.charCodeAt(m_pos+1),56320==(64512&c2)&&(c=65536+(c-55296<<10)+(c2-56320),m_pos++)),c<128?buf[i++]=c:c<2048?(buf[i++]=192|c>>>6,buf[i++]=128|63&c):c<65536?(buf[i++]=224|c>>>12,buf[i++]=128|c>>>6&63,buf[i++]=128|63&c):(buf[i++]=240|c>>>18,buf[i++]=128|c>>>12&63,buf[i++]=128|c>>>6&63,buf[i++]=128|63&c);return buf},strings_buf2string=(buf,max)=>{const len=max||buf.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(buf.subarray(0,max));let i,out;const utf16buf=new Array(2*len);for(out=0,i=0;i<len;){let c=buf[i++];if(c<128){utf16buf[out++]=c;continue}let c_len=_utf8len[c];if(c_len>4)utf16buf[out++]=65533,i+=c_len-1;else{for(c&=2===c_len?31:3===c_len?15:7;c_len>1&&i<len;)c=c<<6|63&buf[i++],c_len--;c_len>1?utf16buf[out++]=65533:c<65536?utf16buf[out++]=c:(c-=65536,utf16buf[out++]=55296|c>>10&1023,utf16buf[out++]=56320|1023&c)}}return((buf,len)=>{if(len<65534&&buf.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,buf.length===len?buf:buf.subarray(0,len));let result="";for(let i=0;i<len;i++)result+=String.fromCharCode(buf[i]);return result})(utf16buf,out)},strings_utf8border=(buf,max)=>{(max=max||buf.length)>buf.length&&(max=buf.length);let pos=max-1;for(;pos>=0&&128==(192&buf[pos]);)pos--;return pos<0||0===pos?max:pos+_utf8len[buf[pos]]>max?pos:max};var zstream=function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH:Z_SYNC_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(options){this.options=common_assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},options||{});let opt=this.options;opt.raw&&opt.windowBits>0?opt.windowBits=-opt.windowBits:opt.gzip&&opt.windowBits>0&&opt.windowBits<16&&(opt.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let status=deflate_1$2.deflateInit2(this.strm,opt.level,opt.method,opt.windowBits,opt.memLevel,opt.strategy);if(status!==Z_OK$2)throw new Error(messages[status]);if(opt.header&&deflate_1$2.deflateSetHeader(this.strm,opt.header),opt.dictionary){let dict;if(dict="string"==typeof opt.dictionary?strings_string2buf(opt.dictionary):"[object ArrayBuffer]"===toString$1.call(opt.dictionary)?new Uint8Array(opt.dictionary):opt.dictionary,status=deflate_1$2.deflateSetDictionary(this.strm,dict),status!==Z_OK$2)throw new Error(messages[status]);this._dict_set=!0}}function deflate$1(input,options){const deflator=new Deflate$1(options);if(deflator.push(input,!0),deflator.err)throw deflator.msg||messages[deflator.err];return deflator.result}Deflate$1.prototype.push=function(data,flush_mode){const strm=this.strm,chunkSize=this.options.chunkSize;let status,_flush_mode;if(this.ended)return!1;for(_flush_mode=flush_mode===~~flush_mode?flush_mode:!0===flush_mode?Z_FINISH$2:Z_NO_FLUSH$1,"string"==typeof data?strm.input=strings_string2buf(data):"[object ArrayBuffer]"===toString$1.call(data)?strm.input=new Uint8Array(data):strm.input=data,strm.next_in=0,strm.avail_in=strm.input.length;;)if(0===strm.avail_out&&(strm.output=new Uint8Array(chunkSize),strm.next_out=0,strm.avail_out=chunkSize),(_flush_mode===Z_SYNC_FLUSH||_flush_mode===Z_FULL_FLUSH)&&strm.avail_out<=6)this.onData(strm.output.subarray(0,strm.next_out)),strm.avail_out=0;else{if(status=deflate_1$2.deflate(strm,_flush_mode),status===Z_STREAM_END$2)return strm.next_out>0&&this.onData(strm.output.subarray(0,strm.next_out)),status=deflate_1$2.deflateEnd(this.strm),this.onEnd(status),this.ended=!0,status===Z_OK$2;if(0!==strm.avail_out){if(_flush_mode>0&&strm.next_out>0)this.onData(strm.output.subarray(0,strm.next_out)),strm.avail_out=0;else if(0===strm.avail_in)break}else this.onData(strm.output)}return!0},Deflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)},Deflate$1.prototype.onEnd=function(status){status===Z_OK$2&&(this.result=common_flattenChunks(this.chunks)),this.chunks=[],this.err=status,this.msg=this.strm.msg};var deflate_1$1={Deflate:Deflate$1,deflate:deflate$1,deflateRaw:function deflateRaw$1(input,options){return(options=options||{}).raw=!0,deflate$1(input,options)},gzip:function gzip$1(input,options){return(options=options||{}).gzip=!0,deflate$1(input,options)},constants:constants$2};var inffast=function inflate_fast(strm,start){let _in,last,_out,beg,end,dmax,wsize,whave,wnext,s_window,hold,bits,lcode,dcode,lmask,dmask,here,op,len,dist,from,from_source,input,output;const state=strm.state;_in=strm.next_in,input=strm.input,last=_in+(strm.avail_in-5),_out=strm.next_out,output=strm.output,beg=_out-(start-strm.avail_out),end=_out+(strm.avail_out-257),dmax=state.dmax,wsize=state.wsize,whave=state.whave,wnext=state.wnext,s_window=state.window,hold=state.hold,bits=state.bits,lcode=state.lencode,dcode=state.distcode,lmask=(1<<state.lenbits)-1,dmask=(1<<state.distbits)-1;top:do{bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=lcode[hold&lmask];dolen:for(;;){if(op=here>>>24,hold>>>=op,bits-=op,op=here>>>16&255,0===op)output[_out++]=65535&here;else{if(!(16&op)){if(64&op){if(32&op){state.mode=16191;break top}strm.msg="invalid literal/length code",state.mode=16209;break top}here=lcode[(65535&here)+(hold&(1<<op)-1)];continue dolen}for(len=65535&here,op&=15,op&&(bits<op&&(hold+=input[_in++]<<bits,bits+=8),len+=hold&(1<<op)-1,hold>>>=op,bits-=op),bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=dcode[hold&dmask];;){if(op=here>>>24,hold>>>=op,bits-=op,op=here>>>16&255,16&op){if(dist=65535&here,op&=15,bits<op&&(hold+=input[_in++]<<bits,bits+=8,bits<op&&(hold+=input[_in++]<<bits,bits+=8)),dist+=hold&(1<<op)-1,dist>dmax){strm.msg="invalid distance too far back",state.mode=16209;break top}if(hold>>>=op,bits-=op,op=_out-beg,dist>op){if(op=dist-op,op>whave&&state.sane){strm.msg="invalid distance too far back",state.mode=16209;break top}if(from=0,from_source=s_window,0===wnext){if(from+=wsize-op,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}}else if(wnext<op){if(from+=wsize+wnext-op,op-=wnext,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);if(from=0,wnext<len){op=wnext,len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}}}else if(from+=wnext-op,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}for(;len>2;)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;len&&(output[_out++]=from_source[from++],len>1&&(output[_out++]=from_source[from++]))}else{from=_out-dist;do{output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3}while(len>2);len&&(output[_out++]=output[from++],len>1&&(output[_out++]=output[from++]))}break}if(64&op){strm.msg="invalid distance code",state.mode=16209;break top}here=dcode[(65535&here)+(hold&(1<<op)-1)]}}break}}while(_in<last&&_out<end);len=bits>>3,_in-=len,bits-=len<<3,hold&=(1<<bits)-1,strm.next_in=_in,strm.next_out=_out,strm.avail_in=_in<last?last-_in+5:5-(_in-last),strm.avail_out=_out<end?end-_out+257:257-(_out-end),state.hold=hold,state.bits=bits};const lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var inftrees=(type,lens,lens_index,codes,table,table_index,work,opts)=>{const bits=opts.bits;let incr,fill,low,mask,next,match,len=0,sym=0,min=0,max=0,root=0,curr=0,drop=0,left=0,used=0,huff=0,base=null;const count=new Uint16Array(16),offs=new Uint16Array(16);let here_bits,here_op,here_val,extra=null;for(len=0;len<=15;len++)count[len]=0;for(sym=0;sym<codes;sym++)count[lens[lens_index+sym]]++;for(root=bits,max=15;max>=1&&0===count[max];max--);if(root>max&&(root=max),0===max)return table[table_index++]=20971520,table[table_index++]=20971520,opts.bits=1,0;for(min=1;min<max&&0===count[min];min++);for(root<min&&(root=min),left=1,len=1;len<=15;len++)if(left<<=1,left-=count[len],left<0)return-1;if(left>0&&(0===type||1!==max))return-1;for(offs[1]=0,len=1;len<15;len++)offs[len+1]=offs[len]+count[len];for(sym=0;sym<codes;sym++)0!==lens[lens_index+sym]&&(work[offs[lens[lens_index+sym]]++]=sym);if(0===type?(base=extra=work,match=20):1===type?(base=lbase,extra=lext,match=257):(base=dbase,extra=dext,match=0),huff=0,sym=0,len=min,next=table_index,curr=root,drop=0,low=-1,used=1<<root,mask=used-1,1===type&&used>852||2===type&&used>592)return 1;for(;;){here_bits=len-drop,work[sym]+1<match?(here_op=0,here_val=work[sym]):work[sym]>=match?(here_op=extra[work[sym]-match],here_val=base[work[sym]-match]):(here_op=96,here_val=0),incr=1<<len-drop,fill=1<<curr,min=fill;do{fill-=incr,table[next+(huff>>drop)+fill]=here_bits<<24|here_op<<16|here_val}while(0!==fill);for(incr=1<<len-1;huff&incr;)incr>>=1;if(0!==incr?(huff&=incr-1,huff+=incr):huff=0,sym++,0===--count[len]){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){for(0===drop&&(drop=root),next+=min,curr=len-drop,left=1<<curr;curr+drop<max&&(left-=count[curr+drop],!(left<=0));)curr++,left<<=1;if(used+=1<<curr,1===type&&used>852||2===type&&used>592)return 1;low=huff&mask,table[low]=root<<24|curr<<16|next-table_index}}return 0!==huff&&(table[next+huff]=len-drop<<24|64<<16),opts.bits=root,0};const{Z_FINISH:Z_FINISH$1,Z_BLOCK:Z_BLOCK,Z_TREES:Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR:Z_BUF_ERROR,Z_DEFLATED:Z_DEFLATED}=constants$2,BAD=16209,zswap32=q=>(q>>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24);function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck=strm=>{if(!strm)return 1;const state=strm.state;return!state||state.strm!==strm||state.mode<16180||state.mode>16211?1:0},inflateResetKeep=strm=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return strm.total_in=strm.total_out=state.total=0,strm.msg="",state.wrap&&(strm.adler=1&state.wrap),state.mode=16180,state.last=0,state.havedict=0,state.flags=-1,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new Int32Array(852),state.distcode=state.distdyn=new Int32Array(592),state.sane=1,state.back=-1,Z_OK$1},inflateReset=strm=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return state.wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)},inflateReset2=(strm,windowBits)=>{let wrap;if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return windowBits<0?(wrap=0,windowBits=-windowBits):(wrap=5+(windowBits>>4),windowBits<48&&(windowBits&=15)),windowBits&&(windowBits<8||windowBits>15)?Z_STREAM_ERROR$1:(null!==state.window&&state.wbits!==windowBits&&(state.window=null),state.wrap=wrap,state.wbits=windowBits,inflateReset(strm))},inflateInit2=(strm,windowBits)=>{if(!strm)return Z_STREAM_ERROR$1;const state=new InflateState;strm.state=state,state.strm=strm,state.window=null,state.mode=16180;const ret=inflateReset2(strm,windowBits);return ret!==Z_OK$1&&(strm.state=null),ret};let lenfix,distfix,virgin=!0;const fixedtables=state=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let sym=0;for(;sym<144;)state.lens[sym++]=8;for(;sym<256;)state.lens[sym++]=9;for(;sym<280;)state.lens[sym++]=7;for(;sym<288;)state.lens[sym++]=8;for(inftrees(1,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;sym<32;)state.lens[sym++]=5;inftrees(2,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5},updatewindow=(strm,src,end,copy)=>{let dist;const state=strm.state;return null===state.window&&(state.wsize=1<<state.wbits,state.wnext=0,state.whave=0,state.window=new Uint8Array(state.wsize)),copy>=state.wsize?(state.window.set(src.subarray(end-state.wsize,end),0),state.wnext=0,state.whave=state.wsize):(dist=state.wsize-state.wnext,dist>copy&&(dist=copy),state.window.set(src.subarray(end-copy,end-copy+dist),state.wnext),(copy-=dist)?(state.window.set(src.subarray(end-copy,end),0),state.wnext=copy,state.whave=state.wsize):(state.wnext+=dist,state.wnext===state.wsize&&(state.wnext=0),state.whave<state.wsize&&(state.whave+=dist))),0};var inflate_2$1=(strm,flush)=>{let state,input,output,next,put,have,left,hold,bits,_in,_out,copy,from,from_source,here_bits,here_op,here_val,last_bits,last_op,last_val,len,ret,here=0;const hbuf=new Uint8Array(4);let opts,n;const order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(strm)||!strm.output||!strm.input&&0!==strm.avail_in)return Z_STREAM_ERROR$1;state=strm.state,16191===state.mode&&(state.mode=16192),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,_in=have,_out=left,ret=Z_OK$1;inf_leave:for(;;)switch(state.mode){case 16180:if(0===state.wrap){state.mode=16192;break}for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(2&state.wrap&&35615===hold){0===state.wbits&&(state.wbits=15),state.check=0,hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0),hold=0,bits=0,state.mode=16181;break}if(state.head&&(state.head.done=!1),!(1&state.wrap)||(((255&hold)<<8)+(hold>>8))%31){strm.msg="incorrect header check",state.mode=BAD;break}if((15&hold)!==Z_DEFLATED){strm.msg="unknown compression method",state.mode=BAD;break}if(hold>>>=4,bits-=4,len=8+(15&hold),0===state.wbits&&(state.wbits=len),len>15||len>state.wbits){strm.msg="invalid window size",state.mode=BAD;break}state.dmax=1<<state.wbits,state.flags=0,strm.adler=state.check=1,state.mode=512&hold?16189:16191,hold=0,bits=0;break;case 16181:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.flags=hold,(255&state.flags)!==Z_DEFLATED){strm.msg="unknown compression method",state.mode=BAD;break}if(57344&state.flags){strm.msg="unknown header flags set",state.mode=BAD;break}state.head&&(state.head.text=hold>>8&1),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=16182;case 16182:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.time=hold),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32_1(state.check,hbuf,4,0)),hold=0,bits=0,state.mode=16183;case 16183:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.xflags=255&hold,state.head.os=hold>>8),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=16184;case 16184:if(1024&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length=hold,state.head&&(state.head.extra_len=hold),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0)),hold=0,bits=0}else state.head&&(state.head.extra=null);state.mode=16185;case 16185:if(1024&state.flags&&(copy=state.length,copy>have&&(copy=have),copy&&(state.head&&(len=state.head.extra_len-state.length,state.head.extra||(state.head.extra=new Uint8Array(state.head.extra_len)),state.head.extra.set(input.subarray(next,next+copy),len)),512&state.flags&&4&state.wrap&&(state.check=crc32_1(state.check,input,copy,next)),have-=copy,next+=copy,state.length-=copy),state.length))break inf_leave;state.length=0,state.mode=16186;case 16186:if(2048&state.flags){if(0===have)break inf_leave;copy=0;do{len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.name+=String.fromCharCode(len))}while(len&©<have);if(512&state.flags&&4&state.wrap&&(state.check=crc32_1(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.name=null);state.length=0,state.mode=16187;case 16187:if(4096&state.flags){if(0===have)break inf_leave;copy=0;do{len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.comment+=String.fromCharCode(len))}while(len&©<have);if(512&state.flags&&4&state.wrap&&(state.check=crc32_1(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.comment=null);state.mode=16188;case 16188:if(512&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(4&state.wrap&&hold!==(65535&state.check)){strm.msg="header crc mismatch",state.mode=BAD;break}hold=0,bits=0}state.head&&(state.head.hcrc=state.flags>>9&1,state.head.done=!0),strm.adler=state.check=0,state.mode=16191;break;case 16189:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}strm.adler=state.check=zswap32(hold),hold=0,bits=0,state.mode=16190;case 16190:if(0===state.havedict)return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,Z_NEED_DICT$1;strm.adler=state.check=1,state.mode=16191;case 16191:if(flush===Z_BLOCK||flush===Z_TREES)break inf_leave;case 16192:if(state.last){hold>>>=7&bits,bits-=7&bits,state.mode=16206;break}for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}switch(state.last=1&hold,hold>>>=1,bits-=1,3&hold){case 0:state.mode=16193;break;case 1:if(fixedtables(state),state.mode=16199,flush===Z_TREES){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=16196;break;case 3:strm.msg="invalid block type",state.mode=BAD}hold>>>=2,bits-=2;break;case 16193:for(hold>>>=7&bits,bits-=7&bits;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if((65535&hold)!=(hold>>>16^65535)){strm.msg="invalid stored block lengths",state.mode=BAD;break}if(state.length=65535&hold,hold=0,bits=0,state.mode=16194,flush===Z_TREES)break inf_leave;case 16194:state.mode=16195;case 16195:if(copy=state.length,copy){if(copy>have&&(copy=have),copy>left&&(copy=left),0===copy)break inf_leave;output.set(input.subarray(next,next+copy),put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=16191;break;case 16196:for(;bits<14;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.nlen=257+(31&hold),hold>>>=5,bits-=5,state.ndist=1+(31&hold),hold>>>=5,bits-=5,state.ncode=4+(15&hold),hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols",state.mode=BAD;break}state.have=0,state.mode=16197;case 16197:for(;state.have<state.ncode;){for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.lens[order[state.have++]]=7&hold,hold>>>=3,bits-=3}for(;state.have<19;)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inftrees(0,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid code lengths set",state.mode=BAD;break}state.have=0,state.mode=16198;case 16198:for(;state.have<state.nlen+state.ndist;){for(;here=state.lencode[hold&(1<<state.lenbits)-1],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_val<16)hold>>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(16===here_val){for(n=here_bits+2;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold>>>=here_bits,bits-=here_bits,0===state.have){strm.msg="invalid bit length repeat",state.mode=BAD;break}len=state.lens[state.have-1],copy=3+(3&hold),hold>>>=2,bits-=2}else if(17===here_val){for(n=here_bits+3;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=3+(7&hold),hold>>>=3,bits-=3}else{for(n=here_bits+7;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=11+(127&hold),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat",state.mode=BAD;break}for(;copy--;)state.lens[state.have++]=len}}if(state.mode===BAD)break;if(0===state.lens[256]){strm.msg="invalid code -- missing end-of-block",state.mode=BAD;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inftrees(1,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid literal/lengths set",state.mode=BAD;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inftrees(2,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg="invalid distances set",state.mode=BAD;break}if(state.mode=16199,flush===Z_TREES)break inf_leave;case 16199:state.mode=16200;case 16200:if(have>=6&&left>=258){strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inffast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,16191===state.mode&&(state.back=-1);break}for(state.back=0;here=state.lencode[hold&(1<<state.lenbits)-1],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_op&&!(240&here_op)){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,0===here_op){state.mode=16205;break}if(32&here_op){state.back=-1,state.mode=16191;break}if(64&here_op){strm.msg="invalid literal/length code",state.mode=BAD;break}state.extra=15&here_op,state.mode=16201;case 16201:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=16202;case 16202:for(;here=state.distcode[hold&(1<<state.distbits)-1],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(!(240&here_op)){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,64&here_op){strm.msg="invalid distance code",state.mode=BAD;break}state.offset=here_val,state.extra=15&here_op,state.mode=16203;case 16203:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.offset+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back",state.mode=BAD;break}state.mode=16204;case 16204:if(0===left)break inf_leave;if(copy=_out-left,state.offset>copy){if(copy=state.offset-copy,copy>state.whave&&state.sane){strm.msg="invalid distance too far back",state.mode=BAD;break}copy>state.wnext?(copy-=state.wnext,from=state.wsize-copy):from=state.wnext-copy,copy>state.length&&(copy=state.length),from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;copy>left&&(copy=left),left-=copy,state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);0===state.length&&(state.mode=16200);break;case 16205:if(0===left)break inf_leave;output[put++]=state.length,left--,state.mode=16200;break;case 16206:if(state.wrap){for(;bits<32;){if(0===have)break inf_leave;have--,hold|=input[next++]<<bits,bits+=8}if(_out-=left,strm.total_out+=_out,state.total+=_out,4&state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,put-_out):adler32_1(state.check,output,_out,put-_out)),_out=left,4&state.wrap&&(state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check",state.mode=BAD;break}hold=0,bits=0}state.mode=16207;case 16207:if(state.wrap&&state.flags){for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(4&state.wrap&&hold!==(4294967295&state.total)){strm.msg="incorrect length check",state.mode=BAD;break}hold=0,bits=0}state.mode=16208;case 16208:ret=Z_STREAM_END$1;break inf_leave;case BAD:ret=Z_DATA_ERROR$1;break inf_leave;case 16210:return Z_MEM_ERROR$1;default:return Z_STREAM_ERROR$1}return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<16206||flush!==Z_FINISH$1))&&updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out),_in-=strm.avail_in,_out-=strm.avail_out,strm.total_in+=_in,strm.total_out+=_out,state.total+=_out,4&state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,strm.next_out-_out):adler32_1(state.check,output,_out,strm.next_out-_out)),strm.data_type=state.bits+(state.last?64:0)+(16191===state.mode?128:0)+(16199===state.mode||16194===state.mode?256:0),(0===_in&&0===_out||flush===Z_FINISH$1)&&ret===Z_OK$1&&(ret=Z_BUF_ERROR),ret},inflateEnd_1=strm=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;let state=strm.state;return state.window&&(state.window=null),strm.state=null,Z_OK$1},inflateGetHeader_1=(strm,head)=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return 2&state.wrap?(state.head=head,head.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary_1=(strm,dictionary)=>{const dictLength=dictionary.length;let state,dictid,ret;return inflateStateCheck(strm)?Z_STREAM_ERROR$1:(state=strm.state,0!==state.wrap&&16190!==state.mode?Z_STREAM_ERROR$1:16190===state.mode&&(dictid=1,dictid=adler32_1(dictid,dictionary,dictLength,0),dictid!==state.check)?Z_DATA_ERROR$1:(ret=updatewindow(strm,dictionary,dictLength,dictLength),ret?(state.mode=16210,Z_MEM_ERROR$1):(state.havedict=1,Z_OK$1)))},inflate_1$2={inflateReset:inflateReset,inflateReset2:inflateReset2,inflateResetKeep:inflateResetKeep,inflateInit:strm=>inflateInit2(strm,15),inflateInit2:inflateInit2,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo:"pako inflate (from Nodeca project)"};var gzheader=function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const toString=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH,Z_FINISH:Z_FINISH,Z_OK:Z_OK,Z_STREAM_END:Z_STREAM_END,Z_NEED_DICT:Z_NEED_DICT,Z_STREAM_ERROR:Z_STREAM_ERROR,Z_DATA_ERROR:Z_DATA_ERROR,Z_MEM_ERROR:Z_MEM_ERROR}=constants$2;function Inflate$1(options){this.options=common_assign({chunkSize:65536,windowBits:15,to:""},options||{});const opt=this.options;opt.raw&&opt.windowBits>=0&&opt.windowBits<16&&(opt.windowBits=-opt.windowBits,0===opt.windowBits&&(opt.windowBits=-15)),!(opt.windowBits>=0&&opt.windowBits<16)||options&&options.windowBits||(opt.windowBits+=32),opt.windowBits>15&&opt.windowBits<48&&(15&opt.windowBits||(opt.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let status=inflate_1$2.inflateInit2(this.strm,opt.windowBits);if(status!==Z_OK)throw new Error(messages[status]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),opt.dictionary&&("string"==typeof opt.dictionary?opt.dictionary=strings_string2buf(opt.dictionary):"[object ArrayBuffer]"===toString.call(opt.dictionary)&&(opt.dictionary=new Uint8Array(opt.dictionary)),opt.raw&&(status=inflate_1$2.inflateSetDictionary(this.strm,opt.dictionary),status!==Z_OK)))throw new Error(messages[status])}function inflate$1(input,options){const inflator=new Inflate$1(options);if(inflator.push(input),inflator.err)throw inflator.msg||messages[inflator.err];return inflator.result}Inflate$1.prototype.push=function(data,flush_mode){const strm=this.strm,chunkSize=this.options.chunkSize,dictionary=this.options.dictionary;let status,_flush_mode,last_avail_out;if(this.ended)return!1;for(_flush_mode=flush_mode===~~flush_mode?flush_mode:!0===flush_mode?Z_FINISH:Z_NO_FLUSH,"[object ArrayBuffer]"===toString.call(data)?strm.input=new Uint8Array(data):strm.input=data,strm.next_in=0,strm.avail_in=strm.input.length;;){for(0===strm.avail_out&&(strm.output=new Uint8Array(chunkSize),strm.next_out=0,strm.avail_out=chunkSize),status=inflate_1$2.inflate(strm,_flush_mode),status===Z_NEED_DICT&&dictionary&&(status=inflate_1$2.inflateSetDictionary(strm,dictionary),status===Z_OK?status=inflate_1$2.inflate(strm,_flush_mode):status===Z_DATA_ERROR&&(status=Z_NEED_DICT));strm.avail_in>0&&status===Z_STREAM_END&&strm.state.wrap>0&&0!==data[strm.next_in];)inflate_1$2.inflateReset(strm),status=inflate_1$2.inflate(strm,_flush_mode);switch(status){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(status),this.ended=!0,!1}if(last_avail_out=strm.avail_out,strm.next_out&&(0===strm.avail_out||status===Z_STREAM_END))if("string"===this.options.to){let next_out_utf8=strings_utf8border(strm.output,strm.next_out),tail=strm.next_out-next_out_utf8,utf8str=strings_buf2string(strm.output,next_out_utf8);strm.next_out=tail,strm.avail_out=chunkSize-tail,tail&&strm.output.set(strm.output.subarray(next_out_utf8,next_out_utf8+tail),0),this.onData(utf8str)}else this.onData(strm.output.length===strm.next_out?strm.output:strm.output.subarray(0,strm.next_out));if(status!==Z_OK||0!==last_avail_out){if(status===Z_STREAM_END)return status=inflate_1$2.inflateEnd(this.strm),this.onEnd(status),this.ended=!0,!0;if(0===strm.avail_in)break}}return!0},Inflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)},Inflate$1.prototype.onEnd=function(status){status===Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=common_flattenChunks(this.chunks)),this.chunks=[],this.err=status,this.msg=this.strm.msg};var inflate_1$1={Inflate:Inflate$1,inflate:inflate$1,inflateRaw:function inflateRaw$1(input,options){return(options=options||{}).raw=!0,inflate$1(input,options)},ungzip:inflate$1,constants:constants$2};const{Deflate:Deflate,deflate:deflate,deflateRaw:deflateRaw,gzip:gzip}=deflate_1$1,{Inflate:Inflate,inflate:inflate,inflateRaw:inflateRaw,ungzip:ungzip}=inflate_1$1;var pako={Deflate:Deflate,deflate:deflate,deflateRaw:deflateRaw,gzip:gzip,Inflate:Inflate,inflate:inflate,inflateRaw:inflateRaw,ungzip:ungzip,constants:constants$2};class DistribuicaoHandler$1{environment;utility;metodo;constructor(environment,utility,metodo){this.utility=utility,this.environment=environment,this.metodo=metodo}salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chCTe){const{pathXMLDistribuicao:pathXMLDistribuicao,baixarXMLDistribuicao:baixarXMLDistribuicao,armazenarRetornoEmJSON:armazenarRetornoEmJSON}=this.environment.config.dfe;baixarXMLDistribuicao&&(this.utility.salvaXML({data:XMLDistribuicao,fileName:chCTe,metodo:this.metodo,path:pathXMLDistribuicao}),armazenarRetornoEmJSON&&this.utility.salvaJSON({data:XMLDistribuicaoInJson,fileName:chCTe,metodo:this.metodo,path:pathXMLDistribuicao}))}deCompressDFeXML(loteDistDFeInt,metodo,xmlConsulta){logger.info("Descomprimindo XML",{context:"DistribuicaoHandler"});const json=new XmlParser,files=[];return xml2js$1.parseString(loteDistDFeInt,(err,result)=>{if(err)throw new Error(`Erro ao descomprimir o XML: ${err}`);this.utility.findInObj(result,"docZip").forEach(docZip=>{const xmlString=this.decodeDocZip(docZip),cleanedXml=this.removeSignatureTag(xmlString),parsedResult=this.parseXml(cleanedXml);if(!parsedResult)return;let chCTe=this.getChCTe(parsedResult),tipo=this.getTipo(parsedResult);const nsu=docZip.$.NSU;if(parsedResult.procEventoCTe){chCTe=`${chCTe}-event-${this.utility.findInObj(parsedResult,"tpEvento")}`,tipo="event"}const xmlDistribuicaoInJson=json.convertXmlToJson(cleanedXml,`${metodo}_${tipo}`,nsu);this.handleResponse(xmlDistribuicaoInJson,cleanedXml,chCTe),files.push(chCTe)})}),files}decodeDocZip(docZip){logger.info("Decodificando DocZip",{context:"DistribuicaoHandler"});const base64String=docZip._;let binaryString=atob(base64String),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);let decompressedData=pako.inflate(bytes);return new TextDecoder("utf-8").decode(decompressedData)}removeSignatureTag(xmlString){return xmlString.replace(/<Signature.*?<\/Signature>/gs,"")}parseXml(xmlString){let parsedResult;return xml2js$1.parseString(xmlString,(err,result)=>{err?(console.error("Erro ao parsear o XML decomprimido:",err),parsedResult=null):parsedResult=result}),parsedResult}getChCTe(parsedResult){return this.utility.findInObj(parsedResult,"chCTe")}getTipo(parsedResult){return this.utility.findInObj(parsedResult,"resCTe")?"res":parsedResult.procEventoCTe?"event":"proc"}handleResponse(XMLDistribuicaoInJson,XMLDistribuicao,chCTe){this.salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chCTe);const xMotivo=this.utility.findInObj(XMLDistribuicaoInJson,"xMotivo");if(xMotivo&&(xMotivo.includes("Rejeição")||xMotivo.includes("Rejeicao")))throw new Error(XMLDistribuicaoInJson.xMotivo)}}class CTEDistribuicaoDFeService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"CTeDistribuicaoDFe",axios,saveFiles,gerarConsulta)}gerarXml(data){return this.gerarXmlCTeDistribuicaoDFe(data)}gerarXmlCTeDistribuicaoDFe(data){logger.info("Montando estrutura do XML em JSON",{context:"CTEDistribuicaoDFeService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{versao:"1.00",xmlns:"http://www.portalfiscal.inf.br/cte"},tpAmb:ambiente,...data};return this.xmlBuilder.gerarXml(xmlObject,"distDFeInt",this.metodo)}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType};logger.http("Iniciando comunicação com o webservice",{context:"CTEDistribuicaoDFeService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"CTEDistribuicaoDFeService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlCTeDistribuicaoDFe(data),console.log({xmlConsulta:xmlConsulta});const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,!0,"1.00","CTe",!0,"cteDistDFeInteresse","cteDadosMsg");xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent);if(responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo),"137"===responseInJson.retDistDFeInt.cStat)return{data:{},xMotivo:responseInJson.retDistDFeInt.xMotivo,filesList:[]};const filesList=new DistribuicaoHandler$1(this.environment,this.utility,this.metodo).deCompressDFeXML(xmlRetorno.data,this.metodo,xmlConsulta);return{data:responseInJson,xMotivo:this.utility.findInObj(responseInJson,"xMotivo"),filesList:filesList}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class CTEDistribuicaoDFePorNSU extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class CTEDistribuicaoDFePorUltNSU extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class CTEDistribuicaoDFePorNSUService extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class CTEDistribuicaoDFePorUltNSUService extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEInutilizacao{nfeInutilizacaoService;constructor(nfeInutilizacaoService){this.nfeInutilizacaoService=nfeInutilizacaoService}async Exec(data){return await this.nfeInutilizacaoService.Exec(data)}}class NFECartaDeCorrecao{nfeCartaDeCorrecaoServiceService;constructor(nfeCartaDeCorrecaoServiceService){this.nfeCartaDeCorrecaoServiceService=nfeCartaDeCorrecaoServiceService}async Exec(data){return await this.nfeCartaDeCorrecaoServiceService.Exec(data)}}class NFEDesconhecimentoDaOperacao{nfeDesconhecimentoDaOperacaoServiceService;constructor(nfeDesconhecimentoDaOperacaoServiceService){this.nfeDesconhecimentoDaOperacaoServiceService=nfeDesconhecimentoDaOperacaoServiceService}async Exec(data){return await this.nfeDesconhecimentoDaOperacaoServiceService.Exec(data)}}class NFERetornoAutorizacao{nfeRetornoAutorizacaoService;constructor(nfeRetornoAutorizacaoService){this.nfeRetornoAutorizacaoService=nfeRetornoAutorizacaoService}async getXmlRetorno(data){return await this.nfeRetornoAutorizacaoService.getXmlRetorno(data)}}function filterFieldsByType(source,requiredFields){const result={};for(const key of requiredFields)key in source&&""!==source[key]&&(result[key]=source[key]);return result}const COFINSMap={"01":"COFINSAliq","02":"COFINSAliq","03":"COFINSQtde","04":"COFINSNT","05":"COFINSNT","06":"COFINSNT","07":"COFINSNT","08":"COFINSNT","09":"COFINSNT",49:"COFINSOutr",50:"COFINSOutr",51:"COFINSOutr",52:"COFINSOutr",53:"COFINSOutr",54:"COFINSOutr",55:"COFINSOutr",56:"COFINSOutr",60:"COFINSOutr",61:"COFINSOutr",62:"COFINSOutr",63:"COFINSOutr",64:"COFINSOutr",65:"COFINSOutr",66:"COFINSOutr",67:"COFINSOutr",70:"COFINSOutr",71:"COFINSOutr",72:"COFINSOutr",73:"COFINSOutr",74:"COFINSOutr",75:"COFINSOutr",98:"COFINSOutr",99:"COFINSOutr"},PISMap={"01":"PISAliq","02":"PISAliq","03":"PISQtde","04":"PISNT","05":"PISNT","06":"PISNT","07":"PISNT","08":"PISNT","09":"PISNT",49:"PISOutr",50:"PISOutr",51:"PISOutr",52:"PISOutr",53:"PISOutr",54:"PISOutr",55:"PISOutr",56:"PISOutr",60:"PISOutr",61:"PISOutr",62:"PISOutr",63:"PISOutr",64:"PISOutr",65:"PISOutr",66:"PISOutr",67:"PISOutr",70:"PISOutr",71:"PISOutr",72:"PISOutr",73:"PISOutr",74:"PISOutr",75:"PISOutr",98:"PISOutr",99:"PISOutr"},ICMSMap={"00":"ICMS00","02":"ICMS02",10:"ICMS10",20:"ICMS20",30:"ICMS30",40:"ICMS40",41:"ICMS40",50:"ICMS40",51:"ICMS51",60:"ICMS60",61:"ICMS61",70:"ICMS70",90:"ICMS90",101:"ICMSSN101",102:"ICMSSN102",103:"ICMSSN102",201:"ICMSSN201",202:"ICMSSN202",203:"ICMSSN202",500:"ICMSSN500",900:"ICMSSN900"},mountCOFINS=cofins=>{const{CST:CST}=cofins,cst_cofins=CST;let cofinsKey=COFINSMap[CST];cofinsKey||(console.warn(`Código de situação tributária do COFINS ${cst_cofins} não é reconhecido. Alterado para padrão 'COFINSAliq'.`),cofinsKey="COFINSAliq");const requiredFields={COFINSAliq:["CST","vBC","pCOFINS","vCOFINS"],COFINSQtde:["CST","qBCProd","vAliqProd","vCOFINS"],COFINSNT:["CST"],COFINSOutr:["CST","vBC","pCOFINS","qBCProd","vAliqProd","vCOFINS"]};if(cofinsKey in requiredFields){const cofinsProperties=filterFieldsByType(cofins,requiredFields[cofinsKey]);return{[cofinsKey]:cofinsProperties}}return console.warn(`Chave COFINS '${cofinsKey}' não reconhecida.`),{}},mountPIS=pis=>{const{CST:CST}=pis,cst_pis=CST;let pisKey=PISMap[cst_pis];pisKey||(console.warn(`Código de situação tributária do PIS ${cst_pis} não é reconhecido. Alterado para padrão 'PISAliq'.`),pisKey="PISAliq");const requiredFields={PISAliq:["CST","vBC","pPIS","vPIS"],PISQtde:["CST","qBCProd","vAliqProd","vPIS"],PISNT:["CST"],PISOutr:["CST","vBC","pPIS","qBCProd","vAliqProd","vPIS"]};if(pisKey in requiredFields){const pisProperties=filterFieldsByType(pis,requiredFields[pisKey]);return{[pisKey]:pisProperties}}return console.warn(`Chave PIS '${pisKey}' não reconhecida.`),{}},mountICMS=icms=>{const{CST:CST,CSOSN:CSOSN}=icms;let cod_sit=CST;CST?.trim()?.length>0?cod_sit=CST.length>2?CST.substring(1,3):CST:CSOSN&&(cod_sit=CSOSN?.trim()?.length>3?CSOSN.substring(1,4):String(CSOSN));let icmsKey=ICMSMap[cod_sit];icmsKey||(console.warn(`Código de situação tributária ${cod_sit} não é reconhecido. Alterado para padrão 'ICMS00'.`),icmsKey="ICMS00");const requiredFields={ICMS00:["orig","CST","modBC","vBC","pICMS","vICMS","pFCP","vFCP"],ICMS02:["orig","CST","qBCMono","adRemICMS","vICMSMono"],ICMS10:["orig","CST","modBC","vBC","pICMS","vICMS","vBCFCP","pFCP","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vICMSSTDeson","motDesICMSST"],ICMS15:["orig","CST","qBCMono","adRemICMS","vICMSMono","qBCMonoReten","adRemICMSReten","vICMSMonoReten","pRedAdRem","motRedAdRem"],ICMS20:["orig","CST","modBC","pRedBC","vBC","pICMS","vICMS","vBCFCP","pFCP","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS30:["orig","CST","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vBCFCPST","pFCPST","vFCPST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS40:["orig","CST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS41:["orig","CST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS50:["orig","CST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS51:["orig","CST","modBC","pRedBC","vBC","pICMS","vICMS","vICMSOp","pDif","vICMSDif"],ICMS53:["orig","CST","qBCMono","adRemICMS","vICMSMonoOp","pDif","vICMSMonoDif","vICMSMono","qBCMonoDif","adRemICMSDif"],ICMS60:["orig","CST","vBCSTRet","pST","vICMSSubstituto","vICMSSTRet","vBCFCPSTRet","pFCPSTRet","vFCPSTRet","pRedBCEfet","vBCEfet","pICMSEfet","vICMSEfet"],ICMS61:["orig","CST","qBCMonoRet","adRemICMSRet","vICMSMonoRet"],ICMS70:["orig","CST","modBC","pRedBC","vBC","pICMS","vICMS","vBCST","pICMSST","vICMSST","vICMSDeson","motDesICMS","indDeduzDeson","modBCST","pMVAST","pRedBCST"],ICMS90:["orig","CST","modBC","vBC","pRedBC","pICMS","vICMS","vBCFCP","pFCP","vFCP","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vBCFCPST","pFCPST","vFCPST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMSPart:["orig","CST","modBC","vBC","pRedBC","pICMS","vICMS","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","pBCOp","UFST","vBCFCPST","pFCPST","vFCPST"],ICMSST:["orig","CST","vBCSTRet","pST","vICMSSubstituto","vICMSSTRet","vBCFCPSTRet","pFCPSTRet","vFCPSTRet","vBCSTDest","vICMSSTDest"],ICMSSN101:["orig","CSOSN","pCredSN","vCredICMSSN"],ICMSSN102:["orig","CSOSN"],ICMSSN201:["orig","CSOSN","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","pFCPST","vFCPST"],ICMSSN202:["orig","CSOSN","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vFCPST","vBCFCPST","pFCPST"],ICMSSN500:["orig","CSOSN","vBCSTRet","pST","vICMSSubstituto","vICMSSTRet","vBCFCPSTRet","pFCPSTRet","vFCPSTRet","pRedBCEfet","vBCEfet","pICMSEfet","vICMSEfet"],ICMSSN900:["orig","CSOSN","modBC","vBC","pRedBC","pICMS","vICMS","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vBCFCPST","pFCPST","vFCPST","pCredSN","vCredICMSSN"]};if(icmsKey in requiredFields){const icmsProperties=filterFieldsByType(icms,requiredFields[icmsKey]);return{[icmsKey]:icmsProperties}}return console.warn(`Chave ICMS '${icmsKey}' não reconhecida.`),{}};class NFERetornoAutorizacaoService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFERetAutorizacao",axios,saveFiles,gerarConsulta)}gerarXml(data){const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe",versao:"4.00"},tpAmb:ambiente,nRec:data};return this.xmlBuilder.gerarXml(xmlObject,"consReciNFe",this.metodo)}async getRetornoRecibo(nRec,xmlNFe){const xmlConsulta=this.gerarXml(nRec),{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo);this.utility.salvaConsulta(xmlConsulta,xmlFormated,this.metodo);const xmlRetorno=await this.axios.post(webServiceUrl,xmlFormated,{headers:{"Content-Type":this.setContentType(),SOAPAction:action},httpsAgent:agent}),responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo);this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo);const{protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno.data);if(!protNFe)throw new Error("Não foi possível encontrar a tag 'protNFe'. Talvez a NFe ainda não tenha sido processada.");return this.getXmlRetornoAutorizacao(protNFe,xmlNFe)}getXmlRetornoAutorizacao(protNFe,xmlNFe){const XMLs=[];for(let i=0;i<protNFe.length;i++){const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},_:"[XML]"};let xml=this.xmlBuilder.gerarXml(baseXML,"nfeProc",this.metodo);const formatedProtNFe=protNFe,xmlCompleto=xmlNFe.find(item=>-1!==item.indexOf(formatedProtNFe[i].infProt[0].chNFe[0]));if(xmlCompleto){const protTag=this.xmlBuilder.gerarXml(protNFe[i],"protNFe",this.metodo),xmlFinal=[xmlCompleto];xmlFinal.push(protTag),xml=xml.replace("[XML]",xmlFinal.join("")),xml=`<?xml version="1.0" encoding="UTF-8"?>${xml}`,XMLs.push(xml)}}return{success:!0,message:"xMotivo",data:XMLs}}async getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:xmlNFe}){if(1===tipoEmissao&&protNFe)return this.getXmlRetornoAutorizacao(protNFe,xmlNFe);if(0===tipoEmissao&&nRec)return this.getRetornoRecibo(nRec,xmlNFe);throw new Error("Não foi possível buscar o retorno da autorização.")}}class NFEAutorizacaoService extends BaseNFE{xmlNFe;constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEAutorizacao",axios,saveFiles,gerarConsulta),this.xmlNFe=[]}gerarXml(data){return this.gerarXmlNFeAutorizacao(data)}salvaArquivos(xmlConsulta,responseInJson,xmlRetorno,options){const config=this.environment.getConfig();let dateAndTimeInFileName=config.dfe.incluirTimestampNoNomeDosArquivos;const createFileName=(prefix,includeMethodName)=>{const dtaTime=dateAndTimeInFileName?`-${format(new Date,"dd-MM-yyyy-HHmm")}`:"";return`${includeMethodName?`${this.metodo}`:""}${prefix?includeMethodName?`-${prefix}`:`${prefix}`:""}${responseInJson.chNFe?`-${responseInJson.chNFe}`:""}${dtaTime}`},salvarArquivo=(data,prefix,path,fileType,includeMethodName)=>{const fileName=createFileName(prefix,includeMethodName),method="xml"===fileType?"salvaXML":"salvaJSON";this.utility[method]({data:data,fileName:fileName,metodo:this.metodo,path:path})};let xmlAutorizacaoInJson={},xMotivoPorXml=[],xmlsInJson=[];if(options){const{xmlAutorizacao:xmlAutorizacao}=options,json=new XmlParser;for(let i=0;i<xmlAutorizacao.length;i++){xmlAutorizacaoInJson=json.convertXmlToJson(xmlAutorizacao[i],"NFEAutorizacaoFinal"),xmlsInJson.push(xmlAutorizacaoInJson);const chNFe=xmlAutorizacaoInJson.protNFe.infProt.chNFe,xMotivo=xmlAutorizacaoInJson.protNFe.infProt.xMotivo,cStat=xmlAutorizacaoInJson.protNFe.infProt.cStat;xMotivoPorXml.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat}),config.dfe.armazenarXMLAutorizacao&&(salvarArquivo(xmlAutorizacao[i],chNFe,config.dfe.pathXMLAutorizacao,"xml",!1),salvarArquivo(xmlAutorizacaoInJson,chNFe,config.dfe.pathXMLAutorizacao,"json",!1))}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}async trataRetorno(xmlRetorno,indSinc,responseInJson){const{nRec:nRec,protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno);let tipoEmissao=0;1===indSinc&&protNFe&&(tipoEmissao=1);const nfeRetornoAutService=new NFERetornoAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeRetornoAut=new NFERetornoAutorizacao(nfeRetornoAutService);1!==tipoEmissao&&await new Promise(resolve=>setTimeout(resolve,1e3*Number(responseInJson.infRec?.tMed||5)));return await nfeRetornoAut.getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:this.xmlNFe})}anoMesEmissao(dhEmi){const dataAtual=new Date(dhEmi);return dataAtual.getFullYear().toString().slice(-2)+(dataAtual.getMonth()+1).toString().padStart(2,"0")}gerarCodigoNumerico(){return Math.floor(1e8*Math.random()).toString().padStart(8,"0")}calcularModulo11(sequencia){const pesos=[4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2];let somatoria=0;for(let i=0;i<sequencia.length;i++)somatoria+=parseInt(sequencia.charAt(i))*pesos[i];const restoDivisao=somatoria%11;return 0===restoDivisao||1===restoDivisao?0:11-restoDivisao}calcularDigitoVerificador(data){const{infNFe:{Id:Id,ide:{cUF:cUF,mod:mod,serie:serie,nNF:nNF,tpEmis:tpEmis,cNF:cNF,dhEmi:dhEmi},emit:{CNPJCPF:CNPJCPF}}}=data;if(Id)return this.chaveNfe=Id,{chaveAcesso:`NFe${Id}`,dv:parseInt(Id.charAt(Id.length-1),10)};const sequencia=`${cUF}${this.anoMesEmissao(dhEmi)}${CNPJCPF}${mod}${String(serie).padStart(3,"0")}${String(nNF).padStart(9,"0")}${tpEmis}${cNF}`,dv=this.calcularModulo11(sequencia),chaveAcesso=`NFe${sequencia}`+dv;return this.chaveNfe=`${sequencia}${dv}`,{chaveAcesso:chaveAcesso,dv:dv}}validaDocumento(doc,campo){const nfeAutorizacaoHandler=new ValidaCPFCNPJ,{documentoValido:documentoValido,tipoDoDocumento:tipoDoDocumento}=nfeAutorizacaoHandler.validarCpfCnpj(doc);if(console.log({documentoValido:documentoValido,tipoDoDocumento:tipoDoDocumento}),!documentoValido||"Desconhecido"===tipoDoDocumento){throw new Error("Desconhecido"===tipoDoDocumento?`Documento do ${campo} ausente ou inválido`:`${tipoDoDocumento} do ${campo} é inválido`)}return tipoDoDocumento}gerarXmlNFeAutorizacao(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFEAutorizacaoService"});const createXML=NFe=>{if(NFe?.infNFe?.det instanceof Array){const formatedItens=NFe.infNFe.det.map((det,index)=>{if(det.imposto?.ICMS?.dadosICMS){const icms=mountICMS(det.imposto.ICMS.dadosICMS);det.imposto.ICMS=icms}if(det.imposto.PIS?.dadosPIS){const pis=mountPIS(det.imposto.PIS.dadosPIS);det.imposto.PIS=pis}if(det.imposto.COFINS?.dadosCOFINS){const cofins=mountCOFINS(det.imposto.COFINS.dadosCOFINS);det.imposto.COFINS=cofins}return{$:{nItem:index+1},...det}});NFe.infNFe.det=formatedItens}const{chaveAcesso:chaveAcesso,dv:dv}=this.calcularDigitoVerificador(NFe);if(NFe.infNFe.ide.cDV=dv,NFe.infNFe.ide.verProc=NFe.infNFe.ide.verProc||"1.0.0.0",delete NFe.infNFe.Id,NFe.infNFe.emit=Object.assign({[this.validaDocumento(String(NFe.infNFe.emit.CNPJCPF),"emitente")]:NFe.infNFe.emit.CNPJCPF},NFe.infNFe.emit),delete NFe.infNFe.emit.CNPJCPF,NFe.infNFe.dest&&(NFe.infNFe.dest=Object.assign({[this.validaDocumento(String(NFe.infNFe.dest?.CNPJCPF||""),"destinatário")]:NFe.infNFe.dest?.CNPJCPF||""},NFe.infNFe.dest),delete NFe.infNFe.dest.CNPJCPF),NFe.infNFe.transp.transporta&&(NFe.infNFe.transp.transporta=Object.assign({[this.validaDocumento(String(NFe.infNFe.transp.transporta?.CNPJCPF),"transportador")]:NFe.infNFe.transp.transporta?.CNPJCPF},NFe.infNFe.transp.transporta),delete NFe.infNFe.transp.transporta?.CNPJCPF),NFe.infNFe?.NFref instanceof Array){const NFrefArray=NFe.infNFe.NFref;NFrefArray&&NFrefArray.length>0&&(NFe.infNFe.NFref=NFrefArray.map(NFref=>(NFref.refNFP&&(NFref.refNFP=Object.assign({[this.validaDocumento(String(NFref.refNFP.CNPJCPF),"produtor rural")]:NFref.refNFP.CNPJCPF},NFref.refNFP),delete NFref.refNFP.CNPJCPF),NFref)))}else NFe.infNFe.NFref&&NFe.infNFe.NFref.refNFP&&(NFe.infNFe.NFref.refNFP=Object.assign({[this.validaDocumento(String(NFe.infNFe.NFref.refNFP.CNPJCPF),"produtor rural")]:NFe.infNFe.NFref.refNFP.CNPJCPF},NFe.infNFe.NFref.refNFP));NFe.infNFe.dest&&2===NFe.infNFe.ide.tpAmb&&(NFe.infNFe.dest.xNome="NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL");const xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe"},infNFe:{$:{versao:"4.00",Id:chaveAcesso},...NFe.infNFe}},eventoXML=this.xmlBuilder.gerarXml(xmlObject,"NFe",this.metodo),xmlAssinado=this.xmlBuilder.assinarXML(eventoXML,"infNFe");this.xmlNFe.push(xmlAssinado)};if(data.NFe instanceof Array)for(let i=0;i<data.NFe.length;i++){createXML(data.NFe[i])}else createXML(data.NFe);const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},idLote:data.idLote,indSinc:data.indSinc,_:"[XML]"};return this.xmlBuilder.gerarXml(baseXML,"enviNFe",this.metodo).replace("[XML]",this.xmlNFe.join(""))}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType};logger.http("Iniciando comunicação com o webservice",{context:"NFEAutorizacaoService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"NFEAutorizacaoService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlNFeAutorizacao(data);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo);xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent);responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo);const retorno=await this.trataRetorno(xmlRetorno.data,data.indSinc,responseInJson),xmlFinal=this.salvaArquivos(xmlConsulta,responseInJson,xmlRetorno.data,{xmlAutorizacao:retorno.data,xMotivo:retorno.message});return logger.info("NFe transmitida com sucesso",{context:"NFEAutorizacaoService"}),{success:!0,xMotivo:xmlFinal.xMotivo,xmls:xmlFinal.response}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class NFEconsultaProtocoloService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEConsultaProtocolo",axios,saveFiles,gerarConsulta)}gerarXml(chave){logger.info("Montando estrutuda do XML em JSON",{context:"NFEconsultaProtocoloService"});const{nfe:{ambiente:ambiente,versaoDF:versaoDF}}=this.environment.getConfig(),xmlObject={$:{versao:versaoDF,xmlns:"http://www.portalfiscal.inf.br/nfe"},tpAmb:ambiente,xServ:"CONSULTAR",chNFe:chave};return this.xmlBuilder.gerarXml(xmlObject,"consSitNFe",this.metodo)}}class NFEStatusServico{nfeStatusServicoService;constructor(nfeStatusServicoService){this.nfeStatusServicoService=nfeStatusServicoService}async Exec(data){return await this.nfeStatusServicoService.Exec(data)}}class NFERecepcaoEvento{nfeRecepcaoEventoService;constructor(nfeRecepcaoEventoService){this.nfeRecepcaoEventoService=nfeRecepcaoEventoService}async Exec(data){return await this.nfeRecepcaoEventoService.Exec(data)}}class NFERecepcaoEventoService extends BaseNFE{tpEvento;modelo;xmlEventosNacionais;xmlEventosRegionais;xMotivoPorEvento;constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"RecepcaoEvento",axios,saveFiles,gerarConsulta),this.tpEvento="",this.modelo="NFe",this.xmlEventosNacionais=[],this.xmlEventosRegionais=[],this.xMotivoPorEvento=[],console.log("constructor recepcao evento service")}getID(evento){const{tpEvento:tpEvento,chNFe:chNFe,nSeqEvento:nSeqEvento}=evento;if("string"!=typeof tpEvento||!/^\d{6}$/.test(tpEvento))throw new Error("tpEvento deve ser uma string com 6 dígitos.");if("string"!=typeof chNFe||!/^\d{44}$/.test(chNFe))throw new Error("chNFe deve ser uma string com 44 dígitos.");if(!Number.isInteger(nSeqEvento)||nSeqEvento<1||nSeqEvento>99)throw new Error("nSeqEvento deve ser um número entre 1 e 99.");const id=`ID${tpEvento}${chNFe}${nSeqEvento.toString().padStart(2,"0")}`;if(54!==id.length)throw new Error("O ID construído não tem 54 caracteres.");return id}isAmbienteNacional(tpEvento){switch(tpEvento){case"210210":case"210200":case"210220":case"210240":case"110140":return!0;default:return!1}}getTipoEventoName(tpEvento){switch(tpEvento){case"210210":return"Ciência da Operação";case"210200":return"Confirmação da Operaçã";case"210220":return"Desconhecimento da Operação";case"210240":return"Operação não Realizada";case"110110":return"Carta de Correção";case"110111":return"Cancelamento";case"110140":return"EPEC";default:return"Desconhecido"}}separaEventosPorAmbiente(evento){logger.info("Dividindo eventos por ambiente",{context:"NFERecepcaoEventoService"});return{nacional:evento.filter(event=>["210210","210200","210220","210240","110140"].includes(event.tpEvento)),regional:evento.filter(event=>!["210210","210200","210220","210240","110140"].includes(event.tpEvento))}}gerarXmlRecepcaoEvento(evento,idLote,ambienteNacional){const{nfe:{ambiente:ambiente,versaoDF:versaoDF},dfe:{UF:UF}}=this.environment.getConfig();for(let i=0;i<evento.length;i++){const eventoProps=evento[i],{tpAmb:tpAmb,cOrgao:cOrgao,tpEvento:tpEvento,chNFe:chNFe,nSeqEvento:nSeqEvento,CNPJ:CNPJ,CPF:CPF,detEvento:detEvento,dhEvento:dhEvento,verEvento:verEvento}=eventoProps,idEvento=this.getID(eventoProps),orgao=ambienteNacional?91:cOrgao;this.tpEvento=tpEvento;const eventoObject={$:{versao:"1.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},infEvento:{$:{Id:idEvento},cOrgao:orgao,tpAmb:ambiente,...CNPJ?{CNPJ:CNPJ}:{CPF:CPF},chNFe:chNFe,dhEvento:dhEvento,tpEvento:tpEvento,nSeqEvento:nSeqEvento,verEvento:verEvento,detEvento:{$:{versao:"1.00"},...detEvento}}},eventoXML=this.xmlBuilder.gerarXml(eventoObject,"evento",this.metodo),xmlAssinado=this.xmlBuilder.assinarXML(eventoXML,"infEvento");ambienteNacional?this.xmlEventosNacionais.push(xmlAssinado):this.xmlEventosRegionais.push(xmlAssinado)}const envEvento={$:{versao:"1.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},idLote:idLote,_:"[XML]"},xml=this.xmlBuilder.gerarXml(envEvento,"envEvento",this.metodo);return ambienteNacional?xml.replace("[XML]",this.xmlEventosNacionais.join("")):xml.replace("[XML]",this.xmlEventosRegionais.join(""))}trataRetorno(responseInJson){logger.info("Tratando retorno dos eventos",{context:"NFERecepcaoEventoService"});const retornoEventos=this.utility.findInObj(responseInJson,"retEvento");if(retornoEventos instanceof Array){for(let i=0;i<retornoEventos.length;i++){const chNFe=retornoEventos[i].infEvento.chNFe,xMotivo=retornoEventos[i].infEvento.xMotivo,cStat=retornoEventos[i].infEvento.cStat,tipoEvento=this.getTipoEventoName(retornoEventos[i].infEvento.tpEvento);this.xMotivoPorEvento.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat,tipoEvento:tipoEvento})}return this.xMotivoPorEvento}const chNFe=retornoEventos.infEvento.chNFe,xMotivo=retornoEventos.infEvento.xMotivo,cStat=retornoEventos.infEvento.cStat,tipoEvento=this.getTipoEventoName(retornoEventos.infEvento.tpEvento);return this.xMotivoPorEvento.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat,tipoEvento:tipoEvento}),this.xMotivoPorEvento}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType,SOAPAction:action};logger.http("Iniciando comunicação com o webservice",{context:"BaseNFE",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"BaseNFE",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async enviaEvento(evento,idLote,tipoAmbiente){let xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="";const ContentType=this.setContentType(),ambienteNacional=0===tipoAmbiente;try{xmlConsulta=this.gerarXmlRecepcaoEvento(evento,idLote,ambienteNacional);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,ambienteNacional||this.isAmbienteNacional(this.tpEvento),"",this.modelo);xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;return(await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent)).data}finally{const fileName=ambienteNacional?"RecepcaoEvento[Nacional]-consulta":"RecepcaoEvento[Regional]-consulta";this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo,fileName)}}async Exec(data){const{evento:evento,idLote:idLote,modelo:modelo}=data,{nacional:nacional,regional:regional}=this.separaEventosPorAmbiente(evento);"65"===modelo&&(this.modelo="NFCe");let responseNacionalInJson,responseRegionalInJson=null,finalResponseInJson=[];if(nacional.length>0){const retornoNacional=await this.enviaEvento(nacional,idLote,0);responseNacionalInJson=this.utility.verificaRejeicao(retornoNacional,this.metodo),this.utility.salvaRetorno(retornoNacional,responseNacionalInJson,this.metodo,"RecepcaoEvento[Nacional]-retorno"),this.trataRetorno(responseNacionalInJson),finalResponseInJson.push(responseNacionalInJson)}if(regional.length>0){const retornoRegional=await this.enviaEvento(regional,idLote,1);responseRegionalInJson=this.utility.verificaRejeicao(retornoRegional,this.metodo),this.utility.salvaRetorno(retornoRegional,responseRegionalInJson,this.metodo,"RecepcaoEvento[Regional]-retorno"),this.trataRetorno(responseRegionalInJson),finalResponseInJson.push(responseRegionalInJson)}return{success:!0,xMotivos:this.xMotivoPorEvento,response:finalResponseInJson}}}class NFECancelamentoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFECartaDeCorrecaoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFECienciaDaOperacaoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEDesconhecimentoDaOperacaoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEEpecService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEOperacaoNaoRealizadaService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEAutorizacao{nfeAutorizacaoService;constructor(nfeAutorizacaoService){this.nfeAutorizacaoService=nfeAutorizacaoService}async Exec(data){return await this.nfeAutorizacaoService.Exec(data)}}class DistribuicaoHandler{environment;utility;metodo;constructor(environment,utility,metodo){this.utility=utility,this.environment=environment,this.metodo=metodo}salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chNFe){const{pathXMLDistribuicao:pathXMLDistribuicao,baixarXMLDistribuicao:baixarXMLDistribuicao,armazenarRetornoEmJSON:armazenarRetornoEmJSON}=this.environment.config.dfe;baixarXMLDistribuicao&&(this.utility.salvaXML({data:XMLDistribuicao,fileName:chNFe,metodo:this.metodo,path:pathXMLDistribuicao}),armazenarRetornoEmJSON&&this.utility.salvaJSON({data:XMLDistribuicaoInJson,fileName:chNFe,metodo:this.metodo,path:pathXMLDistribuicao}))}deCompressDFeXML(loteDistDFeInt,metodo,xmlConsulta){logger.info("Descomprimindo XML",{context:"DistribuicaoHandler"});const json=new XmlParser,files=[];return xml2js$1.parseString(loteDistDFeInt,(err,result)=>{if(err)throw new Error(`Erro ao descomprimir o XML: ${err}`);this.utility.findInObj(result,"docZip").forEach(docZip=>{const xmlString=this.decodeDocZip(docZip),cleanedXml=this.removeSignatureTag(xmlString),parsedResult=this.parseXml(cleanedXml);if(!parsedResult)return;let chNFe=this.getChNFe(parsedResult),tipo=this.getTipo(parsedResult);const nsu=docZip.$.NSU;if(parsedResult.procEventoNFe){chNFe=`${chNFe}-event-${this.utility.findInObj(parsedResult,"tpEvento")}`,tipo="event"}const xmlDistribuicaoInJson=json.convertXmlToJson(cleanedXml,`${metodo}_${tipo}`,nsu);this.handleResponse(xmlDistribuicaoInJson,cleanedXml,chNFe),files.push(chNFe)})}),files}decodeDocZip(docZip){logger.info("Decodificando DocZip",{context:"DistribuicaoHandler"});const base64String=docZip._;let binaryString=atob(base64String),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);let decompressedData=pako.inflate(bytes);return new TextDecoder("utf-8").decode(decompressedData)}removeSignatureTag(xmlString){return xmlString.replace(/<Signature.*?<\/Signature>/gs,"")}parseXml(xmlString){let parsedResult;return xml2js$1.parseString(xmlString,(err,result)=>{err?(console.error("Erro ao parsear o XML decomprimido:",err),parsedResult=null):parsedResult=result}),parsedResult}getChNFe(parsedResult){return this.utility.findInObj(parsedResult,"chNFe")}getTipo(parsedResult){return this.utility.findInObj(parsedResult,"resNFe")?"res":parsedResult.procEventoNFe?"event":"proc"}handleResponse(XMLDistribuicaoInJson,XMLDistribuicao,chNFe){this.salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chNFe);const xMotivo=this.utility.findInObj(XMLDistribuicaoInJson,"xMotivo");if(xMotivo&&(xMotivo.includes("Rejeição")||xMotivo.includes("Rejeicao")))throw new Error(XMLDistribuicaoInJson.xMotivo)}}class NFEDistribuicaoDFeService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFeDistribuicaoDFe",axios,saveFiles,gerarConsulta)}gerarXml(data){return this.gerarXmlNFeDistribuicaoDFe(data)}gerarXmlNFeDistribuicaoDFe(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFEDistribuicaoDFeService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{versao:"1.01",xmlns:"http://www.portalfiscal.inf.br/nfe"},tpAmb:ambiente,...data};return this.xmlBuilder.gerarXml(xmlObject,"distDFeInt",this.metodo)}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType};logger.http("Iniciando comunicação com o webservice",{context:"NFEDistribuicaoDFeService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"NFEDistribuicaoDFeService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlNFeDistribuicaoDFe(data);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,!0,"1.01","NFe",!0,"nfeDistDFeInteresse");xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent);if(responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo),"137"===responseInJson.retDistDFeInt.cStat)return{data:{},xMotivo:responseInJson.retDistDFeInt.xMotivo,filesList:[]};const filesList=new DistribuicaoHandler(this.environment,this.utility,this.metodo).deCompressDFeXML(xmlRetorno.data,this.metodo,xmlConsulta);return{data:responseInJson,xMotivo:this.utility.findInObj(responseInJson,"xMotivo"),filesList:filesList}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class NFEDistribuicaoDFePorUltNSUService extends NFEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEDistribuicaoDFePorNSUService extends NFEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEDistribuicaoDFePorChaveService extends NFEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEInutilizacaoService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEInutilizacao",axios,saveFiles,gerarConsulta)}gerarXml(chave){return this.gerarXmlNFeInutilizacao(chave)}criarId(codigoUF,ano,cnpj,modelo,serie,numeroInicial,numeroFinal){return`ID${codigoUF}${ano}${cnpj}${modelo}${serie}${numeroInicial}${numeroFinal}`}getModelo(data){return data?.mod?"55"===data.mod?"NFe":"NFCe":super.getModelo(data)}gerarXmlNFeInutilizacao(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFEInutilizacaoService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),{cUF:cUF,ano:ano,CNPJ:CNPJ,mod:mod,serie:serie,nNFIni:nNFIni,nNFFin:nNFFin,xJust:xJust}=data,anoFormatado=ano.toString().slice(-2),serieFormatada=serie.padStart(3,"0"),numNFIniFormatado=nNFIni.padStart(9,"0"),numNFFinFormatado=nNFFin.padStart(9,"0"),id=this.criarId(cUF,anoFormatado,CNPJ,mod,serieFormatada,numNFIniFormatado,numNFFinFormatado);if(-1===[55,65].indexOf(Number(mod)))throw new Error(`Modelo do documento para inutilização deve ser 55 ou 65. Modelo informado: ${mod}`);const xmlObject={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},infInut:{$:{Id:`${id}`},tpAmb:ambiente,xServ:"INUTILIZAR",cUF:cUF,ano:ano,CNPJ:CNPJ,mod:mod,serie:serie,nNFIni:nNFIni,nNFFin:nNFFin,xJust:xJust}},xml=this.xmlBuilder.gerarXml(xmlObject,"inutNFe",this.metodo);return this.xmlBuilder.assinarXML(xml,"infInut")}}var hasRequiredCrypt,charenc_1,hasRequiredCharenc,hasRequiredSha1,sha1$1={exports:{}},crypt={exports:{}};function requireCrypt(){return hasRequiredCrypt||(hasRequiredCrypt=1,base64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",crypt$1={rotl:function(n,b){return n<<b|n>>>32-b},rotr:function(n,b){return n<<32-b|n>>>b},endian:function(n){if(n.constructor==Number)return 16711935&crypt$1.rotl(n,8)|4278255360&crypt$1.rotl(n,24);for(var i=0;i<n.length;i++)n[i]=crypt$1.endian(n[i]);return n},randomBytes:function(n){for(var bytes=[];n>0;n--)bytes.push(Math.floor(256*Math.random()));return bytes},bytesToWords:function(bytes){for(var words=[],i=0,b=0;i<bytes.length;i++,b+=8)words[b>>>5]|=bytes[i]<<24-b%32;return words},wordsToBytes:function(words){for(var bytes=[],b=0;b<32*words.length;b+=8)bytes.push(words[b>>>5]>>>24-b%32&255);return bytes},bytesToHex:function(bytes){for(var hex=[],i=0;i<bytes.length;i++)hex.push((bytes[i]>>>4).toString(16)),hex.push((15&bytes[i]).toString(16));return hex.join("")},hexToBytes:function(hex){for(var bytes=[],c=0;c<hex.length;c+=2)bytes.push(parseInt(hex.substr(c,2),16));return bytes},bytesToBase64:function(bytes){for(var base64=[],i=0;i<bytes.length;i+=3)for(var triplet=bytes[i]<<16|bytes[i+1]<<8|bytes[i+2],j=0;j<4;j++)8*i+6*j<=8*bytes.length?base64.push(base64map.charAt(triplet>>>6*(3-j)&63)):base64.push("=");return base64.join("")},base64ToBytes:function(base64){base64=base64.replace(/[^A-Z0-9+\/]/gi,"");for(var bytes=[],i=0,imod4=0;i<base64.length;imod4=++i%4)0!=imod4&&bytes.push((base64map.indexOf(base64.charAt(i-1))&Math.pow(2,-2*imod4+8)-1)<<2*imod4|base64map.indexOf(base64.charAt(i))>>>6-2*imod4);return bytes}},crypt.exports=crypt$1),crypt.exports;var base64map,crypt$1}function requireCharenc(){if(hasRequiredCharenc)return charenc_1;hasRequiredCharenc=1;var charenc={utf8:{stringToBytes:function(str){return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)))},bytesToString:function(bytes){return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)))}},bin:{stringToBytes:function(str){for(var bytes=[],i=0;i<str.length;i++)bytes.push(255&str.charCodeAt(i));return bytes},bytesToString:function(bytes){for(var str=[],i=0;i<bytes.length;i++)str.push(String.fromCharCode(bytes[i]));return str.join("")}}};return charenc_1=charenc}var sha1Exports=function requireSha1(){return hasRequiredSha1||(hasRequiredSha1=1,function(){var crypt=requireCrypt(),utf8=requireCharenc().utf8,bin=requireCharenc().bin,api=function(message,options){var digestbytes=crypt.wordsToBytes(function(message){message.constructor==String?message=utf8.stringToBytes(message):"undefined"!=typeof Buffer&&"function"==typeof Buffer.isBuffer&&Buffer.isBuffer(message)?message=Array.prototype.slice.call(message,0):Array.isArray(message)||(message=message.toString());var m=crypt.bytesToWords(message),l=8*message.length,w=[],H0=1732584193,H1=-271733879,H2=-1732584194,H3=271733878,H4=-1009589776;m[l>>5]|=128<<24-l%32,m[15+(l+64>>>9<<4)]=l;for(var i=0;i<m.length;i+=16){for(var a=H0,b=H1,c=H2,d=H3,e=H4,j=0;j<80;j++){if(j<16)w[j]=m[i+j];else{var n=w[j-3]^w[j-8]^w[j-14]^w[j-16];w[j]=n<<1|n>>>31}var t=(H0<<5|H0>>>27)+H4+(w[j]>>>0)+(j<20?1518500249+(H1&H2|~H1&H3):j<40?1859775393+(H1^H2^H3):j<60?(H1&H2|H1&H3|H2&H3)-1894007588:(H1^H2^H3)-899497514);H4=H3,H3=H2,H2=H1<<30|H1>>>2,H1=H0,H0=t}H0+=a,H1+=b,H2+=c,H3+=d,H4+=e}return[H0,H1,H2,H3,H4]}(message));return options&&options.asBytes?digestbytes:options&&options.asString?bin.bytesToString(digestbytes):crypt.bytesToHex(digestbytes)};api._blocksize=16,api._digestsize=20,sha1$1.exports=api}()),sha1$1.exports}(),sha1=getDefaultExportFromCjs(sha1Exports);function generateQRCodeURLOnline(chaveAcesso,versaoQRCode,tipoAmbiente,identificadorCSC,csc,utility){const urlQRCodeNFCe=utility.getUrlNFCe("URL-QRCode",!1,""),baseString=`${chaveAcesso=chaveAcesso.replace("NFe","")}|${versaoQRCode}|${tipoAmbiente}|${identificadorCSC}`;return`${urlQRCodeNFCe}?p=${baseString}|${function generateSHA1Hash(input){return require$$0$4.createHash("sha1").update(input).digest("hex")}(`${baseString}${csc}`)}`}function generateQRCodeURLOffline(chaveAcesso,versaoQRCode,tipoAmbiente,diaDataEmissao,valorTotalNfce,digVal,identificadorCSC,csc,utility){const urlQRCodeNFCe=utility.getUrlNFCe("URL-QRCode",!1,"");chaveAcesso=chaveAcesso.replace("NFe","");const digestValueHex=function calcularDigestValueHex(digVal){return Buffer.from(digVal).toString("hex")}(digVal),baseString=`${chaveAcesso}|${versaoQRCode}|${tipoAmbiente}|${diaDataEmissao}|${valorTotalNfce}|${digestValueHex}|${identificadorCSC}`;return`${urlQRCodeNFCe}?p=${baseString}|${sha1(`${baseString}${csc}`).toUpperCase()}`}class NFCERetornoAutorizacaoService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFERetAutorizacao",axios,saveFiles,gerarConsulta)}gerarXml(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFCEAutorizacaoService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe",versao:"4.00"},tpAmb:ambiente,nRec:data};return this.xmlBuilder.gerarXml(xmlObject,"consReciNFe",this.metodo)}async getRetornoRecibo(nRec,xmlNFe){const xmlConsulta=this.gerarXml(nRec),{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo);this.utility.salvaConsulta(xmlConsulta,xmlFormated,this.metodo);const xmlRetorno=await this.axios.post(webServiceUrl,xmlFormated,{headers:{"Content-Type":this.setContentType(),SOAPAction:action},httpsAgent:agent}),responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo);this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo);const{protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno.data);if(!protNFe)throw new Error("Não foi possível encontrar a tag 'protNFe'. Talvez a NFe ainda não tenha sido processada.");return this.getXmlRetornoAutorizacao(protNFe,xmlNFe)}getXmlRetornoAutorizacao(protNFe,xmlNFe){const XMLs=[];for(let i=0;i<protNFe.length;i++){const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},_:"[XML]"};let xml=this.xmlBuilder.gerarXml(baseXML,"nfeProc",this.metodo);const formatedProtNFe=protNFe,xmlCompleto=xmlNFe.find(item=>-1!==item.indexOf(formatedProtNFe[i].infProt[0].chNFe[0]));if(xmlCompleto){const protTag=this.xmlBuilder.gerarXml(protNFe[i],"protNFe",this.metodo),xmlFinal=[xmlCompleto];xmlFinal.push(protTag),xml=xml.replace("[XML]",xmlFinal.join("")),xml=`<?xml version="1.0" encoding="UTF-8"?>${xml}`,XMLs.push(xml)}}return{success:!0,message:"xMotivo",data:XMLs}}async getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:xmlNFe}){if(1===tipoEmissao&&protNFe)return this.getXmlRetornoAutorizacao(protNFe,xmlNFe);if(0===tipoEmissao&&nRec)return this.getRetornoRecibo(nRec,xmlNFe);throw new Error("Não foi possível buscar o retorno da autorização.")}}class NFCERetornoAutorizacao{nfceAutorizacaoRetornoService;constructor(nfceAutorizacaoRetornoService){this.nfceAutorizacaoRetornoService=nfceAutorizacaoRetornoService}async getXmlRetorno(data){return await this.nfceAutorizacaoRetornoService.getXmlRetorno(data)}}class NFCEAutorizacaoService extends BaseNFE{xmlNFe;constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEAutorizacao",axios,saveFiles,gerarConsulta),this.xmlNFe=[]}gerarXml(data){return this.gerarXmlNFCEAutorizacao(data)}salvaArquivos(xmlConsulta,responseInJson,xmlRetorno,options){const config=this.environment.getConfig();let dateAndTimeInFileName=config.dfe.incluirTimestampNoNomeDosArquivos;const createFileName=(prefix,includeMethodName)=>{const dtaTime=dateAndTimeInFileName?`-${format(new Date,"dd-MM-yyyy-HHmm")}`:"";return`${includeMethodName?`${this.metodo}`:""}${prefix?includeMethodName?`-${prefix}`:`${prefix}`:""}${responseInJson.chNFe?`-${responseInJson.chNFe}`:""}${dtaTime}`},salvarArquivo=(data,prefix,path,fileType,includeMethodName)=>{const fileName=createFileName(prefix,includeMethodName),method="xml"===fileType?"salvaXML":"salvaJSON";this.utility[method]({data:data,fileName:fileName,metodo:this.metodo,path:path})};let xmlAutorizacaoInJson={},xMotivoPorXml=[],xmlsInJson=[];if(options){const{xmlAutorizacao:xmlAutorizacao}=options,json=new XmlParser;for(let i=0;i<xmlAutorizacao.length;i++){xmlAutorizacaoInJson=json.convertXmlToJson(xmlAutorizacao[i],"NFCEAutorizacaoFinal"),xmlsInJson.push(xmlAutorizacaoInJson);const chNFe=xmlAutorizacaoInJson.protNFe.infProt.chNFe,xMotivo=xmlAutorizacaoInJson.protNFe.infProt.xMotivo,cStat=xmlAutorizacaoInJson.protNFe.infProt.cStat;xMotivoPorXml.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat}),config.dfe.armazenarXMLAutorizacao&&(salvarArquivo(xmlAutorizacao[i],chNFe,config.dfe.pathXMLAutorizacao,"xml",!1),salvarArquivo(xmlAutorizacaoInJson,chNFe,config.dfe.pathXMLAutorizacao,"json",!1))}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}async trataRetorno(xmlRetorno,indSinc,responseInJson){try{const{nRec:nRec,protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno);let tipoEmissao=0;1===indSinc&&protNFe&&(tipoEmissao=1);const nfeRetornoAutService=new NFCERetornoAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeRetornoAut=new NFCERetornoAutorizacao(nfeRetornoAutService);return await nfeRetornoAut.getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:this.xmlNFe})}catch(error){throw new Error(error.message)}}anoMesEmissao(dhEmi){const dataAtual=new Date(dhEmi);return dataAtual.getFullYear().toString().slice(-2)+(dataAtual.getMonth()+1).toString().padStart(2,"0")}diaEmissao(dhEmi){return new Date(dhEmi).getDate().toString().padStart(2,"0")}calcularModulo11(sequencia){const pesos=[4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2];let somatoria=0;for(let i=0;i<sequencia.length;i++)somatoria+=parseInt(sequencia.charAt(i))*pesos[i];const restoDivisao=somatoria%11;return 0===restoDivisao||1===restoDivisao?0:11-restoDivisao}calcularDigitoVerificador(data){const{infNFe:{Id:Id,ide:{cUF:cUF,mod:mod,serie:serie,nNF:nNF,tpEmis:tpEmis,cNF:cNF,dhEmi:dhEmi},emit:{CNPJCPF:CNPJCPF}}}=data;if(Id)return this.chaveNfe=Id,{chaveAcesso:`NFe${Id}`,dv:parseInt(Id.charAt(Id.length-1),10)};const sequencia=`${cUF}${this.anoMesEmissao(dhEmi)}${CNPJCPF}${mod}${String(serie).padStart(3,"0")}${String(nNF).padStart(9,"0")}${tpEmis}${cNF}`,dv=this.calcularModulo11(sequencia),chaveAcesso=`NFe${sequencia}`+dv;return this.chaveNfe=`${sequencia}${dv}`,{chaveAcesso:chaveAcesso,dv:dv}}validaDocumento(doc,campo){const nfeAutorizacaoHandler=new ValidaCPFCNPJ,{documentoValido:documentoValido,tipoDoDocumento:tipoDoDocumento}=nfeAutorizacaoHandler.validarCpfCnpj(doc);if(!documentoValido||"Desconhecido"===tipoDoDocumento){throw new Error("Desconhecido"===tipoDoDocumento?`Documento do ${campo} ausente ou inválido`:`${tipoDoDocumento} do ${campo} é inválido`)}return tipoDoDocumento}extrairDigestValue(xmlAssinado){const match=xmlAssinado.match(/<DigestValue>([^<]+)<\/DigestValue>/);if(match&&match[1])return match[1];throw new Error("DigestValue não encontrado no XML assinado.")}gerarXmlNFCEAutorizacao(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFCEAutorizacaoService"});const createXML=NFe=>{if(NFe?.infNFe?.det instanceof Array){const formatedItens=NFe.infNFe.det.map((det,index)=>{if(det.imposto.ICMS?.dadosICMS){const icms=mountICMS(det.imposto.ICMS.dadosICMS);det.imposto.ICMS=icms}if(det.imposto.PIS?.dadosPIS){const pis=mountPIS(det.imposto.PIS.dadosPIS);det.imposto.PIS=pis}if(det.imposto.COFINS?.dadosCOFINS){const cofins=mountCOFINS(det.imposto.COFINS.dadosCOFINS);det.imposto.COFINS=cofins}return{$:{nItem:index+1},...det}});NFe.infNFe.det=formatedItens}const{chaveAcesso:chaveAcesso,dv:dv}=this.calcularDigitoVerificador(NFe);if(NFe.infNFe.ide.cDV=dv,NFe.infNFe.ide.verProc=NFe.infNFe.ide.verProc||"1.0.0.0",NFe.infNFe.emit=Object.assign({[this.validaDocumento(String(NFe.infNFe.emit.CNPJCPF),"emitente")]:NFe.infNFe.emit.CNPJCPF},NFe.infNFe.emit),delete NFe.infNFe.emit.CNPJCPF,NFe.infNFe.dest&&(NFe.infNFe.dest=Object.assign({[this.validaDocumento(String(NFe.infNFe.dest?.CNPJCPF||""),"destinatário")]:NFe.infNFe.dest?.CNPJCPF||""},NFe.infNFe.dest),delete NFe.infNFe.dest.CNPJCPF),NFe.infNFe.transp.transporta&&(NFe.infNFe.transp.transporta=Object.assign({[this.validaDocumento(String(NFe.infNFe.transp.transporta?.CNPJCPF),"transportador")]:NFe.infNFe.transp.transporta?.CNPJCPF},NFe.infNFe.transp.transporta),delete NFe.infNFe.transp.transporta?.CNPJCPF),NFe.infNFe?.NFref instanceof Array){const NFrefArray=NFe.infNFe.NFref;NFrefArray&&NFrefArray.length>0&&(NFe.infNFe.NFref=NFrefArray.map(NFref=>(NFref.refNFP&&(NFref.refNFP=Object.assign({[this.validaDocumento(String(NFref.refNFP.CNPJCPF),"produtor rural")]:NFref.refNFP.CNPJCPF},NFref.refNFP),delete NFref.refNFP.CNPJCPF),NFref)))}else NFe.infNFe.NFref&&NFe.infNFe.NFref.refNFP&&(NFe.infNFe.NFref.refNFP=Object.assign({[this.validaDocumento(String(NFe.infNFe.NFref.refNFP.CNPJCPF),"produtor rural")]:NFe.infNFe.NFref.refNFP.CNPJCPF},NFe.infNFe.NFref.refNFP));NFe.infNFe.dest&&2===NFe.infNFe.ide.tpAmb&&(NFe.infNFe.dest.xNome="NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL");const{nfe:{idCSC:idCSC,tokenCSC:tokenCSC}}=this.environment.getConfig();let qrCode="";[4,9].includes(NFe.infNFe.ide.tpEmis)||(qrCode=generateQRCodeURLOnline(chaveAcesso,"2",NFe.infNFe.ide.tpAmb,Number(idCSC),String(tokenCSC),this.utility));const urlConsultaNFCe=this.utility.getUrlNFCe("URL-ConsultaNFCe",!1,""),xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe"},infNFe:{$:{versao:"4.00",Id:chaveAcesso},...(NFe={...NFe,infNFeSupl:{qrCode:qrCode,urlChave:urlConsultaNFCe}}).infNFe},infNFeSupl:{...NFe.infNFeSupl}},eventoXML=this.xmlBuilder.gerarXml(xmlObject,"NFe",this.metodo);let xmlAssinado=this.xmlBuilder.assinarXML(eventoXML,"infNFe");if([4,9].includes(NFe.infNFe.ide.tpEmis)){const digestValue=this.extrairDigestValue(xmlAssinado),tpAmb=NFe.infNFe.ide.tpAmb,valNF=NFe.infNFe.total.ICMSTot.vNF,diaEmissao=this.diaEmissao(NFe.infNFe.ide.dhEmi);qrCode=generateQRCodeURLOffline(chaveAcesso,"2",tpAmb,diaEmissao,valNF,digestValue,Number(idCSC),String(tokenCSC),this.utility),xml2js$1.parseString(xmlAssinado,(err,result)=>{if(err)throw new Error("Erro ao parsear o XML para atualização do qrCode:");if(!result.NFe?.infNFeSupl[0]?.qrCode)throw new Error("Tag qrCode não encontrada no XML.");{result.NFe.infNFeSupl[0].qrCode[0]=qrCode;const builder=new xml2jsExports.Builder({headless:!0,renderOpts:{pretty:!1}});xmlAssinado=builder.buildObject(result)}})}this.xmlNFe.push(xmlAssinado)};if(data.NFe instanceof Array)for(let i=0;i<data.NFe.length;i++){createXML(data.NFe[i])}else createXML(data.NFe);const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},idLote:data.idLote,indSinc:data.indSinc,_:"[XML]"};return this.xmlBuilder.gerarXml(baseXML,"enviNFe",this.metodo).replace("[XML]",this.xmlNFe.join(""))}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),{nfe:{tokenCSC:tokenCSC}}=this.environment.getConfig(),headers={"Content-Type":ContentType,SOAPAction:action,CSC:tokenCSC};logger.http("Iniciando comunicação com o webservice",{context:"NFCEAutorizacaoService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"NFCEAutorizacaoService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlNFCEAutorizacao(data);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,!1,"","NFCe");xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent),responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo),retorno=await this.trataRetorno(xmlRetorno.data,data.indSinc,responseInJson),xmlFinal=this.salvaArquivos(xmlConsulta,responseInJson,xmlRetorno.data,{xmlAutorizacao:retorno.data,xMotivo:retorno.message});return xmlFinal.xMotivo=xmlFinal.xMotivo.map(item=>({...item,xMotivo:item.xMotivo.replace("NF-e","NFC-e")})),logger.info("NFCe transmitida com sucesso",{context:"NFCEAutorizacaoService"}),{success:!0,xMotivo:xmlFinal.xMotivo,xmls:xmlFinal.response}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class NFeWizardService{config={};environment={};utility={};xmlBuilder={};axios={};saveFiles={};gerarConsulta={};constructor(){if(new.target)return new Proxy(this,{get(target,prop,receiver){const origMethod=target[prop];return"function"==typeof origMethod?async function(...args){return"NFE_LoadEnvironment"===prop||await target.validateEnvironment(prop),origMethod.apply(target,args)}:Reflect.get(target,prop,receiver)}})}async NFE_LoadEnvironment({config:config}){try{this.config=config,this.environment=new Environment(this.config);const{axios:axios}=await this.environment.loadEnvironment();this.axios=axios,this.utility=new Utility(this.environment),this.saveFiles=new SaveFiles(this.environment,this.utility),this.xmlBuilder=new XmlBuilder(this.environment),this.gerarConsulta=new GerarConsulta(this.environment,this.utility,this.xmlBuilder)}catch(error){throw logger.error("",error,{context:"NFE_LoadEnvironment"}),new Error(`Erro ao inicializar a lib: ${error}`)}}async NFE_ConsultaStatusServico(){try{const nfeStatusServicoService=new NFEStatusServicoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeStatusServico=new NFEStatusServico(nfeStatusServicoService),response=await nfeStatusServico.Exec();return console.log("Retorno NFE_ConsultaStatusServico"),console.log(` ${response.xMotivo}`),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_ConsultaStatusServico"}),new Error(`NFE_ConsultaStatusServico: ${error.message}`)}}async NFE_ConsultaProtocolo(chave){try{const nfeConsultaProtocoloService=new NFEconsultaProtocoloService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeConsultaProtocolo=new NFEConsultaProtocolo(nfeConsultaProtocoloService),response=await nfeConsultaProtocolo.Exec(chave);return console.log("Retorno NFE_ConsultaProtocolo"),console.log(` ${response.xMotivo}`),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_ConsultaProtocolo"}),new Error(`NFE_ConsultaProtocolo: ${error.message}`)}}async NFE_RecepcaoEvento(evento){try{const nfeRecepcaoEventoService=new NFERecepcaoEventoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeRecepcaoEvento=new NFERecepcaoEvento(nfeRecepcaoEventoService),response=await nfeRecepcaoEvento.Exec(evento);return console.log("Retorno NFE_RecepcaoEvento"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_RecepcaoEvento"}),new Error(`NFE_RecepcaoEvento: ${error.message}`)}}async NFE_EventoPrevioDeEmissaoEmContingencia(evento){try{const nfeEpecService=new NFEEpecService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeEpec=new NFEEpec(nfeEpecService),response=await nfeEpec.Exec(evento);return console.log("Retorno NFEEpec"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_EventoPrevioDeEmissaoEmContingencia"}),new Error(`NFEEpec: ${error.message}`)}}async NFE_Cancelamento(evento){try{const nfeCancelamentoService=new NFECancelamentoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeCancelamento=new NFECancelamento(nfeCancelamentoService),response=await nfeCancelamento.Exec(evento);return console.log("Retorno NFE_Cancelamento"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_Cancelamento"}),new Error(`NFE_Cancelamento: ${error.message}`)}}async NFE_CienciaDaOperacao(evento){try{const nfeCienciaDaOperacaoService=new NFECienciaDaOperacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeCienciaDaOperacao=new NFECienciaDaOperacao(nfeCienciaDaOperacaoService),response=await nfeCienciaDaOperacao.Exec(evento);return console.log("Retorno NFE_CienciaDaOperacao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_CienciaDaOperacao"}),new Error(`NFE_CienciaDaOperacao: ${error.message}`)}}async NFE_ConfirmacaoDaOperacao(evento){try{const nfeConfirmacaoDaOperacaoService=new NFECienciaDaOperacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeConfirmacaoDaOperacao=new NFEConfirmacaoDaOperacao(nfeConfirmacaoDaOperacaoService),response=await nfeConfirmacaoDaOperacao.Exec(evento);return console.log("Retorno NFE_ConfirmacaoDaOperacao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_ConfirmacaoDaOperacao"}),new Error(`NFE_ConfirmacaoDaOperacao: ${error.message}`)}}async NFE_OperacaoNaoRealizada(evento){try{const nfeOperacaoNaoRealizadaService=new NFEOperacaoNaoRealizadaService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeOperacaoNaoRealizada=new NFEOperacaoNaoRealizada(nfeOperacaoNaoRealizadaService),response=await nfeOperacaoNaoRealizada.Exec(evento);return console.log("Retorno NFE_OperacaoNaoRealizada"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_OperacaoNaoRealizada"}),new Error(`NFE_OperacaoNaoRealizada: ${error.message}`)}}async NFE_CartaDeCorrecao(evento){try{const nfeCartaDeCorrecaoService=new NFECartaDeCorrecaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeCartaDeCorrecao=new NFECartaDeCorrecao(nfeCartaDeCorrecaoService),response=await nfeCartaDeCorrecao.Exec(evento);return console.log("Retorno NFE_CartaDeCorrecao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_CartaDeCorrecao"}),new Error(`NFE_CartaDeCorrecao: ${error.message}`)}}async NFE_DesconhecimentoDaOperacao(evento){try{const nfeDesconhecimentoDaOperacaoService=new NFEDesconhecimentoDaOperacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeDesconhecimentoDaOperacao=new NFEDesconhecimentoDaOperacao(nfeDesconhecimentoDaOperacaoService),response=await nfeDesconhecimentoDaOperacao.Exec(evento);return console.log("Retorno NFE_DesconhecimentoDaOperacao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_DesconhecimentoDaOperacao"}),new Error(`NFE_DesconhecimentoDaOperacao: ${error.message}`)}}async NFE_DistribuicaoDFe(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFeService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFERecepcaoEvento$1(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFe"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFe"}),new Error(`NFE_DistribuicaoDFe: ${error.message}`)}}async NFE_DistribuicaoDFePorUltNSU(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFePorUltNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFEDistribuicaoDFePorUltNSU(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFePorUltNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFePorUltNSU"}),new Error(`NFE_DistribuicaoDFePorUltNSU: ${error.message}`)}}async NFE_DistribuicaoDFePorNSU(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFePorNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFEDistribuicaoDFePorNSU(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFePorNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFePorNSU"}),new Error(`NFE_DistribuicaoDFePorNSU: ${error.message}`)}}async NFE_DistribuicaoDFePorChave(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFePorChaveService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFEDistribuicaoDFePorChave(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFePorChave"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFePorChave"}),new Error(`NFE_DistribuicaoDFePorChave: ${error.message}`)}}async CTE_DistribuicaoDFe(data){try{const distribuicaoDFeService=new CTEDistribuicaoDFeService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new CTEDistribuicaoDFe(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno CTE_DistribuicaoDFe"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"CTE_DistribuicaoDFe"}),new Error(`CTE_DistribuicaoDFe: ${error.message}`)}}async CTE_DistribuicaoDFePorUltNSU(data){try{new CTEDistribuicaoDFePorUltNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta);const distribuicaoDFe=new CTEDistribuicaoDFePorUltNSU(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),response=await distribuicaoDFe.Exec(data);return console.log("Retorno CTE_DistribuicaoDFePorUltNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"CTE_DistribuicaoDFePorUltNSU"}),new Error(`CTE_DistribuicaoDFePorUltNSU: ${error.message}`)}}async CTE_DistribuicaoDFePorNSU(data){try{new CTEDistribuicaoDFePorNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta);const distribuicaoDFe=new CTEDistribuicaoDFePorNSU(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),response=await distribuicaoDFe.Exec(data);return console.log("Retorno CTE_DistribuicaoDFePorNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"CTE_DistribuicaoDFePorNSU"}),new Error(`CTE_DistribuicaoDFePorNSU: ${error.message}`)}}async NFE_Autorizacao(data){try{const autorizacaoService=new NFEAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),autorizacao=new NFEAutorizacao(autorizacaoService),response=await autorizacao.Exec(data);return console.log("Retorno NFE_Autorizacao"),console.table(response.xMotivo),console.log("==================================="),response.xmls}catch(error){throw logger.error("",error,{context:"NFE_Autorizacao"}),new Error(`NFE_Autorizacao: ${error.message}`)}}async NFCE_Autorizacao(data){try{const autorizacaoService=new NFCEAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),autorizacao=new NFCEAutorizacao(autorizacaoService),response=await autorizacao.Exec(data);return console.log("Retorno NFCE_Autorizacao"),console.table(response.xMotivo),console.log("==================================="),response.xmls}catch(error){throw logger.error("",error,{context:"NFCE_Autorizacao"}),new Error(`NFCE_Autorizacao: ${error.message}`)}}async NFE_Inutilizacao(data){try{const inutilizacaoService=new NFEInutilizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),inutilizacao=new NFEInutilizacao(inutilizacaoService),response=await inutilizacao.Exec(data);return console.log("Retorno NFE_Inutilizacao"),console.log(` ${response.xMotivo}`),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_Inutilizacao"}),new Error(`NFE_Inutilizacao: ${error.message}`)}}async NFE_GerarDanfe(data){try{const{dfe:{exibirMarcaDaguaDanfe:exibirMarcaDaguaDanfe}}=this.environment.getConfig(),distribuicaoDFe=new NFEGerarDanfe(data),response=await distribuicaoDFe.generatePDF(exibirMarcaDaguaDanfe);return console.log("Retorno NFE_GerarDanfe"),console.log(response.message),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_GerarDanfe"}),new Error(`NFE_GerarDanfe: ${error.message}`)}}async NFCE_GerarDanfe(data){try{const{dfe:{exibirMarcaDaguaDanfe:exibirMarcaDaguaDanfe}}=this.environment.getConfig(),distribuicaoDFe=new NFCEGerarDanfe(data),response=await distribuicaoDFe.generatePDF(exibirMarcaDaguaDanfe);return console.log("Retorno NFCE_GerarDanfe"),console.log(response.message),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFCE_GerarDanfe"}),new Error(`NFCE_GerarDanfe: ${error.message}`)}}NFE_EnviaEmail(mailParams){try{const response=new MailController(this.environment).sendEmail(mailParams);return console.log("Retorno NFE_EnviaEmail"),console.log("E-mail enviado com sucesso."),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_EnviaEmail"}),new Error(`NFE_EnviaEmail: ${error.message}`)}}async validateEnvironment(prop){if(!this.environment.isLoaded)throw new Error(`Ambiente não carregado. Por favor, carregue o ambiente utilizando o método "NFE_LoadEnvironment({ sua_configuracao })" antes de chamar o método ${prop}.`)}}exports.default=class NFeWizard{nfeWizardService;constructor(){this.nfeWizardService=new NFeWizardService}async NFE_LoadEnvironment({config:config}){await this.nfeWizardService.NFE_LoadEnvironment({config:config})}async NFE_ConsultaStatusServico(){return await this.nfeWizardService.NFE_ConsultaStatusServico()}async NFE_ConsultaProtocolo(chave){return this.nfeWizardService.NFE_ConsultaProtocolo(chave)}async NFE_RecepcaoEvento(evento){return await this.nfeWizardService.NFE_RecepcaoEvento(evento)}async NFE_EventoPrevioDeEmissaoEmContingencia(evento){return await this.nfeWizardService.NFE_EventoPrevioDeEmissaoEmContingencia(evento)}async NFE_Cancelamento(evento){return await this.nfeWizardService.NFE_Cancelamento(evento)}async NFE_CienciaDaOperacao(evento){return await this.nfeWizardService.NFE_CienciaDaOperacao(evento)}async NFE_ConfirmacaoDaOperacao(evento){return await this.nfeWizardService.NFE_ConfirmacaoDaOperacao(evento)}async NFE_OperacaoNaoRealizada(evento){return await this.nfeWizardService.NFE_OperacaoNaoRealizada(evento)}async NFE_CartaDeCorrecao(evento){return await this.nfeWizardService.NFE_CartaDeCorrecao(evento)}async NFE_DesconhecimentoDaOperacao(evento){return await this.nfeWizardService.NFE_DesconhecimentoDaOperacao(evento)}async NFE_DistribuicaoDFe(data){return await this.nfeWizardService.NFE_DistribuicaoDFe(data)}async NFE_DistribuicaoDFePorUltNSU(data){return await this.nfeWizardService.NFE_DistribuicaoDFePorUltNSU(data)}async NFE_DistribuicaoDFePorNSU(data){return await this.nfeWizardService.NFE_DistribuicaoDFePorNSU(data)}async NFE_DistribuicaoDFePorChave(data){return await this.nfeWizardService.NFE_DistribuicaoDFePorChave(data)}async CTE_DistribuicaoDFe(data){return await this.nfeWizardService.CTE_DistribuicaoDFe(data)}async CTE_DistribuicaoDFePorUltNSU(data){return await this.nfeWizardService.CTE_DistribuicaoDFePorUltNSU(data)}async CTE_DistribuicaoDFePorNSU(data){return await this.nfeWizardService.CTE_DistribuicaoDFePorNSU(data)}async NFE_Autorizacao(data){return await this.nfeWizardService.NFE_Autorizacao(data)}async NFCE_Autorizacao(data){return await this.nfeWizardService.NFCE_Autorizacao(data)}async NFE_Inutilizacao(data){return await this.nfeWizardService.NFE_Inutilizacao(data)}async NFE_GerarDanfe(data){return await this.nfeWizardService.NFE_GerarDanfe(data)}async NFCE_GerarDanfe(data){return await this.nfeWizardService.NFCE_GerarDanfe(data)}NFE_EnviaEmail(mailParams){return this.nfeWizardService.NFE_EnviaEmail(mailParams)}},exports.mountCOFINS=mountCOFINS,exports.mountICMS=mountICMS,exports.mountPIS=mountPIS;
|
|
9
|
+
/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */function zero$1(buf){let len=buf.length;for(;--len>=0;)buf[len]=0}const extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),static_ltree=new Array(576);zero$1(static_ltree);const static_dtree=new Array(60);zero$1(static_dtree);const _dist_code=new Array(512);zero$1(_dist_code);const _length_code=new Array(256);zero$1(_length_code);const base_length=new Array(29);zero$1(base_length);const base_dist=new Array(30);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}zero$1(base_dist);const d_code=dist=>dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)],put_short=(s,w)=>{s.pending_buf[s.pending++]=255&w,s.pending_buf[s.pending++]=w>>>8&255},send_bits=(s,value,length)=>{s.bi_valid>16-length?(s.bi_buf|=value<<s.bi_valid&65535,put_short(s,s.bi_buf),s.bi_buf=value>>16-s.bi_valid,s.bi_valid+=length-16):(s.bi_buf|=value<<s.bi_valid&65535,s.bi_valid+=length)},send_code=(s,c,tree)=>{send_bits(s,tree[2*c],tree[2*c+1])},bi_reverse=(code,len)=>{let res=0;do{res|=1&code,code>>>=1,res<<=1}while(--len>0);return res>>>1},gen_codes=(tree,max_code,bl_count)=>{const next_code=new Array(16);let bits,n,code=0;for(bits=1;bits<=15;bits++)code=code+bl_count[bits-1]<<1,next_code[bits]=code;for(n=0;n<=max_code;n++){let len=tree[2*n+1];0!==len&&(tree[2*n]=bi_reverse(next_code[len]++,len))}},init_block=s=>{let n;for(n=0;n<286;n++)s.dyn_ltree[2*n]=0;for(n=0;n<30;n++)s.dyn_dtree[2*n]=0;for(n=0;n<19;n++)s.bl_tree[2*n]=0;s.dyn_ltree[512]=1,s.opt_len=s.static_len=0,s.sym_next=s.matches=0},bi_windup=s=>{s.bi_valid>8?put_short(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},smaller=(tree,n,m,depth)=>{const _n2=2*n,_m2=2*m;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]},pqdownheap=(s,tree,k)=>{const v=s.heap[k];let j=k<<1;for(;j<=s.heap_len&&(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)&&j++,!smaller(tree,v,s.heap[j],s.depth));)s.heap[k]=s.heap[j],k=j,j<<=1;s.heap[k]=v},compress_block=(s,ltree,dtree)=>{let dist,lc,code,extra,sx=0;if(0!==s.sym_next)do{dist=255&s.pending_buf[s.sym_buf+sx++],dist+=(255&s.pending_buf[s.sym_buf+sx++])<<8,lc=s.pending_buf[s.sym_buf+sx++],0===dist?send_code(s,lc,ltree):(code=_length_code[lc],send_code(s,code+256+1,ltree),extra=extra_lbits[code],0!==extra&&(lc-=base_length[code],send_bits(s,lc,extra)),dist--,code=d_code(dist),send_code(s,code,dtree),extra=extra_dbits[code],0!==extra&&(dist-=base_dist[code],send_bits(s,dist,extra)))}while(sx<s.sym_next);send_code(s,256,ltree)},build_tree=(s,desc)=>{const tree=desc.dyn_tree,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,elems=desc.stat_desc.elems;let n,m,node,max_code=-1;for(s.heap_len=0,s.heap_max=573,n=0;n<elems;n++)0!==tree[2*n]?(s.heap[++s.heap_len]=max_code=n,s.depth[n]=0):tree[2*n+1]=0;for(;s.heap_len<2;)node=s.heap[++s.heap_len]=max_code<2?++max_code:0,tree[2*node]=1,s.depth[node]=0,s.opt_len--,has_stree&&(s.static_len-=stree[2*node+1]);for(desc.max_code=max_code,n=s.heap_len>>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do{n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[2*node]=tree[2*n]+tree[2*m],s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1,tree[2*n+1]=tree[2*m+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1)}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],((s,desc)=>{const tree=desc.dyn_tree,max_code=desc.max_code,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length;let h,n,m,bits,xbits,f,overflow=0;for(bits=0;bits<=15;bits++)s.bl_count[bits]=0;for(tree[2*s.heap[s.heap_max]+1]=0,h=s.heap_max+1;h<573;h++)n=s.heap[h],bits=tree[2*tree[2*n+1]+1]+1,bits>max_length&&(bits=max_length,overflow++),tree[2*n+1]=bits,n>max_code||(s.bl_count[bits]++,xbits=0,n>=base&&(xbits=extra[n-base]),f=tree[2*n],s.opt_len+=f*(bits+xbits),has_stree&&(s.static_len+=f*(stree[2*n+1]+xbits)));if(0!==overflow){do{for(bits=max_length-1;0===s.bl_count[bits];)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0);for(bits=max_length;0!==bits;bits--)for(n=s.bl_count[bits];0!==n;)m=s.heap[--h],m>max_code||(tree[2*m+1]!==bits&&(s.opt_len+=(bits-tree[2*m+1])*tree[2*m],tree[2*m+1]=bits),n--)}})(s,desc),gen_codes(tree,max_code,s.bl_count)},scan_tree=(s,tree,max_code)=>{let n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),tree[2*(max_code+1)+1]=65535,n=0;n<=max_code;n++)curlen=nextlen,nextlen=tree[2*(n+1)+1],++count<max_count&&curlen===nextlen||(count<min_count?s.bl_tree[2*curlen]+=count:0!==curlen?(curlen!==prevlen&&s.bl_tree[2*curlen]++,s.bl_tree[32]++):count<=10?s.bl_tree[34]++:s.bl_tree[36]++,count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4))},send_tree=(s,tree,max_code)=>{let n,curlen,prevlen=-1,nextlen=tree[1],count=0,max_count=7,min_count=4;for(0===nextlen&&(max_count=138,min_count=3),n=0;n<=max_code;n++)if(curlen=nextlen,nextlen=tree[2*(n+1)+1],!(++count<max_count&&curlen===nextlen)){if(count<min_count)do{send_code(s,curlen,s.bl_tree)}while(0!==--count);else 0!==curlen?(curlen!==prevlen&&(send_code(s,curlen,s.bl_tree),count--),send_code(s,16,s.bl_tree),send_bits(s,count-3,2)):count<=10?(send_code(s,17,s.bl_tree),send_bits(s,count-3,3)):(send_code(s,18,s.bl_tree),send_bits(s,count-11,7));count=0,prevlen=curlen,0===nextlen?(max_count=138,min_count=3):curlen===nextlen?(max_count=6,min_count=3):(max_count=7,min_count=4)}};let static_init_done=!1;const _tr_stored_block$1=(s,buf,stored_len,last)=>{send_bits(s,0+(last?1:0),3),bi_windup(s),put_short(s,stored_len),put_short(s,~stored_len),stored_len&&s.pending_buf.set(s.window.subarray(buf,buf+stored_len),s.pending),s.pending+=stored_len};var _tr_init_1=s=>{static_init_done||((()=>{let n,bits,length,code,dist;const bl_count=new Array(16);for(length=0,code=0;code<28;code++)for(base_length[code]=length,n=0;n<1<<extra_lbits[code];n++)_length_code[length++]=code;for(_length_code[length-1]=code,dist=0,code=0;code<16;code++)for(base_dist[code]=dist,n=0;n<1<<extra_dbits[code];n++)_dist_code[dist++]=code;for(dist>>=7;code<30;code++)for(base_dist[code]=dist<<7,n=0;n<1<<extra_dbits[code]-7;n++)_dist_code[256+dist++]=code;for(bits=0;bits<=15;bits++)bl_count[bits]=0;for(n=0;n<=143;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(;n<=255;)static_ltree[2*n+1]=9,n++,bl_count[9]++;for(;n<=279;)static_ltree[2*n+1]=7,n++,bl_count[7]++;for(;n<=287;)static_ltree[2*n+1]=8,n++,bl_count[8]++;for(gen_codes(static_ltree,287,bl_count),n=0;n<30;n++)static_dtree[2*n+1]=5,static_dtree[2*n]=bi_reverse(n,5);static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,257,286,15),static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,30,15),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,19,7)})(),static_init_done=!0),s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc),s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc),s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc),s.bi_buf=0,s.bi_valid=0,init_block(s)},_tr_flush_block_1=(s,buf,stored_len,last)=>{let opt_lenb,static_lenb,max_blindex=0;s.level>0?(2===s.strm.data_type&&(s.strm.data_type=(s=>{let n,block_mask=4093624447;for(n=0;n<=31;n++,block_mask>>>=1)if(1&block_mask&&0!==s.dyn_ltree[2*n])return 0;if(0!==s.dyn_ltree[18]||0!==s.dyn_ltree[20]||0!==s.dyn_ltree[26])return 1;for(n=32;n<256;n++)if(0!==s.dyn_ltree[2*n])return 1;return 0})(s)),build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=(s=>{let max_blindex;for(scan_tree(s,s.dyn_ltree,s.l_desc.max_code),scan_tree(s,s.dyn_dtree,s.d_desc.max_code),build_tree(s,s.bl_desc),max_blindex=18;max_blindex>=3&&0===s.bl_tree[2*bl_order[max_blindex]+1];max_blindex--);return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex})(s),opt_lenb=s.opt_len+3+7>>>3,static_lenb=s.static_len+3+7>>>3,static_lenb<=opt_lenb&&(opt_lenb=static_lenb)):opt_lenb=static_lenb=stored_len+5,stored_len+4<=opt_lenb&&-1!==buf?_tr_stored_block$1(s,buf,stored_len,last):4===s.strategy||static_lenb===opt_lenb?(send_bits(s,2+(last?1:0),3),compress_block(s,static_ltree,static_dtree)):(send_bits(s,4+(last?1:0),3),((s,lcodes,dcodes,blcodes)=>{let rank;for(send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4),rank=0;rank<blcodes;rank++)send_bits(s,s.bl_tree[2*bl_order[rank]+1],3);send_tree(s,s.dyn_ltree,lcodes-1),send_tree(s,s.dyn_dtree,dcodes-1)})(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree)),init_block(s),last&&bi_windup(s)},_tr_tally_1=(s,dist,lc)=>(s.pending_buf[s.sym_buf+s.sym_next++]=dist,s.pending_buf[s.sym_buf+s.sym_next++]=dist>>8,s.pending_buf[s.sym_buf+s.sym_next++]=lc,0===dist?s.dyn_ltree[2*lc]++:(s.matches++,dist--,s.dyn_ltree[2*(_length_code[lc]+256+1)]++,s.dyn_dtree[2*d_code(dist)]++),s.sym_next===s.sym_end),trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block$1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:s=>{send_bits(s,2,3),send_code(s,256,static_ltree),(s=>{16===s.bi_valid?(put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=255&s.bi_buf,s.bi_buf>>=8,s.bi_valid-=8)})(s)}};var adler32_1=(adler,buf,len,pos)=>{let s1=65535&adler,s2=adler>>>16&65535,n=0;for(;0!==len;){n=len>2e3?2e3:len,len-=n;do{s1=s1+buf[pos++]|0,s2=s2+s1|0}while(--n);s1%=65521,s2%=65521}return s1|s2<<16};const crcTable=new Uint32Array((()=>{let c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=1&c?3988292384^c>>>1:c>>>1;table[n]=c}return table})());var crc32_1=(crc,buf,len,pos)=>{const t=crcTable,end=pos+len;crc^=-1;for(let i=pos;i<end;i++)crc=crc>>>8^t[255&(crc^buf[i])];return-1^crc},messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:_tr_init,_tr_stored_block:_tr_stored_block,_tr_flush_block:_tr_flush_block,_tr_tally:_tr_tally,_tr_align:_tr_align}=trees,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH:Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED:Z_FILTERED,Z_HUFFMAN_ONLY:Z_HUFFMAN_ONLY,Z_RLE:Z_RLE,Z_FIXED:Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN:Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2,err=(strm,errorCode)=>(strm.msg=messages[errorCode],errorCode),rank=f=>2*f-(f>4?9:0),zero=buf=>{let len=buf.length;for(;--len>=0;)buf[len]=0},slide_hash=s=>{let n,m,p,wsize=s.w_size;n=s.hash_size,p=n;do{m=s.head[--p],s.head[p]=m>=wsize?m-wsize:0}while(--n);n=wsize,p=n;do{m=s.prev[--p],s.prev[p]=m>=wsize?m-wsize:0}while(--n)};let HASH=(s,prev,data)=>(prev<<s.hash_shift^data)&s.hash_mask;const flush_pending=strm=>{const s=strm.state;let len=s.pending;len>strm.avail_out&&(len=strm.avail_out),0!==len&&(strm.output.set(s.pending_buf.subarray(s.pending_out,s.pending_out+len),strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,0===s.pending&&(s.pending_out=0))},flush_block_only=(s,last)=>{_tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)},put_byte=(s,b)=>{s.pending_buf[s.pending++]=b},putShortMSB=(s,b)=>{s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=255&b},read_buf=(strm,buf,start,size)=>{let len=strm.avail_in;return len>size&&(len=size),0===len?0:(strm.avail_in-=len,buf.set(strm.input.subarray(strm.next_in,strm.next_in+len),start),1===strm.state.wrap?strm.adler=adler32_1(strm.adler,buf,len,start):2===strm.state.wrap&&(strm.adler=crc32_1(strm.adler,buf,len,start)),strm.next_in+=len,strm.total_in+=len,len)},longest_match=(s,cur_match)=>{let match,len,chain_length=s.max_chain_length,scan=s.strstart,best_len=s.prev_length,nice_match=s.nice_match;const limit=s.strstart>s.w_size-262?s.strstart-(s.w_size-262):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+258;let scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];s.prev_length>=s.good_match&&(chain_length>>=2),nice_match>s.lookahead&&(nice_match=s.lookahead);do{if(match=cur_match,_win[match+best_len]===scan_end&&_win[match+best_len-1]===scan_end1&&_win[match]===_win[scan]&&_win[++match]===_win[scan+1]){scan+=2,match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);if(len=258-(strend-scan),scan=strend-258,len>best_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}}while((cur_match=prev[cur_match&wmask])>limit&&0!==--chain_length);return best_len<=s.lookahead?best_len:s.lookahead},fill_window=s=>{const _w_size=s.w_size;let n,more,str;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-262)&&(s.window.set(s.window.subarray(_w_size,_w_size+_w_size-more),0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,s.insert>s.strstart&&(s.insert=s.strstart),slide_hash(s),more+=_w_size),0===s.strm.avail_in)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=3)for(str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=HASH(s,s.ins_h,s.window[str+1]);s.insert&&(s.ins_h=HASH(s,s.ins_h,s.window[str+3-1]),s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++,s.insert--,!(s.lookahead+s.insert<3)););}while(s.lookahead<262&&0!==s.strm.avail_in)},deflate_stored=(s,flush)=>{let len,left,have,min_block=s.pending_buf_size-5>s.w_size?s.w_size:s.pending_buf_size-5,last=0,used=s.strm.avail_in;do{if(len=65535,have=s.bi_valid+42>>3,s.strm.avail_out<have)break;if(have=s.strm.avail_out-have,left=s.strstart-s.block_start,len>left+s.strm.avail_in&&(len=left+s.strm.avail_in),len>have&&(len=have),len<min_block&&(0===len&&flush!==Z_FINISH$3||flush===Z_NO_FLUSH$2||len!==left+s.strm.avail_in))break;last=flush===Z_FINISH$3&&len===left+s.strm.avail_in?1:0,_tr_stored_block(s,0,0,last),s.pending_buf[s.pending-4]=len,s.pending_buf[s.pending-3]=len>>8,s.pending_buf[s.pending-2]=~len,s.pending_buf[s.pending-1]=~len>>8,flush_pending(s.strm),left&&(left>len&&(left=len),s.strm.output.set(s.window.subarray(s.block_start,s.block_start+left),s.strm.next_out),s.strm.next_out+=left,s.strm.avail_out-=left,s.strm.total_out+=left,s.block_start+=left,len-=left),len&&(read_buf(s.strm,s.strm.output,s.strm.next_out,len),s.strm.next_out+=len,s.strm.avail_out-=len,s.strm.total_out+=len)}while(0===last);return used-=s.strm.avail_in,used&&(used>=s.w_size?(s.matches=2,s.window.set(s.strm.input.subarray(s.strm.next_in-s.w_size,s.strm.next_in),0),s.strstart=s.w_size,s.insert=s.strstart):(s.window_size-s.strstart<=used&&(s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,s.insert>s.strstart&&(s.insert=s.strstart)),s.window.set(s.strm.input.subarray(s.strm.next_in-used,s.strm.next_in),s.strstart),s.strstart+=used,s.insert+=used>s.w_size-s.insert?s.w_size-s.insert:used),s.block_start=s.strstart),s.high_water<s.strstart&&(s.high_water=s.strstart),last?4:flush!==Z_NO_FLUSH$2&&flush!==Z_FINISH$3&&0===s.strm.avail_in&&s.strstart===s.block_start?2:(have=s.window_size-s.strstart,s.strm.avail_in>have&&s.block_start>=s.w_size&&(s.block_start-=s.w_size,s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,have+=s.w_size,s.insert>s.strstart&&(s.insert=s.strstart)),have>s.strm.avail_in&&(have=s.strm.avail_in),have&&(read_buf(s.strm,s.window,s.strstart,have),s.strstart+=have,s.insert+=have>s.w_size-s.insert?s.w_size-s.insert:have),s.high_water<s.strstart&&(s.high_water=s.strstart),have=s.bi_valid+42>>3,have=s.pending_buf_size-have>65535?65535:s.pending_buf_size-have,min_block=have>s.w_size?s.w_size:have,left=s.strstart-s.block_start,(left>=min_block||(left||flush===Z_FINISH$3)&&flush!==Z_NO_FLUSH$2&&0===s.strm.avail_in&&left<=have)&&(len=left>have?have:left,last=flush===Z_FINISH$3&&0===s.strm.avail_in&&len===left?1:0,_tr_stored_block(s,s.block_start,len,last),s.block_start+=len,flush_pending(s.strm)),last?3:1)},deflate_fast=(s,flush)=>{let hash_head,bflush;for(;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&flush===Z_NO_FLUSH$2)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),0!==hash_head&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head)),s.match_length>=3)if(bflush=_tr_tally(s,s.strstart-s.match_start,s.match_length-3),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=3){s.match_length--;do{s.strstart++,s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart}while(0!==--s.match_length);s.strstart++}else s.strstart+=s.match_length,s.match_length=0,s.ins_h=s.window[s.strstart],s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+1]);else bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=s.strstart<2?s.strstart:2,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2},deflate_slow=(s,flush)=>{let hash_head,bflush,max_insert;for(;;){if(s.lookahead<262){if(fill_window(s),s.lookahead<262&&flush===Z_NO_FLUSH$2)return 1;if(0===s.lookahead)break}if(hash_head=0,s.lookahead>=3&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),s.prev_length=s.match_length,s.prev_match=s.match_start,s.match_length=2,0!==hash_head&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-262&&(s.match_length=longest_match(s,hash_head),s.match_length<=5&&(s.strategy===Z_FILTERED||3===s.match_length&&s.strstart-s.match_start>4096)&&(s.match_length=2)),s.prev_length>=3&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-3,bflush=_tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-3),s.lookahead-=s.prev_length-1,s.prev_length-=2;do{++s.strstart<=max_insert&&(s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+3-1]),hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart)}while(0!==--s.prev_length);if(s.match_available=0,s.match_length=2,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}else if(s.match_available){if(bflush=_tr_tally(s,0,s.window[s.strstart-1]),bflush&&flush_block_only(s,!1),s.strstart++,s.lookahead--,0===s.strm.avail_out)return 1}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(bflush=_tr_tally(s,0,s.window[s.strstart-1]),s.match_available=0),s.insert=s.strstart<2?s.strstart:2,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2};function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const deflateStateCheck=strm=>{if(!strm)return 1;const s=strm.state;return!s||s.strm!==strm||42!==s.status&&57!==s.status&&69!==s.status&&73!==s.status&&91!==s.status&&103!==s.status&&113!==s.status&&666!==s.status?1:0},deflateResetKeep=strm=>{if(deflateStateCheck(strm))return err(strm,Z_STREAM_ERROR$2);strm.total_in=strm.total_out=0,strm.data_type=Z_UNKNOWN;const s=strm.state;return s.pending=0,s.pending_out=0,s.wrap<0&&(s.wrap=-s.wrap),s.status=2===s.wrap?57:s.wrap?42:113,strm.adler=2===s.wrap?0:1,s.last_flush=-2,_tr_init(s),Z_OK$3},deflateReset=strm=>{const ret=deflateResetKeep(strm);var s;return ret===Z_OK$3&&((s=strm.state).window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=2,s.match_available=0,s.ins_h=0),ret},deflateInit2=(strm,level,method,windowBits,memLevel,strategy)=>{if(!strm)return Z_STREAM_ERROR$2;let wrap=1;if(level===Z_DEFAULT_COMPRESSION$1&&(level=6),windowBits<0?(wrap=0,windowBits=-windowBits):windowBits>15&&(wrap=2,windowBits-=16),memLevel<1||memLevel>9||method!==Z_DEFLATED$2||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED||8===windowBits&&1!==wrap)return err(strm,Z_STREAM_ERROR$2);8===windowBits&&(windowBits=9);const s=new DeflateState;return strm.state=s,s.strm=strm,s.status=42,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=memLevel+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new Uint8Array(2*s.w_size),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<memLevel+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=3*(s.lit_bufsize-1),s.level=level,s.strategy=strategy,s.method=method,deflateReset(strm)};var deflate_1$2={deflateInit:(strm,level)=>deflateInit2(strm,level,Z_DEFLATED$2,15,8,Z_DEFAULT_STRATEGY$1),deflateInit2:deflateInit2,deflateReset:deflateReset,deflateResetKeep:deflateResetKeep,deflateSetHeader:(strm,head)=>deflateStateCheck(strm)||2!==strm.state.wrap?Z_STREAM_ERROR$2:(strm.state.gzhead=head,Z_OK$3),deflate:(strm,flush)=>{if(deflateStateCheck(strm)||flush>Z_BLOCK$1||flush<0)return strm?err(strm,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const s=strm.state;if(!strm.output||0!==strm.avail_in&&!strm.input||666===s.status&&flush!==Z_FINISH$3)return err(strm,0===strm.avail_out?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const old_flush=s.last_flush;if(s.last_flush=flush,0!==s.pending){if(flush_pending(strm),0===strm.avail_out)return s.last_flush=-1,Z_OK$3}else if(0===strm.avail_in&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH$3)return err(strm,Z_BUF_ERROR$1);if(666===s.status&&0!==strm.avail_in)return err(strm,Z_BUF_ERROR$1);if(42===s.status&&0===s.wrap&&(s.status=113),42===s.status){let header=Z_DEFLATED$2+(s.w_bits-8<<4)<<8,level_flags=-1;if(level_flags=s.strategy>=Z_HUFFMAN_ONLY||s.level<2?0:s.level<6?1:6===s.level?2:3,header|=level_flags<<6,0!==s.strstart&&(header|=32),header+=31-header%31,putShortMSB(s,header),0!==s.strstart&&(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),strm.adler=1,s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3}if(57===s.status)if(strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),s.gzhead)put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),put_byte(s,255&s.gzhead.time),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,9===s.level?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0),put_byte(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(put_byte(s,255&s.gzhead.extra.length),put_byte(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69;else if(put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,9===s.level?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0),put_byte(s,3),s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;if(69===s.status){if(s.gzhead.extra){let beg=s.pending,left=(65535&s.gzhead.extra.length)-s.gzindex;for(;s.pending+left>s.pending_buf_size;){let copy=s.pending_buf_size-s.pending;if(s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex,s.gzindex+copy),s.pending),s.pending=s.pending_buf_size,s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex+=copy,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;beg=0,left-=copy}let gzhead_extra=new Uint8Array(s.gzhead.extra);s.pending_buf.set(gzhead_extra.subarray(s.gzindex,s.gzindex+left),s.pending),s.pending+=left,s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex=0}s.status=73}if(73===s.status){if(s.gzhead.name){let val,beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;beg=0}val=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val);s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),s.gzindex=0}s.status=91}if(91===s.status){if(s.gzhead.comment){let val,beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg)),flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3;beg=0}val=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,put_byte(s,val)}while(0!==val);s.gzhead.hcrc&&s.pending>beg&&(strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg))}s.status=103}if(103===s.status){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size&&(flush_pending(strm),0!==s.pending))return s.last_flush=-1,Z_OK$3;put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),strm.adler=0}if(s.status=113,flush_pending(strm),0!==s.pending)return s.last_flush=-1,Z_OK$3}if(0!==strm.avail_in||0!==s.lookahead||flush!==Z_NO_FLUSH$2&&666!==s.status){let bstate=0===s.level?deflate_stored(s,flush):s.strategy===Z_HUFFMAN_ONLY?((s,flush)=>{let bflush;for(;;){if(0===s.lookahead&&(fill_window(s),0===s.lookahead)){if(flush===Z_NO_FLUSH$2)return 1;break}if(s.match_length=0,bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=0,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2})(s,flush):s.strategy===Z_RLE?((s,flush)=>{let bflush,prev,scan,strend;const _win=s.window;for(;;){if(s.lookahead<=258){if(fill_window(s),s.lookahead<=258&&flush===Z_NO_FLUSH$2)return 1;if(0===s.lookahead)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(scan=s.strstart-1,prev=_win[scan],prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan])){strend=s.strstart+258;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=258-(strend-scan),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(bflush=_tr_tally(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(bflush=_tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),bflush&&(flush_block_only(s,!1),0===s.strm.avail_out))return 1}return s.insert=0,flush===Z_FINISH$3?(flush_block_only(s,!0),0===s.strm.avail_out?3:4):s.sym_next&&(flush_block_only(s,!1),0===s.strm.avail_out)?1:2})(s,flush):configuration_table[s.level].func(s,flush);if(3!==bstate&&4!==bstate||(s.status=666),1===bstate||3===bstate)return 0===strm.avail_out&&(s.last_flush=-1),Z_OK$3;if(2===bstate&&(flush===Z_PARTIAL_FLUSH?_tr_align(s):flush!==Z_BLOCK$1&&(_tr_stored_block(s,0,0,!1),flush===Z_FULL_FLUSH$1&&(zero(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),flush_pending(strm),0===strm.avail_out))return s.last_flush=-1,Z_OK$3}return flush!==Z_FINISH$3?Z_OK$3:s.wrap<=0?Z_STREAM_END$3:(2===s.wrap?(put_byte(s,255&strm.adler),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,255&strm.total_in),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255)):(putShortMSB(s,strm.adler>>>16),putShortMSB(s,65535&strm.adler)),flush_pending(strm),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?Z_OK$3:Z_STREAM_END$3)},deflateEnd:strm=>{if(deflateStateCheck(strm))return Z_STREAM_ERROR$2;const status=strm.state.status;return strm.state=null,113===status?err(strm,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary:(strm,dictionary)=>{let dictLength=dictionary.length;if(deflateStateCheck(strm))return Z_STREAM_ERROR$2;const s=strm.state,wrap=s.wrap;if(2===wrap||1===wrap&&42!==s.status||s.lookahead)return Z_STREAM_ERROR$2;if(1===wrap&&(strm.adler=adler32_1(strm.adler,dictionary,dictLength,0)),s.wrap=0,dictLength>=s.w_size){0===wrap&&(zero(s.head),s.strstart=0,s.block_start=0,s.insert=0);let tmpDict=new Uint8Array(s.w_size);tmpDict.set(dictionary.subarray(dictLength-s.w_size,dictLength),0),dictionary=tmpDict,dictLength=s.w_size}const avail=strm.avail_in,next=strm.next_in,input=strm.input;for(strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);s.lookahead>=3;){let str=s.strstart,n=s.lookahead-2;do{s.ins_h=HASH(s,s.ins_h,s.window[str+3-1]),s.prev[str&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=str,str++}while(--n);s.strstart=str,s.lookahead=2,fill_window(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,strm.next_in=next,strm.input=input,strm.avail_in=avail,s.wrap=wrap,Z_OK$3},deflateInfo:"pako deflate (from Nodeca project)"};const _has=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);var common_assign=function(obj){const sources=Array.prototype.slice.call(arguments,1);for(;sources.length;){const source=sources.shift();if(source){if("object"!=typeof source)throw new TypeError(source+"must be non-object");for(const p in source)_has(source,p)&&(obj[p]=source[p])}}return obj},common_flattenChunks=chunks=>{let len=0;for(let i=0,l=chunks.length;i<l;i++)len+=chunks[i].length;const result=new Uint8Array(len);for(let i=0,pos=0,l=chunks.length;i<l;i++){let chunk=chunks[i];result.set(chunk,pos),pos+=chunk.length}return result};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let q=0;q<256;q++)_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1;_utf8len[254]=_utf8len[254]=1;var strings_string2buf=str=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(str);let buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos<str_len;m_pos++)c=str.charCodeAt(m_pos),55296==(64512&c)&&m_pos+1<str_len&&(c2=str.charCodeAt(m_pos+1),56320==(64512&c2)&&(c=65536+(c-55296<<10)+(c2-56320),m_pos++)),buf_len+=c<128?1:c<2048?2:c<65536?3:4;for(buf=new Uint8Array(buf_len),i=0,m_pos=0;i<buf_len;m_pos++)c=str.charCodeAt(m_pos),55296==(64512&c)&&m_pos+1<str_len&&(c2=str.charCodeAt(m_pos+1),56320==(64512&c2)&&(c=65536+(c-55296<<10)+(c2-56320),m_pos++)),c<128?buf[i++]=c:c<2048?(buf[i++]=192|c>>>6,buf[i++]=128|63&c):c<65536?(buf[i++]=224|c>>>12,buf[i++]=128|c>>>6&63,buf[i++]=128|63&c):(buf[i++]=240|c>>>18,buf[i++]=128|c>>>12&63,buf[i++]=128|c>>>6&63,buf[i++]=128|63&c);return buf},strings_buf2string=(buf,max)=>{const len=max||buf.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(buf.subarray(0,max));let i,out;const utf16buf=new Array(2*len);for(out=0,i=0;i<len;){let c=buf[i++];if(c<128){utf16buf[out++]=c;continue}let c_len=_utf8len[c];if(c_len>4)utf16buf[out++]=65533,i+=c_len-1;else{for(c&=2===c_len?31:3===c_len?15:7;c_len>1&&i<len;)c=c<<6|63&buf[i++],c_len--;c_len>1?utf16buf[out++]=65533:c<65536?utf16buf[out++]=c:(c-=65536,utf16buf[out++]=55296|c>>10&1023,utf16buf[out++]=56320|1023&c)}}return((buf,len)=>{if(len<65534&&buf.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,buf.length===len?buf:buf.subarray(0,len));let result="";for(let i=0;i<len;i++)result+=String.fromCharCode(buf[i]);return result})(utf16buf,out)},strings_utf8border=(buf,max)=>{(max=max||buf.length)>buf.length&&(max=buf.length);let pos=max-1;for(;pos>=0&&128==(192&buf[pos]);)pos--;return pos<0||0===pos?max:pos+_utf8len[buf[pos]]>max?pos:max};var zstream=function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const toString$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH:Z_SYNC_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;function Deflate$1(options){this.options=common_assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},options||{});let opt=this.options;opt.raw&&opt.windowBits>0?opt.windowBits=-opt.windowBits:opt.gzip&&opt.windowBits>0&&opt.windowBits<16&&(opt.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let status=deflate_1$2.deflateInit2(this.strm,opt.level,opt.method,opt.windowBits,opt.memLevel,opt.strategy);if(status!==Z_OK$2)throw new Error(messages[status]);if(opt.header&&deflate_1$2.deflateSetHeader(this.strm,opt.header),opt.dictionary){let dict;if(dict="string"==typeof opt.dictionary?strings_string2buf(opt.dictionary):"[object ArrayBuffer]"===toString$1.call(opt.dictionary)?new Uint8Array(opt.dictionary):opt.dictionary,status=deflate_1$2.deflateSetDictionary(this.strm,dict),status!==Z_OK$2)throw new Error(messages[status]);this._dict_set=!0}}function deflate$1(input,options){const deflator=new Deflate$1(options);if(deflator.push(input,!0),deflator.err)throw deflator.msg||messages[deflator.err];return deflator.result}Deflate$1.prototype.push=function(data,flush_mode){const strm=this.strm,chunkSize=this.options.chunkSize;let status,_flush_mode;if(this.ended)return!1;for(_flush_mode=flush_mode===~~flush_mode?flush_mode:!0===flush_mode?Z_FINISH$2:Z_NO_FLUSH$1,"string"==typeof data?strm.input=strings_string2buf(data):"[object ArrayBuffer]"===toString$1.call(data)?strm.input=new Uint8Array(data):strm.input=data,strm.next_in=0,strm.avail_in=strm.input.length;;)if(0===strm.avail_out&&(strm.output=new Uint8Array(chunkSize),strm.next_out=0,strm.avail_out=chunkSize),(_flush_mode===Z_SYNC_FLUSH||_flush_mode===Z_FULL_FLUSH)&&strm.avail_out<=6)this.onData(strm.output.subarray(0,strm.next_out)),strm.avail_out=0;else{if(status=deflate_1$2.deflate(strm,_flush_mode),status===Z_STREAM_END$2)return strm.next_out>0&&this.onData(strm.output.subarray(0,strm.next_out)),status=deflate_1$2.deflateEnd(this.strm),this.onEnd(status),this.ended=!0,status===Z_OK$2;if(0!==strm.avail_out){if(_flush_mode>0&&strm.next_out>0)this.onData(strm.output.subarray(0,strm.next_out)),strm.avail_out=0;else if(0===strm.avail_in)break}else this.onData(strm.output)}return!0},Deflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)},Deflate$1.prototype.onEnd=function(status){status===Z_OK$2&&(this.result=common_flattenChunks(this.chunks)),this.chunks=[],this.err=status,this.msg=this.strm.msg};var deflate_1$1={Deflate:Deflate$1,deflate:deflate$1,deflateRaw:function deflateRaw$1(input,options){return(options=options||{}).raw=!0,deflate$1(input,options)},gzip:function gzip$1(input,options){return(options=options||{}).gzip=!0,deflate$1(input,options)},constants:constants$2};var inffast=function inflate_fast(strm,start){let _in,last,_out,beg,end,dmax,wsize,whave,wnext,s_window,hold,bits,lcode,dcode,lmask,dmask,here,op,len,dist,from,from_source,input,output;const state=strm.state;_in=strm.next_in,input=strm.input,last=_in+(strm.avail_in-5),_out=strm.next_out,output=strm.output,beg=_out-(start-strm.avail_out),end=_out+(strm.avail_out-257),dmax=state.dmax,wsize=state.wsize,whave=state.whave,wnext=state.wnext,s_window=state.window,hold=state.hold,bits=state.bits,lcode=state.lencode,dcode=state.distcode,lmask=(1<<state.lenbits)-1,dmask=(1<<state.distbits)-1;top:do{bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=lcode[hold&lmask];dolen:for(;;){if(op=here>>>24,hold>>>=op,bits-=op,op=here>>>16&255,0===op)output[_out++]=65535&here;else{if(!(16&op)){if(64&op){if(32&op){state.mode=16191;break top}strm.msg="invalid literal/length code",state.mode=16209;break top}here=lcode[(65535&here)+(hold&(1<<op)-1)];continue dolen}for(len=65535&here,op&=15,op&&(bits<op&&(hold+=input[_in++]<<bits,bits+=8),len+=hold&(1<<op)-1,hold>>>=op,bits-=op),bits<15&&(hold+=input[_in++]<<bits,bits+=8,hold+=input[_in++]<<bits,bits+=8),here=dcode[hold&dmask];;){if(op=here>>>24,hold>>>=op,bits-=op,op=here>>>16&255,16&op){if(dist=65535&here,op&=15,bits<op&&(hold+=input[_in++]<<bits,bits+=8,bits<op&&(hold+=input[_in++]<<bits,bits+=8)),dist+=hold&(1<<op)-1,dist>dmax){strm.msg="invalid distance too far back",state.mode=16209;break top}if(hold>>>=op,bits-=op,op=_out-beg,dist>op){if(op=dist-op,op>whave&&state.sane){strm.msg="invalid distance too far back",state.mode=16209;break top}if(from=0,from_source=s_window,0===wnext){if(from+=wsize-op,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}}else if(wnext<op){if(from+=wsize+wnext-op,op-=wnext,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);if(from=0,wnext<len){op=wnext,len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}}}else if(from+=wnext-op,op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist,from_source=output}for(;len>2;)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;len&&(output[_out++]=from_source[from++],len>1&&(output[_out++]=from_source[from++]))}else{from=_out-dist;do{output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3}while(len>2);len&&(output[_out++]=output[from++],len>1&&(output[_out++]=output[from++]))}break}if(64&op){strm.msg="invalid distance code",state.mode=16209;break top}here=dcode[(65535&here)+(hold&(1<<op)-1)]}}break}}while(_in<last&&_out<end);len=bits>>3,_in-=len,bits-=len<<3,hold&=(1<<bits)-1,strm.next_in=_in,strm.next_out=_out,strm.avail_in=_in<last?last-_in+5:5-(_in-last),strm.avail_out=_out<end?end-_out+257:257-(_out-end),state.hold=hold,state.bits=bits};const lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var inftrees=(type,lens,lens_index,codes,table,table_index,work,opts)=>{const bits=opts.bits;let incr,fill,low,mask,next,match,len=0,sym=0,min=0,max=0,root=0,curr=0,drop=0,left=0,used=0,huff=0,base=null;const count=new Uint16Array(16),offs=new Uint16Array(16);let here_bits,here_op,here_val,extra=null;for(len=0;len<=15;len++)count[len]=0;for(sym=0;sym<codes;sym++)count[lens[lens_index+sym]]++;for(root=bits,max=15;max>=1&&0===count[max];max--);if(root>max&&(root=max),0===max)return table[table_index++]=20971520,table[table_index++]=20971520,opts.bits=1,0;for(min=1;min<max&&0===count[min];min++);for(root<min&&(root=min),left=1,len=1;len<=15;len++)if(left<<=1,left-=count[len],left<0)return-1;if(left>0&&(0===type||1!==max))return-1;for(offs[1]=0,len=1;len<15;len++)offs[len+1]=offs[len]+count[len];for(sym=0;sym<codes;sym++)0!==lens[lens_index+sym]&&(work[offs[lens[lens_index+sym]]++]=sym);if(0===type?(base=extra=work,match=20):1===type?(base=lbase,extra=lext,match=257):(base=dbase,extra=dext,match=0),huff=0,sym=0,len=min,next=table_index,curr=root,drop=0,low=-1,used=1<<root,mask=used-1,1===type&&used>852||2===type&&used>592)return 1;for(;;){here_bits=len-drop,work[sym]+1<match?(here_op=0,here_val=work[sym]):work[sym]>=match?(here_op=extra[work[sym]-match],here_val=base[work[sym]-match]):(here_op=96,here_val=0),incr=1<<len-drop,fill=1<<curr,min=fill;do{fill-=incr,table[next+(huff>>drop)+fill]=here_bits<<24|here_op<<16|here_val}while(0!==fill);for(incr=1<<len-1;huff&incr;)incr>>=1;if(0!==incr?(huff&=incr-1,huff+=incr):huff=0,sym++,0===--count[len]){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){for(0===drop&&(drop=root),next+=min,curr=len-drop,left=1<<curr;curr+drop<max&&(left-=count[curr+drop],!(left<=0));)curr++,left<<=1;if(used+=1<<curr,1===type&&used>852||2===type&&used>592)return 1;low=huff&mask,table[low]=root<<24|curr<<16|next-table_index}}return 0!==huff&&(table[next+huff]=len-drop<<24|64<<16),opts.bits=root,0};const{Z_FINISH:Z_FINISH$1,Z_BLOCK:Z_BLOCK,Z_TREES:Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR:Z_BUF_ERROR,Z_DEFLATED:Z_DEFLATED}=constants$2,BAD=16209,zswap32=q=>(q>>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24);function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck=strm=>{if(!strm)return 1;const state=strm.state;return!state||state.strm!==strm||state.mode<16180||state.mode>16211?1:0},inflateResetKeep=strm=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return strm.total_in=strm.total_out=state.total=0,strm.msg="",state.wrap&&(strm.adler=1&state.wrap),state.mode=16180,state.last=0,state.havedict=0,state.flags=-1,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new Int32Array(852),state.distcode=state.distdyn=new Int32Array(592),state.sane=1,state.back=-1,Z_OK$1},inflateReset=strm=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return state.wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)},inflateReset2=(strm,windowBits)=>{let wrap;if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return windowBits<0?(wrap=0,windowBits=-windowBits):(wrap=5+(windowBits>>4),windowBits<48&&(windowBits&=15)),windowBits&&(windowBits<8||windowBits>15)?Z_STREAM_ERROR$1:(null!==state.window&&state.wbits!==windowBits&&(state.window=null),state.wrap=wrap,state.wbits=windowBits,inflateReset(strm))},inflateInit2=(strm,windowBits)=>{if(!strm)return Z_STREAM_ERROR$1;const state=new InflateState;strm.state=state,state.strm=strm,state.window=null,state.mode=16180;const ret=inflateReset2(strm,windowBits);return ret!==Z_OK$1&&(strm.state=null),ret};let lenfix,distfix,virgin=!0;const fixedtables=state=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let sym=0;for(;sym<144;)state.lens[sym++]=8;for(;sym<256;)state.lens[sym++]=9;for(;sym<280;)state.lens[sym++]=7;for(;sym<288;)state.lens[sym++]=8;for(inftrees(1,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;sym<32;)state.lens[sym++]=5;inftrees(2,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5},updatewindow=(strm,src,end,copy)=>{let dist;const state=strm.state;return null===state.window&&(state.wsize=1<<state.wbits,state.wnext=0,state.whave=0,state.window=new Uint8Array(state.wsize)),copy>=state.wsize?(state.window.set(src.subarray(end-state.wsize,end),0),state.wnext=0,state.whave=state.wsize):(dist=state.wsize-state.wnext,dist>copy&&(dist=copy),state.window.set(src.subarray(end-copy,end-copy+dist),state.wnext),(copy-=dist)?(state.window.set(src.subarray(end-copy,end),0),state.wnext=copy,state.whave=state.wsize):(state.wnext+=dist,state.wnext===state.wsize&&(state.wnext=0),state.whave<state.wsize&&(state.whave+=dist))),0};var inflate_2$1=(strm,flush)=>{let state,input,output,next,put,have,left,hold,bits,_in,_out,copy,from,from_source,here_bits,here_op,here_val,last_bits,last_op,last_val,len,ret,here=0;const hbuf=new Uint8Array(4);let opts,n;const order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(strm)||!strm.output||!strm.input&&0!==strm.avail_in)return Z_STREAM_ERROR$1;state=strm.state,16191===state.mode&&(state.mode=16192),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,_in=have,_out=left,ret=Z_OK$1;inf_leave:for(;;)switch(state.mode){case 16180:if(0===state.wrap){state.mode=16192;break}for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(2&state.wrap&&35615===hold){0===state.wbits&&(state.wbits=15),state.check=0,hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0),hold=0,bits=0,state.mode=16181;break}if(state.head&&(state.head.done=!1),!(1&state.wrap)||(((255&hold)<<8)+(hold>>8))%31){strm.msg="incorrect header check",state.mode=BAD;break}if((15&hold)!==Z_DEFLATED){strm.msg="unknown compression method",state.mode=BAD;break}if(hold>>>=4,bits-=4,len=8+(15&hold),0===state.wbits&&(state.wbits=len),len>15||len>state.wbits){strm.msg="invalid window size",state.mode=BAD;break}state.dmax=1<<state.wbits,state.flags=0,strm.adler=state.check=1,state.mode=512&hold?16189:16191,hold=0,bits=0;break;case 16181:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.flags=hold,(255&state.flags)!==Z_DEFLATED){strm.msg="unknown compression method",state.mode=BAD;break}if(57344&state.flags){strm.msg="unknown header flags set",state.mode=BAD;break}state.head&&(state.head.text=hold>>8&1),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=16182;case 16182:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.time=hold),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32_1(state.check,hbuf,4,0)),hold=0,bits=0,state.mode=16183;case 16183:for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.head&&(state.head.xflags=255&hold,state.head.os=hold>>8),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0)),hold=0,bits=0,state.mode=16184;case 16184:if(1024&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length=hold,state.head&&(state.head.extra_len=hold),512&state.flags&&4&state.wrap&&(hbuf[0]=255&hold,hbuf[1]=hold>>>8&255,state.check=crc32_1(state.check,hbuf,2,0)),hold=0,bits=0}else state.head&&(state.head.extra=null);state.mode=16185;case 16185:if(1024&state.flags&&(copy=state.length,copy>have&&(copy=have),copy&&(state.head&&(len=state.head.extra_len-state.length,state.head.extra||(state.head.extra=new Uint8Array(state.head.extra_len)),state.head.extra.set(input.subarray(next,next+copy),len)),512&state.flags&&4&state.wrap&&(state.check=crc32_1(state.check,input,copy,next)),have-=copy,next+=copy,state.length-=copy),state.length))break inf_leave;state.length=0,state.mode=16186;case 16186:if(2048&state.flags){if(0===have)break inf_leave;copy=0;do{len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.name+=String.fromCharCode(len))}while(len&©<have);if(512&state.flags&&4&state.wrap&&(state.check=crc32_1(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.name=null);state.length=0,state.mode=16187;case 16187:if(4096&state.flags){if(0===have)break inf_leave;copy=0;do{len=input[next+copy++],state.head&&len&&state.length<65536&&(state.head.comment+=String.fromCharCode(len))}while(len&©<have);if(512&state.flags&&4&state.wrap&&(state.check=crc32_1(state.check,input,copy,next)),have-=copy,next+=copy,len)break inf_leave}else state.head&&(state.head.comment=null);state.mode=16188;case 16188:if(512&state.flags){for(;bits<16;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(4&state.wrap&&hold!==(65535&state.check)){strm.msg="header crc mismatch",state.mode=BAD;break}hold=0,bits=0}state.head&&(state.head.hcrc=state.flags>>9&1,state.head.done=!0),strm.adler=state.check=0,state.mode=16191;break;case 16189:for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}strm.adler=state.check=zswap32(hold),hold=0,bits=0,state.mode=16190;case 16190:if(0===state.havedict)return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,Z_NEED_DICT$1;strm.adler=state.check=1,state.mode=16191;case 16191:if(flush===Z_BLOCK||flush===Z_TREES)break inf_leave;case 16192:if(state.last){hold>>>=7&bits,bits-=7&bits,state.mode=16206;break}for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}switch(state.last=1&hold,hold>>>=1,bits-=1,3&hold){case 0:state.mode=16193;break;case 1:if(fixedtables(state),state.mode=16199,flush===Z_TREES){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=16196;break;case 3:strm.msg="invalid block type",state.mode=BAD}hold>>>=2,bits-=2;break;case 16193:for(hold>>>=7&bits,bits-=7&bits;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if((65535&hold)!=(hold>>>16^65535)){strm.msg="invalid stored block lengths",state.mode=BAD;break}if(state.length=65535&hold,hold=0,bits=0,state.mode=16194,flush===Z_TREES)break inf_leave;case 16194:state.mode=16195;case 16195:if(copy=state.length,copy){if(copy>have&&(copy=have),copy>left&&(copy=left),0===copy)break inf_leave;output.set(input.subarray(next,next+copy),put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=16191;break;case 16196:for(;bits<14;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(state.nlen=257+(31&hold),hold>>>=5,bits-=5,state.ndist=1+(31&hold),hold>>>=5,bits-=5,state.ncode=4+(15&hold),hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols",state.mode=BAD;break}state.have=0,state.mode=16197;case 16197:for(;state.have<state.ncode;){for(;bits<3;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.lens[order[state.have++]]=7&hold,hold>>>=3,bits-=3}for(;state.have<19;)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inftrees(0,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid code lengths set",state.mode=BAD;break}state.have=0,state.mode=16198;case 16198:for(;state.have<state.nlen+state.ndist;){for(;here=state.lencode[hold&(1<<state.lenbits)-1],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_val<16)hold>>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(16===here_val){for(n=here_bits+2;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(hold>>>=here_bits,bits-=here_bits,0===state.have){strm.msg="invalid bit length repeat",state.mode=BAD;break}len=state.lens[state.have-1],copy=3+(3&hold),hold>>>=2,bits-=2}else if(17===here_val){for(n=here_bits+3;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=3+(7&hold),hold>>>=3,bits-=3}else{for(n=here_bits+7;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=here_bits,bits-=here_bits,len=0,copy=11+(127&hold),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat",state.mode=BAD;break}for(;copy--;)state.lens[state.have++]=len}}if(state.mode===BAD)break;if(0===state.lens[256]){strm.msg="invalid code -- missing end-of-block",state.mode=BAD;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inftrees(1,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg="invalid literal/lengths set",state.mode=BAD;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inftrees(2,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg="invalid distances set",state.mode=BAD;break}if(state.mode=16199,flush===Z_TREES)break inf_leave;case 16199:state.mode=16200;case 16200:if(have>=6&&left>=258){strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inffast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,16191===state.mode&&(state.back=-1);break}for(state.back=0;here=state.lencode[hold&(1<<state.lenbits)-1],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(here_op&&!(240&here_op)){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,0===here_op){state.mode=16205;break}if(32&here_op){state.back=-1,state.mode=16191;break}if(64&here_op){strm.msg="invalid literal/length code",state.mode=BAD;break}state.extra=15&here_op,state.mode=16201;case 16201:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.length+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=16202;case 16202:for(;here=state.distcode[hold&(1<<state.distbits)-1],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(!(240&here_op)){for(last_bits=here_bits,last_op=here_op,last_val=here_val;here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=65535&here,!(last_bits+here_bits<=bits);){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}hold>>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,64&here_op){strm.msg="invalid distance code",state.mode=BAD;break}state.offset=here_val,state.extra=15&here_op,state.mode=16203;case 16203:if(state.extra){for(n=state.extra;bits<n;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}state.offset+=hold&(1<<state.extra)-1,hold>>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back",state.mode=BAD;break}state.mode=16204;case 16204:if(0===left)break inf_leave;if(copy=_out-left,state.offset>copy){if(copy=state.offset-copy,copy>state.whave&&state.sane){strm.msg="invalid distance too far back",state.mode=BAD;break}copy>state.wnext?(copy-=state.wnext,from=state.wsize-copy):from=state.wnext-copy,copy>state.length&&(copy=state.length),from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;copy>left&&(copy=left),left-=copy,state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);0===state.length&&(state.mode=16200);break;case 16205:if(0===left)break inf_leave;output[put++]=state.length,left--,state.mode=16200;break;case 16206:if(state.wrap){for(;bits<32;){if(0===have)break inf_leave;have--,hold|=input[next++]<<bits,bits+=8}if(_out-=left,strm.total_out+=_out,state.total+=_out,4&state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,put-_out):adler32_1(state.check,output,_out,put-_out)),_out=left,4&state.wrap&&(state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check",state.mode=BAD;break}hold=0,bits=0}state.mode=16207;case 16207:if(state.wrap&&state.flags){for(;bits<32;){if(0===have)break inf_leave;have--,hold+=input[next++]<<bits,bits+=8}if(4&state.wrap&&hold!==(4294967295&state.total)){strm.msg="incorrect length check",state.mode=BAD;break}hold=0,bits=0}state.mode=16208;case 16208:ret=Z_STREAM_END$1;break inf_leave;case BAD:ret=Z_DATA_ERROR$1;break inf_leave;case 16210:return Z_MEM_ERROR$1;default:return Z_STREAM_ERROR$1}return strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<16206||flush!==Z_FINISH$1))&&updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out),_in-=strm.avail_in,_out-=strm.avail_out,strm.total_in+=_in,strm.total_out+=_out,state.total+=_out,4&state.wrap&&_out&&(strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,strm.next_out-_out):adler32_1(state.check,output,_out,strm.next_out-_out)),strm.data_type=state.bits+(state.last?64:0)+(16191===state.mode?128:0)+(16199===state.mode||16194===state.mode?256:0),(0===_in&&0===_out||flush===Z_FINISH$1)&&ret===Z_OK$1&&(ret=Z_BUF_ERROR),ret},inflateEnd_1=strm=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;let state=strm.state;return state.window&&(state.window=null),strm.state=null,Z_OK$1},inflateGetHeader_1=(strm,head)=>{if(inflateStateCheck(strm))return Z_STREAM_ERROR$1;const state=strm.state;return 2&state.wrap?(state.head=head,head.done=!1,Z_OK$1):Z_STREAM_ERROR$1},inflateSetDictionary_1=(strm,dictionary)=>{const dictLength=dictionary.length;let state,dictid,ret;return inflateStateCheck(strm)?Z_STREAM_ERROR$1:(state=strm.state,0!==state.wrap&&16190!==state.mode?Z_STREAM_ERROR$1:16190===state.mode&&(dictid=1,dictid=adler32_1(dictid,dictionary,dictLength,0),dictid!==state.check)?Z_DATA_ERROR$1:(ret=updatewindow(strm,dictionary,dictLength,dictLength),ret?(state.mode=16210,Z_MEM_ERROR$1):(state.havedict=1,Z_OK$1)))},inflate_1$2={inflateReset:inflateReset,inflateReset2:inflateReset2,inflateResetKeep:inflateResetKeep,inflateInit:strm=>inflateInit2(strm,15),inflateInit2:inflateInit2,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo:"pako inflate (from Nodeca project)"};var gzheader=function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const toString=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH,Z_FINISH:Z_FINISH,Z_OK:Z_OK,Z_STREAM_END:Z_STREAM_END,Z_NEED_DICT:Z_NEED_DICT,Z_STREAM_ERROR:Z_STREAM_ERROR,Z_DATA_ERROR:Z_DATA_ERROR,Z_MEM_ERROR:Z_MEM_ERROR}=constants$2;function Inflate$1(options){this.options=common_assign({chunkSize:65536,windowBits:15,to:""},options||{});const opt=this.options;opt.raw&&opt.windowBits>=0&&opt.windowBits<16&&(opt.windowBits=-opt.windowBits,0===opt.windowBits&&(opt.windowBits=-15)),!(opt.windowBits>=0&&opt.windowBits<16)||options&&options.windowBits||(opt.windowBits+=32),opt.windowBits>15&&opt.windowBits<48&&(15&opt.windowBits||(opt.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream,this.strm.avail_out=0;let status=inflate_1$2.inflateInit2(this.strm,opt.windowBits);if(status!==Z_OK)throw new Error(messages[status]);if(this.header=new gzheader,inflate_1$2.inflateGetHeader(this.strm,this.header),opt.dictionary&&("string"==typeof opt.dictionary?opt.dictionary=strings_string2buf(opt.dictionary):"[object ArrayBuffer]"===toString.call(opt.dictionary)&&(opt.dictionary=new Uint8Array(opt.dictionary)),opt.raw&&(status=inflate_1$2.inflateSetDictionary(this.strm,opt.dictionary),status!==Z_OK)))throw new Error(messages[status])}function inflate$1(input,options){const inflator=new Inflate$1(options);if(inflator.push(input),inflator.err)throw inflator.msg||messages[inflator.err];return inflator.result}Inflate$1.prototype.push=function(data,flush_mode){const strm=this.strm,chunkSize=this.options.chunkSize,dictionary=this.options.dictionary;let status,_flush_mode,last_avail_out;if(this.ended)return!1;for(_flush_mode=flush_mode===~~flush_mode?flush_mode:!0===flush_mode?Z_FINISH:Z_NO_FLUSH,"[object ArrayBuffer]"===toString.call(data)?strm.input=new Uint8Array(data):strm.input=data,strm.next_in=0,strm.avail_in=strm.input.length;;){for(0===strm.avail_out&&(strm.output=new Uint8Array(chunkSize),strm.next_out=0,strm.avail_out=chunkSize),status=inflate_1$2.inflate(strm,_flush_mode),status===Z_NEED_DICT&&dictionary&&(status=inflate_1$2.inflateSetDictionary(strm,dictionary),status===Z_OK?status=inflate_1$2.inflate(strm,_flush_mode):status===Z_DATA_ERROR&&(status=Z_NEED_DICT));strm.avail_in>0&&status===Z_STREAM_END&&strm.state.wrap>0&&0!==data[strm.next_in];)inflate_1$2.inflateReset(strm),status=inflate_1$2.inflate(strm,_flush_mode);switch(status){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(status),this.ended=!0,!1}if(last_avail_out=strm.avail_out,strm.next_out&&(0===strm.avail_out||status===Z_STREAM_END))if("string"===this.options.to){let next_out_utf8=strings_utf8border(strm.output,strm.next_out),tail=strm.next_out-next_out_utf8,utf8str=strings_buf2string(strm.output,next_out_utf8);strm.next_out=tail,strm.avail_out=chunkSize-tail,tail&&strm.output.set(strm.output.subarray(next_out_utf8,next_out_utf8+tail),0),this.onData(utf8str)}else this.onData(strm.output.length===strm.next_out?strm.output:strm.output.subarray(0,strm.next_out));if(status!==Z_OK||0!==last_avail_out){if(status===Z_STREAM_END)return status=inflate_1$2.inflateEnd(this.strm),this.onEnd(status),this.ended=!0,!0;if(0===strm.avail_in)break}}return!0},Inflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)},Inflate$1.prototype.onEnd=function(status){status===Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=common_flattenChunks(this.chunks)),this.chunks=[],this.err=status,this.msg=this.strm.msg};var inflate_1$1={Inflate:Inflate$1,inflate:inflate$1,inflateRaw:function inflateRaw$1(input,options){return(options=options||{}).raw=!0,inflate$1(input,options)},ungzip:inflate$1,constants:constants$2};const{Deflate:Deflate,deflate:deflate,deflateRaw:deflateRaw,gzip:gzip}=deflate_1$1,{Inflate:Inflate,inflate:inflate,inflateRaw:inflateRaw,ungzip:ungzip}=inflate_1$1;var pako={Deflate:Deflate,deflate:deflate,deflateRaw:deflateRaw,gzip:gzip,Inflate:Inflate,inflate:inflate,inflateRaw:inflateRaw,ungzip:ungzip,constants:constants$2};class DistribuicaoHandler$1{environment;utility;metodo;constructor(environment,utility,metodo){this.utility=utility,this.environment=environment,this.metodo=metodo}salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chCTe){const{pathXMLDistribuicao:pathXMLDistribuicao,baixarXMLDistribuicao:baixarXMLDistribuicao,armazenarRetornoEmJSON:armazenarRetornoEmJSON}=this.environment.config.dfe;baixarXMLDistribuicao&&(this.utility.salvaXML({data:XMLDistribuicao,fileName:chCTe,metodo:this.metodo,path:pathXMLDistribuicao}),armazenarRetornoEmJSON&&this.utility.salvaJSON({data:XMLDistribuicaoInJson,fileName:chCTe,metodo:this.metodo,path:pathXMLDistribuicao}))}deCompressDFeXML(loteDistDFeInt,metodo,xmlConsulta){logger.info("Descomprimindo XML",{context:"DistribuicaoHandler"});const json=new XmlParser,files=[];return xml2js$1.parseString(loteDistDFeInt,(err,result)=>{if(err)throw new Error(`Erro ao descomprimir o XML: ${err}`);this.utility.findInObj(result,"docZip").forEach(docZip=>{const xmlString=this.decodeDocZip(docZip),cleanedXml=this.removeSignatureTag(xmlString),parsedResult=this.parseXml(cleanedXml);if(!parsedResult)return;let chCTe=this.getChCTe(parsedResult),tipo=this.getTipo(parsedResult);const nsu=docZip.$.NSU;if(parsedResult.procEventoCTe){chCTe=`${chCTe}-event-${this.utility.findInObj(parsedResult,"tpEvento")}`,tipo="event"}const xmlDistribuicaoInJson=json.convertXmlToJson(cleanedXml,`${metodo}_${tipo}`,nsu);this.handleResponse(xmlDistribuicaoInJson,cleanedXml,chCTe),files.push(chCTe)})}),files}decodeDocZip(docZip){logger.info("Decodificando DocZip",{context:"DistribuicaoHandler"});const base64String=docZip._;let binaryString=atob(base64String),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);let decompressedData=pako.inflate(bytes);return new TextDecoder("utf-8").decode(decompressedData)}removeSignatureTag(xmlString){return xmlString.replace(/<Signature.*?<\/Signature>/gs,"")}parseXml(xmlString){let parsedResult;return xml2js$1.parseString(xmlString,(err,result)=>{err?(console.error("Erro ao parsear o XML decomprimido:",err),parsedResult=null):parsedResult=result}),parsedResult}getChCTe(parsedResult){return this.utility.findInObj(parsedResult,"chCTe")}getTipo(parsedResult){return this.utility.findInObj(parsedResult,"resCTe")?"res":parsedResult.procEventoCTe?"event":"proc"}handleResponse(XMLDistribuicaoInJson,XMLDistribuicao,chCTe){this.salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chCTe);const xMotivo=this.utility.findInObj(XMLDistribuicaoInJson,"xMotivo");if(xMotivo&&(xMotivo.includes("Rejeição")||xMotivo.includes("Rejeicao")))throw new Error(XMLDistribuicaoInJson.xMotivo)}}class CTEDistribuicaoDFeService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"CTeDistribuicaoDFe",axios,saveFiles,gerarConsulta)}gerarXml(data){return this.gerarXmlCTeDistribuicaoDFe(data)}gerarXmlCTeDistribuicaoDFe(data){logger.info("Montando estrutura do XML em JSON",{context:"CTEDistribuicaoDFeService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{versao:"1.00",xmlns:"http://www.portalfiscal.inf.br/cte"},tpAmb:ambiente,...data};return this.xmlBuilder.gerarXml(xmlObject,"distDFeInt",this.metodo)}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType};logger.http("Iniciando comunicação com o webservice",{context:"CTEDistribuicaoDFeService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"CTEDistribuicaoDFeService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlCTeDistribuicaoDFe(data),console.log({xmlConsulta:xmlConsulta});const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,!0,"1.00","CTe",!0,"cteDistDFeInteresse","cteDadosMsg");xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent);if(responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo),"137"===responseInJson.retDistDFeInt.cStat)return{data:{},xMotivo:responseInJson.retDistDFeInt.xMotivo,filesList:[]};const filesList=new DistribuicaoHandler$1(this.environment,this.utility,this.metodo).deCompressDFeXML(xmlRetorno.data,this.metodo,xmlConsulta);return{data:responseInJson,xMotivo:this.utility.findInObj(responseInJson,"xMotivo"),filesList:filesList}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class CTEDistribuicaoDFePorNSU extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class CTEDistribuicaoDFePorUltNSU extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class CTEDistribuicaoDFePorNSUService extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class CTEDistribuicaoDFePorUltNSUService extends CTEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEInutilizacao{nfeInutilizacaoService;constructor(nfeInutilizacaoService){this.nfeInutilizacaoService=nfeInutilizacaoService}async Exec(data){return await this.nfeInutilizacaoService.Exec(data)}}class NFECartaDeCorrecao{nfeCartaDeCorrecaoServiceService;constructor(nfeCartaDeCorrecaoServiceService){this.nfeCartaDeCorrecaoServiceService=nfeCartaDeCorrecaoServiceService}async Exec(data){return await this.nfeCartaDeCorrecaoServiceService.Exec(data)}}class NFEDesconhecimentoDaOperacao{nfeDesconhecimentoDaOperacaoServiceService;constructor(nfeDesconhecimentoDaOperacaoServiceService){this.nfeDesconhecimentoDaOperacaoServiceService=nfeDesconhecimentoDaOperacaoServiceService}async Exec(data){return await this.nfeDesconhecimentoDaOperacaoServiceService.Exec(data)}}class NFERetornoAutorizacao{nfeRetornoAutorizacaoService;constructor(nfeRetornoAutorizacaoService){this.nfeRetornoAutorizacaoService=nfeRetornoAutorizacaoService}async getXmlRetorno(data){return await this.nfeRetornoAutorizacaoService.getXmlRetorno(data)}}function filterFieldsByType(source,requiredFields){const result={};for(const key of requiredFields)key in source&&""!==source[key]&&(result[key]=source[key]);return result}const COFINSMap={"01":"COFINSAliq","02":"COFINSAliq","03":"COFINSQtde","04":"COFINSNT","05":"COFINSNT","06":"COFINSNT","07":"COFINSNT","08":"COFINSNT","09":"COFINSNT",49:"COFINSOutr",50:"COFINSOutr",51:"COFINSOutr",52:"COFINSOutr",53:"COFINSOutr",54:"COFINSOutr",55:"COFINSOutr",56:"COFINSOutr",60:"COFINSOutr",61:"COFINSOutr",62:"COFINSOutr",63:"COFINSOutr",64:"COFINSOutr",65:"COFINSOutr",66:"COFINSOutr",67:"COFINSOutr",70:"COFINSOutr",71:"COFINSOutr",72:"COFINSOutr",73:"COFINSOutr",74:"COFINSOutr",75:"COFINSOutr",98:"COFINSOutr",99:"COFINSOutr"},PISMap={"01":"PISAliq","02":"PISAliq","03":"PISQtde","04":"PISNT","05":"PISNT","06":"PISNT","07":"PISNT","08":"PISNT","09":"PISNT",49:"PISOutr",50:"PISOutr",51:"PISOutr",52:"PISOutr",53:"PISOutr",54:"PISOutr",55:"PISOutr",56:"PISOutr",60:"PISOutr",61:"PISOutr",62:"PISOutr",63:"PISOutr",64:"PISOutr",65:"PISOutr",66:"PISOutr",67:"PISOutr",70:"PISOutr",71:"PISOutr",72:"PISOutr",73:"PISOutr",74:"PISOutr",75:"PISOutr",98:"PISOutr",99:"PISOutr"},ICMSMap={"00":"ICMS00","02":"ICMS02",10:"ICMS10",20:"ICMS20",30:"ICMS30",40:"ICMS40",41:"ICMS40",50:"ICMS40",51:"ICMS51",60:"ICMS60",61:"ICMS61",70:"ICMS70",90:"ICMS90",101:"ICMSSN101",102:"ICMSSN102",103:"ICMSSN102",201:"ICMSSN201",202:"ICMSSN202",203:"ICMSSN202",500:"ICMSSN500",900:"ICMSSN900"},mountCOFINS=cofins=>{const{CST:CST}=cofins,cst_cofins=CST;let cofinsKey=COFINSMap[CST];cofinsKey||(console.warn(`Código de situação tributária do COFINS ${cst_cofins} não é reconhecido. Alterado para padrão 'COFINSAliq'.`),cofinsKey="COFINSAliq");const requiredFields={COFINSAliq:["CST","vBC","pCOFINS","vCOFINS"],COFINSQtde:["CST","qBCProd","vAliqProd","vCOFINS"],COFINSNT:["CST"],COFINSOutr:["CST","vBC","pCOFINS","qBCProd","vAliqProd","vCOFINS"]};if(cofinsKey in requiredFields){const cofinsProperties=filterFieldsByType(cofins,requiredFields[cofinsKey]);return{[cofinsKey]:cofinsProperties}}return console.warn(`Chave COFINS '${cofinsKey}' não reconhecida.`),{}},mountPIS=pis=>{const{CST:CST}=pis,cst_pis=CST;let pisKey=PISMap[cst_pis];pisKey||(console.warn(`Código de situação tributária do PIS ${cst_pis} não é reconhecido. Alterado para padrão 'PISAliq'.`),pisKey="PISAliq");const requiredFields={PISAliq:["CST","vBC","pPIS","vPIS"],PISQtde:["CST","qBCProd","vAliqProd","vPIS"],PISNT:["CST"],PISOutr:["CST","vBC","pPIS","qBCProd","vAliqProd","vPIS"]};if(pisKey in requiredFields){const pisProperties=filterFieldsByType(pis,requiredFields[pisKey]);return{[pisKey]:pisProperties}}return console.warn(`Chave PIS '${pisKey}' não reconhecida.`),{}},mountICMS=icms=>{const{CST:CST,CSOSN:CSOSN}=icms;let cod_sit=CST;CST?.trim()?.length>0?cod_sit=CST.length>2?CST.substring(1,3):CST:CSOSN&&(cod_sit=CSOSN?.trim()?.length>3?CSOSN.substring(1,4):String(CSOSN));let icmsKey=ICMSMap[cod_sit];icmsKey||(console.warn(`Código de situação tributária ${cod_sit} não é reconhecido. Alterado para padrão 'ICMS00'.`),icmsKey="ICMS00");const requiredFields={ICMS00:["orig","CST","modBC","vBC","pICMS","vICMS","pFCP","vFCP"],ICMS02:["orig","CST","qBCMono","adRemICMS","vICMSMono"],ICMS10:["orig","CST","modBC","vBC","pICMS","vICMS","vBCFCP","pFCP","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vICMSSTDeson","motDesICMSST"],ICMS15:["orig","CST","qBCMono","adRemICMS","vICMSMono","qBCMonoReten","adRemICMSReten","vICMSMonoReten","pRedAdRem","motRedAdRem"],ICMS20:["orig","CST","modBC","pRedBC","vBC","pICMS","vICMS","vBCFCP","pFCP","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS30:["orig","CST","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vBCFCPST","pFCPST","vFCPST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS40:["orig","CST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS41:["orig","CST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS50:["orig","CST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMS51:["orig","CST","modBC","pRedBC","vBC","pICMS","vICMS","vICMSOp","pDif","vICMSDif"],ICMS53:["orig","CST","qBCMono","adRemICMS","vICMSMonoOp","pDif","vICMSMonoDif","vICMSMono","qBCMonoDif","adRemICMSDif"],ICMS60:["orig","CST","vBCSTRet","pST","vICMSSubstituto","vICMSSTRet","vBCFCPSTRet","pFCPSTRet","vFCPSTRet","pRedBCEfet","vBCEfet","pICMSEfet","vICMSEfet"],ICMS61:["orig","CST","qBCMonoRet","adRemICMSRet","vICMSMonoRet"],ICMS70:["orig","CST","modBC","pRedBC","vBC","pICMS","vICMS","vBCST","pICMSST","vICMSST","vICMSDeson","motDesICMS","indDeduzDeson","modBCST","pMVAST","pRedBCST"],ICMS90:["orig","CST","modBC","vBC","pRedBC","pICMS","vICMS","vBCFCP","pFCP","vFCP","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vBCFCPST","pFCPST","vFCPST","vICMSDeson","motDesICMS","indDeduzDeson"],ICMSPart:["orig","CST","modBC","vBC","pRedBC","pICMS","vICMS","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","pBCOp","UFST","vBCFCPST","pFCPST","vFCPST"],ICMSST:["orig","CST","vBCSTRet","pST","vICMSSubstituto","vICMSSTRet","vBCFCPSTRet","pFCPSTRet","vFCPSTRet","vBCSTDest","vICMSSTDest"],ICMSSN101:["orig","CSOSN","pCredSN","vCredICMSSN"],ICMSSN102:["orig","CSOSN"],ICMSSN201:["orig","CSOSN","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","pFCPST","vFCPST"],ICMSSN202:["orig","CSOSN","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vFCPST","vBCFCPST","pFCPST"],ICMSSN500:["orig","CSOSN","vBCSTRet","pST","vICMSSubstituto","vICMSSTRet","vBCFCPSTRet","pFCPSTRet","vFCPSTRet","pRedBCEfet","vBCEfet","pICMSEfet","vICMSEfet"],ICMSSN900:["orig","CSOSN","modBC","vBC","pRedBC","pICMS","vICMS","modBCST","pMVAST","pRedBCST","vBCST","pICMSST","vICMSST","vBCFCPST","pFCPST","vFCPST","pCredSN","vCredICMSSN"]};if(icmsKey in requiredFields){const icmsProperties=filterFieldsByType(icms,requiredFields[icmsKey]);return{[icmsKey]:icmsProperties}}return console.warn(`Chave ICMS '${icmsKey}' não reconhecida.`),{}};class NFERetornoAutorizacaoService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFERetAutorizacao",axios,saveFiles,gerarConsulta)}gerarXml(data){const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe",versao:"4.00"},tpAmb:ambiente,nRec:data};return this.xmlBuilder.gerarXml(xmlObject,"consReciNFe",this.metodo)}async getRetornoRecibo(nRec,xmlNFe){const xmlConsulta=this.gerarXml(nRec),{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo);this.utility.salvaConsulta(xmlConsulta,xmlFormated,this.metodo);const xmlRetorno=await this.axios.post(webServiceUrl,xmlFormated,{headers:{"Content-Type":this.setContentType(),SOAPAction:action},httpsAgent:agent}),responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo);this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo);const{protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno.data);if(!protNFe)throw new Error("Não foi possível encontrar a tag 'protNFe'. Talvez a NFe ainda não tenha sido processada.");return this.getXmlRetornoAutorizacao(protNFe,xmlNFe)}getXmlRetornoAutorizacao(protNFe,xmlNFe){const XMLs=[];for(let i=0;i<protNFe.length;i++){const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},_:"[XML]"};let xml=this.xmlBuilder.gerarXml(baseXML,"nfeProc",this.metodo);const formatedProtNFe=protNFe,xmlCompleto=xmlNFe.find(item=>-1!==item.indexOf(formatedProtNFe[i].infProt[0].chNFe[0]));if(xmlCompleto){const protTag=this.xmlBuilder.gerarXml(protNFe[i],"protNFe",this.metodo),xmlFinal=[xmlCompleto];xmlFinal.push(protTag),xml=xml.replace("[XML]",xmlFinal.join("")),xml=`<?xml version="1.0" encoding="UTF-8"?>${xml}`,XMLs.push(xml)}}return{success:!0,message:"xMotivo",data:XMLs}}async getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:xmlNFe}){if(1===tipoEmissao&&protNFe)return this.getXmlRetornoAutorizacao(protNFe,xmlNFe);if(0===tipoEmissao&&nRec)return this.getRetornoRecibo(nRec,xmlNFe);throw new Error("Não foi possível buscar o retorno da autorização.")}}class NFEAutorizacaoService extends BaseNFE{xmlNFe;constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEAutorizacao",axios,saveFiles,gerarConsulta),this.xmlNFe=[]}gerarXml(data){return this.gerarXmlNFeAutorizacao(data)}salvaArquivos(xmlConsulta,responseInJson,xmlRetorno,options){const config=this.environment.getConfig();let dateAndTimeInFileName=config.dfe.incluirTimestampNoNomeDosArquivos;const createFileName=(prefix,includeMethodName)=>{const dtaTime=dateAndTimeInFileName?`-${format(new Date,"dd-MM-yyyy-HHmm")}`:"";return`${includeMethodName?`${this.metodo}`:""}${prefix?includeMethodName?`-${prefix}`:`${prefix}`:""}${responseInJson.chNFe?`-${responseInJson.chNFe}`:""}${dtaTime}`},salvarArquivo=(data,prefix,path,fileType,includeMethodName)=>{const fileName=createFileName(prefix,includeMethodName),method="xml"===fileType?"salvaXML":"salvaJSON";this.utility[method]({data:data,fileName:fileName,metodo:this.metodo,path:path})};let xmlAutorizacaoInJson={},xMotivoPorXml=[],xmlsInJson=[];if(options){const{xmlAutorizacao:xmlAutorizacao}=options,json=new XmlParser;for(let i=0;i<xmlAutorizacao.length;i++){xmlAutorizacaoInJson=json.convertXmlToJson(xmlAutorizacao[i],"NFEAutorizacaoFinal"),xmlsInJson.push(xmlAutorizacaoInJson);const chNFe=xmlAutorizacaoInJson.protNFe.infProt.chNFe,xMotivo=xmlAutorizacaoInJson.protNFe.infProt.xMotivo,cStat=xmlAutorizacaoInJson.protNFe.infProt.cStat;xMotivoPorXml.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat}),config.dfe.armazenarXMLAutorizacao&&(salvarArquivo(xmlAutorizacao[i],chNFe,config.dfe.pathXMLAutorizacao,"xml",!1),salvarArquivo(xmlAutorizacaoInJson,chNFe,config.dfe.pathXMLAutorizacao,"json",!1))}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}async trataRetorno(xmlRetorno,indSinc,responseInJson){const{nRec:nRec,protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno);let tipoEmissao=0;1===indSinc&&protNFe&&(tipoEmissao=1);const nfeRetornoAutService=new NFERetornoAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeRetornoAut=new NFERetornoAutorizacao(nfeRetornoAutService);1!==tipoEmissao&&await new Promise(resolve=>setTimeout(resolve,1e3*Number(responseInJson.infRec?.tMed||5)));return await nfeRetornoAut.getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:this.xmlNFe})}anoMesEmissao(dhEmi){const dataAtual=new Date(dhEmi);return dataAtual.getFullYear().toString().slice(-2)+(dataAtual.getMonth()+1).toString().padStart(2,"0")}gerarCodigoNumerico(){return Math.floor(1e8*Math.random()).toString().padStart(8,"0")}calcularModulo11(sequencia){const pesos=[4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2];let somatoria=0;for(let i=0;i<sequencia.length;i++)somatoria+=parseInt(sequencia.charAt(i))*pesos[i];const restoDivisao=somatoria%11;return 0===restoDivisao||1===restoDivisao?0:11-restoDivisao}calcularDigitoVerificador(data){const{infNFe:{Id:Id,ide:{cUF:cUF,mod:mod,serie:serie,nNF:nNF,tpEmis:tpEmis,cNF:cNF,dhEmi:dhEmi},emit:{CNPJCPF:CNPJCPF}}}=data;if(Id)return this.chaveNfe=Id,{chaveAcesso:`NFe${Id}`,dv:parseInt(Id.charAt(Id.length-1),10)};const sequencia=`${cUF}${this.anoMesEmissao(dhEmi)}${CNPJCPF}${mod}${String(serie).padStart(3,"0")}${String(nNF).padStart(9,"0")}${tpEmis}${cNF}`,dv=this.calcularModulo11(sequencia),chaveAcesso=`NFe${sequencia}`+dv;return this.chaveNfe=`${sequencia}${dv}`,{chaveAcesso:chaveAcesso,dv:dv}}validaDocumento(doc,campo){const nfeAutorizacaoHandler=new ValidaCPFCNPJ,{documentoValido:documentoValido,tipoDoDocumento:tipoDoDocumento}=nfeAutorizacaoHandler.validarCpfCnpj(doc);if(console.log({documentoValido:documentoValido,tipoDoDocumento:tipoDoDocumento}),!documentoValido||"Desconhecido"===tipoDoDocumento){throw new Error("Desconhecido"===tipoDoDocumento?`Documento do ${campo} ausente ou inválido`:`${tipoDoDocumento} do ${campo} é inválido`)}return tipoDoDocumento}gerarXmlNFeAutorizacao(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFEAutorizacaoService"});const createXML=NFe=>{if(NFe?.infNFe?.det instanceof Array){const formatedItens=NFe.infNFe.det.map((det,index)=>{if(det.imposto?.ICMS?.dadosICMS){const icms=mountICMS(det.imposto.ICMS.dadosICMS);det.imposto.ICMS=icms}if(det.imposto.PIS?.dadosPIS){const pis=mountPIS(det.imposto.PIS.dadosPIS);det.imposto.PIS=pis}if(det.imposto.COFINS?.dadosCOFINS){const cofins=mountCOFINS(det.imposto.COFINS.dadosCOFINS);det.imposto.COFINS=cofins}return{$:{nItem:index+1},...det}});NFe.infNFe.det=formatedItens}const{chaveAcesso:chaveAcesso,dv:dv}=this.calcularDigitoVerificador(NFe);if(NFe.infNFe.ide.cDV=dv,NFe.infNFe.ide.verProc=NFe.infNFe.ide.verProc||"1.0.0.0",delete NFe.infNFe.Id,NFe.infNFe.emit=Object.assign({[this.validaDocumento(String(NFe.infNFe.emit.CNPJCPF),"emitente")]:NFe.infNFe.emit.CNPJCPF},NFe.infNFe.emit),delete NFe.infNFe.emit.CNPJCPF,NFe.infNFe.dest&&(NFe.infNFe.dest=Object.assign({[this.validaDocumento(String(NFe.infNFe.dest?.CNPJCPF||""),"destinatário")]:NFe.infNFe.dest?.CNPJCPF||""},NFe.infNFe.dest),delete NFe.infNFe.dest.CNPJCPF),NFe.infNFe.transp.transporta&&(NFe.infNFe.transp.transporta=Object.assign({[this.validaDocumento(String(NFe.infNFe.transp.transporta?.CNPJCPF),"transportador")]:NFe.infNFe.transp.transporta?.CNPJCPF},NFe.infNFe.transp.transporta),delete NFe.infNFe.transp.transporta?.CNPJCPF),NFe.infNFe?.NFref instanceof Array){const NFrefArray=NFe.infNFe.NFref;NFrefArray&&NFrefArray.length>0&&(NFe.infNFe.NFref=NFrefArray.map(NFref=>(NFref.refNFP&&(NFref.refNFP=Object.assign({[this.validaDocumento(String(NFref.refNFP.CNPJCPF),"produtor rural")]:NFref.refNFP.CNPJCPF},NFref.refNFP),delete NFref.refNFP.CNPJCPF),NFref)))}else NFe.infNFe.NFref&&NFe.infNFe.NFref.refNFP&&(NFe.infNFe.NFref.refNFP=Object.assign({[this.validaDocumento(String(NFe.infNFe.NFref.refNFP.CNPJCPF),"produtor rural")]:NFe.infNFe.NFref.refNFP.CNPJCPF},NFe.infNFe.NFref.refNFP));NFe.infNFe.dest&&2===NFe.infNFe.ide.tpAmb&&(NFe.infNFe.dest.xNome="NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL");const xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe"},infNFe:{$:{versao:"4.00",Id:chaveAcesso},...NFe.infNFe}},eventoXML=this.xmlBuilder.gerarXml(xmlObject,"NFe",this.metodo),xmlAssinado=this.xmlBuilder.assinarXML(eventoXML,"infNFe");this.xmlNFe.push(xmlAssinado)};if(data.NFe instanceof Array)for(let i=0;i<data.NFe.length;i++){createXML(data.NFe[i])}else createXML(data.NFe);const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},idLote:data.idLote,indSinc:data.indSinc,_:"[XML]"};return this.xmlBuilder.gerarXml(baseXML,"enviNFe",this.metodo).replace("[XML]",this.xmlNFe.join(""))}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType};logger.http("Iniciando comunicação com o webservice",{context:"NFEAutorizacaoService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"NFEAutorizacaoService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlNFeAutorizacao(data);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo);xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent);responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo);const retorno=await this.trataRetorno(xmlRetorno.data,data.indSinc,responseInJson),xmlFinal=this.salvaArquivos(xmlConsulta,responseInJson,xmlRetorno.data,{xmlAutorizacao:retorno.data,xMotivo:retorno.message});return logger.info("NFe transmitida com sucesso",{context:"NFEAutorizacaoService"}),{success:!0,xMotivo:xmlFinal.xMotivo,xmls:xmlFinal.response}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class NFEconsultaProtocoloService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEConsultaProtocolo",axios,saveFiles,gerarConsulta)}gerarXml(chave){logger.info("Montando estrutuda do XML em JSON",{context:"NFEconsultaProtocoloService"});const{nfe:{ambiente:ambiente,versaoDF:versaoDF}}=this.environment.getConfig(),xmlObject={$:{versao:versaoDF,xmlns:"http://www.portalfiscal.inf.br/nfe"},tpAmb:ambiente,xServ:"CONSULTAR",chNFe:chave};return this.xmlBuilder.gerarXml(xmlObject,"consSitNFe",this.metodo)}}class NFEStatusServico{nfeStatusServicoService;constructor(nfeStatusServicoService){this.nfeStatusServicoService=nfeStatusServicoService}async Exec(data){return await this.nfeStatusServicoService.Exec(data)}}class NFERecepcaoEvento{nfeRecepcaoEventoService;constructor(nfeRecepcaoEventoService){this.nfeRecepcaoEventoService=nfeRecepcaoEventoService}async Exec(data){return await this.nfeRecepcaoEventoService.Exec(data)}}class NFERecepcaoEventoService extends BaseNFE{tpEvento;modelo;xmlEventosNacionais;xmlEventosRegionais;xMotivoPorEvento;constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"RecepcaoEvento",axios,saveFiles,gerarConsulta),this.tpEvento="",this.modelo="NFe",this.xmlEventosNacionais=[],this.xmlEventosRegionais=[],this.xMotivoPorEvento=[],console.log("constructor recepcao evento service")}getID(evento){const{tpEvento:tpEvento,chNFe:chNFe,nSeqEvento:nSeqEvento}=evento;if("string"!=typeof tpEvento||!/^\d{6}$/.test(tpEvento))throw new Error("tpEvento deve ser uma string com 6 dígitos.");if("string"!=typeof chNFe||!/^\d{44}$/.test(chNFe))throw new Error("chNFe deve ser uma string com 44 dígitos.");if(!Number.isInteger(nSeqEvento)||nSeqEvento<1||nSeqEvento>99)throw new Error("nSeqEvento deve ser um número entre 1 e 99.");const id=`ID${tpEvento}${chNFe}${nSeqEvento.toString().padStart(2,"0")}`;if(54!==id.length)throw new Error("O ID construído não tem 54 caracteres.");return id}isAmbienteNacional(tpEvento){switch(tpEvento){case"210210":case"210200":case"210220":case"210240":case"110140":return!0;default:return!1}}getTipoEventoName(tpEvento){switch(tpEvento){case"210210":return"Ciência da Operação";case"210200":return"Confirmação da Operaçã";case"210220":return"Desconhecimento da Operação";case"210240":return"Operação não Realizada";case"110110":return"Carta de Correção";case"110111":return"Cancelamento";case"110140":return"EPEC";default:return"Desconhecido"}}separaEventosPorAmbiente(evento){logger.info("Dividindo eventos por ambiente",{context:"NFERecepcaoEventoService"});return{nacional:evento.filter(event=>["210210","210200","210220","210240","110140"].includes(event.tpEvento)),regional:evento.filter(event=>!["210210","210200","210220","210240","110140"].includes(event.tpEvento))}}gerarXmlRecepcaoEvento(evento,idLote,ambienteNacional){const{nfe:{ambiente:ambiente,versaoDF:versaoDF},dfe:{UF:UF}}=this.environment.getConfig();for(let i=0;i<evento.length;i++){const eventoProps=evento[i],{tpAmb:tpAmb,cOrgao:cOrgao,tpEvento:tpEvento,chNFe:chNFe,nSeqEvento:nSeqEvento,CNPJ:CNPJ,CPF:CPF,detEvento:detEvento,dhEvento:dhEvento,verEvento:verEvento}=eventoProps,idEvento=this.getID(eventoProps),orgao=ambienteNacional?91:cOrgao;this.tpEvento=tpEvento;const eventoObject={$:{versao:"1.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},infEvento:{$:{Id:idEvento},cOrgao:orgao,tpAmb:ambiente,...CNPJ?{CNPJ:CNPJ}:{CPF:CPF},chNFe:chNFe,dhEvento:dhEvento,tpEvento:tpEvento,nSeqEvento:nSeqEvento,verEvento:verEvento,detEvento:{$:{versao:"1.00"},...detEvento}}},eventoXML=this.xmlBuilder.gerarXml(eventoObject,"evento",this.metodo),xmlAssinado=this.xmlBuilder.assinarXML(eventoXML,"infEvento");ambienteNacional?this.xmlEventosNacionais.push(xmlAssinado):this.xmlEventosRegionais.push(xmlAssinado)}const envEvento={$:{versao:"1.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},idLote:idLote,_:"[XML]"},xml=this.xmlBuilder.gerarXml(envEvento,"envEvento",this.metodo);return ambienteNacional?xml.replace("[XML]",this.xmlEventosNacionais.join("")):xml.replace("[XML]",this.xmlEventosRegionais.join(""))}trataRetorno(responseInJson){logger.info("Tratando retorno dos eventos",{context:"NFERecepcaoEventoService"});const retornoEventos=this.utility.findInObj(responseInJson,"retEvento");if(retornoEventos instanceof Array){for(let i=0;i<retornoEventos.length;i++){const chNFe=retornoEventos[i].infEvento.chNFe,xMotivo=retornoEventos[i].infEvento.xMotivo,cStat=retornoEventos[i].infEvento.cStat,tipoEvento=this.getTipoEventoName(retornoEventos[i].infEvento.tpEvento);this.xMotivoPorEvento.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat,tipoEvento:tipoEvento})}return this.xMotivoPorEvento}const chNFe=retornoEventos.infEvento.chNFe,xMotivo=retornoEventos.infEvento.xMotivo,cStat=retornoEventos.infEvento.cStat,tipoEvento=this.getTipoEventoName(retornoEventos.infEvento.tpEvento);return this.xMotivoPorEvento.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat,tipoEvento:tipoEvento}),this.xMotivoPorEvento}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType,SOAPAction:action};logger.http("Iniciando comunicação com o webservice",{context:"BaseNFE",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"BaseNFE",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async enviaEvento(evento,idLote,tipoAmbiente){let xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="";const ContentType=this.setContentType(),ambienteNacional=0===tipoAmbiente;try{xmlConsulta=this.gerarXmlRecepcaoEvento(evento,idLote,ambienteNacional);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,ambienteNacional||this.isAmbienteNacional(this.tpEvento),"",this.modelo);xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;return(await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent)).data}finally{const fileName=ambienteNacional?"RecepcaoEvento[Nacional]-consulta":"RecepcaoEvento[Regional]-consulta";this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo,fileName)}}async Exec(data){const{evento:evento,idLote:idLote,modelo:modelo}=data,{nacional:nacional,regional:regional}=this.separaEventosPorAmbiente(evento);"65"===modelo&&(this.modelo="NFCe");let responseNacionalInJson,responseRegionalInJson=null,finalResponseInJson=[];if(nacional.length>0){const retornoNacional=await this.enviaEvento(nacional,idLote,0);responseNacionalInJson=this.utility.verificaRejeicao(retornoNacional,this.metodo),this.utility.salvaRetorno(retornoNacional,responseNacionalInJson,this.metodo,"RecepcaoEvento[Nacional]-retorno"),this.trataRetorno(responseNacionalInJson),finalResponseInJson.push(responseNacionalInJson)}if(regional.length>0){const retornoRegional=await this.enviaEvento(regional,idLote,1);responseRegionalInJson=this.utility.verificaRejeicao(retornoRegional,this.metodo),this.utility.salvaRetorno(retornoRegional,responseRegionalInJson,this.metodo,"RecepcaoEvento[Regional]-retorno"),this.trataRetorno(responseRegionalInJson),finalResponseInJson.push(responseRegionalInJson)}return{success:!0,xMotivos:this.xMotivoPorEvento,response:finalResponseInJson}}}class NFECancelamentoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFECartaDeCorrecaoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFECienciaDaOperacaoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEDesconhecimentoDaOperacaoService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEEpecService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEOperacaoNaoRealizadaService extends NFERecepcaoEventoService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEAutorizacao{nfeAutorizacaoService;constructor(nfeAutorizacaoService){this.nfeAutorizacaoService=nfeAutorizacaoService}async Exec(data){return await this.nfeAutorizacaoService.Exec(data)}}class DistribuicaoHandler{environment;utility;metodo;constructor(environment,utility,metodo){this.utility=utility,this.environment=environment,this.metodo=metodo}salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chNFe){const{pathXMLDistribuicao:pathXMLDistribuicao,baixarXMLDistribuicao:baixarXMLDistribuicao,armazenarRetornoEmJSON:armazenarRetornoEmJSON}=this.environment.config.dfe;baixarXMLDistribuicao&&(this.utility.salvaXML({data:XMLDistribuicao,fileName:chNFe,metodo:this.metodo,path:pathXMLDistribuicao}),armazenarRetornoEmJSON&&this.utility.salvaJSON({data:XMLDistribuicaoInJson,fileName:chNFe,metodo:this.metodo,path:pathXMLDistribuicao}))}deCompressDFeXML(loteDistDFeInt,metodo,xmlConsulta){logger.info("Descomprimindo XML",{context:"DistribuicaoHandler"});const json=new XmlParser,files=[];return xml2js$1.parseString(loteDistDFeInt,(err,result)=>{if(err)throw new Error(`Erro ao descomprimir o XML: ${err}`);this.utility.findInObj(result,"docZip").forEach(docZip=>{const xmlString=this.decodeDocZip(docZip),cleanedXml=this.removeSignatureTag(xmlString),parsedResult=this.parseXml(cleanedXml);if(!parsedResult)return;let chNFe=this.getChNFe(parsedResult),tipo=this.getTipo(parsedResult);const nsu=docZip.$.NSU;if(parsedResult.procEventoNFe){chNFe=`${chNFe}-event-${this.utility.findInObj(parsedResult,"tpEvento")}`,tipo="event"}const xmlDistribuicaoInJson=json.convertXmlToJson(cleanedXml,`${metodo}_${tipo}`,nsu);this.handleResponse(xmlDistribuicaoInJson,cleanedXml,chNFe),files.push(chNFe)})}),files}decodeDocZip(docZip){logger.info("Decodificando DocZip",{context:"DistribuicaoHandler"});const base64String=docZip._;let binaryString=atob(base64String),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);let decompressedData=pako.inflate(bytes);return new TextDecoder("utf-8").decode(decompressedData)}removeSignatureTag(xmlString){return xmlString.replace(/<Signature.*?<\/Signature>/gs,"")}parseXml(xmlString){let parsedResult;return xml2js$1.parseString(xmlString,(err,result)=>{err?(console.error("Erro ao parsear o XML decomprimido:",err),parsedResult=null):parsedResult=result}),parsedResult}getChNFe(parsedResult){return this.utility.findInObj(parsedResult,"chNFe")}getTipo(parsedResult){return this.utility.findInObj(parsedResult,"resNFe")?"res":parsedResult.procEventoNFe?"event":"proc"}handleResponse(XMLDistribuicaoInJson,XMLDistribuicao,chNFe){this.salvaArquivos(XMLDistribuicaoInJson,XMLDistribuicao,chNFe);const xMotivo=this.utility.findInObj(XMLDistribuicaoInJson,"xMotivo");if(xMotivo&&(xMotivo.includes("Rejeição")||xMotivo.includes("Rejeicao")))throw new Error(XMLDistribuicaoInJson.xMotivo)}}class NFEDistribuicaoDFeService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFeDistribuicaoDFe",axios,saveFiles,gerarConsulta)}gerarXml(data){return this.gerarXmlNFeDistribuicaoDFe(data)}gerarXmlNFeDistribuicaoDFe(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFEDistribuicaoDFeService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{versao:"1.01",xmlns:"http://www.portalfiscal.inf.br/nfe"},tpAmb:ambiente,...data};return this.xmlBuilder.gerarXml(xmlObject,"distDFeInt",this.metodo)}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),headers={"Content-Type":ContentType};logger.http("Iniciando comunicação com o webservice",{context:"NFEDistribuicaoDFeService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"NFEDistribuicaoDFeService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlNFeDistribuicaoDFe(data);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,!0,"1.01","NFe",!0,"nfeDistDFeInteresse");xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent);if(responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo),"137"===responseInJson.retDistDFeInt.cStat)return{data:{},xMotivo:responseInJson.retDistDFeInt.xMotivo,filesList:[]};const filesList=new DistribuicaoHandler(this.environment,this.utility,this.metodo).deCompressDFeXML(xmlRetorno.data,this.metodo,xmlConsulta);return{data:responseInJson,xMotivo:this.utility.findInObj(responseInJson,"xMotivo"),filesList:filesList}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class NFEDistribuicaoDFePorUltNSUService extends NFEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEDistribuicaoDFePorNSUService extends NFEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEDistribuicaoDFePorChaveService extends NFEDistribuicaoDFeService{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta)}}class NFEInutilizacaoService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEInutilizacao",axios,saveFiles,gerarConsulta)}gerarXml(chave){return this.gerarXmlNFeInutilizacao(chave)}criarId(codigoUF,ano,cnpj,modelo,serie,numeroInicial,numeroFinal){return`ID${codigoUF}${ano}${cnpj}${modelo}${serie}${numeroInicial}${numeroFinal}`}getModelo(data){return data?.mod?"55"===data.mod?"NFe":"NFCe":super.getModelo(data)}gerarXmlNFeInutilizacao(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFEInutilizacaoService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),{cUF:cUF,ano:ano,CNPJ:CNPJ,mod:mod,serie:serie,nNFIni:nNFIni,nNFFin:nNFFin,xJust:xJust}=data,anoFormatado=ano.toString().slice(-2),serieFormatada=serie.padStart(3,"0"),numNFIniFormatado=nNFIni.padStart(9,"0"),numNFFinFormatado=nNFFin.padStart(9,"0"),id=this.criarId(cUF,anoFormatado,CNPJ,mod,serieFormatada,numNFIniFormatado,numNFFinFormatado);if(-1===[55,65].indexOf(Number(mod)))throw new Error(`Modelo do documento para inutilização deve ser 55 ou 65. Modelo informado: ${mod}`);const xmlObject={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},infInut:{$:{Id:`${id}`},tpAmb:ambiente,xServ:"INUTILIZAR",cUF:cUF,ano:ano,CNPJ:CNPJ,mod:mod,serie:serie,nNFIni:nNFIni,nNFFin:nNFFin,xJust:xJust}},xml=this.xmlBuilder.gerarXml(xmlObject,"inutNFe",this.metodo);return this.xmlBuilder.assinarXML(xml,"infInut")}}var hasRequiredCrypt,charenc_1,hasRequiredCharenc,hasRequiredSha1,sha1$1={exports:{}},crypt={exports:{}};function requireCrypt(){return hasRequiredCrypt||(hasRequiredCrypt=1,base64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",crypt$1={rotl:function(n,b){return n<<b|n>>>32-b},rotr:function(n,b){return n<<32-b|n>>>b},endian:function(n){if(n.constructor==Number)return 16711935&crypt$1.rotl(n,8)|4278255360&crypt$1.rotl(n,24);for(var i=0;i<n.length;i++)n[i]=crypt$1.endian(n[i]);return n},randomBytes:function(n){for(var bytes=[];n>0;n--)bytes.push(Math.floor(256*Math.random()));return bytes},bytesToWords:function(bytes){for(var words=[],i=0,b=0;i<bytes.length;i++,b+=8)words[b>>>5]|=bytes[i]<<24-b%32;return words},wordsToBytes:function(words){for(var bytes=[],b=0;b<32*words.length;b+=8)bytes.push(words[b>>>5]>>>24-b%32&255);return bytes},bytesToHex:function(bytes){for(var hex=[],i=0;i<bytes.length;i++)hex.push((bytes[i]>>>4).toString(16)),hex.push((15&bytes[i]).toString(16));return hex.join("")},hexToBytes:function(hex){for(var bytes=[],c=0;c<hex.length;c+=2)bytes.push(parseInt(hex.substr(c,2),16));return bytes},bytesToBase64:function(bytes){for(var base64=[],i=0;i<bytes.length;i+=3)for(var triplet=bytes[i]<<16|bytes[i+1]<<8|bytes[i+2],j=0;j<4;j++)8*i+6*j<=8*bytes.length?base64.push(base64map.charAt(triplet>>>6*(3-j)&63)):base64.push("=");return base64.join("")},base64ToBytes:function(base64){base64=base64.replace(/[^A-Z0-9+\/]/gi,"");for(var bytes=[],i=0,imod4=0;i<base64.length;imod4=++i%4)0!=imod4&&bytes.push((base64map.indexOf(base64.charAt(i-1))&Math.pow(2,-2*imod4+8)-1)<<2*imod4|base64map.indexOf(base64.charAt(i))>>>6-2*imod4);return bytes}},crypt.exports=crypt$1),crypt.exports;var base64map,crypt$1}function requireCharenc(){if(hasRequiredCharenc)return charenc_1;hasRequiredCharenc=1;var charenc={utf8:{stringToBytes:function(str){return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)))},bytesToString:function(bytes){return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)))}},bin:{stringToBytes:function(str){for(var bytes=[],i=0;i<str.length;i++)bytes.push(255&str.charCodeAt(i));return bytes},bytesToString:function(bytes){for(var str=[],i=0;i<bytes.length;i++)str.push(String.fromCharCode(bytes[i]));return str.join("")}}};return charenc_1=charenc}var sha1Exports=function requireSha1(){return hasRequiredSha1||(hasRequiredSha1=1,function(){var crypt=requireCrypt(),utf8=requireCharenc().utf8,bin=requireCharenc().bin,api=function(message,options){var digestbytes=crypt.wordsToBytes(function(message){message.constructor==String?message=utf8.stringToBytes(message):"undefined"!=typeof Buffer&&"function"==typeof Buffer.isBuffer&&Buffer.isBuffer(message)?message=Array.prototype.slice.call(message,0):Array.isArray(message)||(message=message.toString());var m=crypt.bytesToWords(message),l=8*message.length,w=[],H0=1732584193,H1=-271733879,H2=-1732584194,H3=271733878,H4=-1009589776;m[l>>5]|=128<<24-l%32,m[15+(l+64>>>9<<4)]=l;for(var i=0;i<m.length;i+=16){for(var a=H0,b=H1,c=H2,d=H3,e=H4,j=0;j<80;j++){if(j<16)w[j]=m[i+j];else{var n=w[j-3]^w[j-8]^w[j-14]^w[j-16];w[j]=n<<1|n>>>31}var t=(H0<<5|H0>>>27)+H4+(w[j]>>>0)+(j<20?1518500249+(H1&H2|~H1&H3):j<40?1859775393+(H1^H2^H3):j<60?(H1&H2|H1&H3|H2&H3)-1894007588:(H1^H2^H3)-899497514);H4=H3,H3=H2,H2=H1<<30|H1>>>2,H1=H0,H0=t}H0+=a,H1+=b,H2+=c,H3+=d,H4+=e}return[H0,H1,H2,H3,H4]}(message));return options&&options.asBytes?digestbytes:options&&options.asString?bin.bytesToString(digestbytes):crypt.bytesToHex(digestbytes)};api._blocksize=16,api._digestsize=20,sha1$1.exports=api}()),sha1$1.exports}(),sha1=getDefaultExportFromCjs(sha1Exports);function generateQRCodeURLOnline(chaveAcesso,versaoQRCode,tipoAmbiente,identificadorCSC,csc,utility){const urlQRCodeNFCe=utility.getUrlNFCe("URL-QRCode",!1,""),baseString=`${chaveAcesso=chaveAcesso.replace("NFe","")}|${versaoQRCode}|${tipoAmbiente}|${identificadorCSC}`;return`${urlQRCodeNFCe}?p=${baseString}|${function generateSHA1Hash(input){return require$$0$4.createHash("sha1").update(input).digest("hex")}(`${baseString}${csc}`)}`}function generateQRCodeURLOffline(chaveAcesso,versaoQRCode,tipoAmbiente,diaDataEmissao,valorTotalNfce,digVal,identificadorCSC,csc,utility){const urlQRCodeNFCe=utility.getUrlNFCe("URL-QRCode",!1,"");chaveAcesso=chaveAcesso.replace("NFe","");const digestValueHex=function calcularDigestValueHex(digVal){return Buffer.from(digVal).toString("hex")}(digVal),baseString=`${chaveAcesso}|${versaoQRCode}|${tipoAmbiente}|${diaDataEmissao}|${valorTotalNfce}|${digestValueHex}|${identificadorCSC}`;return`${urlQRCodeNFCe}?p=${baseString}|${sha1(`${baseString}${csc}`).toUpperCase()}`}class NFCERetornoAutorizacaoService extends BaseNFE{constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFERetAutorizacao",axios,saveFiles,gerarConsulta)}gerarXml(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFCEAutorizacaoService"});const{nfe:{ambiente:ambiente}}=this.environment.getConfig(),xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe",versao:"4.00"},tpAmb:ambiente,nRec:data};return this.xmlBuilder.gerarXml(xmlObject,"consReciNFe",this.metodo)}async getRetornoRecibo(nRec,xmlNFe){const xmlConsulta=this.gerarXml(nRec),{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo);this.utility.salvaConsulta(xmlConsulta,xmlFormated,this.metodo);const xmlRetorno=await this.axios.post(webServiceUrl,xmlFormated,{headers:{"Content-Type":this.setContentType(),SOAPAction:action},httpsAgent:agent}),responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo);this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo);const{protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno.data);if(!protNFe)throw new Error("Não foi possível encontrar a tag 'protNFe'. Talvez a NFe ainda não tenha sido processada.");return this.getXmlRetornoAutorizacao(protNFe,xmlNFe)}getXmlRetornoAutorizacao(protNFe,xmlNFe){const XMLs=[];for(let i=0;i<protNFe.length;i++){const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},_:"[XML]"};let xml=this.xmlBuilder.gerarXml(baseXML,"nfeProc",this.metodo);const formatedProtNFe=protNFe,xmlCompleto=xmlNFe.find(item=>-1!==item.indexOf(formatedProtNFe[i].infProt[0].chNFe[0]));if(xmlCompleto){const protTag=this.xmlBuilder.gerarXml(protNFe[i],"protNFe",this.metodo),xmlFinal=[xmlCompleto];xmlFinal.push(protTag),xml=xml.replace("[XML]",xmlFinal.join("")),xml=`<?xml version="1.0" encoding="UTF-8"?>${xml}`,XMLs.push(xml)}}return{success:!0,message:"xMotivo",data:XMLs}}async getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:xmlNFe}){if(1===tipoEmissao&&protNFe)return this.getXmlRetornoAutorizacao(protNFe,xmlNFe);if(0===tipoEmissao&&nRec)return this.getRetornoRecibo(nRec,xmlNFe);throw new Error("Não foi possível buscar o retorno da autorização.")}}class NFCERetornoAutorizacao{nfceAutorizacaoRetornoService;constructor(nfceAutorizacaoRetornoService){this.nfceAutorizacaoRetornoService=nfceAutorizacaoRetornoService}async getXmlRetorno(data){return await this.nfceAutorizacaoRetornoService.getXmlRetorno(data)}}class NFCEAutorizacaoService extends BaseNFE{xmlNFe;constructor(environment,utility,xmlBuilder,axios,saveFiles,gerarConsulta){super(environment,utility,xmlBuilder,"NFEAutorizacao",axios,saveFiles,gerarConsulta),this.xmlNFe=[]}gerarXml(data){return this.gerarXmlNFCEAutorizacao(data)}salvaArquivos(xmlConsulta,responseInJson,xmlRetorno,options){const config=this.environment.getConfig();let dateAndTimeInFileName=config.dfe.incluirTimestampNoNomeDosArquivos;const createFileName=(prefix,includeMethodName)=>{const dtaTime=dateAndTimeInFileName?`-${format(new Date,"dd-MM-yyyy-HHmm")}`:"";return`${includeMethodName?`${this.metodo}`:""}${prefix?includeMethodName?`-${prefix}`:`${prefix}`:""}${responseInJson.chNFe?`-${responseInJson.chNFe}`:""}${dtaTime}`},salvarArquivo=(data,prefix,path,fileType,includeMethodName)=>{const fileName=createFileName(prefix,includeMethodName),method="xml"===fileType?"salvaXML":"salvaJSON";this.utility[method]({data:data,fileName:fileName,metodo:this.metodo,path:path})};let xmlAutorizacaoInJson={},xMotivoPorXml=[],xmlsInJson=[];if(options){const{xmlAutorizacao:xmlAutorizacao}=options,json=new XmlParser;for(let i=0;i<xmlAutorizacao.length;i++){xmlAutorizacaoInJson=json.convertXmlToJson(xmlAutorizacao[i],"NFCEAutorizacaoFinal"),xmlsInJson.push(xmlAutorizacaoInJson);const chNFe=xmlAutorizacaoInJson.protNFe.infProt.chNFe,xMotivo=xmlAutorizacaoInJson.protNFe.infProt.xMotivo,cStat=xmlAutorizacaoInJson.protNFe.infProt.cStat;xMotivoPorXml.push({chNFe:chNFe,xMotivo:xMotivo,cStat:cStat}),config.dfe.armazenarXMLAutorizacao&&(salvarArquivo(xmlAutorizacao[i],chNFe,config.dfe.pathXMLAutorizacao,"xml",!1),salvarArquivo(xmlAutorizacaoInJson,chNFe,config.dfe.pathXMLAutorizacao,"json",!1))}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}return{success:!0,xMotivo:xMotivoPorXml,response:xmlsInJson}}async trataRetorno(xmlRetorno,indSinc,responseInJson){try{const{nRec:nRec,protNFe:protNFe}=this.utility.getProtNFe(xmlRetorno);let tipoEmissao=0;1===indSinc&&protNFe&&(tipoEmissao=1);const nfeRetornoAutService=new NFCERetornoAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeRetornoAut=new NFCERetornoAutorizacao(nfeRetornoAutService);return await nfeRetornoAut.getXmlRetorno({tipoEmissao:tipoEmissao,nRec:nRec,protNFe:protNFe,xmlNFe:this.xmlNFe})}catch(error){throw new Error(error.message)}}anoMesEmissao(dhEmi){const dataAtual=new Date(dhEmi);return dataAtual.getFullYear().toString().slice(-2)+(dataAtual.getMonth()+1).toString().padStart(2,"0")}diaEmissao(dhEmi){return new Date(dhEmi).getDate().toString().padStart(2,"0")}calcularModulo11(sequencia){const pesos=[4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2];let somatoria=0;for(let i=0;i<sequencia.length;i++)somatoria+=parseInt(sequencia.charAt(i))*pesos[i];const restoDivisao=somatoria%11;return 0===restoDivisao||1===restoDivisao?0:11-restoDivisao}calcularDigitoVerificador(data){const{infNFe:{Id:Id,ide:{cUF:cUF,mod:mod,serie:serie,nNF:nNF,tpEmis:tpEmis,cNF:cNF,dhEmi:dhEmi},emit:{CNPJCPF:CNPJCPF}}}=data;if(Id)return this.chaveNfe=Id,{chaveAcesso:`NFe${Id}`,dv:parseInt(Id.charAt(Id.length-1),10)};const sequencia=`${cUF}${this.anoMesEmissao(dhEmi)}${CNPJCPF}${mod}${String(serie).padStart(3,"0")}${String(nNF).padStart(9,"0")}${tpEmis}${cNF}`,dv=this.calcularModulo11(sequencia),chaveAcesso=`NFe${sequencia}`+dv;return this.chaveNfe=`${sequencia}${dv}`,{chaveAcesso:chaveAcesso,dv:dv}}validaDocumento(doc,campo){const nfeAutorizacaoHandler=new ValidaCPFCNPJ,{documentoValido:documentoValido,tipoDoDocumento:tipoDoDocumento}=nfeAutorizacaoHandler.validarCpfCnpj(doc);if(!documentoValido||"Desconhecido"===tipoDoDocumento){throw new Error("Desconhecido"===tipoDoDocumento?`Documento do ${campo} ausente ou inválido`:`${tipoDoDocumento} do ${campo} é inválido`)}return tipoDoDocumento}extrairDigestValue(xmlAssinado){const match=xmlAssinado.match(/<DigestValue>([^<]+)<\/DigestValue>/);if(match&&match[1])return match[1];throw new Error("DigestValue não encontrado no XML assinado.")}gerarXmlNFCEAutorizacao(data){logger.info("Montando estrutuda do XML em JSON",{context:"NFCEAutorizacaoService"});const createXML=NFe=>{if(NFe?.infNFe?.det instanceof Array){const formatedItens=NFe.infNFe.det.map((det,index)=>{if(det.imposto.ICMS?.dadosICMS){const icms=mountICMS(det.imposto.ICMS.dadosICMS);det.imposto.ICMS=icms}if(det.imposto.PIS?.dadosPIS){const pis=mountPIS(det.imposto.PIS.dadosPIS);det.imposto.PIS=pis}if(det.imposto.COFINS?.dadosCOFINS){const cofins=mountCOFINS(det.imposto.COFINS.dadosCOFINS);det.imposto.COFINS=cofins}return{$:{nItem:index+1},...det}});NFe.infNFe.det=formatedItens}const{chaveAcesso:chaveAcesso,dv:dv}=this.calcularDigitoVerificador(NFe);if(NFe.infNFe.ide.cDV=dv,NFe.infNFe.ide.verProc=NFe.infNFe.ide.verProc||"1.0.0.0",NFe.infNFe.emit=Object.assign({[this.validaDocumento(String(NFe.infNFe.emit.CNPJCPF),"emitente")]:NFe.infNFe.emit.CNPJCPF},NFe.infNFe.emit),delete NFe.infNFe.emit.CNPJCPF,NFe.infNFe.dest){const tipoDocDest=this.validaDocumento(String(NFe.infNFe.dest?.CNPJCPF||""),"destinatário"),cnpjcpfValue=NFe.infNFe.dest?.CNPJCPF||"",xNomeValue=2===NFe.infNFe.ide.tpAmb?"NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL":NFe.infNFe.dest.xNome,{CNPJCPF:CNPJCPF,xNome:xNome,...restoDest}=NFe.infNFe.dest;NFe.infNFe.dest={[tipoDocDest]:cnpjcpfValue,...xNomeValue&&{xNome:xNomeValue},...restoDest}}if(NFe.infNFe.transp.transporta&&(NFe.infNFe.transp.transporta=Object.assign({[this.validaDocumento(String(NFe.infNFe.transp.transporta?.CNPJCPF),"transportador")]:NFe.infNFe.transp.transporta?.CNPJCPF},NFe.infNFe.transp.transporta),delete NFe.infNFe.transp.transporta?.CNPJCPF),NFe.infNFe?.NFref instanceof Array){const NFrefArray=NFe.infNFe.NFref;NFrefArray&&NFrefArray.length>0&&(NFe.infNFe.NFref=NFrefArray.map(NFref=>(NFref.refNFP&&(NFref.refNFP=Object.assign({[this.validaDocumento(String(NFref.refNFP.CNPJCPF),"produtor rural")]:NFref.refNFP.CNPJCPF},NFref.refNFP),delete NFref.refNFP.CNPJCPF),NFref)))}else NFe.infNFe.NFref&&NFe.infNFe.NFref.refNFP&&(NFe.infNFe.NFref.refNFP=Object.assign({[this.validaDocumento(String(NFe.infNFe.NFref.refNFP.CNPJCPF),"produtor rural")]:NFe.infNFe.NFref.refNFP.CNPJCPF},NFe.infNFe.NFref.refNFP));const{nfe:{idCSC:idCSC,tokenCSC:tokenCSC}}=this.environment.getConfig();let qrCode="";[4,9].includes(NFe.infNFe.ide.tpEmis)||(qrCode=generateQRCodeURLOnline(chaveAcesso,"2",NFe.infNFe.ide.tpAmb,Number(idCSC),String(tokenCSC),this.utility));const urlConsultaNFCe=this.utility.getUrlNFCe("URL-ConsultaNFCe",!1,""),xmlObject={$:{xmlns:"http://www.portalfiscal.inf.br/nfe"},infNFe:{$:{versao:"4.00",Id:chaveAcesso},...(NFe={...NFe,infNFeSupl:{qrCode:qrCode,urlChave:urlConsultaNFCe}}).infNFe},infNFeSupl:{...NFe.infNFeSupl}},eventoXML=this.xmlBuilder.gerarXml(xmlObject,"NFe",this.metodo);let xmlAssinado=this.xmlBuilder.assinarXML(eventoXML,"infNFe");if([4,9].includes(NFe.infNFe.ide.tpEmis)){const digestValue=this.extrairDigestValue(xmlAssinado),tpAmb=NFe.infNFe.ide.tpAmb,valNF=NFe.infNFe.total.ICMSTot.vNF,diaEmissao=this.diaEmissao(NFe.infNFe.ide.dhEmi);qrCode=generateQRCodeURLOffline(chaveAcesso,"2",tpAmb,diaEmissao,valNF,digestValue,Number(idCSC),String(tokenCSC),this.utility),xml2js$1.parseString(xmlAssinado,(err,result)=>{if(err)throw new Error("Erro ao parsear o XML para atualização do qrCode:");if(!result.NFe?.infNFeSupl[0]?.qrCode)throw new Error("Tag qrCode não encontrada no XML.");{result.NFe.infNFeSupl[0].qrCode[0]=qrCode;const builder=new xml2jsExports.Builder({headless:!0,renderOpts:{pretty:!1}});xmlAssinado=builder.buildObject(result)}})}this.xmlNFe.push(xmlAssinado)};if(data.NFe instanceof Array)for(let i=0;i<data.NFe.length;i++){createXML(data.NFe[i])}else createXML(data.NFe);const baseXML={$:{versao:"4.00",xmlns:"http://www.portalfiscal.inf.br/nfe"},idLote:data.idLote,indSinc:data.indSinc,_:"[XML]"};return this.xmlBuilder.gerarXml(baseXML,"enviNFe",this.metodo).replace("[XML]",this.xmlNFe.join(""))}async callWebService(xmlConsulta,webServiceUrl,ContentType,action,agent){const startTime=Date.now(),{nfe:{tokenCSC:tokenCSC}}=this.environment.getConfig(),headers={"Content-Type":ContentType,SOAPAction:action,CSC:tokenCSC};logger.http("Iniciando comunicação com o webservice",{context:"NFCEAutorizacaoService",method:this.metodo,url:webServiceUrl,action:action,headers:headers});const response=await this.axios.post(webServiceUrl,xmlConsulta,{headers:headers,httpsAgent:agent}),duration=Date.now()-startTime;return logger.http("Comunicação concluída com sucesso",{context:"NFCEAutorizacaoService",method:this.metodo,duration:`${duration}ms`,responseSize:response.data?JSON.stringify(response.data).length:0}),response}async Exec(data){let responseInJson,xmlConsulta="",xmlConsultaSoap="",webServiceUrlTmp="",xmlRetorno={};const ContentType=this.setContentType();try{xmlConsulta=this.gerarXmlNFCEAutorizacao(data);const{xmlFormated:xmlFormated,agent:agent,webServiceUrl:webServiceUrl,action:action}=await this.gerarConsulta.gerarConsulta(xmlConsulta,this.metodo,!1,"","NFCe");xmlConsultaSoap=xmlFormated,webServiceUrlTmp=webServiceUrl;const xmlRetorno=await this.callWebService(xmlFormated,webServiceUrl,ContentType,action,agent),responseInJson=this.utility.verificaRejeicao(xmlRetorno.data,this.metodo),retorno=await this.trataRetorno(xmlRetorno.data,data.indSinc,responseInJson),xmlFinal=this.salvaArquivos(xmlConsulta,responseInJson,xmlRetorno.data,{xmlAutorizacao:retorno.data,xMotivo:retorno.message});return xmlFinal.xMotivo=xmlFinal.xMotivo.map(item=>({...item,xMotivo:item.xMotivo.replace("NF-e","NFC-e")})),logger.info("NFCe transmitida com sucesso",{context:"NFCEAutorizacaoService"}),{success:!0,xMotivo:xmlFinal.xMotivo,xmls:xmlFinal.response}}finally{this.utility.salvaConsulta(xmlConsulta,xmlConsultaSoap,this.metodo),this.utility.salvaRetorno(xmlRetorno.data,responseInJson,this.metodo)}}}class NFeWizardService{config={};environment={};utility={};xmlBuilder={};axios={};saveFiles={};gerarConsulta={};constructor(){if(new.target)return new Proxy(this,{get(target,prop,receiver){const origMethod=target[prop];return"function"==typeof origMethod?async function(...args){return"NFE_LoadEnvironment"===prop||await target.validateEnvironment(prop),origMethod.apply(target,args)}:Reflect.get(target,prop,receiver)}})}async NFE_LoadEnvironment({config:config}){try{this.config=config,this.environment=new Environment(this.config);const{axios:axios}=await this.environment.loadEnvironment();this.axios=axios,this.utility=new Utility(this.environment),this.saveFiles=new SaveFiles(this.environment,this.utility),this.xmlBuilder=new XmlBuilder(this.environment),this.gerarConsulta=new GerarConsulta(this.environment,this.utility,this.xmlBuilder)}catch(error){throw logger.error("",error,{context:"NFE_LoadEnvironment"}),new Error(`Erro ao inicializar a lib: ${error}`)}}async NFE_ConsultaStatusServico(){try{const nfeStatusServicoService=new NFEStatusServicoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeStatusServico=new NFEStatusServico(nfeStatusServicoService),response=await nfeStatusServico.Exec();return console.log("Retorno NFE_ConsultaStatusServico"),console.log(` ${response.xMotivo}`),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_ConsultaStatusServico"}),new Error(`NFE_ConsultaStatusServico: ${error.message}`)}}async NFE_ConsultaProtocolo(chave){try{const nfeConsultaProtocoloService=new NFEconsultaProtocoloService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeConsultaProtocolo=new NFEConsultaProtocolo(nfeConsultaProtocoloService),response=await nfeConsultaProtocolo.Exec(chave);return console.log("Retorno NFE_ConsultaProtocolo"),console.log(` ${response.xMotivo}`),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_ConsultaProtocolo"}),new Error(`NFE_ConsultaProtocolo: ${error.message}`)}}async NFE_RecepcaoEvento(evento){try{const nfeRecepcaoEventoService=new NFERecepcaoEventoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeRecepcaoEvento=new NFERecepcaoEvento(nfeRecepcaoEventoService),response=await nfeRecepcaoEvento.Exec(evento);return console.log("Retorno NFE_RecepcaoEvento"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_RecepcaoEvento"}),new Error(`NFE_RecepcaoEvento: ${error.message}`)}}async NFE_EventoPrevioDeEmissaoEmContingencia(evento){try{const nfeEpecService=new NFEEpecService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeEpec=new NFEEpec(nfeEpecService),response=await nfeEpec.Exec(evento);return console.log("Retorno NFEEpec"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_EventoPrevioDeEmissaoEmContingencia"}),new Error(`NFEEpec: ${error.message}`)}}async NFE_Cancelamento(evento){try{const nfeCancelamentoService=new NFECancelamentoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeCancelamento=new NFECancelamento(nfeCancelamentoService),response=await nfeCancelamento.Exec(evento);return console.log("Retorno NFE_Cancelamento"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_Cancelamento"}),new Error(`NFE_Cancelamento: ${error.message}`)}}async NFE_CienciaDaOperacao(evento){try{const nfeCienciaDaOperacaoService=new NFECienciaDaOperacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeCienciaDaOperacao=new NFECienciaDaOperacao(nfeCienciaDaOperacaoService),response=await nfeCienciaDaOperacao.Exec(evento);return console.log("Retorno NFE_CienciaDaOperacao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_CienciaDaOperacao"}),new Error(`NFE_CienciaDaOperacao: ${error.message}`)}}async NFE_ConfirmacaoDaOperacao(evento){try{const nfeConfirmacaoDaOperacaoService=new NFECienciaDaOperacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeConfirmacaoDaOperacao=new NFEConfirmacaoDaOperacao(nfeConfirmacaoDaOperacaoService),response=await nfeConfirmacaoDaOperacao.Exec(evento);return console.log("Retorno NFE_ConfirmacaoDaOperacao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_ConfirmacaoDaOperacao"}),new Error(`NFE_ConfirmacaoDaOperacao: ${error.message}`)}}async NFE_OperacaoNaoRealizada(evento){try{const nfeOperacaoNaoRealizadaService=new NFEOperacaoNaoRealizadaService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeOperacaoNaoRealizada=new NFEOperacaoNaoRealizada(nfeOperacaoNaoRealizadaService),response=await nfeOperacaoNaoRealizada.Exec(evento);return console.log("Retorno NFE_OperacaoNaoRealizada"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_OperacaoNaoRealizada"}),new Error(`NFE_OperacaoNaoRealizada: ${error.message}`)}}async NFE_CartaDeCorrecao(evento){try{const nfeCartaDeCorrecaoService=new NFECartaDeCorrecaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeCartaDeCorrecao=new NFECartaDeCorrecao(nfeCartaDeCorrecaoService),response=await nfeCartaDeCorrecao.Exec(evento);return console.log("Retorno NFE_CartaDeCorrecao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_CartaDeCorrecao"}),new Error(`NFE_CartaDeCorrecao: ${error.message}`)}}async NFE_DesconhecimentoDaOperacao(evento){try{const nfeDesconhecimentoDaOperacaoService=new NFEDesconhecimentoDaOperacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),nfeDesconhecimentoDaOperacao=new NFEDesconhecimentoDaOperacao(nfeDesconhecimentoDaOperacaoService),response=await nfeDesconhecimentoDaOperacao.Exec(evento);return console.log("Retorno NFE_DesconhecimentoDaOperacao"),console.table(response.xMotivos),console.log("==================================="),response.response}catch(error){throw logger.error("",error,{context:"NFE_DesconhecimentoDaOperacao"}),new Error(`NFE_DesconhecimentoDaOperacao: ${error.message}`)}}async NFE_DistribuicaoDFe(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFeService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFERecepcaoEvento$1(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFe"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFe"}),new Error(`NFE_DistribuicaoDFe: ${error.message}`)}}async NFE_DistribuicaoDFePorUltNSU(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFePorUltNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFEDistribuicaoDFePorUltNSU(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFePorUltNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFePorUltNSU"}),new Error(`NFE_DistribuicaoDFePorUltNSU: ${error.message}`)}}async NFE_DistribuicaoDFePorNSU(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFePorNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFEDistribuicaoDFePorNSU(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFePorNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFePorNSU"}),new Error(`NFE_DistribuicaoDFePorNSU: ${error.message}`)}}async NFE_DistribuicaoDFePorChave(data){try{const distribuicaoDFeService=new NFEDistribuicaoDFePorChaveService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new NFEDistribuicaoDFePorChave(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno NFE_DistribuicaoDFePorChave"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"NFE_DistribuicaoDFePorChave"}),new Error(`NFE_DistribuicaoDFePorChave: ${error.message}`)}}async CTE_DistribuicaoDFe(data){try{const distribuicaoDFeService=new CTEDistribuicaoDFeService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),distribuicaoDFe=new CTEDistribuicaoDFe(distribuicaoDFeService),response=await distribuicaoDFe.Exec(data);return console.log("Retorno CTE_DistribuicaoDFe"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"CTE_DistribuicaoDFe"}),new Error(`CTE_DistribuicaoDFe: ${error.message}`)}}async CTE_DistribuicaoDFePorUltNSU(data){try{new CTEDistribuicaoDFePorUltNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta);const distribuicaoDFe=new CTEDistribuicaoDFePorUltNSU(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),response=await distribuicaoDFe.Exec(data);return console.log("Retorno CTE_DistribuicaoDFePorUltNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"CTE_DistribuicaoDFePorUltNSU"}),new Error(`CTE_DistribuicaoDFePorUltNSU: ${error.message}`)}}async CTE_DistribuicaoDFePorNSU(data){try{new CTEDistribuicaoDFePorNSUService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta);const distribuicaoDFe=new CTEDistribuicaoDFePorNSU(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),response=await distribuicaoDFe.Exec(data);return console.log("Retorno CTE_DistribuicaoDFePorNSU"),console.log(` ${response.xMotivo}`),console.log("==================================="),response.data}catch(error){throw logger.error("",error,{context:"CTE_DistribuicaoDFePorNSU"}),new Error(`CTE_DistribuicaoDFePorNSU: ${error.message}`)}}async NFE_Autorizacao(data){try{const autorizacaoService=new NFEAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),autorizacao=new NFEAutorizacao(autorizacaoService),response=await autorizacao.Exec(data);return console.log("Retorno NFE_Autorizacao"),console.table(response.xMotivo),console.log("==================================="),response.xmls}catch(error){throw logger.error("",error,{context:"NFE_Autorizacao"}),new Error(`NFE_Autorizacao: ${error.message}`)}}async NFCE_Autorizacao(data){try{const autorizacaoService=new NFCEAutorizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),autorizacao=new NFCEAutorizacao(autorizacaoService),response=await autorizacao.Exec(data);return console.log("Retorno NFCE_Autorizacao"),console.table(response.xMotivo),console.log("==================================="),response.xmls}catch(error){throw logger.error("",error,{context:"NFCE_Autorizacao"}),new Error(`NFCE_Autorizacao: ${error.message}`)}}async NFE_Inutilizacao(data){try{const inutilizacaoService=new NFEInutilizacaoService(this.environment,this.utility,this.xmlBuilder,this.axios,this.saveFiles,this.gerarConsulta),inutilizacao=new NFEInutilizacao(inutilizacaoService),response=await inutilizacao.Exec(data);return console.log("Retorno NFE_Inutilizacao"),console.log(` ${response.xMotivo}`),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_Inutilizacao"}),new Error(`NFE_Inutilizacao: ${error.message}`)}}async NFE_GerarDanfe(data){try{const{dfe:{exibirMarcaDaguaDanfe:exibirMarcaDaguaDanfe}}=this.environment.getConfig(),distribuicaoDFe=new NFEGerarDanfe(data),response=await distribuicaoDFe.generatePDF(exibirMarcaDaguaDanfe);return console.log("Retorno NFE_GerarDanfe"),console.log(response.message),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_GerarDanfe"}),new Error(`NFE_GerarDanfe: ${error.message}`)}}async NFCE_GerarDanfe(data){try{const{dfe:{exibirMarcaDaguaDanfe:exibirMarcaDaguaDanfe}}=this.environment.getConfig(),distribuicaoDFe=new NFCEGerarDanfe(data),response=await distribuicaoDFe.generatePDF(exibirMarcaDaguaDanfe);return console.log("Retorno NFCE_GerarDanfe"),console.log(response.message),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFCE_GerarDanfe"}),new Error(`NFCE_GerarDanfe: ${error.message}`)}}NFE_EnviaEmail(mailParams){try{const response=new MailController(this.environment).sendEmail(mailParams);return console.log("Retorno NFE_EnviaEmail"),console.log("E-mail enviado com sucesso."),console.log("==================================="),response}catch(error){throw logger.error("",error,{context:"NFE_EnviaEmail"}),new Error(`NFE_EnviaEmail: ${error.message}`)}}async validateEnvironment(prop){if(!this.environment.isLoaded)throw new Error(`Ambiente não carregado. Por favor, carregue o ambiente utilizando o método "NFE_LoadEnvironment({ sua_configuracao })" antes de chamar o método ${prop}.`)}}exports.default=class NFeWizard{nfeWizardService;constructor(){this.nfeWizardService=new NFeWizardService}async NFE_LoadEnvironment({config:config}){await this.nfeWizardService.NFE_LoadEnvironment({config:config})}async NFE_ConsultaStatusServico(){return await this.nfeWizardService.NFE_ConsultaStatusServico()}async NFE_ConsultaProtocolo(chave){return this.nfeWizardService.NFE_ConsultaProtocolo(chave)}async NFE_RecepcaoEvento(evento){return await this.nfeWizardService.NFE_RecepcaoEvento(evento)}async NFE_EventoPrevioDeEmissaoEmContingencia(evento){return await this.nfeWizardService.NFE_EventoPrevioDeEmissaoEmContingencia(evento)}async NFE_Cancelamento(evento){return await this.nfeWizardService.NFE_Cancelamento(evento)}async NFE_CienciaDaOperacao(evento){return await this.nfeWizardService.NFE_CienciaDaOperacao(evento)}async NFE_ConfirmacaoDaOperacao(evento){return await this.nfeWizardService.NFE_ConfirmacaoDaOperacao(evento)}async NFE_OperacaoNaoRealizada(evento){return await this.nfeWizardService.NFE_OperacaoNaoRealizada(evento)}async NFE_CartaDeCorrecao(evento){return await this.nfeWizardService.NFE_CartaDeCorrecao(evento)}async NFE_DesconhecimentoDaOperacao(evento){return await this.nfeWizardService.NFE_DesconhecimentoDaOperacao(evento)}async NFE_DistribuicaoDFe(data){return await this.nfeWizardService.NFE_DistribuicaoDFe(data)}async NFE_DistribuicaoDFePorUltNSU(data){return await this.nfeWizardService.NFE_DistribuicaoDFePorUltNSU(data)}async NFE_DistribuicaoDFePorNSU(data){return await this.nfeWizardService.NFE_DistribuicaoDFePorNSU(data)}async NFE_DistribuicaoDFePorChave(data){return await this.nfeWizardService.NFE_DistribuicaoDFePorChave(data)}async CTE_DistribuicaoDFe(data){return await this.nfeWizardService.CTE_DistribuicaoDFe(data)}async CTE_DistribuicaoDFePorUltNSU(data){return await this.nfeWizardService.CTE_DistribuicaoDFePorUltNSU(data)}async CTE_DistribuicaoDFePorNSU(data){return await this.nfeWizardService.CTE_DistribuicaoDFePorNSU(data)}async NFE_Autorizacao(data){return await this.nfeWizardService.NFE_Autorizacao(data)}async NFCE_Autorizacao(data){return await this.nfeWizardService.NFCE_Autorizacao(data)}async NFE_Inutilizacao(data){return await this.nfeWizardService.NFE_Inutilizacao(data)}async NFE_GerarDanfe(data){return await this.nfeWizardService.NFE_GerarDanfe(data)}async NFCE_GerarDanfe(data){return await this.nfeWizardService.NFCE_GerarDanfe(data)}NFE_EnviaEmail(mailParams){return this.nfeWizardService.NFE_EnviaEmail(mailParams)}},exports.mountCOFINS=mountCOFINS,exports.mountICMS=mountICMS,exports.mountPIS=mountPIS;
|
|
10
10
|
//# sourceMappingURL=index.cjs.map
|