billion-context 0.1.207 → 0.1.208

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.
@@ -306,7 +306,7 @@ ${pendingInterceptorsFormatter.format(pending)}`.trim())}};module.exports=MockAg
306
306
  )
307
307
  `)}close(){this.#db.close()}get(key){assertCacheKey(key);const value=this.#findValue(key);return value?{body:value.body?Buffer.from(value.body.buffer,value.body.byteOffset,value.body.byteLength):void 0,statusCode:value.statusCode,statusMessage:value.statusMessage,headers:value.headers?JSON.parse(value.headers):void 0,etag:value.etag?value.etag:void 0,vary:value.vary?JSON.parse(value.vary):void 0,cacheControlDirectives:value.cacheControlDirectives?JSON.parse(value.cacheControlDirectives):void 0,cachedAt:value.cachedAt,staleAt:value.staleAt,deleteAt:value.deleteAt}:void 0}set(key,value){assertCacheKey(key);const url=this.#makeValueUrl(key);const body=Array.isArray(value.body)?Buffer.concat(value.body):value.body;const size=body?.byteLength;if(size&&size>this.#maxEntrySize){return}const existingValue=this.#findValue(key,true);if(existingValue){this.#updateValueQuery.run(body,value.deleteAt,value.statusCode,value.statusMessage,value.headers?JSON.stringify(value.headers):null,value.etag?value.etag:null,value.cacheControlDirectives?JSON.stringify(value.cacheControlDirectives):null,value.cachedAt,value.staleAt,existingValue.id)}else{this.#insertValueQuery.run(url,key.method,body,value.deleteAt,value.statusCode,value.statusMessage,value.headers?JSON.stringify(value.headers):null,value.etag?value.etag:null,value.cacheControlDirectives?JSON.stringify(value.cacheControlDirectives):null,value.vary?JSON.stringify(value.vary):null,value.cachedAt,value.staleAt);this.#prune()}}createWriteStream(key,value){assertCacheKey(key);assertCacheValue(value);let size=0;const body=[];const store=this;return new Writable({decodeStrings:true,write(chunk,encoding,callback){size+=chunk.byteLength;if(size<store.#maxEntrySize){body.push(chunk)}else{this.destroy()}callback()},final(callback){store.set(key,{...value,body});callback()}})}delete(key){if(typeof key!=="object"){throw new TypeError(`expected key to be object, got ${typeof key}`)}this.#deleteByUrlQuery.run(this.#makeValueUrl(key))}#prune(){if(Number.isFinite(this.#maxCount)&&this.size<=this.#maxCount){return 0}{const removed=this.#deleteExpiredValuesQuery.run(Date.now()).changes;if(removed){return removed}}{const removed=this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount*.1),1)).changes;if(removed){return removed}}return 0}get size(){const{total}=this.#countEntriesQuery.get();return total}#makeValueUrl(key){return`${key.origin}/${key.path}`}#findValue(key,canBeExpired=false){const url=this.#makeValueUrl(key);const{headers,method}=key;const values=this.#getValuesQuery.all(url,method);if(values.length===0){return void 0}const now=Date.now();for(const value of values){if(now>=value.deleteAt&&!canBeExpired){continue}let matches=true;if(value.vary){const vary=JSON.parse(value.vary);for(const header in vary){if(!headerValueEquals(headers[header],vary[header])){matches=false;break}}}if(matches){return value}}return void 0}};function headerValueEquals(lhs,rhs){if(lhs==null&&rhs==null){return true}if(lhs==null&&rhs!=null||lhs!=null&&rhs==null){return false}if(Array.isArray(lhs)&&Array.isArray(rhs)){if(lhs.length!==rhs.length){return false}for(let i=0;i<lhs.length;i++){if(lhs[i]!==rhs[i]){return false}}return true}return lhs===rhs}}});var require_headers=__commonJS({"node_modules/undici/lib/web/fetch/headers.js"(exports,module){"use strict";var{kConstruct}=require_symbols();var{kEnumerableProperty}=require_util();var{iteratorMixin,isValidHeaderName,isValidHeaderValue}=require_util2();var{webidl}=require_webidl();var assert=__require("assert");var util=__require("util");function isHTTPWhiteSpaceCharCode(code){return code===10||code===13||code===9||code===32}function headerValueNormalize(potentialValue){let i=0;let j2=potentialValue.length;while(j2>i&&isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j2-1)))--j2;while(j2>i&&isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i)))++i;return i===0&&j2===potentialValue.length?potentialValue:potentialValue.substring(i,j2)}function fill(headers,object){if(Array.isArray(object)){for(let i=0;i<object.length;++i){const header=object[i];if(header.length!==2){throw webidl.errors.exception({header:"Headers constructor",message:`expected name/value pair to be length 2, found ${header.length}.`})}appendHeader(headers,header[0],header[1])}}else if(typeof object==="object"&&object!==null){const keys=Object.keys(object);for(let i=0;i<keys.length;++i){appendHeader(headers,keys[i],object[keys[i]])}}else{throw webidl.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})}}function appendHeader(headers,name,value){value=headerValueNormalize(value);if(!isValidHeaderName(name)){throw webidl.errors.invalidArgument({prefix:"Headers.append",value:name,type:"header name"})}else if(!isValidHeaderValue(value)){throw webidl.errors.invalidArgument({prefix:"Headers.append",value,type:"header value"})}if(getHeadersGuard(headers)==="immutable"){throw new TypeError("immutable")}return getHeadersList(headers).append(name,value,false)}function headersListSortAndCombine(target){const headersList=getHeadersList(target);if(!headersList){return[]}if(headersList.sortedMap){return headersList.sortedMap}const headers=[];const names=headersList.toSortedArray();const cookies=headersList.cookies;if(cookies===null||cookies.length===1){return headersList.sortedMap=names}for(let i=0;i<names.length;++i){const{0:name,1:value}=names[i];if(name==="set-cookie"){for(let j2=0;j2<cookies.length;++j2){headers.push([name,cookies[j2]])}}else{headers.push([name,value])}}return headersList.sortedMap=headers}function compareHeaderName(a,b2){return a[0]<b2[0]?-1:1}var HeadersList=class _HeadersList{cookies=null;sortedMap;headersMap;constructor(init){if(init instanceof _HeadersList){this.headersMap=new Map(init.headersMap);this.sortedMap=init.sortedMap;this.cookies=init.cookies===null?null:[...init.cookies]}else{this.headersMap=new Map(init);this.sortedMap=null}}contains(name,isLowerCase){return this.headersMap.has(isLowerCase?name:name.toLowerCase())}clear(){this.headersMap.clear();this.sortedMap=null;this.cookies=null}append(name,value,isLowerCase){this.sortedMap=null;const lowercaseName=isLowerCase?name:name.toLowerCase();const exists=this.headersMap.get(lowercaseName);if(exists){const delimiter=lowercaseName==="cookie"?"; ":", ";this.headersMap.set(lowercaseName,{name:exists.name,value:`${exists.value}${delimiter}${value}`})}else{this.headersMap.set(lowercaseName,{name,value})}if(lowercaseName==="set-cookie"){(this.cookies??=[]).push(value)}}set(name,value,isLowerCase){this.sortedMap=null;const lowercaseName=isLowerCase?name:name.toLowerCase();if(lowercaseName==="set-cookie"){this.cookies=[value]}this.headersMap.set(lowercaseName,{name,value})}delete(name,isLowerCase){this.sortedMap=null;if(!isLowerCase)name=name.toLowerCase();if(name==="set-cookie"){this.cookies=null}this.headersMap.delete(name)}get(name,isLowerCase){return this.headersMap.get(isLowerCase?name:name.toLowerCase())?.value??null}*[Symbol.iterator](){for(const{0:name,1:{value}}of this.headersMap){yield[name,value]}}get entries(){const headers={};if(this.headersMap.size!==0){for(const{name,value}of this.headersMap.values()){headers[name]=value}}return headers}rawValues(){return this.headersMap.values()}get entriesList(){const headers=[];if(this.headersMap.size!==0){for(const{0:lowerName,1:{name,value}}of this.headersMap){if(lowerName==="set-cookie"){for(const cookie of this.cookies){headers.push([name,cookie])}}else{headers.push([name,value])}}}return headers}toSortedArray(){const size=this.headersMap.size;const array=new Array(size);if(size<=32){if(size===0){return array}const iterator=this.headersMap[Symbol.iterator]();const firstValue=iterator.next().value;array[0]=[firstValue[0],firstValue[1].value];assert(firstValue[1].value!==null);for(let i=1,j2=0,right=0,left=0,pivot=0,x,value;i<size;++i){value=iterator.next().value;x=array[i]=[value[0],value[1].value];assert(x[1]!==null);left=0;right=i;while(left<right){pivot=left+(right-left>>1);if(array[pivot][0]<=x[0]){left=pivot+1}else{right=pivot}}if(i!==pivot){j2=i;while(j2>left){array[j2]=array[--j2]}array[left]=x}}if(!iterator.next().done){throw new TypeError("Unreachable")}return array}else{let i=0;for(const{0:name,1:{value}}of this.headersMap){array[i++]=[name,value];assert(value!==null)}return array.sort(compareHeaderName)}}};var Headers2=class _Headers{#guard;#headersList;constructor(init=void 0){webidl.util.markAsUncloneable(this);if(init===kConstruct){return}this.#headersList=new HeadersList;this.#guard="none";if(init!==void 0){init=webidl.converters.HeadersInit(init,"Headers constructor","init");fill(this,init)}}append(name,value){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,2,"Headers.append");const prefix="Headers.append";name=webidl.converters.ByteString(name,prefix,"name");value=webidl.converters.ByteString(value,prefix,"value");return appendHeader(this,name,value)}delete(name){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,1,"Headers.delete");const prefix="Headers.delete";name=webidl.converters.ByteString(name,prefix,"name");if(!isValidHeaderName(name)){throw webidl.errors.invalidArgument({prefix:"Headers.delete",value:name,type:"header name"})}if(this.#guard==="immutable"){throw new TypeError("immutable")}if(!this.#headersList.contains(name,false)){return}this.#headersList.delete(name,false)}get(name){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,1,"Headers.get");const prefix="Headers.get";name=webidl.converters.ByteString(name,prefix,"name");if(!isValidHeaderName(name)){throw webidl.errors.invalidArgument({prefix,value:name,type:"header name"})}return this.#headersList.get(name,false)}has(name){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,1,"Headers.has");const prefix="Headers.has";name=webidl.converters.ByteString(name,prefix,"name");if(!isValidHeaderName(name)){throw webidl.errors.invalidArgument({prefix,value:name,type:"header name"})}return this.#headersList.contains(name,false)}set(name,value){webidl.brandCheck(this,_Headers);webidl.argumentLengthCheck(arguments,2,"Headers.set");const prefix="Headers.set";name=webidl.converters.ByteString(name,prefix,"name");value=webidl.converters.ByteString(value,prefix,"value");value=headerValueNormalize(value);if(!isValidHeaderName(name)){throw webidl.errors.invalidArgument({prefix,value:name,type:"header name"})}else if(!isValidHeaderValue(value)){throw webidl.errors.invalidArgument({prefix,value,type:"header value"})}if(this.#guard==="immutable"){throw new TypeError("immutable")}this.#headersList.set(name,value,false)}getSetCookie(){webidl.brandCheck(this,_Headers);const list=this.#headersList.cookies;if(list){return[...list]}return[]}[util.inspect.custom](depth,options){options.depth??=depth;return`Headers ${util.formatWithOptions(options,this.#headersList.entries)}`}static getHeadersGuard(o){return o.#guard}static setHeadersGuard(o,guard){o.#guard=guard}static getHeadersList(o){return o.#headersList}static setHeadersList(target,list){target.#headersList=list}};var{getHeadersGuard,setHeadersGuard,getHeadersList,setHeadersList}=Headers2;Reflect.deleteProperty(Headers2,"getHeadersGuard");Reflect.deleteProperty(Headers2,"setHeadersGuard");Reflect.deleteProperty(Headers2,"getHeadersList");Reflect.deleteProperty(Headers2,"setHeadersList");iteratorMixin("Headers",Headers2,headersListSortAndCombine,0,1);Object.defineProperties(Headers2.prototype,{append:kEnumerableProperty,delete:kEnumerableProperty,get:kEnumerableProperty,has:kEnumerableProperty,set:kEnumerableProperty,getSetCookie:kEnumerableProperty,[Symbol.toStringTag]:{value:"Headers",configurable:true},[util.inspect.custom]:{enumerable:false}});webidl.converters.HeadersInit=function(V2,prefix,argument){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT){const iterator=Reflect.get(V2,Symbol.iterator);if(!util.types.isProxy(V2)&&iterator===Headers2.prototype.entries){try{return getHeadersList(V2).entriesList}catch{}}if(typeof iterator==="function"){return webidl.converters["sequence<sequence<ByteString>>"](V2,prefix,argument,iterator.bind(V2))}return webidl.converters["record<ByteString, ByteString>"](V2,prefix,argument)}throw webidl.errors.conversionFailed({prefix:"Headers constructor",argument:"Argument 1",types:["sequence<sequence<ByteString>>","record<ByteString, ByteString>"]})};module.exports={fill,compareHeaderName,Headers:Headers2,HeadersList,getHeadersGuard,setHeadersGuard,setHeadersList,getHeadersList}}});var require_response=__commonJS({"node_modules/undici/lib/web/fetch/response.js"(exports,module){"use strict";var{Headers:Headers2,HeadersList,fill,getHeadersGuard,setHeadersGuard,setHeadersList}=require_headers();var{extractBody,cloneBody,mixinBody,streamRegistry,bodyUnusable}=require_body();var util=require_util();var nodeUtil=__require("util");var{kEnumerableProperty}=util;var{isValidReasonPhrase,isCancelled,isAborted,isErrorLike,environmentSettingsObject:relevantRealm}=require_util2();var{redirectStatusSet,nullBodyStatus}=require_constants3();var{webidl}=require_webidl();var{URLSerializer}=require_data_url();var{kConstruct}=require_symbols();var assert=__require("assert");var{isomorphicEncode,serializeJavascriptValueToJSONString}=require_infra();var textEncoder=new TextEncoder("utf-8");var Response2=class _Response{#headers;#state;static error(){const responseObject=fromInnerResponse(makeNetworkError(),"immutable");return responseObject}static json(data,init=void 0){webidl.argumentLengthCheck(arguments,1,"Response.json");if(init!==null){init=webidl.converters.ResponseInit(init)}const bytes=textEncoder.encode(serializeJavascriptValueToJSONString(data));const body=extractBody(bytes);const responseObject=fromInnerResponse(makeResponse({}),"response");initializeResponse(responseObject,init,{body:body[0],type:"application/json"});return responseObject}static redirect(url,status=302){webidl.argumentLengthCheck(arguments,1,"Response.redirect");url=webidl.converters.USVString(url);status=webidl.converters["unsigned short"](status);let parsedURL;try{parsedURL=new URL(url,relevantRealm.settingsObject.baseUrl)}catch(err){throw new TypeError(`Failed to parse URL from ${url}`,{cause:err})}if(!redirectStatusSet.has(status)){throw new RangeError(`Invalid status code ${status}`)}const responseObject=fromInnerResponse(makeResponse({}),"immutable");responseObject.#state.status=status;const value=isomorphicEncode(URLSerializer(parsedURL));responseObject.#state.headersList.append("location",value,true);return responseObject}constructor(body=null,init=void 0){webidl.util.markAsUncloneable(this);if(body===kConstruct){return}if(body!==null){body=webidl.converters.BodyInit(body,"Response","body")}init=webidl.converters.ResponseInit(init);this.#state=makeResponse({});this.#headers=new Headers2(kConstruct);setHeadersGuard(this.#headers,"response");setHeadersList(this.#headers,this.#state.headersList);let bodyWithType=null;if(body!=null){const[extractedBody,type]=extractBody(body);bodyWithType={body:extractedBody,type}}initializeResponse(this,init,bodyWithType)}get type(){webidl.brandCheck(this,_Response);return this.#state.type}get url(){webidl.brandCheck(this,_Response);const urlList=this.#state.urlList;const url=urlList[urlList.length-1]??null;if(url===null){return""}return URLSerializer(url,true)}get redirected(){webidl.brandCheck(this,_Response);return this.#state.urlList.length>1}get status(){webidl.brandCheck(this,_Response);return this.#state.status}get ok(){webidl.brandCheck(this,_Response);return this.#state.status>=200&&this.#state.status<=299}get statusText(){webidl.brandCheck(this,_Response);return this.#state.statusText}get headers(){webidl.brandCheck(this,_Response);return this.#headers}get body(){webidl.brandCheck(this,_Response);return this.#state.body?this.#state.body.stream:null}get bodyUsed(){webidl.brandCheck(this,_Response);return!!this.#state.body&&util.isDisturbed(this.#state.body.stream)}clone(){webidl.brandCheck(this,_Response);if(bodyUnusable(this.#state)){throw webidl.errors.exception({header:"Response.clone",message:"Body has already been consumed."})}const clonedResponse=cloneResponse(this.#state);if(this.#state.urlList.length!==0&&this.#state.body?.stream){streamRegistry.register(this,new WeakRef(this.#state.body.stream))}return fromInnerResponse(clonedResponse,getHeadersGuard(this.#headers))}[nodeUtil.inspect.custom](depth,options){if(options.depth===null){options.depth=2}options.colors??=true;const properties={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${nodeUtil.formatWithOptions(options,properties)}`}static getResponseHeaders(response){return response.#headers}static setResponseHeaders(response,newHeaders){response.#headers=newHeaders}static getResponseState(response){return response.#state}static setResponseState(response,newState){response.#state=newState}};var{getResponseHeaders,setResponseHeaders,getResponseState,setResponseState}=Response2;Reflect.deleteProperty(Response2,"getResponseHeaders");Reflect.deleteProperty(Response2,"setResponseHeaders");Reflect.deleteProperty(Response2,"getResponseState");Reflect.deleteProperty(Response2,"setResponseState");mixinBody(Response2,getResponseState);Object.defineProperties(Response2.prototype,{type:kEnumerableProperty,url:kEnumerableProperty,status:kEnumerableProperty,ok:kEnumerableProperty,redirected:kEnumerableProperty,statusText:kEnumerableProperty,headers:kEnumerableProperty,clone:kEnumerableProperty,body:kEnumerableProperty,bodyUsed:kEnumerableProperty,[Symbol.toStringTag]:{value:"Response",configurable:true}});Object.defineProperties(Response2,{json:kEnumerableProperty,redirect:kEnumerableProperty,error:kEnumerableProperty});function cloneResponse(response){if(response.internalResponse){return filterResponse(cloneResponse(response.internalResponse),response.type)}const newResponse=makeResponse({...response,body:null});if(response.body!=null){newResponse.body=cloneBody(response.body)}return newResponse}function makeResponse(init){return{aborted:false,rangeRequested:false,timingAllowPassed:false,requestIncludesCredentials:false,type:"default",status:200,timingInfo:null,cacheState:"",statusText:"",...init,headersList:init?.headersList?new HeadersList(init?.headersList):new HeadersList,urlList:init?.urlList?[...init.urlList]:[]}}function makeNetworkError(reason){const isError=isErrorLike(reason);return makeResponse({type:"error",status:0,error:isError?reason:new Error(reason?String(reason):reason),aborted:reason&&reason.name==="AbortError"})}function isNetworkError(response){return response.type==="error"&&response.status===0}function makeFilteredResponse(response,state3){state3={internalResponse:response,...state3};return new Proxy(response,{get(target,p2){return p2 in state3?state3[p2]:target[p2]},set(target,p2,value){assert(!(p2 in state3));target[p2]=value;return true}})}function filterResponse(response,type){if(type==="basic"){return makeFilteredResponse(response,{type:"basic",headersList:response.headersList})}else if(type==="cors"){return makeFilteredResponse(response,{type:"cors",headersList:response.headersList})}else if(type==="opaque"){return makeFilteredResponse(response,{type:"opaque",urlList:[],status:0,statusText:"",body:null})}else if(type==="opaqueredirect"){return makeFilteredResponse(response,{type:"opaqueredirect",status:0,statusText:"",headersList:[],body:null})}else{assert(false)}}function makeAppropriateNetworkError(fetchParams,err=null){assert(isCancelled(fetchParams));return isAborted(fetchParams)?makeNetworkError(Object.assign(new DOMException("The operation was aborted.","AbortError"),{cause:err})):makeNetworkError(Object.assign(new DOMException("Request was cancelled."),{cause:err}))}function initializeResponse(response,init,body){if(init.status!==null&&(init.status<200||init.status>599)){throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')}if("statusText"in init&&init.statusText!=null){if(!isValidReasonPhrase(String(init.statusText))){throw new TypeError("Invalid statusText")}}if("status"in init&&init.status!=null){getResponseState(response).status=init.status}if("statusText"in init&&init.statusText!=null){getResponseState(response).statusText=init.statusText}if("headers"in init&&init.headers!=null){fill(getResponseHeaders(response),init.headers)}if(body){if(nullBodyStatus.includes(response.status)){throw webidl.errors.exception({header:"Response constructor",message:`Invalid response status code ${response.status}`})}getResponseState(response).body=body.body;if(body.type!=null&&!getResponseState(response).headersList.contains("content-type",true)){getResponseState(response).headersList.append("content-type",body.type,true)}}}function fromInnerResponse(innerResponse,guard){const response=new Response2(kConstruct);setResponseState(response,innerResponse);const headers=new Headers2(kConstruct);setResponseHeaders(response,headers);setHeadersList(headers,innerResponse.headersList);setHeadersGuard(headers,guard);if(innerResponse.urlList.length!==0&&innerResponse.body?.stream){streamRegistry.register(response,new WeakRef(innerResponse.body.stream))}return response}webidl.converters.XMLHttpRequestBodyInit=function(V2,prefix,name){if(typeof V2==="string"){return webidl.converters.USVString(V2,prefix,name)}if(webidl.is.Blob(V2)){return V2}if(webidl.is.BufferSource(V2)){return V2}if(webidl.is.FormData(V2)){return V2}if(webidl.is.URLSearchParams(V2)){return V2}return webidl.converters.DOMString(V2,prefix,name)};webidl.converters.BodyInit=function(V2,prefix,argument){if(webidl.is.ReadableStream(V2)){return V2}if(V2?.[Symbol.asyncIterator]){return V2}return webidl.converters.XMLHttpRequestBodyInit(V2,prefix,argument)};webidl.converters.ResponseInit=webidl.dictionaryConverter([{key:"status",converter:webidl.converters["unsigned short"],defaultValue:()=>200},{key:"statusText",converter:webidl.converters.ByteString,defaultValue:()=>""},{key:"headers",converter:webidl.converters.HeadersInit}]);webidl.is.Response=webidl.util.MakeTypeAssertion(Response2);module.exports={isNetworkError,makeNetworkError,makeResponse,makeAppropriateNetworkError,filterResponse,Response:Response2,cloneResponse,fromInnerResponse,getResponseState}}});var require_request2=__commonJS({"node_modules/undici/lib/web/fetch/request.js"(exports,module){"use strict";var{extractBody,mixinBody,cloneBody,bodyUnusable}=require_body();var{Headers:Headers2,fill:fillHeaders,HeadersList,setHeadersGuard,getHeadersGuard,setHeadersList,getHeadersList}=require_headers();var util=require_util();var nodeUtil=__require("util");var{isValidHTTPToken,sameOrigin,environmentSettingsObject}=require_util2();var{forbiddenMethodsSet,corsSafeListedMethodsSet,referrerPolicy,requestRedirect,requestMode,requestCredentials,requestCache,requestDuplex}=require_constants3();var{kEnumerableProperty,normalizedMethodRecordsBase,normalizedMethodRecords}=util;var{webidl}=require_webidl();var{URLSerializer}=require_data_url();var{kConstruct}=require_symbols();var assert=__require("assert");var{getMaxListeners,setMaxListeners,defaultMaxListeners}=__require("events");var kAbortController=Symbol("abortController");var requestFinalizer=new FinalizationRegistry(({signal,abort})=>{signal.removeEventListener("abort",abort)});var dependentControllerMap=new WeakMap;var abortSignalHasEventHandlerLeakWarning;try{abortSignalHasEventHandlerLeakWarning=getMaxListeners(new AbortController().signal)>0}catch{abortSignalHasEventHandlerLeakWarning=false}function buildAbort(acRef){return abort;function abort(){const ac=acRef.deref();if(ac!==void 0){requestFinalizer.unregister(abort);this.removeEventListener("abort",abort);ac.abort(this.reason);const controllerList=dependentControllerMap.get(ac.signal);if(controllerList!==void 0){if(controllerList.size!==0){for(const ref of controllerList){const ctrl=ref.deref();if(ctrl!==void 0){ctrl.abort(this.reason)}}controllerList.clear()}dependentControllerMap.delete(ac.signal)}}}}var patchMethodWarning=false;var Request2=class _Request{#signal;#dispatcher;#headers;#state;constructor(input,init=void 0){webidl.util.markAsUncloneable(this);if(input===kConstruct){return}const prefix="Request constructor";webidl.argumentLengthCheck(arguments,1,prefix);input=webidl.converters.RequestInfo(input);init=webidl.converters.RequestInit(init);let request=null;let fallbackMode=null;const baseUrl=environmentSettingsObject.settingsObject.baseUrl;let signal=null;if(typeof input==="string"){this.#dispatcher=init.dispatcher;let parsedURL;try{parsedURL=new URL(input,baseUrl)}catch(err){throw new TypeError("Failed to parse URL from "+input,{cause:err})}if(parsedURL.username||parsedURL.password){throw new TypeError("Request cannot be constructed from a URL that includes credentials: "+input)}request=makeRequest({urlList:[parsedURL]});fallbackMode="cors"}else{assert(webidl.is.Request(input));request=input.#state;signal=input.#signal;this.#dispatcher=init.dispatcher||input.#dispatcher}const origin=environmentSettingsObject.settingsObject.origin;let window2="client";if(request.window?.constructor?.name==="EnvironmentSettingsObject"&&sameOrigin(request.window,origin)){window2=request.window}if(init.window!=null){throw new TypeError(`'window' option '${window2}' must be null`)}if("window"in init){window2="no-window"}request=makeRequest({method:request.method,headersList:request.headersList,unsafeRequest:request.unsafeRequest,client:environmentSettingsObject.settingsObject,window:window2,priority:request.priority,origin:request.origin,referrer:request.referrer,referrerPolicy:request.referrerPolicy,mode:request.mode,credentials:request.credentials,cache:request.cache,redirect:request.redirect,integrity:request.integrity,keepalive:request.keepalive,reloadNavigation:request.reloadNavigation,historyNavigation:request.historyNavigation,urlList:[...request.urlList]});const initHasKey=Object.keys(init).length!==0;if(initHasKey){if(request.mode==="navigate"){request.mode="same-origin"}request.reloadNavigation=false;request.historyNavigation=false;request.origin="client";request.referrer="client";request.referrerPolicy="";request.url=request.urlList[request.urlList.length-1];request.urlList=[request.url]}if(init.referrer!==void 0){const referrer=init.referrer;if(referrer===""){request.referrer="no-referrer"}else{let parsedReferrer;try{parsedReferrer=new URL(referrer,baseUrl)}catch(err){throw new TypeError(`Referrer "${referrer}" is not a valid URL.`,{cause:err})}if(parsedReferrer.protocol==="about:"&&parsedReferrer.hostname==="client"||origin&&!sameOrigin(parsedReferrer,environmentSettingsObject.settingsObject.baseUrl)){request.referrer="client"}else{request.referrer=parsedReferrer}}}if(init.referrerPolicy!==void 0){request.referrerPolicy=init.referrerPolicy}let mode;if(init.mode!==void 0){mode=init.mode}else{mode=fallbackMode}if(mode==="navigate"){throw webidl.errors.exception({header:"Request constructor",message:"invalid request mode navigate."})}if(mode!=null){request.mode=mode}if(init.credentials!==void 0){request.credentials=init.credentials}if(init.cache!==void 0){request.cache=init.cache}if(request.cache==="only-if-cached"&&request.mode!=="same-origin"){throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode")}if(init.redirect!==void 0){request.redirect=init.redirect}if(init.integrity!=null){request.integrity=String(init.integrity)}if(init.keepalive!==void 0){request.keepalive=Boolean(init.keepalive)}if(init.method!==void 0){let method=init.method;const mayBeNormalized=normalizedMethodRecords[method];if(mayBeNormalized!==void 0){request.method=mayBeNormalized}else{if(!isValidHTTPToken(method)){throw new TypeError(`'${method}' is not a valid HTTP method.`)}const upperCase=method.toUpperCase();if(forbiddenMethodsSet.has(upperCase)){throw new TypeError(`'${method}' HTTP method is unsupported.`)}method=normalizedMethodRecordsBase[upperCase]??method;request.method=method}if(!patchMethodWarning&&request.method==="patch"){process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:"UNDICI-FETCH-patch"});patchMethodWarning=true}}if(init.signal!==void 0){signal=init.signal}this.#state=request;const ac=new AbortController;this.#signal=ac.signal;if(signal!=null){if(signal.aborted){ac.abort(signal.reason)}else{this[kAbortController]=ac;const acRef=new WeakRef(ac);const abort=buildAbort(acRef);if(abortSignalHasEventHandlerLeakWarning&&getMaxListeners(signal)===defaultMaxListeners){setMaxListeners(1500,signal)}util.addAbortListener(signal,abort);requestFinalizer.register(ac,{signal,abort},abort)}}this.#headers=new Headers2(kConstruct);setHeadersList(this.#headers,request.headersList);setHeadersGuard(this.#headers,"request");if(mode==="no-cors"){if(!corsSafeListedMethodsSet.has(request.method)){throw new TypeError(`'${request.method} is unsupported in no-cors mode.`)}setHeadersGuard(this.#headers,"request-no-cors")}if(initHasKey){const headersList=getHeadersList(this.#headers);const headers=init.headers!==void 0?init.headers:new HeadersList(headersList);headersList.clear();if(headers instanceof HeadersList){for(const{name,value}of headers.rawValues()){headersList.append(name,value,false)}headersList.cookies=headers.cookies}else{fillHeaders(this.#headers,headers)}}const inputBody=webidl.is.Request(input)?input.#state.body:null;if((init.body!=null||inputBody!=null)&&(request.method==="GET"||request.method==="HEAD")){throw new TypeError("Request with GET/HEAD method cannot have body.")}let initBody=null;if(init.body!=null){const[extractedBody,contentType]=extractBody(init.body,request.keepalive);initBody=extractedBody;if(contentType&&!getHeadersList(this.#headers).contains("content-type",true)){this.#headers.append("content-type",contentType,true)}}const inputOrInitBody=initBody??inputBody;if(inputOrInitBody!=null&&inputOrInitBody.source==null){if(initBody!=null&&init.duplex==null){throw new TypeError("RequestInit: duplex option is required when sending a body.")}if(request.mode!=="same-origin"&&request.mode!=="cors"){throw new TypeError('If request is made from ReadableStream, mode should be "same-origin" or "cors"')}request.useCORSPreflightFlag=true}let finalBody=inputOrInitBody;if(initBody==null&&inputBody!=null){if(bodyUnusable(input.#state)){throw new TypeError("Cannot construct a Request with a Request object that has already been used.")}const identityTransform=new TransformStream;inputBody.stream.pipeThrough(identityTransform);finalBody={source:inputBody.source,length:inputBody.length,stream:identityTransform.readable}}this.#state.body=finalBody}get method(){webidl.brandCheck(this,_Request);return this.#state.method}get url(){webidl.brandCheck(this,_Request);return URLSerializer(this.#state.url)}get headers(){webidl.brandCheck(this,_Request);return this.#headers}get destination(){webidl.brandCheck(this,_Request);return this.#state.destination}get referrer(){webidl.brandCheck(this,_Request);if(this.#state.referrer==="no-referrer"){return""}if(this.#state.referrer==="client"){return"about:client"}return this.#state.referrer.toString()}get referrerPolicy(){webidl.brandCheck(this,_Request);return this.#state.referrerPolicy}get mode(){webidl.brandCheck(this,_Request);return this.#state.mode}get credentials(){webidl.brandCheck(this,_Request);return this.#state.credentials}get cache(){webidl.brandCheck(this,_Request);return this.#state.cache}get redirect(){webidl.brandCheck(this,_Request);return this.#state.redirect}get integrity(){webidl.brandCheck(this,_Request);return this.#state.integrity}get keepalive(){webidl.brandCheck(this,_Request);return this.#state.keepalive}get isReloadNavigation(){webidl.brandCheck(this,_Request);return this.#state.reloadNavigation}get isHistoryNavigation(){webidl.brandCheck(this,_Request);return this.#state.historyNavigation}get signal(){webidl.brandCheck(this,_Request);return this.#signal}get body(){webidl.brandCheck(this,_Request);return this.#state.body?this.#state.body.stream:null}get bodyUsed(){webidl.brandCheck(this,_Request);return!!this.#state.body&&util.isDisturbed(this.#state.body.stream)}get duplex(){webidl.brandCheck(this,_Request);return"half"}clone(){webidl.brandCheck(this,_Request);if(bodyUnusable(this.#state)){throw new TypeError("unusable")}const clonedRequest=cloneRequest(this.#state);const ac=new AbortController;if(this.signal.aborted){ac.abort(this.signal.reason)}else{let list=dependentControllerMap.get(this.signal);if(list===void 0){list=new Set;dependentControllerMap.set(this.signal,list)}const acRef=new WeakRef(ac);list.add(acRef);util.addAbortListener(ac.signal,buildAbort(acRef))}return fromInnerRequest(clonedRequest,this.#dispatcher,ac.signal,getHeadersGuard(this.#headers))}[nodeUtil.inspect.custom](depth,options){if(options.depth===null){options.depth=2}options.colors??=true;const properties={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${nodeUtil.formatWithOptions(options,properties)}`}static setRequestSignal(request,newSignal){request.#signal=newSignal;return request}static getRequestDispatcher(request){return request.#dispatcher}static setRequestDispatcher(request,newDispatcher){request.#dispatcher=newDispatcher}static setRequestHeaders(request,newHeaders){request.#headers=newHeaders}static getRequestState(request){return request.#state}static setRequestState(request,newState){request.#state=newState}};var{setRequestSignal,getRequestDispatcher,setRequestDispatcher,setRequestHeaders,getRequestState,setRequestState}=Request2;Reflect.deleteProperty(Request2,"setRequestSignal");Reflect.deleteProperty(Request2,"getRequestDispatcher");Reflect.deleteProperty(Request2,"setRequestDispatcher");Reflect.deleteProperty(Request2,"setRequestHeaders");Reflect.deleteProperty(Request2,"getRequestState");Reflect.deleteProperty(Request2,"setRequestState");mixinBody(Request2,getRequestState);function makeRequest(init){return{method:init.method??"GET",localURLsOnly:init.localURLsOnly??false,unsafeRequest:init.unsafeRequest??false,body:init.body??null,client:init.client??null,reservedClient:init.reservedClient??null,replacesClientId:init.replacesClientId??"",window:init.window??"client",keepalive:init.keepalive??false,serviceWorkers:init.serviceWorkers??"all",initiator:init.initiator??"",destination:init.destination??"",priority:init.priority??null,origin:init.origin??"client",policyContainer:init.policyContainer??"client",referrer:init.referrer??"client",referrerPolicy:init.referrerPolicy??"",mode:init.mode??"no-cors",useCORSPreflightFlag:init.useCORSPreflightFlag??false,credentials:init.credentials??"same-origin",useCredentials:init.useCredentials??false,cache:init.cache??"default",redirect:init.redirect??"follow",integrity:init.integrity??"",cryptoGraphicsNonceMetadata:init.cryptoGraphicsNonceMetadata??"",parserMetadata:init.parserMetadata??"",reloadNavigation:init.reloadNavigation??false,historyNavigation:init.historyNavigation??false,userActivation:init.userActivation??false,taintedOrigin:init.taintedOrigin??false,redirectCount:init.redirectCount??0,responseTainting:init.responseTainting??"basic",preventNoCacheCacheControlHeaderModification:init.preventNoCacheCacheControlHeaderModification??false,done:init.done??false,timingAllowFailed:init.timingAllowFailed??false,useURLCredentials:init.useURLCredentials??void 0,traversableForUserPrompts:init.traversableForUserPrompts??"client",urlList:init.urlList,url:init.urlList[0],headersList:init.headersList?new HeadersList(init.headersList):new HeadersList}}function cloneRequest(request){const newRequest=makeRequest({...request,body:null});if(request.body!=null){newRequest.body=cloneBody(request.body)}return newRequest}function fromInnerRequest(innerRequest,dispatcher,signal,guard){const request=new Request2(kConstruct);setRequestState(request,innerRequest);setRequestDispatcher(request,dispatcher);setRequestSignal(request,signal);const headers=new Headers2(kConstruct);setRequestHeaders(request,headers);setHeadersList(headers,innerRequest.headersList);setHeadersGuard(headers,guard);return request}Object.defineProperties(Request2.prototype,{method:kEnumerableProperty,url:kEnumerableProperty,headers:kEnumerableProperty,redirect:kEnumerableProperty,clone:kEnumerableProperty,signal:kEnumerableProperty,duplex:kEnumerableProperty,destination:kEnumerableProperty,body:kEnumerableProperty,bodyUsed:kEnumerableProperty,isHistoryNavigation:kEnumerableProperty,isReloadNavigation:kEnumerableProperty,keepalive:kEnumerableProperty,integrity:kEnumerableProperty,cache:kEnumerableProperty,credentials:kEnumerableProperty,attribute:kEnumerableProperty,referrerPolicy:kEnumerableProperty,referrer:kEnumerableProperty,mode:kEnumerableProperty,[Symbol.toStringTag]:{value:"Request",configurable:true}});webidl.is.Request=webidl.util.MakeTypeAssertion(Request2);webidl.converters.RequestInfo=function(V2){if(typeof V2==="string"){return webidl.converters.USVString(V2)}if(webidl.is.Request(V2)){return V2}return webidl.converters.USVString(V2)};webidl.converters.RequestInit=webidl.dictionaryConverter([{key:"method",converter:webidl.converters.ByteString},{key:"headers",converter:webidl.converters.HeadersInit},{key:"body",converter:webidl.nullableConverter(webidl.converters.BodyInit)},{key:"referrer",converter:webidl.converters.USVString},{key:"referrerPolicy",converter:webidl.converters.DOMString,allowedValues:referrerPolicy},{key:"mode",converter:webidl.converters.DOMString,allowedValues:requestMode},{key:"credentials",converter:webidl.converters.DOMString,allowedValues:requestCredentials},{key:"cache",converter:webidl.converters.DOMString,allowedValues:requestCache},{key:"redirect",converter:webidl.converters.DOMString,allowedValues:requestRedirect},{key:"integrity",converter:webidl.converters.DOMString},{key:"keepalive",converter:webidl.converters.boolean},{key:"signal",converter:webidl.nullableConverter(signal=>webidl.converters.AbortSignal(signal,"RequestInit","signal"))},{key:"window",converter:webidl.converters.any},{key:"duplex",converter:webidl.converters.DOMString,allowedValues:requestDuplex},{key:"dispatcher",converter:webidl.converters.any},{key:"priority",converter:webidl.converters.DOMString,allowedValues:["high","low","auto"],defaultValue:()=>"auto"}]);module.exports={Request:Request2,makeRequest,fromInnerRequest,cloneRequest,getRequestDispatcher,getRequestState}}});var require_subresource_integrity=__commonJS({"node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js"(exports,module){"use strict";var assert=__require("assert");var{runtimeFeatures}=require_runtime_features();var validSRIHashAlgorithmTokenSet=new Map([["sha256",0],["sha384",1],["sha512",2]]);var crypto5;if(runtimeFeatures.has("crypto")){crypto5=__require("crypto");const cryptoHashes=crypto5.getHashes();if(cryptoHashes.length===0){validSRIHashAlgorithmTokenSet.clear()}for(const algorithm of validSRIHashAlgorithmTokenSet.keys()){if(cryptoHashes.includes(algorithm)===false){validSRIHashAlgorithmTokenSet.delete(algorithm)}}}else{validSRIHashAlgorithmTokenSet.clear()}var getSRIHashAlgorithmIndex=Map.prototype.get.bind(validSRIHashAlgorithmTokenSet);var isValidSRIHashAlgorithm=Map.prototype.has.bind(validSRIHashAlgorithmTokenSet);var bytesMatch=runtimeFeatures.has("crypto")===false||validSRIHashAlgorithmTokenSet.size===0?()=>true:(bytes,metadataList)=>{const parsedMetadata=parseMetadata(metadataList);if(parsedMetadata.length===0){return true}const metadata=getStrongestMetadata(parsedMetadata);for(const item of metadata){const algorithm=item.alg;const expectedValue=item.val;const actualValue=applyAlgorithmToBytes(algorithm,bytes);if(caseSensitiveMatch(actualValue,expectedValue)){return true}}return false};function getStrongestMetadata(metadataList){const result=[];let strongest=null;for(const item of metadataList){assert(isValidSRIHashAlgorithm(item.alg),"Invalid SRI hash algorithm token");if(result.length===0){result.push(item);strongest=item;continue}const currentAlgorithm=strongest.alg;const currentAlgorithmIndex=getSRIHashAlgorithmIndex(currentAlgorithm);const newAlgorithm=item.alg;const newAlgorithmIndex=getSRIHashAlgorithmIndex(newAlgorithm);if(newAlgorithmIndex<currentAlgorithmIndex){continue}else if(newAlgorithmIndex>currentAlgorithmIndex){strongest=item;result[0]=item;result.length=1}else{result.push(item)}}return result}function parseMetadata(metadata){const result=[];for(const item of metadata.split(" ")){const expressionAndOptions=item.split("?",1);const algorithmExpression=expressionAndOptions[0];let base64Value="";const algorithmAndValue=[algorithmExpression.slice(0,6),algorithmExpression.slice(7)];const algorithm=algorithmAndValue[0];if(!isValidSRIHashAlgorithm(algorithm)){continue}if(algorithmAndValue[1]){base64Value=algorithmAndValue[1]}const metadata2={alg:algorithm,val:base64Value};result.push(metadata2)}return result}var applyAlgorithmToBytes=(algorithm,bytes)=>{return crypto5.hash(algorithm,bytes,"base64")};function caseSensitiveMatch(actualValue,expectedValue){let actualValueLength=actualValue.length;if(actualValueLength!==0&&actualValue[actualValueLength-1]==="="){actualValueLength-=1}if(actualValueLength!==0&&actualValue[actualValueLength-1]==="="){actualValueLength-=1}let expectedValueLength=expectedValue.length;if(expectedValueLength!==0&&expectedValue[expectedValueLength-1]==="="){expectedValueLength-=1}if(expectedValueLength!==0&&expectedValue[expectedValueLength-1]==="="){expectedValueLength-=1}if(actualValueLength!==expectedValueLength){return false}for(let i=0;i<actualValueLength;++i){if(actualValue[i]===expectedValue[i]||actualValue[i]==="+"&&expectedValue[i]==="-"||actualValue[i]==="/"&&expectedValue[i]==="_"){continue}return false}return true}module.exports={applyAlgorithmToBytes,bytesMatch,caseSensitiveMatch,isValidSRIHashAlgorithm,getStrongestMetadata,parseMetadata}}});var require_fetch=__commonJS({"node_modules/undici/lib/web/fetch/index.js"(exports,module){"use strict";var{makeNetworkError,makeAppropriateNetworkError,filterResponse,makeResponse,fromInnerResponse,getResponseState}=require_response();var{HeadersList}=require_headers();var{Request:Request2,cloneRequest,getRequestDispatcher,getRequestState}=require_request2();var zlib2=__require("zlib");var{makePolicyContainer,clonePolicyContainer,requestBadPort,TAOCheck,appendRequestOriginHeader,responseLocationURL,requestCurrentURL,setRequestReferrerPolicyOnRedirect,tryUpgradeRequestToAPotentiallyTrustworthyURL,createOpaqueTimingInfo,appendFetchMetadata,corsCheck,crossOriginResourcePolicyCheck,determineRequestsReferrer,coarsenedSharedCurrentTime,sameOrigin,isCancelled,isAborted,isErrorLike,fullyReadBody,readableStreamClose,urlIsLocal,urlIsHttpHttpsScheme,urlHasHttpsScheme,clampAndCoarsenConnectionTimingInfo,simpleRangeHeaderValue,buildContentRange,createInflate,extractMimeType,hasAuthenticationEntry,includesCredentials,isTraversableNavigable}=require_util2();var assert=__require("assert");var{safelyExtractBody,extractBody}=require_body();var{redirectStatusSet,nullBodyStatus,safeMethodsSet,requestBodyHeader,subresourceSet}=require_constants3();var EE=__require("events");var{Readable,pipeline,finished,isErrored,isReadable}=__require("stream");var{addAbortListener,bufferToLowerCasedHeaderName}=require_util();var{dataURLProcessor,serializeAMimeType,minimizeSupportedMimeType}=require_data_url();var{getGlobalDispatcher}=require_global2();var{webidl}=require_webidl();var{STATUS_CODES}=__require("http");var{bytesMatch}=require_subresource_integrity();var{createDeferredPromise}=require_promise();var{isomorphicEncode}=require_infra();var{runtimeFeatures}=require_runtime_features();var hasZstd=runtimeFeatures.has("zstd");var GET_OR_HEAD=["GET","HEAD"];var defaultUserAgent=typeof __UNDICI_IS_NODE__!=="undefined"||typeof esbuildDetection!=="undefined"?"node":"undici";var resolveObjectURL;var Fetch=class extends EE{constructor(dispatcher){super();this.dispatcher=dispatcher;this.connection=null;this.dump=false;this.state="ongoing"}terminate(reason){if(this.state!=="ongoing"){return}this.state="terminated";this.connection?.destroy(reason);this.emit("terminated",reason)}abort(error){if(this.state!=="ongoing"){return}this.state="aborted";if(!error){error=new DOMException("The operation was aborted.","AbortError")}this.serializedAbortReason=error;this.connection?.destroy(error);this.emit("terminated",error)}};function handleFetchDone(response){finalizeAndReportTiming(response,"fetch")}function fetch2(input,init=void 0){webidl.argumentLengthCheck(arguments,1,"globalThis.fetch");let p2=createDeferredPromise();let requestObject;try{requestObject=new Request2(input,init)}catch(e){p2.reject(e);return p2.promise}const request=getRequestState(requestObject);if(requestObject.signal.aborted){abortFetch(p2,request,null,requestObject.signal.reason,null);return p2.promise}const globalObject=request.client.globalObject;if(globalObject?.constructor?.name==="ServiceWorkerGlobalScope"){request.serviceWorkers="none"}let responseObject=null;let locallyAborted=false;let controller=null;addAbortListener(requestObject.signal,()=>{locallyAborted=true;assert(controller!=null);controller.abort(requestObject.signal.reason);const realResponse=responseObject?.deref();abortFetch(p2,request,realResponse,requestObject.signal.reason,controller.controller)});const processResponse=response=>{if(locallyAborted){return}if(response.aborted){abortFetch(p2,request,responseObject,controller.serializedAbortReason,controller.controller);return}if(response.type==="error"){p2.reject(new TypeError("fetch failed",{cause:response.error}));return}responseObject=new WeakRef(fromInnerResponse(response,"immutable"));p2.resolve(responseObject.deref());p2=null};controller=fetching({request,processResponseEndOfBody:handleFetchDone,processResponse,dispatcher:getRequestDispatcher(requestObject),requestObject});return p2.promise}function finalizeAndReportTiming(response,initiatorType="other"){if(response.type==="error"&&response.aborted){return}if(!response.urlList?.length){return}const originalURL=response.urlList[0];let timingInfo=response.timingInfo;let cacheState=response.cacheState;if(!urlIsHttpHttpsScheme(originalURL)){return}if(timingInfo===null){return}if(!response.timingAllowPassed){timingInfo=createOpaqueTimingInfo({startTime:timingInfo.startTime});cacheState=""}timingInfo.endTime=coarsenedSharedCurrentTime();response.timingInfo=timingInfo;markResourceTiming(timingInfo,originalURL.href,initiatorType,globalThis,cacheState,"",response.status)}var markResourceTiming=performance.markResourceTiming;function abortFetch(p2,request,responseObject,error,controller){if(p2){p2.reject(error)}if(request.body?.stream!=null&&isReadable(request.body.stream)){request.body.stream.cancel(error).catch(err=>{if(err.code==="ERR_INVALID_STATE"){return}throw err})}if(responseObject==null){return}const response=getResponseState(responseObject);if(response.body?.stream!=null&&isReadable(response.body.stream)){controller.error(error)}}function fetching({request,processRequestBodyChunkLength,processRequestEndOfBody,processResponse,processResponseEndOfBody,processResponseConsumeBody,useParallelQueue=false,dispatcher=getGlobalDispatcher(),requestObject=null}){assert(dispatcher);let taskDestination=null;let crossOriginIsolatedCapability=false;if(request.client!=null){taskDestination=request.client.globalObject;crossOriginIsolatedCapability=request.client.crossOriginIsolatedCapability}const currentTime=coarsenedSharedCurrentTime(crossOriginIsolatedCapability);const timingInfo=createOpaqueTimingInfo({startTime:currentTime});const fetchParams={controller:new Fetch(dispatcher),request,timingInfo,processRequestBodyChunkLength,processRequestEndOfBody,processResponse,processResponseConsumeBody,processResponseEndOfBody,taskDestination,crossOriginIsolatedCapability,requestObject};assert(!request.body||request.body.stream);if(request.window==="client"){request.window=request.client?.globalObject?.constructor?.name==="Window"?request.client:"no-window"}if(request.origin==="client"){request.origin=request.client.origin}if(request.policyContainer==="client"){if(request.client!=null){request.policyContainer=clonePolicyContainer(request.client.policyContainer)}else{request.policyContainer=makePolicyContainer()}}if(!request.headersList.contains("accept",true)){const value="*/*";request.headersList.append("accept",value,true)}if(!request.headersList.contains("accept-language",true)){request.headersList.append("accept-language","*",true)}if(request.priority===null){}if(subresourceSet.has(request.destination)){}mainFetch(fetchParams,false);return fetchParams.controller}async function mainFetch(fetchParams,recursive){try{const request=fetchParams.request;let response=null;if(request.localURLsOnly&&!urlIsLocal(requestCurrentURL(request))){response=makeNetworkError("local URLs only")}tryUpgradeRequestToAPotentiallyTrustworthyURL(request);if(requestBadPort(request)==="blocked"){response=makeNetworkError("bad port")}if(request.referrerPolicy===""){request.referrerPolicy=request.policyContainer.referrerPolicy}if(request.referrer!=="no-referrer"){request.referrer=determineRequestsReferrer(request)}if(response===null){const currentURL=requestCurrentURL(request);if(sameOrigin(currentURL,request.url)&&request.responseTainting==="basic"||currentURL.protocol==="data:"||(request.mode==="navigate"||request.mode==="websocket")){request.responseTainting="basic";response=await schemeFetch(fetchParams)}else if(request.mode==="same-origin"){response=makeNetworkError('request mode cannot be "same-origin"')}else if(request.mode==="no-cors"){if(request.redirect!=="follow"){response=makeNetworkError('redirect mode cannot be "follow" for "no-cors" request')}else{request.responseTainting="opaque";response=await schemeFetch(fetchParams)}}else if(!urlIsHttpHttpsScheme(requestCurrentURL(request))){response=makeNetworkError("URL scheme must be a HTTP(S) scheme")}else{request.responseTainting="cors";response=await httpFetch(fetchParams)}}if(recursive){return response}if(response.status!==0&&!response.internalResponse){if(request.responseTainting==="cors"){}if(request.responseTainting==="basic"){response=filterResponse(response,"basic")}else if(request.responseTainting==="cors"){response=filterResponse(response,"cors")}else if(request.responseTainting==="opaque"){response=filterResponse(response,"opaque")}else{assert(false)}}let internalResponse=response.status===0?response:response.internalResponse;if(internalResponse.urlList.length===0){internalResponse.urlList.push(...request.urlList)}if(!request.timingAllowFailed){response.timingAllowPassed=true}if(response.type==="opaque"&&internalResponse.status===206&&internalResponse.rangeRequested&&!request.headers.contains("range",true)){response=internalResponse=makeNetworkError()}if(response.status!==0&&(request.method==="HEAD"||request.method==="CONNECT"||nullBodyStatus.includes(internalResponse.status))){internalResponse.body=null;fetchParams.controller.dump=true}if(request.integrity){const processBodyError=reason=>fetchFinale(fetchParams,makeNetworkError(reason));if(request.responseTainting==="opaque"||response.body==null){processBodyError(response.error);return}const processBody=bytes=>{if(!bytesMatch(bytes,request.integrity)){processBodyError("integrity mismatch");return}response.body=safelyExtractBody(bytes)[0];fetchFinale(fetchParams,response)};fullyReadBody(response.body,processBody,processBodyError)}else{fetchFinale(fetchParams,response)}}catch(err){fetchParams.controller.terminate(err)}}function schemeFetch(fetchParams){if(isCancelled(fetchParams)&&fetchParams.request.redirectCount===0){return Promise.resolve(makeAppropriateNetworkError(fetchParams))}const{request}=fetchParams;const{protocol:scheme}=requestCurrentURL(request);switch(scheme){case"about:":{return Promise.resolve(makeNetworkError("about scheme is not supported"))}case"blob:":{if(!resolveObjectURL){resolveObjectURL=__require("buffer").resolveObjectURL}const blobURLEntry=requestCurrentURL(request);if(blobURLEntry.search.length!==0){return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."))}const blob=resolveObjectURL(blobURLEntry.toString());if(request.method!=="GET"||!webidl.is.Blob(blob)){return Promise.resolve(makeNetworkError("invalid method"))}const response=makeResponse();const fullLength=blob.size;const serializedFullLength=isomorphicEncode(`${fullLength}`);const type=blob.type;if(!request.headersList.contains("range",true)){const bodyWithType=extractBody(blob);response.statusText="OK";response.body=bodyWithType[0];response.headersList.set("content-length",serializedFullLength,true);response.headersList.set("content-type",type,true)}else{response.rangeRequested=true;const rangeHeader=request.headersList.get("range",true);const rangeValue=simpleRangeHeaderValue(rangeHeader,true);if(rangeValue==="failure"){return Promise.resolve(makeNetworkError("failed to fetch the data URL"))}let{rangeStartValue:rangeStart,rangeEndValue:rangeEnd}=rangeValue;if(rangeStart===null){rangeStart=fullLength-rangeEnd;rangeEnd=rangeStart+rangeEnd-1}else{if(rangeStart>=fullLength){return Promise.resolve(makeNetworkError("Range start is greater than the blob's size."))}if(rangeEnd===null||rangeEnd>=fullLength){rangeEnd=fullLength-1}}const slicedBlob=blob.slice(rangeStart,rangeEnd+1,type);const slicedBodyWithType=extractBody(slicedBlob);response.body=slicedBodyWithType[0];const serializedSlicedLength=isomorphicEncode(`${slicedBlob.size}`);const contentRange=buildContentRange(rangeStart,rangeEnd,fullLength);response.status=206;response.statusText="Partial Content";response.headersList.set("content-length",serializedSlicedLength,true);response.headersList.set("content-type",type,true);response.headersList.set("content-range",contentRange,true)}return Promise.resolve(response)}case"data:":{const currentURL=requestCurrentURL(request);const dataURLStruct=dataURLProcessor(currentURL);if(dataURLStruct==="failure"){return Promise.resolve(makeNetworkError("failed to fetch the data URL"))}const mimeType=serializeAMimeType(dataURLStruct.mimeType);return Promise.resolve(makeResponse({statusText:"OK",headersList:[["content-type",{name:"Content-Type",value:mimeType}]],body:safelyExtractBody(dataURLStruct.body)[0]}))}case"file:":{return Promise.resolve(makeNetworkError("not implemented... yet..."))}case"http:":case"https:":{return httpFetch(fetchParams).catch(err=>makeNetworkError(err))}default:{return Promise.resolve(makeNetworkError("unknown scheme"))}}}function finalizeResponse(fetchParams,response){fetchParams.request.done=true;if(fetchParams.processResponseDone!=null){queueMicrotask(()=>fetchParams.processResponseDone(response))}}function fetchFinale(fetchParams,response){let timingInfo=fetchParams.timingInfo;const processResponseEndOfBody=()=>{const unsafeEndTime=Date.now();if(fetchParams.request.destination==="document"){fetchParams.controller.fullTimingInfo=timingInfo}fetchParams.controller.reportTimingSteps=()=>{if(!urlIsHttpHttpsScheme(fetchParams.request.url)){return}timingInfo.endTime=unsafeEndTime;let cacheState=response.cacheState;const bodyInfo=response.bodyInfo;if(!response.timingAllowPassed){timingInfo=createOpaqueTimingInfo(timingInfo);cacheState=""}let responseStatus=0;if(fetchParams.request.mode!=="navigate"||!response.hasCrossOriginRedirects){responseStatus=response.status;const mimeType=extractMimeType(response.headersList);if(mimeType!=="failure"){bodyInfo.contentType=minimizeSupportedMimeType(mimeType)}}if(fetchParams.request.initiatorType!=null){markResourceTiming(timingInfo,fetchParams.request.url.href,fetchParams.request.initiatorType,globalThis,cacheState,bodyInfo,responseStatus)}};const processResponseEndOfBodyTask=()=>{fetchParams.request.done=true;if(fetchParams.processResponseEndOfBody!=null){queueMicrotask(()=>fetchParams.processResponseEndOfBody(response))}if(fetchParams.request.initiatorType!=null){fetchParams.controller.reportTimingSteps()}};queueMicrotask(()=>processResponseEndOfBodyTask())};if(fetchParams.processResponse!=null){queueMicrotask(()=>{fetchParams.processResponse(response);fetchParams.processResponse=null})}const internalResponse=response.type==="error"?response:response.internalResponse??response;if(internalResponse.body==null){processResponseEndOfBody()}else{finished(internalResponse.body.stream,()=>{processResponseEndOfBody()})}}async function httpFetch(fetchParams){const request=fetchParams.request;let response=null;let actualResponse=null;const timingInfo=fetchParams.timingInfo;if(request.serviceWorkers==="all"){}if(response===null){if(request.redirect==="follow"){request.serviceWorkers="none"}actualResponse=response=await httpNetworkOrCacheFetch(fetchParams);if(request.responseTainting==="cors"&&corsCheck(request,response)==="failure"){return makeNetworkError("cors failure")}if(TAOCheck(request,response)==="failure"){request.timingAllowFailed=true}}if((request.responseTainting==="opaque"||response.type==="opaque")&&crossOriginResourcePolicyCheck(request.origin,request.client,request.destination,actualResponse)==="blocked"){return makeNetworkError("blocked")}if(redirectStatusSet.has(actualResponse.status)){if(request.redirect!=="manual"){fetchParams.controller.connection.destroy(void 0,false)}if(request.redirect==="error"){response=makeNetworkError("unexpected redirect")}else if(request.redirect==="manual"){response=actualResponse}else if(request.redirect==="follow"){response=await httpRedirectFetch(fetchParams,response)}else{assert(false)}}response.timingInfo=timingInfo;return response}function httpRedirectFetch(fetchParams,response){const request=fetchParams.request;const actualResponse=response.internalResponse?response.internalResponse:response;let locationURL;try{locationURL=responseLocationURL(actualResponse,requestCurrentURL(request).hash);if(locationURL==null){return response}}catch(err){return Promise.resolve(makeNetworkError(err))}if(!urlIsHttpHttpsScheme(locationURL)){return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"))}if(request.redirectCount===20){return Promise.resolve(makeNetworkError("redirect count exceeded"))}request.redirectCount+=1;if(request.mode==="cors"&&(locationURL.username||locationURL.password)&&!sameOrigin(request,locationURL)){return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))}if(request.responseTainting==="cors"&&(locationURL.username||locationURL.password)){return Promise.resolve(makeNetworkError('URL cannot contain credentials for request mode "cors"'))}if(actualResponse.status!==303&&request.body!=null&&request.body.source==null){return Promise.resolve(makeNetworkError())}if([301,302].includes(actualResponse.status)&&request.method==="POST"||actualResponse.status===303&&!GET_OR_HEAD.includes(request.method)){request.method="GET";request.body=null;for(const headerName of requestBodyHeader){request.headersList.delete(headerName)}}if(!sameOrigin(requestCurrentURL(request),locationURL)){request.headersList.delete("authorization",true);request.headersList.delete("proxy-authorization",true);request.headersList.delete("cookie",true);request.headersList.delete("host",true)}if(request.body!=null){assert(request.body.source!=null);request.body=safelyExtractBody(request.body.source)[0]}const timingInfo=fetchParams.timingInfo;timingInfo.redirectEndTime=timingInfo.postRedirectStartTime=coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);if(timingInfo.redirectStartTime===0){timingInfo.redirectStartTime=timingInfo.startTime}request.urlList.push(locationURL);setRequestReferrerPolicyOnRedirect(request,actualResponse);return mainFetch(fetchParams,true)}async function httpNetworkOrCacheFetch(fetchParams,isAuthenticationFetch=false,isNewConnectionFetch=false){const request=fetchParams.request;let httpFetchParams=null;let httpRequest=null;let response=null;const httpCache=null;const revalidatingFlag=false;if(request.window==="no-window"&&request.redirect==="error"){httpFetchParams=fetchParams;httpRequest=request}else{httpRequest=cloneRequest(request);httpFetchParams={...fetchParams};httpFetchParams.request=httpRequest}const includeCredentials=request.credentials==="include"||request.credentials==="same-origin"&&request.responseTainting==="basic";const contentLength=httpRequest.body?httpRequest.body.length:null;let contentLengthHeaderValue=null;if(httpRequest.body==null&&["POST","PUT"].includes(httpRequest.method)){contentLengthHeaderValue="0"}if(contentLength!=null){contentLengthHeaderValue=isomorphicEncode(`${contentLength}`)}if(contentLengthHeaderValue!=null&&!httpRequest.headersList.contains("content-length",true)){httpRequest.headersList.append("content-length",contentLengthHeaderValue,true)}if(contentLength!=null&&httpRequest.keepalive){}if(webidl.is.URL(httpRequest.referrer)){httpRequest.headersList.append("referer",isomorphicEncode(httpRequest.referrer.href),true)}appendRequestOriginHeader(httpRequest);appendFetchMetadata(httpRequest);if(!httpRequest.headersList.contains("user-agent",true)){httpRequest.headersList.append("user-agent",defaultUserAgent,true)}if(httpRequest.cache==="default"&&(httpRequest.headersList.contains("if-modified-since",true)||httpRequest.headersList.contains("if-none-match",true)||httpRequest.headersList.contains("if-unmodified-since",true)||httpRequest.headersList.contains("if-match",true)||httpRequest.headersList.contains("if-range",true))){httpRequest.cache="no-store"}if(httpRequest.cache==="no-cache"&&!httpRequest.preventNoCacheCacheControlHeaderModification&&!httpRequest.headersList.contains("cache-control",true)){httpRequest.headersList.append("cache-control","max-age=0",true)}if(httpRequest.cache==="no-store"||httpRequest.cache==="reload"){if(!httpRequest.headersList.contains("pragma",true)){httpRequest.headersList.append("pragma","no-cache",true)}if(!httpRequest.headersList.contains("cache-control",true)){httpRequest.headersList.append("cache-control","no-cache",true)}}if(httpRequest.headersList.contains("range",true)){httpRequest.headersList.append("accept-encoding","identity",true)}if(!httpRequest.headersList.contains("accept-encoding",true)){if(urlHasHttpsScheme(requestCurrentURL(httpRequest))){httpRequest.headersList.append("accept-encoding","br, gzip, deflate",true)}else{httpRequest.headersList.append("accept-encoding","gzip, deflate",true)}}httpRequest.headersList.delete("host",true);if(includeCredentials){if(!httpRequest.headersList.contains("authorization",true)){let authorizationValue=null;if(hasAuthenticationEntry(httpRequest)&&(httpRequest.useURLCredentials===void 0||!includesCredentials(requestCurrentURL(httpRequest)))){}else if(includesCredentials(requestCurrentURL(httpRequest))&&isAuthenticationFetch){const{username,password}=requestCurrentURL(httpRequest);authorizationValue=`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`}if(authorizationValue!==null){httpRequest.headersList.append("Authorization",authorizationValue,false)}}}if(httpCache==null){httpRequest.cache="no-store"}if(httpRequest.cache!=="no-store"&&httpRequest.cache!=="reload"){}if(response==null){if(httpRequest.cache==="only-if-cached"){return makeNetworkError("only if cached")}const forwardResponse=await httpNetworkFetch(httpFetchParams,includeCredentials,isNewConnectionFetch);if(!safeMethodsSet.has(httpRequest.method)&&forwardResponse.status>=200&&forwardResponse.status<=399){}if(revalidatingFlag&&forwardResponse.status===304){}if(response==null){response=forwardResponse}}response.urlList=[...httpRequest.urlList];if(httpRequest.headersList.contains("range",true)){response.rangeRequested=true}response.requestIncludesCredentials=includeCredentials;if(response.status===401&&httpRequest.responseTainting!=="cors"&&includeCredentials&&(request.useURLCredentials!==void 0||isTraversableNavigable(request.traversableForUserPrompts))){if(request.body!=null){if(request.body.source==null){return response}request.body=safelyExtractBody(request.body.source)[0]}if(request.useURLCredentials===void 0||isAuthenticationFetch){if(isCancelled(fetchParams)){return makeAppropriateNetworkError(fetchParams)}return response}fetchParams.controller.connection.destroy();response=await httpNetworkOrCacheFetch(fetchParams,true)}if(response.status===407){if(request.window==="no-window"){return makeNetworkError()}if(isCancelled(fetchParams)){return makeAppropriateNetworkError(fetchParams)}return makeNetworkError("proxy authentication required")}if(response.status===421&&!isNewConnectionFetch&&(request.body==null||request.body.source!=null)){if(isCancelled(fetchParams)){return makeAppropriateNetworkError(fetchParams)}fetchParams.controller.connection.destroy();response=await httpNetworkOrCacheFetch(fetchParams,isAuthenticationFetch,true)}if(isAuthenticationFetch){}return response}async function httpNetworkFetch(fetchParams,includeCredentials=false,forceNewConnection=false){assert(!fetchParams.controller.connection||fetchParams.controller.connection.destroyed);fetchParams.controller.connection={abort:null,destroyed:false,destroy(err,abort=true){if(!this.destroyed){this.destroyed=true;if(abort){this.abort?.(err??new DOMException("The operation was aborted.","AbortError"))}}}};const request=fetchParams.request;let response=null;const timingInfo=fetchParams.timingInfo;const httpCache=null;if(httpCache==null){request.cache="no-store"}const newConnection=forceNewConnection?"yes":"no";if(request.mode==="websocket"){}else{}let requestBody=null;if(request.body==null&&fetchParams.processRequestEndOfBody){queueMicrotask(()=>fetchParams.processRequestEndOfBody())}else if(request.body!=null){const processBodyChunk=async function*(bytes){if(isCancelled(fetchParams)){return}yield bytes;fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)};const processEndOfBody=()=>{if(isCancelled(fetchParams)){return}if(fetchParams.processRequestEndOfBody){fetchParams.processRequestEndOfBody()}};const processBodyError=e=>{if(isCancelled(fetchParams)){return}if(e.name==="AbortError"){fetchParams.controller.abort()}else{fetchParams.controller.terminate(e)}};requestBody=(async function*(){try{for await(const bytes of request.body.stream){yield*processBodyChunk(bytes)}processEndOfBody()}catch(err){processBodyError(err)}})()}try{const{body,status,statusText,headersList,socket}=await dispatch({body:requestBody});if(socket){response=makeResponse({status,statusText,headersList,socket})}else{const iterator=body[Symbol.asyncIterator]();fetchParams.controller.next=()=>iterator.next();response=makeResponse({status,statusText,headersList})}}catch(err){if(err.name==="AbortError"){fetchParams.controller.connection.destroy();return makeAppropriateNetworkError(fetchParams,err)}return makeNetworkError(err)}const pullAlgorithm=()=>{return fetchParams.controller.resume()};const cancelAlgorithm=reason=>{if(!isCancelled(fetchParams)){fetchParams.controller.abort(reason)}};const stream2=new ReadableStream({start(controller){fetchParams.controller.controller=controller},pull:pullAlgorithm,cancel:cancelAlgorithm,type:"bytes"});response.body={stream:stream2,source:null,length:null};if(!fetchParams.controller.resume){fetchParams.controller.on("terminated",onAborted)}fetchParams.controller.resume=async()=>{while(true){let bytes;let isFailure;try{const{done,value}=await fetchParams.controller.next();if(isAborted(fetchParams)){break}bytes=done?void 0:value}catch(err){if(fetchParams.controller.ended&&!timingInfo.encodedBodySize){bytes=void 0}else{bytes=err;isFailure=true}}if(bytes===void 0){readableStreamClose(fetchParams.controller.controller);finalizeResponse(fetchParams,response);return}timingInfo.decodedBodySize+=bytes?.byteLength??0;if(isFailure){fetchParams.controller.terminate(bytes);return}const buffer=new Uint8Array(bytes);if(buffer.byteLength){fetchParams.controller.controller.enqueue(buffer)}if(isErrored(stream2)){fetchParams.controller.terminate();return}if(fetchParams.controller.controller.desiredSize<=0){return}}};function onAborted(reason){if(isAborted(fetchParams)){response.aborted=true;if(isReadable(stream2)){fetchParams.controller.controller.error(fetchParams.controller.serializedAbortReason)}}else{if(isReadable(stream2)){fetchParams.controller.controller.error(new TypeError("terminated",{cause:isErrorLike(reason)?reason:void 0}))}}fetchParams.controller.connection.destroy()}return response;function dispatch({body}){const url=requestCurrentURL(request);const agent=fetchParams.controller.dispatcher;const path29=url.pathname+url.search;const hasTrailingQuestionMark=url.search.length===0&&url.href[url.href.length-url.hash.length-1]==="?";return new Promise((resolve,reject)=>agent.dispatch({path:hasTrailingQuestionMark?`${path29}?`:path29,origin:url.origin,method:request.method,body:agent.isMockActive?request.body&&(request.body.source||request.body.stream):body,headers:request.headersList.entries,maxRedirections:0,upgrade:request.mode==="websocket"?"websocket":void 0},{body:null,abort:null,onConnect(abort){const{connection}=fetchParams.controller;timingInfo.finalConnectionTimingInfo=clampAndCoarsenConnectionTimingInfo(void 0,timingInfo.postRedirectStartTime,fetchParams.crossOriginIsolatedCapability);if(connection.destroyed){abort(new DOMException("The operation was aborted.","AbortError"))}else{fetchParams.controller.on("terminated",abort);this.abort=connection.abort=abort}timingInfo.finalNetworkRequestStartTime=coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)},onResponseStarted(){timingInfo.finalNetworkResponseStartTime=coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)},onHeaders(status,rawHeaders,resume,statusText){if(status<200){return false}const headersList=new HeadersList;for(let i=0;i<rawHeaders.length;i+=2){const nameStr=bufferToLowerCasedHeaderName(rawHeaders[i]);const value=rawHeaders[i+1];if(Array.isArray(value)&&!Buffer.isBuffer(rawHeaders[i+1])){for(const val of value){headersList.append(nameStr,val.toString("latin1"),true)}}else{headersList.append(nameStr,value.toString("latin1"),true)}}const location=headersList.get("location",true);this.body=new Readable({read:resume});const willFollow=location&&request.redirect==="follow"&&redirectStatusSet.has(status);const decoders=[];if(request.method!=="HEAD"&&request.method!=="CONNECT"&&!nullBodyStatus.includes(status)&&!willFollow){const contentEncoding=headersList.get("content-encoding",true);const codings=contentEncoding?contentEncoding.toLowerCase().split(","):[];const maxContentEncodings=5;if(codings.length>maxContentEncodings){reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`));return true}for(let i=codings.length-1;i>=0;--i){const coding=codings[i].trim();if(coding==="x-gzip"||coding==="gzip"){decoders.push(zlib2.createGunzip({flush:zlib2.constants.Z_SYNC_FLUSH,finishFlush:zlib2.constants.Z_SYNC_FLUSH}))}else if(coding==="deflate"){decoders.push(createInflate({flush:zlib2.constants.Z_SYNC_FLUSH,finishFlush:zlib2.constants.Z_SYNC_FLUSH}))}else if(coding==="br"){decoders.push(zlib2.createBrotliDecompress({flush:zlib2.constants.BROTLI_OPERATION_FLUSH,finishFlush:zlib2.constants.BROTLI_OPERATION_FLUSH}))}else if(coding==="zstd"&&hasZstd){decoders.push(zlib2.createZstdDecompress({flush:zlib2.constants.ZSTD_e_continue,finishFlush:zlib2.constants.ZSTD_e_end}))}else{decoders.length=0;break}}}const onError=this.onError.bind(this);resolve({status,statusText,headersList,body:decoders.length?pipeline(this.body,...decoders,err=>{if(err){this.onError(err)}}).on("error",onError):this.body.on("error",onError)});return true},onData(chunk){if(fetchParams.controller.dump){return}const bytes=chunk;timingInfo.encodedBodySize+=bytes.byteLength;return this.body.push(bytes)},onComplete(){if(this.abort){fetchParams.controller.off("terminated",this.abort)}fetchParams.controller.ended=true;this.body.push(null)},onError(error){if(this.abort){fetchParams.controller.off("terminated",this.abort)}this.body?.destroy(error);fetchParams.controller.terminate(error);reject(error)},onRequestUpgrade(_controller,status,headers,socket){if(socket.session!=null&&status!==200||socket.session==null&&status!==101){return false}const headersList=new HeadersList;for(const[name,value]of Object.entries(headers)){if(value==null){continue}const headerName=name.toLowerCase();if(Array.isArray(value)){for(const entry of value){headersList.append(headerName,String(entry),true)}}else{headersList.append(headerName,String(value),true)}}resolve({status,statusText:STATUS_CODES[status],headersList,socket});return true},onUpgrade(status,rawHeaders,socket){if(socket.session!=null&&status!==200||socket.session==null&&status!==101){return false}const headersList=new HeadersList;for(let i=0;i<rawHeaders.length;i+=2){const nameStr=bufferToLowerCasedHeaderName(rawHeaders[i]);const value=rawHeaders[i+1];if(Array.isArray(value)&&!Buffer.isBuffer(rawHeaders[i+1])){for(const val of value){headersList.append(nameStr,val.toString("latin1"),true)}}else{headersList.append(nameStr,value.toString("latin1"),true)}}resolve({status,statusText:STATUS_CODES[status],headersList,socket});return true}}))}}module.exports={fetch:fetch2,Fetch,fetching,finalizeAndReportTiming}}});var require_util3=__commonJS({"node_modules/undici/lib/web/cache/util.js"(exports,module){"use strict";var assert=__require("assert");var{URLSerializer}=require_data_url();var{isValidHeaderName}=require_util2();function urlEquals(A2,B2,excludeFragment=false){const serializedA=URLSerializer(A2,excludeFragment);const serializedB=URLSerializer(B2,excludeFragment);return serializedA===serializedB}function getFieldValues(header){assert(header!==null);const values=[];for(let value of header.split(",")){value=value.trim();if(isValidHeaderName(value)){values.push(value)}}return values}module.exports={urlEquals,getFieldValues}}});var require_cache3=__commonJS({"node_modules/undici/lib/web/cache/cache.js"(exports,module){"use strict";var assert=__require("assert");var{kConstruct}=require_symbols();var{urlEquals,getFieldValues}=require_util3();var{kEnumerableProperty,isDisturbed}=require_util();var{webidl}=require_webidl();var{cloneResponse,fromInnerResponse,getResponseState}=require_response();var{Request:Request2,fromInnerRequest,getRequestState}=require_request2();var{fetching}=require_fetch();var{urlIsHttpHttpsScheme,readAllBytes}=require_util2();var{createDeferredPromise}=require_promise();var Cache=class _Cache{#relevantRequestResponseList;constructor(){if(arguments[0]!==kConstruct){webidl.illegalConstructor()}webidl.util.markAsUncloneable(this);this.#relevantRequestResponseList=arguments[1]}async match(request,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.match";webidl.argumentLengthCheck(arguments,1,prefix);request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");const p2=this.#internalMatchAll(request,options,1);if(p2.length===0){return}return p2[0]}async matchAll(request=void 0,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.matchAll";if(request!==void 0)request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");return this.#internalMatchAll(request,options)}async add(request){webidl.brandCheck(this,_Cache);const prefix="Cache.add";webidl.argumentLengthCheck(arguments,1,prefix);request=webidl.converters.RequestInfo(request);const requests=[request];const responseArrayPromise=this.addAll(requests);return await responseArrayPromise}async addAll(requests){webidl.brandCheck(this,_Cache);const prefix="Cache.addAll";webidl.argumentLengthCheck(arguments,1,prefix);const responsePromises=[];const requestList=[];for(let request of requests){if(request===void 0){throw webidl.errors.conversionFailed({prefix,argument:"Argument 1",types:["undefined is not allowed"]})}request=webidl.converters.RequestInfo(request);if(typeof request==="string"){continue}const r=getRequestState(request);if(!urlIsHttpHttpsScheme(r.url)||r.method!=="GET"){throw webidl.errors.exception({header:prefix,message:"Expected http/s scheme when method is not GET."})}}const fetchControllers=[];for(const request of requests){const r=getRequestState(new Request2(request));if(!urlIsHttpHttpsScheme(r.url)){throw webidl.errors.exception({header:prefix,message:"Expected http/s scheme."})}r.initiator="fetch";r.destination="subresource";requestList.push(r);const responsePromise=createDeferredPromise();fetchControllers.push(fetching({request:r,processResponse(response){if(response.type==="error"||response.status===206||response.status<200||response.status>299){responsePromise.reject(webidl.errors.exception({header:"Cache.addAll",message:"Received an invalid status code or the request failed."}))}else if(response.headersList.contains("vary")){const fieldValues=getFieldValues(response.headersList.get("vary"));for(const fieldValue of fieldValues){if(fieldValue==="*"){responsePromise.reject(webidl.errors.exception({header:"Cache.addAll",message:"invalid vary field value"}));for(const controller of fetchControllers){controller.abort()}return}}}},processResponseEndOfBody(response){if(response.aborted){responsePromise.reject(new DOMException("aborted","AbortError"));return}responsePromise.resolve(response)}}));responsePromises.push(responsePromise.promise)}const p2=Promise.all(responsePromises);const responses=await p2;const operations=[];let index=0;for(const response of responses){const operation={type:"put",request:requestList[index],response};operations.push(operation);index++}const cacheJobPromise=createDeferredPromise();let errorData=null;try{this.#batchCacheOperations(operations)}catch(e){errorData=e}queueMicrotask(()=>{if(errorData===null){cacheJobPromise.resolve(void 0)}else{cacheJobPromise.reject(errorData)}});return cacheJobPromise.promise}async put(request,response){webidl.brandCheck(this,_Cache);const prefix="Cache.put";webidl.argumentLengthCheck(arguments,2,prefix);request=webidl.converters.RequestInfo(request);response=webidl.converters.Response(response,prefix,"response");let innerRequest=null;if(webidl.is.Request(request)){innerRequest=getRequestState(request)}else{innerRequest=getRequestState(new Request2(request))}if(!urlIsHttpHttpsScheme(innerRequest.url)||innerRequest.method!=="GET"){throw webidl.errors.exception({header:prefix,message:"Expected an http/s scheme when method is not GET"})}const innerResponse=getResponseState(response);if(innerResponse.status===206){throw webidl.errors.exception({header:prefix,message:"Got 206 status"})}if(innerResponse.headersList.contains("vary")){const fieldValues=getFieldValues(innerResponse.headersList.get("vary"));for(const fieldValue of fieldValues){if(fieldValue==="*"){throw webidl.errors.exception({header:prefix,message:"Got * vary field value"})}}}if(innerResponse.body&&(isDisturbed(innerResponse.body.stream)||innerResponse.body.stream.locked)){throw webidl.errors.exception({header:prefix,message:"Response body is locked or disturbed"})}const clonedResponse=cloneResponse(innerResponse);const bodyReadPromise=createDeferredPromise();if(innerResponse.body!=null){const stream2=innerResponse.body.stream;const reader=stream2.getReader();readAllBytes(reader,bodyReadPromise.resolve,bodyReadPromise.reject)}else{bodyReadPromise.resolve(void 0)}const operations=[];const operation={type:"put",request:innerRequest,response:clonedResponse};operations.push(operation);const bytes=await bodyReadPromise.promise;if(clonedResponse.body!=null){clonedResponse.body.source=bytes}const cacheJobPromise=createDeferredPromise();let errorData=null;try{this.#batchCacheOperations(operations)}catch(e){errorData=e}queueMicrotask(()=>{if(errorData===null){cacheJobPromise.resolve()}else{cacheJobPromise.reject(errorData)}});return cacheJobPromise.promise}async delete(request,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.delete";webidl.argumentLengthCheck(arguments,1,prefix);request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");let r=null;if(webidl.is.Request(request)){r=getRequestState(request);if(r.method!=="GET"&&!options.ignoreMethod){return false}}else{assert(typeof request==="string");r=getRequestState(new Request2(request))}const operations=[];const operation={type:"delete",request:r,options};operations.push(operation);const cacheJobPromise=createDeferredPromise();let errorData=null;let requestResponses;try{requestResponses=this.#batchCacheOperations(operations)}catch(e){errorData=e}queueMicrotask(()=>{if(errorData===null){cacheJobPromise.resolve(!!requestResponses?.length)}else{cacheJobPromise.reject(errorData)}});return cacheJobPromise.promise}async keys(request=void 0,options={}){webidl.brandCheck(this,_Cache);const prefix="Cache.keys";if(request!==void 0)request=webidl.converters.RequestInfo(request);options=webidl.converters.CacheQueryOptions(options,prefix,"options");let r=null;if(request!==void 0){if(webidl.is.Request(request)){r=getRequestState(request);if(r.method!=="GET"&&!options.ignoreMethod){return[]}}else if(typeof request==="string"){r=getRequestState(new Request2(request))}}const promise=createDeferredPromise();const requests=[];if(request===void 0){for(const requestResponse of this.#relevantRequestResponseList){requests.push(requestResponse[0])}}else{const requestResponses=this.#queryCache(r,options);for(const requestResponse of requestResponses){requests.push(requestResponse[0])}}queueMicrotask(()=>{const requestList=[];for(const request2 of requests){const requestObject=fromInnerRequest(request2,void 0,new AbortController().signal,"immutable");requestList.push(requestObject)}promise.resolve(Object.freeze(requestList))});return promise.promise}#batchCacheOperations(operations){const cache3=this.#relevantRequestResponseList;const backupCache=[...cache3];const addedItems=[];const resultList=[];try{for(const operation of operations){if(operation.type!=="delete"&&operation.type!=="put"){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:'operation type does not match "delete" or "put"'})}if(operation.type==="delete"&&operation.response!=null){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"delete operation should not have an associated response"})}if(this.#queryCache(operation.request,operation.options,addedItems).length){throw new DOMException("???","InvalidStateError")}let requestResponses;if(operation.type==="delete"){requestResponses=this.#queryCache(operation.request,operation.options);if(requestResponses.length===0){return[]}for(const requestResponse of requestResponses){const idx=cache3.indexOf(requestResponse);assert(idx!==-1);cache3.splice(idx,1)}}else if(operation.type==="put"){if(operation.response==null){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"put operation should have an associated response"})}const r=operation.request;if(!urlIsHttpHttpsScheme(r.url)){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"expected http or https scheme"})}if(r.method!=="GET"){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"not get method"})}if(operation.options!=null){throw webidl.errors.exception({header:"Cache.#batchCacheOperations",message:"options must not be defined"})}requestResponses=this.#queryCache(operation.request);for(const requestResponse of requestResponses){const idx=cache3.indexOf(requestResponse);assert(idx!==-1);cache3.splice(idx,1)}cache3.push([operation.request,operation.response]);addedItems.push([operation.request,operation.response])}resultList.push([operation.request,operation.response])}return resultList}catch(e){this.#relevantRequestResponseList.length=0;this.#relevantRequestResponseList=backupCache;throw e}}#queryCache(requestQuery,options,targetStorage){const resultList=[];const storage=targetStorage??this.#relevantRequestResponseList;for(const requestResponse of storage){const[cachedRequest,cachedResponse]=requestResponse;if(this.#requestMatchesCachedItem(requestQuery,cachedRequest,cachedResponse,options)){resultList.push(requestResponse)}}return resultList}#requestMatchesCachedItem(requestQuery,request,response=null,options){const queryURL=new URL(requestQuery.url);const cachedURL=new URL(request.url);if(options?.ignoreSearch){cachedURL.search="";queryURL.search=""}if(!urlEquals(queryURL,cachedURL,true)){return false}if(response==null||options?.ignoreVary||!response.headersList.contains("vary")){return true}const fieldValues=getFieldValues(response.headersList.get("vary"));for(const fieldValue of fieldValues){if(fieldValue==="*"){return false}const requestValue=request.headersList.get(fieldValue);const queryValue=requestQuery.headersList.get(fieldValue);if(requestValue!==queryValue){return false}}return true}#internalMatchAll(request,options,maxResponses=Infinity){let r=null;if(request!==void 0){if(webidl.is.Request(request)){r=getRequestState(request);if(r.method!=="GET"&&!options.ignoreMethod){return[]}}else if(typeof request==="string"){r=getRequestState(new Request2(request))}}const responses=[];if(request===void 0){for(const requestResponse of this.#relevantRequestResponseList){responses.push(requestResponse[1])}}else{const requestResponses=this.#queryCache(r,options);for(const requestResponse of requestResponses){responses.push(requestResponse[1])}}const responseList=[];for(const response of responses){const responseObject=fromInnerResponse(cloneResponse(response),"immutable");responseList.push(responseObject);if(responseList.length>=maxResponses){break}}return Object.freeze(responseList)}};Object.defineProperties(Cache.prototype,{[Symbol.toStringTag]:{value:"Cache",configurable:true},match:kEnumerableProperty,matchAll:kEnumerableProperty,add:kEnumerableProperty,addAll:kEnumerableProperty,put:kEnumerableProperty,delete:kEnumerableProperty,keys:kEnumerableProperty});var cacheQueryOptionConverters=[{key:"ignoreSearch",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"ignoreMethod",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"ignoreVary",converter:webidl.converters.boolean,defaultValue:()=>false}];webidl.converters.CacheQueryOptions=webidl.dictionaryConverter(cacheQueryOptionConverters);webidl.converters.MultiCacheQueryOptions=webidl.dictionaryConverter([...cacheQueryOptionConverters,{key:"cacheName",converter:webidl.converters.DOMString}]);webidl.converters.Response=webidl.interfaceConverter(webidl.is.Response,"Response");webidl.converters["sequence<RequestInfo>"]=webidl.sequenceConverter(webidl.converters.RequestInfo);module.exports={Cache}}});var require_cachestorage=__commonJS({"node_modules/undici/lib/web/cache/cachestorage.js"(exports,module){"use strict";var{Cache}=require_cache3();var{webidl}=require_webidl();var{kEnumerableProperty}=require_util();var{kConstruct}=require_symbols();var CacheStorage=class _CacheStorage{#caches=new Map;constructor(){if(arguments[0]!==kConstruct){webidl.illegalConstructor()}webidl.util.markAsUncloneable(this)}async match(request,options={}){webidl.brandCheck(this,_CacheStorage);webidl.argumentLengthCheck(arguments,1,"CacheStorage.match");request=webidl.converters.RequestInfo(request);options=webidl.converters.MultiCacheQueryOptions(options);if(options.cacheName!=null){if(this.#caches.has(options.cacheName)){const cacheList=this.#caches.get(options.cacheName);const cache3=new Cache(kConstruct,cacheList);return await cache3.match(request,options)}}else{for(const cacheList of this.#caches.values()){const cache3=new Cache(kConstruct,cacheList);const response=await cache3.match(request,options);if(response!==void 0){return response}}}}async has(cacheName){webidl.brandCheck(this,_CacheStorage);const prefix="CacheStorage.has";webidl.argumentLengthCheck(arguments,1,prefix);cacheName=webidl.converters.DOMString(cacheName,prefix,"cacheName");return this.#caches.has(cacheName)}async open(cacheName){webidl.brandCheck(this,_CacheStorage);const prefix="CacheStorage.open";webidl.argumentLengthCheck(arguments,1,prefix);cacheName=webidl.converters.DOMString(cacheName,prefix,"cacheName");if(this.#caches.has(cacheName)){const cache4=this.#caches.get(cacheName);return new Cache(kConstruct,cache4)}const cache3=[];this.#caches.set(cacheName,cache3);return new Cache(kConstruct,cache3)}async delete(cacheName){webidl.brandCheck(this,_CacheStorage);const prefix="CacheStorage.delete";webidl.argumentLengthCheck(arguments,1,prefix);cacheName=webidl.converters.DOMString(cacheName,prefix,"cacheName");return this.#caches.delete(cacheName)}async keys(){webidl.brandCheck(this,_CacheStorage);const keys=this.#caches.keys();return[...keys]}};Object.defineProperties(CacheStorage.prototype,{[Symbol.toStringTag]:{value:"CacheStorage",configurable:true},match:kEnumerableProperty,has:kEnumerableProperty,open:kEnumerableProperty,delete:kEnumerableProperty,keys:kEnumerableProperty});module.exports={CacheStorage}}});var require_constants4=__commonJS({"node_modules/undici/lib/web/cookies/constants.js"(exports,module){"use strict";var maxAttributeValueSize=1024;var maxNameValuePairSize=4096;module.exports={maxAttributeValueSize,maxNameValuePairSize}}});var require_util4=__commonJS({"node_modules/undici/lib/web/cookies/util.js"(exports,module){"use strict";function isCTLExcludingHtab(value){for(let i=0;i<value.length;++i){const code=value.charCodeAt(i);if(code>=0&&code<=8||code>=10&&code<=31||code===127){return true}}return false}function validateCookieName(name){for(let i=0;i<name.length;++i){const code=name.charCodeAt(i);if(code<33||code>126||code===34||code===40||code===41||code===60||code===62||code===64||code===44||code===59||code===58||code===92||code===47||code===91||code===93||code===63||code===61||code===123||code===125){throw new Error("Invalid cookie name")}}}function validateCookieValue(value){let len=value.length;let i=0;if(value[0]==='"'){if(len===1||value[len-1]!=='"'){throw new Error("Invalid cookie value")}--len;++i}while(i<len){const code=value.charCodeAt(i++);if(code<33||code>126||code===34||code===44||code===59||code===92){throw new Error("Invalid cookie value")}}}function validateCookiePath(path29){for(let i=0;i<path29.length;++i){const code=path29.charCodeAt(i);if(code<32||code>126||code===59){throw new Error("Invalid cookie path")}}}function isLetterOrDigit(code){return code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122}function validateCookieDomain(domain){if(domain===" "){return}if(domain.length>255){throw new Error("Invalid cookie domain")}let labelLength=0;for(let i=0;i<domain.length;++i){const code=domain.charCodeAt(i);if(code===46){if(labelLength===0){throw new Error("Invalid cookie domain")}if(domain.charCodeAt(i-1)===45){throw new Error("Invalid cookie domain")}labelLength=0;continue}if(labelLength===0&&!isLetterOrDigit(code)){throw new Error("Invalid cookie domain")}if(!isLetterOrDigit(code)&&code!==45){throw new Error("Invalid cookie domain")}if(++labelLength>63){throw new Error("Invalid cookie domain")}}if(labelLength===0||domain.charCodeAt(domain.length-1)===45){throw new Error("Invalid cookie domain")}}var IMFDays=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];var IMFMonths=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var IMFPaddedNumbers=Array(61).fill(0).map((_2,i)=>i.toString().padStart(2,"0"));function toIMFDate(date){if(typeof date==="number"){date=new Date(date)}return`${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`}function validateCookieMaxAge(maxAge){if(maxAge<0){throw new Error("Invalid cookie max-age")}}function stringify(cookie){if(cookie.name.length===0){return null}validateCookieName(cookie.name);validateCookieValue(cookie.value);const out=[`${cookie.name}=${cookie.value}`];if(cookie.name.startsWith("__Secure-")){cookie.secure=true}if(cookie.name.startsWith("__Host-")){cookie.secure=true;cookie.domain=null;cookie.path="/"}if(cookie.secure){out.push("Secure")}if(cookie.httpOnly){out.push("HttpOnly")}if(typeof cookie.maxAge==="number"){validateCookieMaxAge(cookie.maxAge);out.push(`Max-Age=${cookie.maxAge}`)}if(cookie.domain){validateCookieDomain(cookie.domain);out.push(`Domain=${cookie.domain}`)}if(cookie.path){validateCookiePath(cookie.path);out.push(`Path=${cookie.path}`)}if(cookie.expires&&cookie.expires.toString()!=="Invalid Date"){out.push(`Expires=${toIMFDate(cookie.expires)}`)}if(cookie.sameSite){out.push(`SameSite=${cookie.sameSite}`)}for(const part of cookie.unparsed){if(!part.includes("=")){throw new Error("Invalid unparsed")}const[key,...value]=part.split("=");const trimmedKey=key.trim();const joinedValue=value.join("=");validateCookieName(trimmedKey);validateCookieValue(joinedValue);out.push(`${trimmedKey}=${joinedValue}`)}return out.join("; ")}module.exports={isCTLExcludingHtab,validateCookieName,validateCookiePath,validateCookieValue,toIMFDate,stringify}}});var require_parse=__commonJS({"node_modules/undici/lib/web/cookies/parse.js"(exports,module){"use strict";var{collectASequenceOfCodePointsFast}=require_infra();var{maxNameValuePairSize,maxAttributeValueSize}=require_constants4();var{isCTLExcludingHtab}=require_util4();var assert=__require("assert");function parseSetCookie(header){if(isCTLExcludingHtab(header)){return null}let nameValuePair="";let unparsedAttributes="";let name="";let value="";if(header.includes(";")){const position={position:0};nameValuePair=collectASequenceOfCodePointsFast(";",header,position);unparsedAttributes=header.slice(position.position)}else{nameValuePair=header}if(!nameValuePair.includes("=")){value=nameValuePair}else{const position={position:0};name=collectASequenceOfCodePointsFast("=",nameValuePair,position);value=nameValuePair.slice(position.position+1)}name=name.trim();value=value.trim();if(name.length+value.length>maxNameValuePairSize){return null}return{name,value,...parseUnparsedAttributes(unparsedAttributes)}}function parseUnparsedAttributes(unparsedAttributes,cookieAttributeList={}){if(unparsedAttributes.length===0){return cookieAttributeList}assert(unparsedAttributes[0]===";");unparsedAttributes=unparsedAttributes.slice(1);let cookieAv="";if(unparsedAttributes.includes(";")){cookieAv=collectASequenceOfCodePointsFast(";",unparsedAttributes,{position:0});unparsedAttributes=unparsedAttributes.slice(cookieAv.length)}else{cookieAv=unparsedAttributes;unparsedAttributes=""}let attributeName="";let attributeValue="";if(cookieAv.includes("=")){const position={position:0};attributeName=collectASequenceOfCodePointsFast("=",cookieAv,position);attributeValue=cookieAv.slice(position.position+1)}else{attributeName=cookieAv}attributeName=attributeName.trim();attributeValue=attributeValue.trim();if(attributeValue.length>maxAttributeValueSize){return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}const attributeNameLowercase=attributeName.toLowerCase();if(attributeNameLowercase==="expires"){const expiryTime=new Date(attributeValue);cookieAttributeList.expires=expiryTime}else if(attributeNameLowercase==="max-age"){const charCode=attributeValue.charCodeAt(0);if((charCode<48||charCode>57)&&attributeValue[0]!=="-"){return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}if(!/^\d+$/.test(attributeValue)){return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}const deltaSeconds=Number(attributeValue);cookieAttributeList.maxAge=deltaSeconds}else if(attributeNameLowercase==="domain"){let cookieDomain=attributeValue;if(cookieDomain[0]==="."){cookieDomain=cookieDomain.slice(1)}cookieDomain=cookieDomain.toLowerCase();cookieAttributeList.domain=cookieDomain}else if(attributeNameLowercase==="path"){let cookiePath="";if(attributeValue.length===0||attributeValue[0]!=="/"){cookiePath="/"}else{cookiePath=attributeValue}cookieAttributeList.path=cookiePath}else if(attributeNameLowercase==="secure"){cookieAttributeList.secure=true}else if(attributeNameLowercase==="httponly"){cookieAttributeList.httpOnly=true}else if(attributeNameLowercase==="samesite"){const attributeValueLowercase=attributeValue.toLowerCase();if(attributeValueLowercase==="none"){cookieAttributeList.sameSite="None"}else if(attributeValueLowercase==="strict"){cookieAttributeList.sameSite="Strict"}else if(attributeValueLowercase==="lax"){cookieAttributeList.sameSite="Lax"}}else{cookieAttributeList.unparsed??=[];cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)}return parseUnparsedAttributes(unparsedAttributes,cookieAttributeList)}module.exports={parseSetCookie,parseUnparsedAttributes}}});var require_cookies=__commonJS({"node_modules/undici/lib/web/cookies/index.js"(exports,module){"use strict";var{parseSetCookie}=require_parse();var{stringify}=require_util4();var{webidl}=require_webidl();var{Headers:Headers2}=require_headers();var brandChecks=webidl.brandCheckMultiple([Headers2,globalThis.Headers].filter(Boolean));function getCookies(headers){webidl.argumentLengthCheck(arguments,1,"getCookies");brandChecks(headers);const cookie=headers.get("cookie");const out={};if(!cookie){return out}for(const piece of cookie.split(";")){const[name,...value]=piece.split("=");out[name.trim()]=value.join("=")}return out}function deleteCookie(headers,name,attributes){brandChecks(headers);const prefix="deleteCookie";webidl.argumentLengthCheck(arguments,2,prefix);name=webidl.converters.DOMString(name,prefix,"name");attributes=webidl.converters.DeleteCookieAttributes(attributes);setCookie(headers,{name,value:"",expires:new Date(0),...attributes})}function getSetCookies(headers){webidl.argumentLengthCheck(arguments,1,"getSetCookies");brandChecks(headers);const cookies=headers.getSetCookie();if(!cookies){return[]}return cookies.map(pair=>parseSetCookie(pair))}function parseCookie(cookie){cookie=webidl.converters.DOMString(cookie);return parseSetCookie(cookie)}function setCookie(headers,cookie){webidl.argumentLengthCheck(arguments,2,"setCookie");brandChecks(headers);cookie=webidl.converters.Cookie(cookie);const str=stringify(cookie);if(str){headers.append("set-cookie",str,true)}}webidl.converters.DeleteCookieAttributes=webidl.dictionaryConverter([{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"path",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"domain",defaultValue:()=>null}]);webidl.converters.Cookie=webidl.dictionaryConverter([{converter:webidl.converters.DOMString,key:"name"},{converter:webidl.converters.DOMString,key:"value"},{converter:webidl.nullableConverter(value=>{if(typeof value==="number"){return webidl.converters["unsigned long long"](value)}return new Date(value)}),key:"expires",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters["long long"]),key:"maxAge",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"domain",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.DOMString),key:"path",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.boolean),key:"secure",defaultValue:()=>null},{converter:webidl.nullableConverter(webidl.converters.boolean),key:"httpOnly",defaultValue:()=>null},{converter:webidl.converters.USVString,key:"sameSite",allowedValues:["Strict","Lax","None"]},{converter:webidl.sequenceConverter(webidl.converters.DOMString),key:"unparsed",defaultValue:()=>[]}]);module.exports={getCookies,deleteCookie,getSetCookies,setCookie,parseCookie}}});var require_events=__commonJS({"node_modules/undici/lib/web/websocket/events.js"(exports,module){"use strict";var{webidl}=require_webidl();var{kEnumerableProperty}=require_util();var{kConstruct}=require_symbols();var MessageEvent=class _MessageEvent extends Event{#eventInit;constructor(type,eventInitDict={}){if(type===kConstruct){super(arguments[1],arguments[2]);webidl.util.markAsUncloneable(this);return}const prefix="MessageEvent constructor";webidl.argumentLengthCheck(arguments,1,prefix);type=webidl.converters.DOMString(type,prefix,"type");eventInitDict=webidl.converters.MessageEventInit(eventInitDict,prefix,"eventInitDict");super(type,eventInitDict);this.#eventInit=eventInitDict;webidl.util.markAsUncloneable(this)}get data(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.data}get origin(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.origin}get lastEventId(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.lastEventId}get source(){webidl.brandCheck(this,_MessageEvent);return this.#eventInit.source}get ports(){webidl.brandCheck(this,_MessageEvent);if(!Object.isFrozen(this.#eventInit.ports)){Object.freeze(this.#eventInit.ports)}return this.#eventInit.ports}initMessageEvent(type,bubbles=false,cancelable=false,data=null,origin="",lastEventId="",source=null,ports=[]){webidl.brandCheck(this,_MessageEvent);webidl.argumentLengthCheck(arguments,1,"MessageEvent.initMessageEvent");return new _MessageEvent(type,{bubbles,cancelable,data,origin,lastEventId,source,ports})}static createFastMessageEvent(type,init){const messageEvent=new _MessageEvent(kConstruct,type,init);messageEvent.#eventInit=init;messageEvent.#eventInit.data??=null;messageEvent.#eventInit.origin??="";messageEvent.#eventInit.lastEventId??="";messageEvent.#eventInit.source??=null;messageEvent.#eventInit.ports??=[];return messageEvent}};var{createFastMessageEvent}=MessageEvent;delete MessageEvent.createFastMessageEvent;var CloseEvent=class _CloseEvent extends Event{#eventInit;constructor(type,eventInitDict={}){const prefix="CloseEvent constructor";webidl.argumentLengthCheck(arguments,1,prefix);type=webidl.converters.DOMString(type,prefix,"type");eventInitDict=webidl.converters.CloseEventInit(eventInitDict);super(type,eventInitDict);this.#eventInit=eventInitDict;webidl.util.markAsUncloneable(this)}get wasClean(){webidl.brandCheck(this,_CloseEvent);return this.#eventInit.wasClean}get code(){webidl.brandCheck(this,_CloseEvent);return this.#eventInit.code}get reason(){webidl.brandCheck(this,_CloseEvent);return this.#eventInit.reason}};var ErrorEvent=class _ErrorEvent extends Event{#eventInit;constructor(type,eventInitDict){const prefix="ErrorEvent constructor";webidl.argumentLengthCheck(arguments,1,prefix);super(type,eventInitDict);webidl.util.markAsUncloneable(this);type=webidl.converters.DOMString(type,prefix,"type");eventInitDict=webidl.converters.ErrorEventInit(eventInitDict??{});this.#eventInit=eventInitDict}get message(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.message}get filename(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.filename}get lineno(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.lineno}get colno(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.colno}get error(){webidl.brandCheck(this,_ErrorEvent);return this.#eventInit.error}};Object.defineProperties(MessageEvent.prototype,{[Symbol.toStringTag]:{value:"MessageEvent",configurable:true},data:kEnumerableProperty,origin:kEnumerableProperty,lastEventId:kEnumerableProperty,source:kEnumerableProperty,ports:kEnumerableProperty,initMessageEvent:kEnumerableProperty});Object.defineProperties(CloseEvent.prototype,{[Symbol.toStringTag]:{value:"CloseEvent",configurable:true},reason:kEnumerableProperty,code:kEnumerableProperty,wasClean:kEnumerableProperty});Object.defineProperties(ErrorEvent.prototype,{[Symbol.toStringTag]:{value:"ErrorEvent",configurable:true},message:kEnumerableProperty,filename:kEnumerableProperty,lineno:kEnumerableProperty,colno:kEnumerableProperty,error:kEnumerableProperty});webidl.converters.MessagePort=webidl.interfaceConverter(webidl.is.MessagePort,"MessagePort");webidl.converters["sequence<MessagePort>"]=webidl.sequenceConverter(webidl.converters.MessagePort);var eventInit=[{key:"bubbles",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"cancelable",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"composed",converter:webidl.converters.boolean,defaultValue:()=>false}];webidl.converters.MessageEventInit=webidl.dictionaryConverter([...eventInit,{key:"data",converter:webidl.converters.any,defaultValue:()=>null},{key:"origin",converter:webidl.converters.USVString,defaultValue:()=>""},{key:"lastEventId",converter:webidl.converters.DOMString,defaultValue:()=>""},{key:"source",converter:webidl.nullableConverter(webidl.converters.MessagePort),defaultValue:()=>null},{key:"ports",converter:webidl.converters["sequence<MessagePort>"],defaultValue:()=>[]}]);webidl.converters.CloseEventInit=webidl.dictionaryConverter([...eventInit,{key:"wasClean",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"code",converter:webidl.converters["unsigned short"],defaultValue:()=>0},{key:"reason",converter:webidl.converters.USVString,defaultValue:()=>""}]);webidl.converters.ErrorEventInit=webidl.dictionaryConverter([...eventInit,{key:"message",converter:webidl.converters.DOMString,defaultValue:()=>""},{key:"filename",converter:webidl.converters.USVString,defaultValue:()=>""},{key:"lineno",converter:webidl.converters["unsigned long"],defaultValue:()=>0},{key:"colno",converter:webidl.converters["unsigned long"],defaultValue:()=>0},{key:"error",converter:webidl.converters.any}]);module.exports={MessageEvent,CloseEvent,ErrorEvent,createFastMessageEvent}}});var require_constants5=__commonJS({"node_modules/undici/lib/web/websocket/constants.js"(exports,module){"use strict";var uid="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";var staticPropertyDescriptors={enumerable:true,writable:false,configurable:false};var states={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};var sentCloseFrameState={SENT:1,RECEIVED:2};var opcodes={CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10};var maxUnsigned16Bit=65535;var parserStates={INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4};var emptyBuffer=Buffer.allocUnsafe(0);var sendHints={text:1,typedArray:2,arrayBuffer:3,blob:4};module.exports={uid,sentCloseFrameState,staticPropertyDescriptors,states,opcodes,maxUnsigned16Bit,parserStates,emptyBuffer,sendHints}}});var require_util5=__commonJS({"node_modules/undici/lib/web/websocket/util.js"(exports,module){"use strict";var{states,opcodes}=require_constants5();var{isUtf8}=__require("buffer");var{removeHTTPWhitespace}=require_data_url();var{collectASequenceOfCodePointsFast}=require_infra();function isConnecting(readyState){return readyState===states.CONNECTING}function isEstablished(readyState){return readyState===states.OPEN}function isClosing(readyState){return readyState===states.CLOSING}function isClosed(readyState){return readyState===states.CLOSED}function fireEvent(e,target,eventFactory=(type,init)=>new Event(type,init),eventInitDict={}){const event=eventFactory(e,eventInitDict);target.dispatchEvent(event)}function websocketMessageReceived(handler,type,data){handler.onMessage(type,data)}function toArrayBuffer(buffer){if(buffer.byteLength===buffer.buffer.byteLength){return buffer.buffer}return new Uint8Array(buffer).buffer}function isValidSubprotocol(protocol){if(protocol.length===0){return false}for(let i=0;i<protocol.length;++i){const code=protocol.charCodeAt(i);if(code<33||code>126||code===34||code===40||code===41||code===44||code===47||code===58||code===59||code===60||code===61||code===62||code===63||code===64||code===91||code===92||code===93||code===123||code===125){return false}}return true}function isValidStatusCode(code){if(code>=1e3&&code<1015){return code!==1004&&code!==1005&&code!==1006}return code>=3e3&&code<=4999}function isControlFrame(opcode){return opcode===opcodes.CLOSE||opcode===opcodes.PING||opcode===opcodes.PONG}function isContinuationFrame(opcode){return opcode===opcodes.CONTINUATION}function isTextBinaryFrame(opcode){return opcode===opcodes.TEXT||opcode===opcodes.BINARY}function isValidOpcode(opcode){return isTextBinaryFrame(opcode)||isContinuationFrame(opcode)||isControlFrame(opcode)}function parseExtensions(extensions){const position={position:0};const extensionList=new Map;while(position.position<extensions.length){const pair=collectASequenceOfCodePointsFast(";",extensions,position);const[name,value=""]=pair.split("=",2);extensionList.set(removeHTTPWhitespace(name,true,false),removeHTTPWhitespace(value,false,true));position.position++}return extensionList}function isValidClientWindowBits(value){if(value.length===0){return false}for(let i=0;i<value.length;i++){const byte=value.charCodeAt(i);if(byte<48||byte>57){return false}}const num=Number.parseInt(value,10);return num>=8&&num<=15}function getURLRecord(url,baseURL){let urlRecord;try{urlRecord=new URL(url,baseURL)}catch(e){throw new DOMException(e,"SyntaxError")}if(urlRecord.protocol==="http:"){urlRecord.protocol="ws:"}else if(urlRecord.protocol==="https:"){urlRecord.protocol="wss:"}if(urlRecord.protocol!=="ws:"&&urlRecord.protocol!=="wss:"){throw new DOMException("expected a ws: or wss: url","SyntaxError")}if(urlRecord.hash.length||urlRecord.href.endsWith("#")){throw new DOMException("hash","SyntaxError")}return urlRecord}function validateCloseCodeAndReason(code,reason){if(code!==null){if(code!==1e3&&(code<3e3||code>4999)){throw new DOMException("invalid code","InvalidAccessError")}}if(reason!==null){const reasonBytesLength=Buffer.byteLength(reason);if(reasonBytesLength>123){throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`,"SyntaxError")}}}var utf8Decode=(()=>{if(typeof process.versions.icu==="string"){const fatalDecoder=new TextDecoder("utf-8",{fatal:true});return fatalDecoder.decode.bind(fatalDecoder)}return function(buffer){if(isUtf8(buffer)){return buffer.toString("utf-8")}throw new TypeError("Invalid utf-8 received.")}})();module.exports={isConnecting,isEstablished,isClosing,isClosed,fireEvent,isValidSubprotocol,isValidStatusCode,websocketMessageReceived,utf8Decode,isControlFrame,isContinuationFrame,isTextBinaryFrame,isValidOpcode,parseExtensions,isValidClientWindowBits,toArrayBuffer,getURLRecord,validateCloseCodeAndReason}}});var require_frame=__commonJS({"node_modules/undici/lib/web/websocket/frame.js"(exports,module){"use strict";var{runtimeFeatures}=require_runtime_features();var{maxUnsigned16Bit,opcodes}=require_constants5();var BUFFER_SIZE=8*1024;var buffer=null;var bufIdx=BUFFER_SIZE;var randomFillSync=runtimeFeatures.has("crypto")?__require("crypto").randomFillSync:function randomFillSync2(buffer2,_offset,_size){for(let i=0;i<buffer2.length;++i){buffer2[i]=Math.random()*255|0}return buffer2};function generateMask(){if(bufIdx===BUFFER_SIZE){bufIdx=0;randomFillSync(buffer??=Buffer.allocUnsafeSlow(BUFFER_SIZE),0,BUFFER_SIZE)}return[buffer[bufIdx++],buffer[bufIdx++],buffer[bufIdx++],buffer[bufIdx++]]}var WebsocketFrameSend=class{constructor(data){this.frameData=data}createFrame(opcode){const frameData=this.frameData;const maskKey=generateMask();const bodyLength=frameData?.byteLength??0;let payloadLength=bodyLength;let offset=6;if(bodyLength>maxUnsigned16Bit){offset+=8;payloadLength=127}else if(bodyLength>125){offset+=2;payloadLength=126}const buffer2=Buffer.allocUnsafe(bodyLength+offset);buffer2[0]=buffer2[1]=0;buffer2[0]|=128;buffer2[0]=(buffer2[0]&240)+opcode;buffer2[offset-4]=maskKey[0];buffer2[offset-3]=maskKey[1];buffer2[offset-2]=maskKey[2];buffer2[offset-1]=maskKey[3];buffer2[1]=payloadLength;if(payloadLength===126){buffer2.writeUInt16BE(bodyLength,2)}else if(payloadLength===127){buffer2[2]=buffer2[3]=0;buffer2.writeUIntBE(bodyLength,4,6)}buffer2[1]|=128;for(let i=0;i<bodyLength;++i){buffer2[offset+i]=frameData[i]^maskKey[i&3]}return buffer2}static createFastTextFrame(buffer2){const maskKey=generateMask();const bodyLength=buffer2.length;for(let i=0;i<bodyLength;++i){buffer2[i]^=maskKey[i&3]}let payloadLength=bodyLength;let offset=6;if(bodyLength>maxUnsigned16Bit){offset+=8;payloadLength=127}else if(bodyLength>125){offset+=2;payloadLength=126}const head=Buffer.allocUnsafeSlow(offset);head[0]=128|opcodes.TEXT;head[1]=payloadLength|128;head[offset-4]=maskKey[0];head[offset-3]=maskKey[1];head[offset-2]=maskKey[2];head[offset-1]=maskKey[3];if(payloadLength===126){head.writeUInt16BE(bodyLength,2)}else if(payloadLength===127){head[2]=head[3]=0;head.writeUIntBE(bodyLength,4,6)}return[head,buffer2]}};module.exports={WebsocketFrameSend,generateMask}}});var require_connection=__commonJS({"node_modules/undici/lib/web/websocket/connection.js"(exports,module){"use strict";var{uid,states,sentCloseFrameState,emptyBuffer,opcodes}=require_constants5();var{parseExtensions,isClosed,isClosing,isEstablished,isConnecting,validateCloseCodeAndReason}=require_util5();var{makeRequest}=require_request2();var{fetching}=require_fetch();var{Headers:Headers2,getHeadersList}=require_headers();var{getDecodeSplit}=require_util2();var{WebsocketFrameSend}=require_frame();var assert=__require("assert");var{runtimeFeatures}=require_runtime_features();var crypto5=runtimeFeatures.has("crypto")?__require("crypto"):null;var warningEmitted=false;function establishWebSocketConnection(url,protocols,client,handler,options){const requestURL=url;requestURL.protocol=url.protocol==="ws:"?"http:":"https:";const request=makeRequest({urlList:[requestURL],client,serviceWorkers:"none",referrer:"no-referrer",mode:"websocket",credentials:"include",cache:"no-store",redirect:"error",useURLCredentials:true});if(options.headers){const headersList=getHeadersList(new Headers2(options.headers));request.headersList=headersList}const keyValue=crypto5.randomBytes(16).toString("base64");request.headersList.append("sec-websocket-key",keyValue,true);request.headersList.append("sec-websocket-version","13",true);for(const protocol of protocols){request.headersList.append("sec-websocket-protocol",protocol,true)}const permessageDeflate="permessage-deflate; client_max_window_bits";request.headersList.append("sec-websocket-extensions",permessageDeflate,true);const controller=fetching({request,useParallelQueue:true,dispatcher:options.dispatcher,processResponse(response){if(response.type==="error"||response.status!==101){if(response.socket?.session==null){failWebsocketConnection(handler,1002,"Received network error or non-101 status code.",response.error);return}if(response.status!==200){failWebsocketConnection(handler,1002,"Received network error or non-200 status code.",response.error);return}}if(warningEmitted===false&&response.socket?.session!=null){process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.","ExperimentalWarning");warningEmitted=true}if(protocols.length!==0&&!response.headersList.get("Sec-WebSocket-Protocol")){failWebsocketConnection(handler,1002,"Server did not respond with sent protocols.");return}if(response.socket.session==null&&response.headersList.get("Upgrade")?.toLowerCase()!=="websocket"){failWebsocketConnection(handler,1002,'Server did not set Upgrade header to "websocket".');return}if(response.socket.session==null&&response.headersList.get("Connection")?.toLowerCase()!=="upgrade"){failWebsocketConnection(handler,1002,'Server did not set Connection header to "upgrade".');return}const secWSAccept=response.headersList.get("Sec-WebSocket-Accept");const digest=crypto5.hash("sha1",keyValue+uid,"base64");if(secWSAccept!==digest){failWebsocketConnection(handler,1002,"Incorrect hash received in Sec-WebSocket-Accept header.");return}const secExtension=response.headersList.get("Sec-WebSocket-Extensions");let extensions;if(secExtension!==null){extensions=parseExtensions(secExtension);if(!extensions.has("permessage-deflate")){failWebsocketConnection(handler,1002,"Sec-WebSocket-Extensions header does not match.");return}}const secProtocol=response.headersList.get("Sec-WebSocket-Protocol");if(secProtocol!==null){const requestProtocols=getDecodeSplit("sec-websocket-protocol",request.headersList);if(!requestProtocols.includes(secProtocol)){failWebsocketConnection(handler,1002,"Protocol was not set in the opening handshake.");return}}response.socket.on("data",handler.onSocketData);response.socket.on("close",handler.onSocketClose);response.socket.on("error",handler.onSocketError);handler.wasEverConnected=true;handler.onConnectionEstablished(response,extensions)}});return controller}function closeWebSocketConnection(object,code,reason,validate=false){code??=null;reason??="";if(validate)validateCloseCodeAndReason(code,reason);if(isClosed(object.readyState)||isClosing(object.readyState)){}else if(!isEstablished(object.readyState)){failWebsocketConnection(object);object.readyState=states.CLOSING}else if(!object.closeState.has(sentCloseFrameState.SENT)&&!object.closeState.has(sentCloseFrameState.RECEIVED)){const frame=new WebsocketFrameSend;if(reason.length!==0&&code===null){code=1e3}assert(code===null||Number.isInteger(code));if(code===null&&reason.length===0){frame.frameData=emptyBuffer}else if(code!==null&&reason===null){frame.frameData=Buffer.allocUnsafe(2);frame.frameData.writeUInt16BE(code,0)}else if(code!==null&&reason!==null){frame.frameData=Buffer.allocUnsafe(2+Buffer.byteLength(reason));frame.frameData.writeUInt16BE(code,0);frame.frameData.write(reason,2,"utf-8")}else{frame.frameData=emptyBuffer}object.socket.write(frame.createFrame(opcodes.CLOSE));object.closeState.add(sentCloseFrameState.SENT);object.readyState=states.CLOSING}else{object.readyState=states.CLOSING}}function failWebsocketConnection(handler,code,reason,cause){if(isEstablished(handler.readyState)){closeWebSocketConnection(handler,code,reason,false)}handler.controller.abort();if(isConnecting(handler.readyState)){handler.onSocketClose()}else if(handler.socket?.destroyed===false){handler.socket.destroy()}}module.exports={establishWebSocketConnection,failWebsocketConnection,closeWebSocketConnection}}});var require_permessage_deflate=__commonJS({"node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports,module){"use strict";var{createInflateRaw,Z_DEFAULT_WINDOWBITS}=__require("zlib");var{isValidClientWindowBits}=require_util5();var{MessageSizeExceededError}=require_errors();var tail=Buffer.from([0,0,255,255]);var kBuffer=Symbol("kBuffer");var kLength=Symbol("kLength");var PerMessageDeflate=class{#inflate;#options={};#maxPayloadSize=0;constructor(extensions,options){this.#options.serverNoContextTakeover=extensions.has("server_no_context_takeover");this.#options.serverMaxWindowBits=extensions.get("server_max_window_bits");this.#maxPayloadSize=options.maxPayloadSize}decompress(chunk,fin,callback){if(!this.#inflate){let windowBits=Z_DEFAULT_WINDOWBITS;if(this.#options.serverMaxWindowBits){if(!isValidClientWindowBits(this.#options.serverMaxWindowBits)){callback(new Error("Invalid server_max_window_bits"));return}windowBits=Number.parseInt(this.#options.serverMaxWindowBits)}try{this.#inflate=createInflateRaw({windowBits})}catch(err){callback(err);return}this.#inflate[kBuffer]=[];this.#inflate[kLength]=0;this.#inflate.on("data",data=>{this.#inflate[kLength]+=data.length;if(this.#maxPayloadSize>0&&this.#inflate[kLength]>this.#maxPayloadSize){callback(new MessageSizeExceededError);this.#inflate.removeAllListeners();this.#inflate=null;return}this.#inflate[kBuffer].push(data)});this.#inflate.on("error",err=>{this.#inflate=null;callback(err)})}this.#inflate.write(chunk);if(fin){this.#inflate.write(tail)}this.#inflate.flush(()=>{if(!this.#inflate){return}const full=Buffer.concat(this.#inflate[kBuffer],this.#inflate[kLength]);this.#inflate[kBuffer].length=0;this.#inflate[kLength]=0;callback(null,full)})}};module.exports={PerMessageDeflate}}});var require_receiver=__commonJS({"node_modules/undici/lib/web/websocket/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream");var assert=__require("assert");var{parserStates,opcodes,states,emptyBuffer,sentCloseFrameState}=require_constants5();var{isValidStatusCode,isValidOpcode,websocketMessageReceived,utf8Decode,isControlFrame,isTextBinaryFrame,isContinuationFrame}=require_util5();var{failWebsocketConnection}=require_connection();var{WebsocketFrameSend}=require_frame();var{PerMessageDeflate}=require_permessage_deflate();var{MessageSizeExceededError}=require_errors();var ByteParser=class extends Writable{#buffers=[];#fragmentsBytes=0;#byteOffset=0;#loop=false;#state=parserStates.INFO;#info={};#fragments=[];#extensions;#handler;#maxFragments;#maxPayloadSize;constructor(handler,extensions,options={}){super();this.#handler=handler;this.#extensions=extensions==null?new Map:extensions;this.#maxFragments=options.maxFragments??0;this.#maxPayloadSize=options.maxPayloadSize??0;if(this.#extensions.has("permessage-deflate")){this.#extensions.set("permessage-deflate",new PerMessageDeflate(extensions,options))}}_write(chunk,_2,callback){this.#buffers.push(chunk);this.#byteOffset+=chunk.length;this.#loop=true;this.run(callback)}#validatePayloadLength(){if(this.#maxPayloadSize>0&&!isControlFrame(this.#info.opcode)&&this.#info.payloadLength+this.#fragmentsBytes>this.#maxPayloadSize){failWebsocketConnection(this.#handler,1009,"Payload size exceeds maximum allowed size");return false}return true}run(callback){while(this.#loop){if(this.#state===parserStates.INFO){if(this.#byteOffset<2){return callback()}const buffer=this.consume(2);const fin=(buffer[0]&128)!==0;const opcode=buffer[0]&15;const masked=(buffer[1]&128)===128;const fragmented=!fin&&opcode!==opcodes.CONTINUATION;const payloadLength=buffer[1]&127;const rsv1=buffer[0]&64;const rsv2=buffer[0]&32;const rsv3=buffer[0]&16;if(!isValidOpcode(opcode)){failWebsocketConnection(this.#handler,1002,"Invalid opcode received");return callback()}if(masked){failWebsocketConnection(this.#handler,1002,"Frame cannot be masked");return callback()}if(rsv1!==0&&!this.#extensions.has("permessage-deflate")){failWebsocketConnection(this.#handler,1002,"Expected RSV1 to be clear.");return}if(rsv2!==0||rsv3!==0){failWebsocketConnection(this.#handler,1002,"RSV1, RSV2, RSV3 must be clear");return}if(fragmented&&!isTextBinaryFrame(opcode)){failWebsocketConnection(this.#handler,1002,"Invalid frame type was fragmented.");return}if(isTextBinaryFrame(opcode)&&this.#fragments.length>0){failWebsocketConnection(this.#handler,1002,"Expected continuation frame");return}if(this.#info.fragmented&&fragmented){failWebsocketConnection(this.#handler,1002,"Fragmented frame exceeded 125 bytes.");return}if((payloadLength>125||fragmented)&&isControlFrame(opcode)){failWebsocketConnection(this.#handler,1002,"Control frame either too large or fragmented");return}if(isContinuationFrame(opcode)&&this.#fragments.length===0&&!this.#info.compressed){failWebsocketConnection(this.#handler,1002,"Unexpected continuation frame");return}if(payloadLength<=125){this.#info.payloadLength=payloadLength;this.#state=parserStates.READ_DATA;if(!this.#validatePayloadLength()){return}}else if(payloadLength===126){this.#state=parserStates.PAYLOADLENGTH_16}else if(payloadLength===127){this.#state=parserStates.PAYLOADLENGTH_64}if(isTextBinaryFrame(opcode)){this.#info.binaryType=opcode;this.#info.compressed=rsv1!==0}this.#info.opcode=opcode;this.#info.masked=masked;this.#info.fin=fin;this.#info.fragmented=fragmented}else if(this.#state===parserStates.PAYLOADLENGTH_16){if(this.#byteOffset<2){return callback()}const buffer=this.consume(2);this.#info.payloadLength=buffer.readUInt16BE(0);this.#state=parserStates.READ_DATA;if(!this.#validatePayloadLength()){return}}else if(this.#state===parserStates.PAYLOADLENGTH_64){if(this.#byteOffset<8){return callback()}const buffer=this.consume(8);const upper=buffer.readUInt32BE(0);const lower=buffer.readUInt32BE(4);if(upper!==0||lower>2**31-1){failWebsocketConnection(this.#handler,1009,"Received payload length > 2^31 bytes.");return}this.#info.payloadLength=lower;this.#state=parserStates.READ_DATA;if(!this.#validatePayloadLength()){return}}else if(this.#state===parserStates.READ_DATA){if(this.#byteOffset<this.#info.payloadLength){return callback()}const body=this.consume(this.#info.payloadLength);if(isControlFrame(this.#info.opcode)){this.#loop=this.parseControlFrame(body);this.#state=parserStates.INFO}else{if(!this.#info.compressed){if(!this.writeFragments(body)){return}if(!this.#info.fragmented&&this.#info.fin){websocketMessageReceived(this.#handler,this.#info.binaryType,this.consumeFragments())}this.#state=parserStates.INFO}else{this.#extensions.get("permessage-deflate").decompress(body,this.#info.fin,(error,data)=>{if(error){const code=error instanceof MessageSizeExceededError?1009:1007;failWebsocketConnection(this.#handler,code,error.message);return}if(!this.writeFragments(data)){return}if(this.#maxPayloadSize>0&&this.#fragmentsBytes>this.#maxPayloadSize){failWebsocketConnection(this.#handler,1009,new MessageSizeExceededError().message);return}if(!this.#info.fin){this.#state=parserStates.INFO;this.#loop=true;this.run(callback);return}websocketMessageReceived(this.#handler,this.#info.binaryType,this.consumeFragments());this.#loop=true;this.#state=parserStates.INFO;this.run(callback)},this.#fragmentsBytes);this.#loop=false;break}}}}}consume(n){if(n>this.#byteOffset){throw new Error("Called consume() before buffers satiated.")}else if(n===0){return emptyBuffer}this.#byteOffset-=n;const first=this.#buffers[0];if(first.length>n){this.#buffers[0]=first.subarray(n,first.length);return first.subarray(0,n)}else if(first.length===n){return this.#buffers.shift()}else{let offset=0;const buffer=Buffer.allocUnsafeSlow(n);while(offset!==n){const next=this.#buffers[0];const length=next.length;if(length+offset===n){buffer.set(this.#buffers.shift(),offset);break}else if(length+offset>n){buffer.set(next.subarray(0,n-offset),offset);this.#buffers[0]=next.subarray(n-offset);break}else{buffer.set(this.#buffers.shift(),offset);offset+=length}}return buffer}}writeFragments(fragment){if(this.#maxFragments>0&&this.#fragments.length===this.#maxFragments){failWebsocketConnection(this.#handler,1008,"Too many message fragments");return false}this.#fragmentsBytes+=fragment.length;this.#fragments.push(fragment);return true}consumeFragments(){const fragments=this.#fragments;if(fragments.length===1){this.#fragmentsBytes=0;return fragments.shift()}let offset=0;const output=Buffer.allocUnsafeSlow(this.#fragmentsBytes);for(let i=0;i<fragments.length;++i){const buffer=fragments[i];output.set(buffer,offset);offset+=buffer.length}this.#fragments=[];this.#fragmentsBytes=0;return output}parseCloseBody(data){assert(data.length!==1);let code;if(data.length>=2){code=data.readUInt16BE(0)}if(code!==void 0&&!isValidStatusCode(code)){return{code:1002,reason:"Invalid status code",error:true}}let reason=data.subarray(2);if(reason[0]===239&&reason[1]===187&&reason[2]===191){reason=reason.subarray(3)}try{reason=utf8Decode(reason)}catch{return{code:1007,reason:"Invalid UTF-8",error:true}}return{code,reason,error:false}}parseControlFrame(body){const{opcode,payloadLength}=this.#info;if(opcode===opcodes.CLOSE){if(payloadLength===1){failWebsocketConnection(this.#handler,1002,"Received close frame with a 1-byte body.");return false}this.#info.closeInfo=this.parseCloseBody(body);if(this.#info.closeInfo.error){const{code,reason}=this.#info.closeInfo;failWebsocketConnection(this.#handler,code,reason);return false}if(!this.#handler.closeState.has(sentCloseFrameState.SENT)&&!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){let body2=emptyBuffer;if(this.#info.closeInfo.code){body2=Buffer.allocUnsafe(2);body2.writeUInt16BE(this.#info.closeInfo.code,0)}const closeFrame=new WebsocketFrameSend(body2);this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE));this.#handler.closeState.add(sentCloseFrameState.SENT)}this.#handler.readyState=states.CLOSING;this.#handler.closeState.add(sentCloseFrameState.RECEIVED);return false}else if(opcode===opcodes.PING){if(!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){const frame=new WebsocketFrameSend(body);this.#handler.socket.write(frame.createFrame(opcodes.PONG));this.#handler.onPing(body)}}else if(opcode===opcodes.PONG){this.#handler.onPong(body)}return true}get closingInfo(){return this.#info.closeInfo}};module.exports={ByteParser}}});var require_sender=__commonJS({"node_modules/undici/lib/web/websocket/sender.js"(exports,module){"use strict";var{WebsocketFrameSend}=require_frame();var{opcodes,sendHints}=require_constants5();var FixedQueue=require_fixed_queue();var SendQueue=class{#queue=new FixedQueue;#running=false;#socket;constructor(socket){this.#socket=socket}add(item,cb,hint){if(hint!==sendHints.blob){if(!this.#running){if(hint===sendHints.text){const{0:head,1:body}=WebsocketFrameSend.createFastTextFrame(item);this.#socket.cork();this.#socket.write(head);this.#socket.write(body,cb);this.#socket.uncork()}else{this.#socket.write(createFrame(item,hint),cb)}}else{const node2={promise:null,callback:cb,frame:createFrame(item,hint)};this.#queue.push(node2)}return}const node={promise:item.arrayBuffer().then(ab=>{node.promise=null;node.frame=createFrame(ab,hint)}),callback:cb,frame:null};this.#queue.push(node);if(!this.#running){this.#run()}}async#run(){this.#running=true;const queue=this.#queue;while(!queue.isEmpty()){const node=queue.shift();if(node.promise!==null){await node.promise}this.#socket.write(node.frame,node.callback);node.callback=node.frame=null}this.#running=false}};function createFrame(data,hint){return new WebsocketFrameSend(toBuffer(data,hint)).createFrame(hint===sendHints.text?opcodes.TEXT:opcodes.BINARY)}function toBuffer(data,hint){switch(hint){case sendHints.text:case sendHints.typedArray:return new Uint8Array(data.buffer,data.byteOffset,data.byteLength);case sendHints.arrayBuffer:case sendHints.blob:return new Uint8Array(data)}}module.exports={SendQueue}}});var require_websocket=__commonJS({"node_modules/undici/lib/web/websocket/websocket.js"(exports,module){"use strict";var{isArrayBuffer}=__require("util/types");var{webidl}=require_webidl();var{URLSerializer}=require_data_url();var{environmentSettingsObject}=require_util2();var{staticPropertyDescriptors,states,sentCloseFrameState,sendHints,opcodes}=require_constants5();var{isConnecting,isEstablished,isClosing,isClosed,isValidSubprotocol,fireEvent,utf8Decode,toArrayBuffer,getURLRecord}=require_util5();var{establishWebSocketConnection,closeWebSocketConnection,failWebsocketConnection}=require_connection();var{ByteParser}=require_receiver();var{kEnumerableProperty}=require_util();var{getGlobalDispatcher}=require_global2();var{ErrorEvent,CloseEvent,createFastMessageEvent}=require_events();var{SendQueue}=require_sender();var{WebsocketFrameSend}=require_frame();var{channels}=require_diagnostics();function getSocketAddress(socket){if(typeof socket?.address==="function"){return socket.address()}if(typeof socket?.session?.socket?.address==="function"){return socket.session.socket.address()}return null}var WebSocket=class _WebSocket extends EventTarget{#events={open:null,error:null,close:null,message:null};#bufferedAmount=0;#protocol="";#extensions="";#sendQueue;#handler={onConnectionEstablished:(response,extensions)=>this.#onConnectionEstablished(response,extensions),onMessage:(opcode,data)=>this.#onMessage(opcode,data),onParserError:err=>failWebsocketConnection(this.#handler,null,err.message),onParserDrain:()=>this.#onParserDrain(),onSocketData:chunk=>{if(!this.#parser.write(chunk)){this.#handler.socket.pause()}},onSocketError:err=>{this.#handler.readyState=states.CLOSING;if(channels.socketError.hasSubscribers){channels.socketError.publish(err)}this.#handler.socket.destroy()},onSocketClose:()=>this.#onSocketClose(),onPing:body=>{if(channels.ping.hasSubscribers){channels.ping.publish({payload:body,websocket:this})}},onPong:body=>{if(channels.pong.hasSubscribers){channels.pong.publish({payload:body,websocket:this})}},readyState:states.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:false};#url;#binaryType;#parser;constructor(url,protocols=[]){super();webidl.util.markAsUncloneable(this);const prefix="WebSocket constructor";webidl.argumentLengthCheck(arguments,1,prefix);const options=webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"](protocols,prefix,"options");url=webidl.converters.USVString(url);protocols=options.protocols;const baseURL=environmentSettingsObject.settingsObject.baseUrl;const urlRecord=getURLRecord(url,baseURL);if(typeof protocols==="string"){protocols=[protocols]}if(protocols.length!==new Set(protocols.map(p2=>p2.toLowerCase())).size){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}if(protocols.length>0&&!protocols.every(p2=>isValidSubprotocol(p2))){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}this.#url=new URL(urlRecord.href);const client=environmentSettingsObject.settingsObject;this.#handler.controller=establishWebSocketConnection(urlRecord,protocols,client,this.#handler,options);this.#handler.readyState=_WebSocket.CONNECTING;this.#binaryType="blob"}close(code=void 0,reason=void 0){webidl.brandCheck(this,_WebSocket);const prefix="WebSocket.close";if(code!==void 0){code=webidl.converters["unsigned short"](code,prefix,"code",webidl.attributes.Clamp)}if(reason!==void 0){reason=webidl.converters.USVString(reason)}code??=null;reason??="";closeWebSocketConnection(this.#handler,code,reason,true)}send(data){webidl.brandCheck(this,_WebSocket);const prefix="WebSocket.send";webidl.argumentLengthCheck(arguments,1,prefix);data=webidl.converters.WebSocketSendData(data,prefix,"data");if(isConnecting(this.#handler.readyState)){throw new DOMException("Sent before connected.","InvalidStateError")}if(!isEstablished(this.#handler.readyState)||isClosing(this.#handler.readyState)){return}if(typeof data==="string"){const buffer=Buffer.from(data);this.#bufferedAmount+=buffer.byteLength;this.#sendQueue.add(buffer,()=>{this.#bufferedAmount-=buffer.byteLength},sendHints.text)}else if(isArrayBuffer(data)){this.#bufferedAmount+=data.byteLength;this.#sendQueue.add(data,()=>{this.#bufferedAmount-=data.byteLength},sendHints.arrayBuffer)}else if(ArrayBuffer.isView(data)){this.#bufferedAmount+=data.byteLength;this.#sendQueue.add(data,()=>{this.#bufferedAmount-=data.byteLength},sendHints.typedArray)}else if(webidl.is.Blob(data)){this.#bufferedAmount+=data.size;this.#sendQueue.add(data,()=>{this.#bufferedAmount-=data.size},sendHints.blob)}}get readyState(){webidl.brandCheck(this,_WebSocket);return this.#handler.readyState}get bufferedAmount(){webidl.brandCheck(this,_WebSocket);return this.#bufferedAmount}get url(){webidl.brandCheck(this,_WebSocket);return URLSerializer(this.#url)}get extensions(){webidl.brandCheck(this,_WebSocket);return this.#extensions}get protocol(){webidl.brandCheck(this,_WebSocket);return this.#protocol}get onopen(){webidl.brandCheck(this,_WebSocket);return this.#events.open}set onopen(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.open){this.removeEventListener("open",this.#events.open)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("open",listener);this.#events.open=fn}else{this.#events.open=null}}get onerror(){webidl.brandCheck(this,_WebSocket);return this.#events.error}set onerror(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.error){this.removeEventListener("error",this.#events.error)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("error",listener);this.#events.error=fn}else{this.#events.error=null}}get onclose(){webidl.brandCheck(this,_WebSocket);return this.#events.close}set onclose(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.close){this.removeEventListener("close",this.#events.close)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("close",listener);this.#events.close=fn}else{this.#events.close=null}}get onmessage(){webidl.brandCheck(this,_WebSocket);return this.#events.message}set onmessage(fn){webidl.brandCheck(this,_WebSocket);if(this.#events.message){this.removeEventListener("message",this.#events.message)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("message",listener);this.#events.message=fn}else{this.#events.message=null}}get binaryType(){webidl.brandCheck(this,_WebSocket);return this.#binaryType}set binaryType(type){webidl.brandCheck(this,_WebSocket);if(type!=="blob"&&type!=="arraybuffer"){this.#binaryType="blob"}else{this.#binaryType=type}}#onConnectionEstablished(response,parsedExtensions){this.#handler.socket=response.socket;const webSocketOptions=this.#handler.controller.dispatcher?.webSocketOptions;const maxFragments=webSocketOptions?.maxFragments;const maxPayloadSize=webSocketOptions?.maxPayloadSize;const parser=new ByteParser(this.#handler,parsedExtensions,{maxFragments,maxPayloadSize});parser.on("drain",()=>this.#handler.onParserDrain());parser.on("error",err=>this.#handler.onParserError(err));this.#parser=parser;this.#sendQueue=new SendQueue(response.socket);this.#handler.readyState=states.OPEN;const extensions=response.headersList.get("sec-websocket-extensions");if(extensions!==null){this.#extensions=extensions}const protocol=response.headersList.get("sec-websocket-protocol");if(protocol!==null){this.#protocol=protocol}fireEvent("open",this);if(channels.open.hasSubscribers){const headers=response.headersList.entries;channels.open.publish({address:getSocketAddress(response.socket),protocol:this.#protocol,extensions:this.#extensions,websocket:this,handshakeResponse:{status:response.status,statusText:response.statusText,headers}})}}#onMessage(type,data){if(this.#handler.readyState!==states.OPEN){return}let dataForEvent;if(type===opcodes.TEXT){try{dataForEvent=utf8Decode(data)}catch{failWebsocketConnection(this.#handler,1007,"Received invalid UTF-8 in text frame.");return}}else if(type===opcodes.BINARY){if(this.#binaryType==="blob"){dataForEvent=new Blob([data])}else{dataForEvent=toArrayBuffer(data)}}fireEvent("message",this,createFastMessageEvent,{origin:this.#url.origin,data:dataForEvent})}#onParserDrain(){this.#handler.socket.resume()}#onSocketClose(){const wasClean=this.#handler.closeState.has(sentCloseFrameState.SENT)&&this.#handler.closeState.has(sentCloseFrameState.RECEIVED);let code=1005;let reason="";const result=this.#parser?.closingInfo;if(result&&!result.error){code=result.code??1005;reason=result.reason}this.#handler.readyState=states.CLOSED;if(!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){code=1006;fireEvent("error",this,(type,init)=>new ErrorEvent(type,init),{error:new TypeError(reason)})}fireEvent("close",this,(type,init)=>new CloseEvent(type,init),{wasClean,code,reason});if(channels.close.hasSubscribers){channels.close.publish({websocket:this,code,reason})}}static ping(ws2,buffer){if(Buffer.isBuffer(buffer)){if(buffer.length>125){throw new TypeError("A PING frame cannot have a body larger than 125 bytes.")}}else if(buffer!==void 0){throw new TypeError("Expected buffer payload")}const readyState=ws2.#handler.readyState;if(isEstablished(readyState)&&!isClosing(readyState)&&!isClosed(readyState)){const frame=new WebsocketFrameSend(buffer);ws2.#handler.socket.write(frame.createFrame(opcodes.PING))}}};var{ping}=WebSocket;Reflect.deleteProperty(WebSocket,"ping");WebSocket.CONNECTING=WebSocket.prototype.CONNECTING=states.CONNECTING;WebSocket.OPEN=WebSocket.prototype.OPEN=states.OPEN;WebSocket.CLOSING=WebSocket.prototype.CLOSING=states.CLOSING;WebSocket.CLOSED=WebSocket.prototype.CLOSED=states.CLOSED;Object.defineProperties(WebSocket.prototype,{CONNECTING:staticPropertyDescriptors,OPEN:staticPropertyDescriptors,CLOSING:staticPropertyDescriptors,CLOSED:staticPropertyDescriptors,url:kEnumerableProperty,readyState:kEnumerableProperty,bufferedAmount:kEnumerableProperty,onopen:kEnumerableProperty,onerror:kEnumerableProperty,onclose:kEnumerableProperty,close:kEnumerableProperty,onmessage:kEnumerableProperty,binaryType:kEnumerableProperty,send:kEnumerableProperty,extensions:kEnumerableProperty,protocol:kEnumerableProperty,[Symbol.toStringTag]:{value:"WebSocket",writable:false,enumerable:false,configurable:true}});Object.defineProperties(WebSocket,{CONNECTING:staticPropertyDescriptors,OPEN:staticPropertyDescriptors,CLOSING:staticPropertyDescriptors,CLOSED:staticPropertyDescriptors});webidl.converters["sequence<DOMString>"]=webidl.sequenceConverter(webidl.converters.DOMString);webidl.converters["DOMString or sequence<DOMString>"]=function(V2,prefix,argument){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT&&Symbol.iterator in V2){return webidl.converters["sequence<DOMString>"](V2)}return webidl.converters.DOMString(V2,prefix,argument)};webidl.converters.WebSocketInit=webidl.dictionaryConverter([{key:"protocols",converter:webidl.converters["DOMString or sequence<DOMString>"],defaultValue:()=>[]},{key:"dispatcher",converter:webidl.converters.any,defaultValue:()=>getGlobalDispatcher()},{key:"headers",converter:webidl.nullableConverter(webidl.converters.HeadersInit)}]);webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"]=function(V2){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT&&!(Symbol.iterator in V2)){return webidl.converters.WebSocketInit(V2)}return{protocols:webidl.converters["DOMString or sequence<DOMString>"](V2)}};webidl.converters.WebSocketSendData=function(V2){if(webidl.util.Type(V2)===webidl.util.Types.OBJECT){if(webidl.is.Blob(V2)){return V2}if(webidl.is.BufferSource(V2)){return V2}}return webidl.converters.USVString(V2)};module.exports={WebSocket,ping}}});var require_websocketerror=__commonJS({"node_modules/undici/lib/web/websocket/stream/websocketerror.js"(exports,module){"use strict";var{webidl}=require_webidl();var{validateCloseCodeAndReason}=require_util5();var{kConstruct}=require_symbols();var{kEnumerableProperty}=require_util();function createInheritableDOMException(){class Test extends DOMException{get reason(){return""}}if(new Test().reason!==void 0){return DOMException}return new Proxy(DOMException,{construct(target,args,newTarget){const instance=Reflect.construct(target,args,target);Object.setPrototypeOf(instance,newTarget.prototype);return instance}})}var WebSocketError=class _WebSocketError extends createInheritableDOMException(){#closeCode;#reason;constructor(message="",init=void 0){message=webidl.converters.DOMString(message,"WebSocketError","message");super(message,"WebSocketError");if(init===kConstruct){return}else if(init!==null){init=webidl.converters.WebSocketCloseInfo(init)}let code=init.closeCode??null;const reason=init.reason??"";validateCloseCodeAndReason(code,reason);if(reason.length!==0&&code===null){code=1e3}this.#closeCode=code;this.#reason=reason}get closeCode(){return this.#closeCode}get reason(){return this.#reason}static createUnvalidatedWebSocketError(message,code,reason){const error=new _WebSocketError(message,kConstruct);error.#closeCode=code;error.#reason=reason;return error}};var{createUnvalidatedWebSocketError}=WebSocketError;delete WebSocketError.createUnvalidatedWebSocketError;Object.defineProperties(WebSocketError.prototype,{closeCode:kEnumerableProperty,reason:kEnumerableProperty,[Symbol.toStringTag]:{value:"WebSocketError",writable:false,enumerable:false,configurable:true}});webidl.is.WebSocketError=webidl.util.MakeTypeAssertion(WebSocketError);module.exports={WebSocketError,createUnvalidatedWebSocketError}}});var require_websocketstream=__commonJS({"node_modules/undici/lib/web/websocket/stream/websocketstream.js"(exports,module){"use strict";var{createDeferredPromise}=require_promise();var{environmentSettingsObject}=require_util2();var{states,opcodes,sentCloseFrameState}=require_constants5();var{webidl}=require_webidl();var{getURLRecord,isValidSubprotocol,isEstablished,utf8Decode}=require_util5();var{establishWebSocketConnection,failWebsocketConnection,closeWebSocketConnection}=require_connection();var{channels}=require_diagnostics();var{WebsocketFrameSend}=require_frame();var{ByteParser}=require_receiver();var{WebSocketError,createUnvalidatedWebSocketError}=require_websocketerror();var{kEnumerableProperty}=require_util();var{utf8DecodeBytes}=require_encoding();var emittedExperimentalWarning=false;var WebSocketStream=class{#url;#openedPromise;#closedPromise;#readableStream;#readableStreamController;#writableStream;#handshakeAborted=false;#handler={onConnectionEstablished:(response,extensions)=>this.#onConnectionEstablished(response,extensions),onMessage:(opcode,data)=>this.#onMessage(opcode,data),onParserError:err=>failWebsocketConnection(this.#handler,null,err.message),onParserDrain:()=>this.#handler.socket.resume(),onSocketData:chunk=>{if(!this.#parser.write(chunk)){this.#handler.socket.pause()}},onSocketError:err=>{this.#handler.readyState=states.CLOSING;if(channels.socketError.hasSubscribers){channels.socketError.publish(err)}this.#handler.socket.destroy()},onSocketClose:()=>this.#onSocketClose(),onPing:()=>{},onPong:()=>{},readyState:states.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:false};#parser;constructor(url,options=void 0){if(!emittedExperimentalWarning){process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.",{code:"UNDICI-WSS"});emittedExperimentalWarning=true}webidl.argumentLengthCheck(arguments,1,"WebSocket");url=webidl.converters.USVString(url);if(options!==null){options=webidl.converters.WebSocketStreamOptions(options)}const baseURL=environmentSettingsObject.settingsObject.baseUrl;const urlRecord=getURLRecord(url,baseURL);const protocols=options.protocols;if(protocols.length!==new Set(protocols.map(p2=>p2.toLowerCase())).size){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}if(protocols.length>0&&!protocols.every(p2=>isValidSubprotocol(p2))){throw new DOMException("Invalid Sec-WebSocket-Protocol value","SyntaxError")}this.#url=urlRecord.toString();this.#openedPromise=createDeferredPromise();this.#closedPromise=createDeferredPromise();if(options.signal!=null){const signal=options.signal;if(signal.aborted){this.#openedPromise.reject(signal.reason);this.#closedPromise.reject(signal.reason);return}signal.addEventListener("abort",()=>{if(!isEstablished(this.#handler.readyState)){failWebsocketConnection(this.#handler);this.#handler.readyState=states.CLOSING;this.#openedPromise.reject(signal.reason);this.#closedPromise.reject(signal.reason);this.#handshakeAborted=true}},{once:true})}const client=environmentSettingsObject.settingsObject;this.#handler.controller=establishWebSocketConnection(urlRecord,protocols,client,this.#handler,options)}get url(){return this.#url.toString()}get opened(){return this.#openedPromise.promise}get closed(){return this.#closedPromise.promise}close(closeInfo=void 0){if(closeInfo!==null){closeInfo=webidl.converters.WebSocketCloseInfo(closeInfo)}const code=closeInfo.closeCode??null;const reason=closeInfo.reason;closeWebSocketConnection(this.#handler,code,reason,true)}#write(chunk){chunk=webidl.converters.WebSocketStreamWrite(chunk);const promise=createDeferredPromise();let data=null;let opcode=null;if(webidl.is.BufferSource(chunk)){data=new Uint8Array(ArrayBuffer.isView(chunk)?new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength):chunk.slice());opcode=opcodes.BINARY}else{let string;try{string=webidl.converters.DOMString(chunk)}catch(e){promise.reject(e);return promise.promise}data=new TextEncoder().encode(string);opcode=opcodes.TEXT}if(!this.#handler.closeState.has(sentCloseFrameState.SENT)&&!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){const frame=new WebsocketFrameSend(data);this.#handler.socket.write(frame.createFrame(opcode),()=>{promise.resolve(void 0)})}return promise.promise}#onConnectionEstablished(response,parsedExtensions){this.#handler.socket=response.socket;const maxFragments=this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments;const maxPayloadSize=this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;const parser=new ByteParser(this.#handler,parsedExtensions,{maxFragments,maxPayloadSize});parser.on("drain",()=>this.#handler.onParserDrain());parser.on("error",err=>this.#handler.onParserError(err));this.#parser=parser;this.#handler.readyState=states.OPEN;const extensions=parsedExtensions??"";const protocol=response.headersList.get("sec-websocket-protocol")??"";const readable=new ReadableStream({start:controller=>{this.#readableStreamController=controller},cancel:reason=>this.#cancel(reason)});const writable=new WritableStream({write:chunk=>this.#write(chunk),close:()=>closeWebSocketConnection(this.#handler,null,null),abort:reason=>this.#closeUsingReason(reason)});this.#readableStream=readable;this.#writableStream=writable;this.#openedPromise.resolve({extensions,protocol,readable,writable})}#onMessage(type,data){if(this.#handler.readyState!==states.OPEN){return}let chunk;if(type===opcodes.TEXT){try{chunk=utf8Decode(data)}catch{failWebsocketConnection(this.#handler,1007,"Received invalid UTF-8 in text frame.");return}}else if(type===opcodes.BINARY){chunk=new Uint8Array(data.buffer,data.byteOffset,data.byteLength)}this.#readableStreamController.enqueue(chunk)}#onSocketClose(){const wasClean=this.#handler.closeState.has(sentCloseFrameState.SENT)&&this.#handler.closeState.has(sentCloseFrameState.RECEIVED);this.#handler.readyState=states.CLOSED;if(this.#handshakeAborted){return}if(!this.#handler.wasEverConnected){this.#openedPromise.reject(new WebSocketError("Socket never opened"))}const result=this.#parser?.closingInfo;let code=result?.code??1005;if(!this.#handler.closeState.has(sentCloseFrameState.SENT)&&!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)){code=1006}const reason=result?.reason==null?"":utf8DecodeBytes(Buffer.from(result.reason));if(wasClean){this.#readableStreamController.close();if(!this.#writableStream.locked){this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to","InvalidStateError"))}this.#closedPromise.resolve({closeCode:code,reason})}else{const error=createUnvalidatedWebSocketError("unclean close",code,reason);this.#readableStreamController?.error(error);this.#writableStream?.abort(error);this.#closedPromise.reject(error)}}#closeUsingReason(reason){let code=null;let reasonString="";if(webidl.is.WebSocketError(reason)){code=reason.closeCode;reasonString=reason.reason}closeWebSocketConnection(this.#handler,code,reasonString)}#cancel(reason){this.#closeUsingReason(reason)}};Object.defineProperties(WebSocketStream.prototype,{url:kEnumerableProperty,opened:kEnumerableProperty,closed:kEnumerableProperty,close:kEnumerableProperty,[Symbol.toStringTag]:{value:"WebSocketStream",writable:false,enumerable:false,configurable:true}});webidl.converters.WebSocketStreamOptions=webidl.dictionaryConverter([{key:"protocols",converter:webidl.sequenceConverter(webidl.converters.USVString),defaultValue:()=>[]},{key:"signal",converter:webidl.nullableConverter(webidl.converters.AbortSignal),defaultValue:()=>null}]);webidl.converters.WebSocketCloseInfo=webidl.dictionaryConverter([{key:"closeCode",converter:V2=>webidl.converters["unsigned short"](V2,webidl.attributes.EnforceRange)},{key:"reason",converter:webidl.converters.USVString,defaultValue:()=>""}]);webidl.converters.WebSocketStreamWrite=function(V2){if(typeof V2==="string"){return webidl.converters.USVString(V2)}return webidl.converters.BufferSource(V2)};module.exports={WebSocketStream}}});var require_util6=__commonJS({"node_modules/undici/lib/web/eventsource/util.js"(exports,module){"use strict";function isValidLastEventId(value){return value.indexOf("\0")===-1}function isASCIINumber(value){if(value.length===0)return false;for(let i=0;i<value.length;i++){if(value.charCodeAt(i)<48||value.charCodeAt(i)>57)return false}return true}module.exports={isValidLastEventId,isASCIINumber}}});var require_eventsource_stream=__commonJS({"node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports,module){"use strict";var{Transform}=__require("stream");var{isASCIINumber,isValidLastEventId}=require_util6();var BOM=[239,187,191];var LF=10;var CR=13;var COLON=58;var SPACE=32;var EventSourceStream=class extends Transform{state;checkBOM=true;crlfCheck=false;eventEndCheck=false;buffer=null;pos=0;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(options={}){options.readableObjectMode=true;super(options);this.state=options.eventSourceSettings||{};if(options.push){this.push=options.push}}_transform(chunk,_encoding,callback){if(chunk.length===0){callback();return}if(this.buffer){this.buffer=Buffer.concat([this.buffer,chunk])}else{this.buffer=chunk}if(this.checkBOM){switch(this.buffer.length){case 1:if(this.buffer[0]===BOM[0]){callback();return}this.checkBOM=false;callback();return;case 2:if(this.buffer[0]===BOM[0]&&this.buffer[1]===BOM[1]){callback();return}this.checkBOM=false;break;case 3:if(this.buffer[0]===BOM[0]&&this.buffer[1]===BOM[1]&&this.buffer[2]===BOM[2]){this.buffer=Buffer.alloc(0);this.checkBOM=false;callback();return}this.checkBOM=false;break;default:if(this.buffer[0]===BOM[0]&&this.buffer[1]===BOM[1]&&this.buffer[2]===BOM[2]){this.buffer=this.buffer.subarray(3)}this.checkBOM=false;break}}while(this.pos<this.buffer.length){if(this.eventEndCheck){if(this.crlfCheck){if(this.buffer[this.pos]===LF){this.buffer=this.buffer.subarray(this.pos+1);this.pos=0;this.crlfCheck=false;continue}this.crlfCheck=false}if(this.buffer[this.pos]===LF||this.buffer[this.pos]===CR){if(this.buffer[this.pos]===CR){this.crlfCheck=true}this.buffer=this.buffer.subarray(this.pos+1);this.pos=0;if(this.event.data!==void 0||this.event.event||this.event.id!==void 0||this.event.retry){this.processEvent(this.event)}this.clearEvent();continue}this.eventEndCheck=false;continue}if(this.buffer[this.pos]===LF||this.buffer[this.pos]===CR){if(this.buffer[this.pos]===CR){this.crlfCheck=true}this.parseLine(this.buffer.subarray(0,this.pos),this.event);this.buffer=this.buffer.subarray(this.pos+1);this.pos=0;this.eventEndCheck=true;continue}this.pos++}callback()}parseLine(line,event){if(line.length===0){return}const colonPosition=line.indexOf(COLON);if(colonPosition===0){return}let field="";let value="";if(colonPosition!==-1){field=line.subarray(0,colonPosition).toString("utf8");let valueStart=colonPosition+1;if(line[valueStart]===SPACE){++valueStart}value=line.subarray(valueStart).toString("utf8")}else{field=line.toString("utf8");value=""}switch(field){case"data":if(event[field]===void 0){event[field]=value}else{event[field]+=`
308
308
  ${value}`}break;case"retry":if(isASCIINumber(value)){event[field]=value}break;case"id":if(isValidLastEventId(value)){event[field]=value}break;case"event":if(value.length>0){event[field]=value}break}}processEvent(event){if(event.retry&&isASCIINumber(event.retry)){this.state.reconnectionTime=parseInt(event.retry,10)}if(event.id!==void 0&&isValidLastEventId(event.id)){this.state.lastEventId=event.id}if(event.data!==void 0){this.push({type:event.event||"message",options:{data:event.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}}clearEvent(){this.event={data:void 0,event:void 0,id:void 0,retry:void 0}}};module.exports={EventSourceStream}}});var require_eventsource=__commonJS({"node_modules/undici/lib/web/eventsource/eventsource.js"(exports,module){"use strict";var{pipeline}=__require("stream");var{fetching}=require_fetch();var{makeRequest}=require_request2();var{webidl}=require_webidl();var{EventSourceStream}=require_eventsource_stream();var{parseMIMEType}=require_data_url();var{createFastMessageEvent}=require_events();var{isNetworkError}=require_response();var{kEnumerableProperty}=require_util();var{environmentSettingsObject}=require_util2();var experimentalWarned=false;var defaultReconnectionTime=3e3;var CONNECTING=0;var OPEN=1;var CLOSED=2;var ANONYMOUS="anonymous";var USE_CREDENTIALS="use-credentials";var EventSource=class _EventSource extends EventTarget{#events={open:null,error:null,message:null};#url;#withCredentials=false;#readyState=CONNECTING;#request=null;#controller=null;#dispatcher;#state;constructor(url,eventSourceInitDict={}){super();webidl.util.markAsUncloneable(this);const prefix="EventSource constructor";webidl.argumentLengthCheck(arguments,1,prefix);if(!experimentalWarned){experimentalWarned=true;process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})}url=webidl.converters.USVString(url);eventSourceInitDict=webidl.converters.EventSourceInitDict(eventSourceInitDict,prefix,"eventSourceInitDict");this.#dispatcher=eventSourceInitDict.node.dispatcher||eventSourceInitDict.dispatcher;this.#state={lastEventId:"",reconnectionTime:eventSourceInitDict.node.reconnectionTime};const settings=environmentSettingsObject;let urlRecord;try{urlRecord=new URL(url,settings.settingsObject.baseUrl);this.#state.origin=urlRecord.origin}catch(e){throw new DOMException(e,"SyntaxError")}this.#url=urlRecord.href;let corsAttributeState=ANONYMOUS;if(eventSourceInitDict.withCredentials===true){corsAttributeState=USE_CREDENTIALS;this.#withCredentials=true}const initRequest={redirect:"follow",keepalive:true,mode:"cors",credentials:corsAttributeState==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};initRequest.client=environmentSettingsObject.settingsObject;initRequest.headersList=[["accept",{name:"accept",value:"text/event-stream"}]];initRequest.cache="no-store";initRequest.initiator="other";initRequest.urlList=[new URL(this.#url)];this.#request=makeRequest(initRequest);this.#connect()}get readyState(){return this.#readyState}get url(){return this.#url}get withCredentials(){return this.#withCredentials}#connect(){if(this.#readyState===CLOSED)return;this.#readyState=CONNECTING;const fetchParams={request:this.#request,dispatcher:this.#dispatcher};const processEventSourceEndOfBody=response=>{if(!isNetworkError(response)){return this.#reconnect()}};fetchParams.processResponseEndOfBody=processEventSourceEndOfBody;fetchParams.processResponse=response=>{if(isNetworkError(response)){if(response.aborted){this.close();this.dispatchEvent(new Event("error"));return}else{this.#reconnect();return}}const contentType=response.headersList.get("content-type",true);const mimeType=contentType!==null?parseMIMEType(contentType):"failure";const contentTypeValid=mimeType!=="failure"&&mimeType.essence==="text/event-stream";if(response.status!==200||contentTypeValid===false){this.close();this.dispatchEvent(new Event("error"));return}this.#readyState=OPEN;this.dispatchEvent(new Event("open"));this.#state.origin=response.urlList[response.urlList.length-1].origin;const eventSourceStream=new EventSourceStream({eventSourceSettings:this.#state,push:event=>{this.dispatchEvent(createFastMessageEvent(event.type,event.options))}});pipeline(response.body.stream,eventSourceStream,error=>{if(error?.aborted===false){this.close();this.dispatchEvent(new Event("error"))}})};this.#controller=fetching(fetchParams)}#reconnect(){if(this.#readyState===CLOSED)return;this.#readyState=CONNECTING;this.dispatchEvent(new Event("error"));setTimeout(()=>{if(this.#readyState!==CONNECTING)return;if(this.#state.lastEventId.length){this.#request.headersList.set("last-event-id",this.#state.lastEventId,true)}this.#connect()},this.#state.reconnectionTime)?.unref()}close(){webidl.brandCheck(this,_EventSource);if(this.#readyState===CLOSED)return;this.#readyState=CLOSED;this.#controller.abort();this.#request=null}get onopen(){return this.#events.open}set onopen(fn){if(this.#events.open){this.removeEventListener("open",this.#events.open)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("open",listener);this.#events.open=fn}else{this.#events.open=null}}get onmessage(){return this.#events.message}set onmessage(fn){if(this.#events.message){this.removeEventListener("message",this.#events.message)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("message",listener);this.#events.message=fn}else{this.#events.message=null}}get onerror(){return this.#events.error}set onerror(fn){if(this.#events.error){this.removeEventListener("error",this.#events.error)}const listener=webidl.converters.EventHandlerNonNull(fn);if(listener!==null){this.addEventListener("error",listener);this.#events.error=fn}else{this.#events.error=null}}};var constantsPropertyDescriptors={CONNECTING:{__proto__:null,configurable:false,enumerable:true,value:CONNECTING,writable:false},OPEN:{__proto__:null,configurable:false,enumerable:true,value:OPEN,writable:false},CLOSED:{__proto__:null,configurable:false,enumerable:true,value:CLOSED,writable:false}};Object.defineProperties(EventSource,constantsPropertyDescriptors);Object.defineProperties(EventSource.prototype,constantsPropertyDescriptors);Object.defineProperties(EventSource.prototype,{close:kEnumerableProperty,onerror:kEnumerableProperty,onmessage:kEnumerableProperty,onopen:kEnumerableProperty,readyState:kEnumerableProperty,url:kEnumerableProperty,withCredentials:kEnumerableProperty});webidl.converters.EventSourceInitDict=webidl.dictionaryConverter([{key:"withCredentials",converter:webidl.converters.boolean,defaultValue:()=>false},{key:"dispatcher",converter:webidl.converters.any},{key:"node",converter:webidl.dictionaryConverter([{key:"reconnectionTime",converter:webidl.converters["unsigned long"],defaultValue:()=>defaultReconnectionTime},{key:"dispatcher",converter:webidl.converters.any}]),defaultValue:()=>({})}]);module.exports={EventSource,defaultReconnectionTime}}});var require_undici=__commonJS({"node_modules/undici/index.js"(exports,module){"use strict";var Client=require_client();var Dispatcher=require_dispatcher();var Pool2=require_pool();var BalancedPool=require_balanced_pool();var RoundRobinPool=require_round_robin_pool();var Agent2=require_agent();var ProxyAgent2=require_proxy_agent();var Socks5ProxyAgent=require_socks5_proxy_agent();var EnvHttpProxyAgent=require_env_http_proxy_agent();var RetryAgent=require_retry_agent();var H2CClient=require_h2c_client();var errors=require_errors();var util=require_util();var{InvalidArgumentError}=errors;var api=require_api();var buildConnector=require_connect();var MockClient=require_mock_client();var{MockCallHistory,MockCallHistoryLog}=require_mock_call_history();var MockAgent=require_mock_agent();var MockPool=require_mock_pool();var SnapshotAgent=require_snapshot_agent();var mockErrors=require_mock_errors();var RetryHandler=require_retry_handler();var{getGlobalDispatcher,setGlobalDispatcher}=require_global2();var DecoratorHandler=require_decorator_handler();var RedirectHandler=require_redirect_handler();Object.assign(Dispatcher.prototype,api);module.exports.Dispatcher=Dispatcher;module.exports.Client=Client;module.exports.Pool=Pool2;module.exports.BalancedPool=BalancedPool;module.exports.RoundRobinPool=RoundRobinPool;module.exports.Agent=Agent2;module.exports.ProxyAgent=ProxyAgent2;module.exports.Socks5ProxyAgent=Socks5ProxyAgent;module.exports.EnvHttpProxyAgent=EnvHttpProxyAgent;module.exports.RetryAgent=RetryAgent;module.exports.H2CClient=H2CClient;module.exports.RetryHandler=RetryHandler;module.exports.DecoratorHandler=DecoratorHandler;module.exports.RedirectHandler=RedirectHandler;module.exports.interceptors={redirect:require_redirect(),responseError:require_response_error(),retry:require_retry(),dump:require_dump(),dns:require_dns(),cache:require_cache2(),decompress:require_decompress(),deduplicate:require_deduplicate()};module.exports.cacheStores={MemoryCacheStore:require_memory_cache_store()};var SqliteCacheStore=require_sqlite_cache_store();module.exports.cacheStores.SqliteCacheStore=SqliteCacheStore;module.exports.buildConnector=buildConnector;module.exports.errors=errors;module.exports.util={parseHeaders:util.parseHeaders,headerNameToString:util.headerNameToString};function makeDispatcher(fn){return(url,opts,handler)=>{if(typeof opts==="function"){handler=opts;opts=null}if(!url||typeof url!=="string"&&typeof url!=="object"&&!(url instanceof URL)){throw new InvalidArgumentError("invalid url")}if(opts!=null&&typeof opts!=="object"){throw new InvalidArgumentError("invalid opts")}if(opts&&opts.path!=null){if(typeof opts.path!=="string"){throw new InvalidArgumentError("invalid opts.path")}let path29=opts.path;if(!opts.path.startsWith("/")){path29=`/${path29}`}url=new URL(util.parseOrigin(url).origin+path29)}else{if(!opts){opts=typeof url==="object"?url:{}}url=util.parseURL(url)}const{agent,dispatcher=getGlobalDispatcher()}=opts;if(agent){throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?")}return fn.call(dispatcher,{...opts,origin:url.origin,path:url.search?`${url.pathname}${url.search}`:url.pathname,method:opts.method||(opts.body?"PUT":"GET")},handler)}}module.exports.setGlobalDispatcher=setGlobalDispatcher;module.exports.getGlobalDispatcher=getGlobalDispatcher;var fetchImpl=require_fetch().fetch;var currentFilename=typeof __filename!=="undefined"?__filename:void 0;function appendFetchStackTrace(err,filename){if(!err||typeof err!=="object"){return}const stack=typeof err.stack==="string"?err.stack:"";const normalizedFilename=filename.replace(/\\/g,"/");if(stack&&(stack.includes(filename)||stack.includes(normalizedFilename))){return}const capture2={};Error.captureStackTrace(capture2,appendFetchStackTrace);if(!capture2.stack){return}const captureLines=capture2.stack.split("\n").slice(1).join("\n");err.stack=stack?`${stack}
309
- ${captureLines}`:capture2.stack}module.exports.fetch=function fetch2(init,options=void 0){return fetchImpl(init,options).catch(err=>{if(currentFilename){appendFetchStackTrace(err,currentFilename)}else if(err&&typeof err==="object"){Error.captureStackTrace(err,module.exports.fetch)}throw err})};module.exports.Headers=require_headers().Headers;module.exports.Response=require_response().Response;module.exports.Request=require_request2().Request;module.exports.FormData=require_formdata().FormData;var{setGlobalOrigin,getGlobalOrigin}=require_global();module.exports.setGlobalOrigin=setGlobalOrigin;module.exports.getGlobalOrigin=getGlobalOrigin;var{CacheStorage}=require_cachestorage();var{kConstruct}=require_symbols();module.exports.caches=new CacheStorage(kConstruct);var{deleteCookie,getCookies,getSetCookies,setCookie,parseCookie}=require_cookies();module.exports.deleteCookie=deleteCookie;module.exports.getCookies=getCookies;module.exports.getSetCookies=getSetCookies;module.exports.setCookie=setCookie;module.exports.parseCookie=parseCookie;var{parseMIMEType,serializeAMimeType}=require_data_url();module.exports.parseMIMEType=parseMIMEType;module.exports.serializeAMimeType=serializeAMimeType;var{CloseEvent,ErrorEvent,MessageEvent}=require_events();var{WebSocket,ping}=require_websocket();module.exports.WebSocket=WebSocket;module.exports.CloseEvent=CloseEvent;module.exports.ErrorEvent=ErrorEvent;module.exports.MessageEvent=MessageEvent;module.exports.ping=ping;module.exports.WebSocketStream=require_websocketstream().WebSocketStream;module.exports.WebSocketError=require_websocketerror().WebSocketError;module.exports.request=makeDispatcher(api.request);module.exports.stream=makeDispatcher(api.stream);module.exports.pipeline=makeDispatcher(api.pipeline);module.exports.connect=makeDispatcher(api.connect);module.exports.upgrade=makeDispatcher(api.upgrade);module.exports.MockClient=MockClient;module.exports.MockCallHistory=MockCallHistory;module.exports.MockCallHistoryLog=MockCallHistoryLog;module.exports.MockPool=MockPool;module.exports.MockAgent=MockAgent;module.exports.SnapshotAgent=SnapshotAgent;module.exports.mockErrors=mockErrors;var{EventSource}=require_eventsource();module.exports.EventSource=EventSource;function install(){globalThis.fetch=module.exports.fetch;globalThis.Headers=module.exports.Headers;globalThis.Response=module.exports.Response;globalThis.Request=module.exports.Request;globalThis.FormData=module.exports.FormData;globalThis.WebSocket=module.exports.WebSocket;globalThis.CloseEvent=module.exports.CloseEvent;globalThis.ErrorEvent=module.exports.ErrorEvent;globalThis.MessageEvent=module.exports.MessageEvent;globalThis.EventSource=module.exports.EventSource}module.exports.install=install}});import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";var transports;var init_fetch_transport=__esm({"src/fetch-transport.ts"(){"use strict";transports=new AsyncLocalStorage2}});var init_upstream_fail=__esm({"src/upstream-fail.ts"(){"use strict"}});import{homedir}from"os";import path3 from"path";function xdg(envVar,fallback){const v2=process.env[envVar];if(v2&&v2.length>0)return path3.resolve(v2);return path3.join(homedir(),fallback)}function configDir(){return path3.join(xdg("XDG_CONFIG_HOME",".config"),"billion-context")}function configFile(){const env=process.env.BILI_CONFIG_FILE;if(env&&env.length>0)return path3.resolve(env);return path3.join(configDir(),"billion-context.json")}function cacheDir(){return path3.join(xdg("XDG_CACHE_HOME",".cache"),"billion-context")}function stateDir(){return path3.join(xdg("XDG_STATE_HOME",".local/state"),"billion-context")}function defaultLogFile(){return path3.join(stateDir(),"bili.log")}var init_paths=__esm({"src/paths.ts"(){"use strict"}});function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}return{setPosition,getPosition:()=>pos,scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:()=>token,getTokenValue:()=>value,getTokenOffset:()=>tokenOffset,getTokenLength:()=>pos-tokenOffset,getTokenStartLine:()=>lineStartOffset,getTokenStartCharacter:()=>tokenOffset-prevTokenLineStartOffset,getTokenError:()=>scanError}}function isWhiteSpace(ch){return ch===32||ch===9}function isLineBreak(ch){return ch===10||ch===13}function isDigit(ch){return ch>=48&&ch<=57}var CharacterCodes;var init_scanner=__esm({"node_modules/jsonc-parser/lib/esm/impl/scanner.js"(){"use strict";(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}))}});var cachedSpaces,maxCachedValues,cachedBreakLinesWithSpaces;var init_string_intern=__esm({"node_modules/jsonc-parser/lib/esm/impl/string-intern.js"(){"use strict";cachedSpaces=new Array(20).fill(0).map((_2,index)=>{return" ".repeat(index)});maxCachedValues=200;cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}}}});var init_format=__esm({"node_modules/jsonc-parser/lib/esm/impl/format.js"(){"use strict";init_scanner();init_string_intern()}});function parse(text,errors=[],options=ParseOptions.DEFAULT){let currentProperty=null;let currentParent=[];const previousParents=[];function onValue(value){if(Array.isArray(currentParent)){currentParent.push(value)}else if(currentProperty!==null){currentParent[currentProperty]=value}}const visitor={onObjectBegin:()=>{const object={};onValue(object);previousParents.push(currentParent);currentParent=object;currentProperty=null},onObjectProperty:name=>{currentProperty=name},onObjectEnd:()=>{currentParent=previousParents.pop()},onArrayBegin:()=>{const array=[];onValue(array);previousParents.push(currentParent);currentParent=array;currentProperty=null},onArrayEnd:()=>{currentParent=previousParents.pop()},onLiteralValue:onValue,onError:(error,offset,length)=>{errors.push({error,offset,length})}};visit(text,visitor,options);return currentParent[0]}function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}var ParseOptions;var init_parser=__esm({"node_modules/jsonc-parser/lib/esm/impl/parser.js"(){"use strict";init_scanner();(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}))}});var init_edit=__esm({"node_modules/jsonc-parser/lib/esm/impl/edit.js"(){"use strict";init_format();init_parser()}});function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}var ScanError,SyntaxKind,parse2,ParseErrorCode;var init_main=__esm({"node_modules/jsonc-parser/lib/esm/main.js"(){"use strict";init_format();init_edit();init_scanner();init_parser();(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));parse2=parse;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}))}});import{execFileSync as execFileSync2}from"child_process";import net from"net";import tls from"tls";var import_undici;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs()}});import{createHash as createHash2}from"crypto";function hashId(s3){return createHash2("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var BILI_PASSTHROUGH_HEADER;var init_util=__esm({"src/util.ts"(){"use strict";BILI_PASSTHROUGH_HEADER="x-bili-passthrough"}});var DEFAULT_MITM_DOMAINS;var init_mitm_domains=__esm({"src/mitm-domains.ts"(){"use strict";DEFAULT_MITM_DOMAINS=["api.anthropic.com","api.openai.com","chatgpt.com"]}});var init_compat_roles=__esm({"src/compat-roles.ts"(){"use strict";init_config()}});var init_compat_drop=__esm({"src/compat-drop.ts"(){"use strict";init_config()}});var init_private_host=__esm({"src/private-host.ts"(){"use strict"}});var SUMMARY_DEFAULT_BUDGET;var init_external_summary_settings=__esm({"src/external-summary-settings.ts"(){"use strict";init_logger();init_private_host();init_knobs();SUMMARY_DEFAULT_BUDGET={totalTimeoutMs:5e4,targetTimeoutMs:25e3,maxSummaryBytes:64*1024}}});import{readFileSync as readFileSync2,existsSync,mkdirSync as mkdirSync2,writeFileSync}from"fs";import{createHash as createHash3}from"crypto";import{dirname}from"path";function resolveRecordedMitmDomains(passed,env=process.env){const fileConfig=loadConfigFile();const enabled=(env.BILI_MITM??(fileConfig.mitm?.enabled===false?"0":"1"))!=="0";if(!enabled)return[];const effective=passed&&passed.length>0?passed.join(","):env.BILI_MITM_DOMAINS;return dedupeDomains([...fileConfig.mitm?.domains??[],...splitCsv(effective)])}function splitCsv(value){if(!value)return[];return value.split(",").map(s3=>s3.trim()).filter(s3=>s3.length>0)}function dedupeDomains(list){const seen=new Set;const out=[];for(const d of list){if(!seen.has(d)){seen.add(d);out.push(d)}}return out}function warnUnknownTopLevelKeys(obj){const unknown=Object.keys(obj).filter(key=>!KNOWN_TOP_LEVEL_KEYS.has(key)&&key!=="allowDshCompaction");if(unknown.length===0)return;const signature=[...unknown].sort().join("\0");if(seenUnknownTopLevelKeySignatures.has(signature))return;seenUnknownTopLevelKeySignatures.add(signature);const misplaced=unknown.filter(key=>COMPRESS_SETTING_FIELDS.has(key));const hint=misplaced.length>0?` \u2014 ${misplaced.map(k2=>`"${k2}" belongs under "compress" (did you mean "compress.${k2}"?)`).join("; ")}`:"";log("warn",`[acp-config] ignoring unknown top-level config key(s): ${unknown.join(", ")}${hint}`)}function parseBiliConfig(raw){try{return JSON.parse(raw)}catch{const errors=[];const value=parse2(raw,errors,{allowTrailingComma:true});if(errors.length===0)return value;const first=errors[0];throw new SyntaxError(`invalid JSON/JSONC at ${lineColumnOf(raw,first.offset)}: ${printParseErrorCode(first.error)}`)}}function lineColumnOf(text,offset){let line=1;let column=1;for(let i=0;i<offset&&i<text.length;i++){if(text.charAt(i)==="\n"){line++;column=1}else column++}return`line ${line} column ${column}`}function loadConfigFile(){const path29=configFile();let raw;let value;try{raw=readFileSync2(path29,"utf8").replace(/^\uFEFF/,"");const cached=configFileCache;if(cached&&cached.raw===raw)return cached.value;const parsed=parseBiliConfig(raw);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){const obj=parsed;warnRemovedDshAllowKey(obj);warnUnknownTopLevelKeys(obj);warnInertResignPassthrough(obj);warnInertStripImages(obj);warnInertRemovedCompressKeys(obj);value=obj}else{value={}}}catch(e){if(e.code!=="ENOENT"){log("error",`[acp-config] failed to parse ${path29}: ${String(e)}`)}if(raw!==void 0)value={}}if(raw===void 0||value===void 0)return{};configFileCache={raw,value};return value}function warnRemovedDshAllowKey(obj){const hits=[];if(Object.prototype.hasOwnProperty.call(obj,"allowDshCompaction")&&obj.allowDshCompaction!==null&&obj.allowDshCompaction!==void 0){hits.push('top-level "allowDshCompaction"')}const d=obj.dsh;if(d!==null&&typeof d==="object"&&!Array.isArray(d)){const live=new Set(["authoredCompaction","contextTab","contextTabLabel"]);for(const key of Object.keys(d))if(!live.has(key))hits.push(`dsh.${key}`)}hits.sort();const sig=hits.join(",");if(sig===""||sig===removedDshAllowKeySignature)return;removedDshAllowKeySignature=sig;log("warn",`[acp-config] ${hits.join(", ")} was removed (#3651, superseding #2028) \u2014 value(s) ignored: dsh native compaction is now refused unconditionally by the wire guard on every lane. Delete it from your config to silence this.`)}function resolveResignSettings(env=process.env,provider={},scheme=RESIGN_BUILTIN_SCHEME){const key=scheme.trim().toLowerCase();const file=loadConfigFile().resign?.[key]??{};const providerBlock=provider?.[key]??{};const enabled=env.BILI_RESIGN!==void 0?env.BILI_RESIGN!=="0":providerBlock.enabled!==void 0?providerBlock.enabled:file.enabled!==false;const passthrough=env.BILI_RESIGN_PASSTHROUGH!==void 0?env.BILI_RESIGN_PASSTHROUGH==="1"||env.BILI_RESIGN_PASSTHROUGH==="true":providerBlock.passthrough!==void 0?providerBlock.passthrough:file.passthrough===true;const credentialRef=env.BILI_CODEARTS_REF?.trim()||providerBlock.credentialRef||file.credentialRef||void 0;return{enabled,passthrough,credentialRef}}function warnInertStripImages(obj){const compress=obj.compress;if(!compress||typeof compress!=="object"||Array.isArray(compress))return;const hit=["stripImages","stripImagesKeepRecent"].filter(k2=>compress[k2]!==void 0);const sig=hit.join(",");if(sig===""||sig===seenInertStripImagesSignature)return;seenInertStripImagesSignature=sig;log("warn",`[acp-config] compress.${hit.join("/compress.")} is INERT \u2014 compress.stripImages was removed: media now folds by default (#2640) and decompress({ imageRef }) recovers folded pixels; nothing is stripped from the wire anymore. Remove the key(s) from the config.`)}function warnInertRemovedCompressKeys(obj){const hits=[];const scanBlock=(block,pathPrefix)=>{if(!block||typeof block!=="object"||Array.isArray(block))return;for(const key of INERT_REMOVED_COMPRESS_KEYS){if(block[key]!==void 0)hits.push(`${pathPrefix}.${key}`)}};scanBlock(obj.compress,"compress");const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const[url,entry]of Object.entries(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const p2=entry;scanBlock(p2.compress,`providers["${url}"].compress`);const models=p2.models;if(models&&typeof models==="object"&&!Array.isArray(models)){for(const[model,mEntry]of Object.entries(models)){if(!mEntry||typeof mEntry!=="object"||Array.isArray(mEntry))continue;scanBlock(mEntry.compress,`providers["${url}"].models["${model}"].compress`)}}}}hits.sort();const sig=hits.join(",");if(sig===""||sig===seenInertRemovedCompressKeysSignature)return;seenInertRemovedCompressKeysSignature=sig;log("warn",`[acp-config] ${hits.join(", ")} is INERT \u2014 compress.imageCompression was removed and no longer does anything at any level (image pre-compression + image_full restore channel, #3266). Remove it from the config; images pass through byte-identical.`)}function warnInertResignPassthrough(obj){const inert=[];const consider=(map,providerBlockFor)=>{if(!map||typeof map!=="object"||Array.isArray(map))return;for(const[key,val]of Object.entries(map)){if(key===RESIGN_BUILTIN_SCHEME)continue;const block=val!==null&&typeof val==="object"&&!Array.isArray(val)?val:{};if(block["passthrough"]!==true)continue;const fileBlock=(obj.resign??{})[key];const providerBlock=providerBlockFor(key);const enabled=process.env.BILI_RESIGN!==void 0?process.env.BILI_RESIGN!=="0":providerBlock?.enabled!==void 0?providerBlock.enabled:fileBlock?.enabled!==false;if(enabled)inert.push(key)}};consider(obj.resign,()=>void 0);const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const entry of Object.values(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const pmap=entry.resign;if(pmap===void 0)continue;consider(pmap,key=>(pmap??{})[key])}}inert.sort();const sig=inert.join(",");if(sig===""||sig===inertResignPassthroughSignature)return;inertResignPassthroughSignature=sig;const list=inert.map(k2=>`resign["${k2}"].passthrough`).join(", ");log("warn",`[acp-config] ${list}=true is INERT \u2014 since the #2090 compress-or-refuse contract, unsigned pass-through exists ONLY for the built-in scheme "${RESIGN_BUILTIN_SCHEME}"; those signed requests stay REFUSED until bili ships a re-signer for them. Restore pre-resign handling with resign["<scheme>"].enabled=false or BILI_RESIGN=0 (the upstream will then reject the rewritten bodies).`)}function resolveZonePortBase(env=process.env){const fromEnv=Number.parseInt(env.BILI_ZONE_PORT??"",10);if(Number.isInteger(fromEnv)&&fromEnv>0&&fromEnv<65536)return fromEnv;return ZONE_PORT_BASE}function resolveNativeAttachExternal(env=process.env){const fromEnv=(env.BILI_NATIVE_ATTACH_EXTERNAL??"").trim().toLowerCase();if(fromEnv==="1"||fromEnv==="true")return true;if(fromEnv==="0"||fromEnv==="false")return false;return loadConfigFile().native?.attachExternal===true}function resolveNativeAttachLanePriority(){const raw=loadConfigFile().native?.attachLanePriority;if(!Array.isArray(raw))return[];const out=[];for(const item of raw){if(typeof item!=="string")continue;const t=item.trim();if(t.length>0&&!out.includes(t))out.push(t)}return out}function resolveNativeAttachPolicy(env=process.env){const norm=v2=>(v2??"").trim().toLowerCase();const fromEnv=norm(env.BILI_NATIVE_ATTACH_POLICY);if(fromEnv==="global-fallback"||fromEnv==="global")return"global-fallback";if(fromEnv==="own-lane"||fromEnv==="ownlane"||fromEnv==="strict")return"own-lane";const file=norm(loadConfigFile().native?.attachPolicy);if(file==="global-fallback"||file==="global")return"global-fallback";return"own-lane"}function resolveNativeAttachUrl(env=process.env){const fromEnv=(env.BILI_MCP_PROXY??"").trim();if(fromEnv.length>0)return fromEnv;const file=(loadConfigFile().native?.attachUrl??"").trim();return file.length>0?file:void 0}var KNOWN_TOP_LEVEL_KEYS,COMPRESS_SETTING_FIELDS,seenUnknownTopLevelKeySignatures,configFileCache,removedDshAllowKeySignature,RESIGN_BUILTIN_SCHEME,inertResignPassthroughSignature,seenInertStripImagesSignature,INERT_REMOVED_COMPRESS_KEYS,seenInertRemovedCompressKeysSignature,ZONE_PORT_BASE;var init_config=__esm({"src/config.ts"(){"use strict";init_main();init_paths();init_logger();init_upstream_proxy();init_log_mask();init_util();init_mitm_domains();init_compat_roles();init_compat_drop();init_external_summary_settings();KNOWN_TOP_LEVEL_KEYS=new Set(["port","host","upstream","providersPath","providers","proxy","modelContextLimit","sessionHeader","log","debug","dumpSse","passthrough","autoUpdate","autoRestartOnUpdate","updateTag","advisoryCheck","advisoryUrl","releaseNotesCheck","releaseNotesUrl","upstreamProxy","upstreamProxyMode","logFile","compress","promptCache","mitm","maskHosts","subagentSplit","forkAdoption","affinitySimhash","resumeInheritance","chainContentDetection","chainEgressStamp","stableSystemAnchor","rollout","dsh","compat","imageBilling","imageTokenCap","claude","native","resign","pi","storage","security","network","persist","sessions","plugin","update","diagnostics","fakeCompletion","codexCompact","ccrRetrievalTtlMs","decompressTmpCap","autoModeForge","imageRescale","guardrails","cacheKeepalive"]);COMPRESS_SETTING_FIELDS=new Set(["modelContextLimit","maxContextLimit","emergencyThresholdPercent","nudgeGrowthTokens","minPressureBenefitTokens","tierNudgeTokens","nudgeModelDecided","nudgeDecisionMaxTokens","preserveRecentMessages","preserveRecentTokens","minCompressRange","minCompressRangeChars","outputHeadroomMaxPct","tiers","protectedLatestTools","protectedTools","neverPreserveRecentTools","preserveRecentTools","visibilityMarkers","rules","injectTool","injectNudge","acknowledgePromptsRisk","absorb","ccr","search","prompts","promptPack","reasoningGuard","outputSteering","priceProfile","reconcile","streamSummary"]);seenUnknownTopLevelKeySignatures=new Set;configFileCache=null;removedDshAllowKeySignature="";RESIGN_BUILTIN_SCHEME="sdk-hmac-sha256";inertResignPassthroughSignature=null;seenInertStripImagesSignature="";INERT_REMOVED_COMPRESS_KEYS=["imageCompression"];seenInertRemovedCompressKeysSignature="";ZONE_PORT_BASE=18787}});var init_duration=__esm({"src/duration.ts"(){"use strict"}});import{createHash as createHash4}from"crypto";var MIN_MEDIA_URL_SPLIT_BYTES,MEDIA_URL_MARKER_RE;var init_identity=__esm({"src/storage/identity.ts"(){"use strict";MIN_MEDIA_URL_SPLIT_BYTES=2048;MEDIA_URL_MARKER_RE=new RegExp(`data:([a-zA-Z0-9.+\\/-]+);base64,([A-Za-z0-9+/=]{${MIN_MEDIA_URL_SPLIT_BYTES},})`,"g")}});function storagePragmas(walJournalSizeLimitBytes){return["PRAGMA journal_mode = WAL","PRAGMA synchronous = NORMAL","PRAGMA busy_timeout = 5000","PRAGMA foreign_keys = ON",`PRAGMA journal_size_limit = ${walJournalSizeLimitBytes}`,"PRAGMA auto_vacuum = INCREMENTAL"]}var WAL_JOURNAL_SIZE_LIMIT,STORAGE_PRAGMAS;var init_schema=__esm({"src/storage/schema.ts"(){"use strict";init_identity();WAL_JOURNAL_SIZE_LIMIT=8*1024*1024;STORAGE_PRAGMAS=storagePragmas(WAL_JOURNAL_SIZE_LIMIT)}});import path4 from"path";function tNumLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tInt(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v2=envRaw!==void 0?Number.parseInt(envRaw,10):(()=>{const f2=loadConfigFile().sessions?.max;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Math.max(1,v2||256)}function sessionResidentMaxBytes(){const v2=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v2)&&v2>=0?Math.floor(v2):512*1024*1024}function updateRegistryBase(){const envRaw=process.env.BILI_UPDATE_REGISTRY;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.registry;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateCheckIntervalMs(){const v2=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v2)&&v2>0?Math.floor(v2):3*60*1e3}var DEFAULT_LIMITS_RECEIVE_BYTES,DEFAULT_LIMITS_DECODED_BYTES,DEFAULT_LIMITS_OUTBOUND_BYTES,DEFAULT_WS_OUTBOUND_BYTES;var init_knobs=__esm({"src/knobs.ts"(){"use strict";init_paths();init_config();init_duration();init_fetch_util();init_upstream_proxy();init_schema();DEFAULT_LIMITS_RECEIVE_BYTES=5*1024*1024*1024;DEFAULT_LIMITS_DECODED_BYTES=10*1024*1024*1024;DEFAULT_LIMITS_OUTBOUND_BYTES=5*1024*1024*1024;DEFAULT_WS_OUTBOUND_BYTES=10*1024*1024}});import{readFileSync as readFileSync3,statSync as statSync2}from"fs";import*as tls2 from"tls";var init_upstream_ca=__esm({"src/upstream-ca.ts"(){"use strict";init_logger();init_knobs()}});var MAX_REQUEST_BYTES,MAX_DECODED_REQUEST_BYTES;var init_request_body_budget=__esm({"src/request-body-budget.ts"(){"use strict";init_knobs();MAX_REQUEST_BYTES=100*1024*1024;MAX_DECODED_REQUEST_BYTES=2*MAX_REQUEST_BYTES}});var import_undici2,UPSTREAM_TIMEOUT_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_fetch_transport();init_upstream_fail();init_upstream_ca();init_knobs();init_request_body_budget();init_request_body_budget();UPSTREAM_TIMEOUT_MS=12*60*1e3}});var require_forge=__commonJS({"node_modules/node-forge/lib/forge.js"(exports,module){"use strict";module.exports={options:{usePureJavaScript:false}}}});var require_baseN=__commonJS({"node_modules/node-forge/lib/baseN.js"(exports,module){"use strict";var api={};module.exports=api;var _reverseAlphabets={};api.encode=function(input,alphabet,maxline){if(typeof alphabet!=="string"){throw new TypeError('"alphabet" must be a string.')}if(maxline!==void 0&&typeof maxline!=="number"){throw new TypeError('"maxline" must be a number.')}var output="";if(!(input instanceof Uint8Array)){output=_encodeWithByteBuffer(input,alphabet)}else{var i=0;var base=alphabet.length;var first=alphabet.charAt(0);var digits=[0];for(i=0;i<input.length;++i){for(var j2=0,carry=input[i];j2<digits.length;++j2){carry+=digits[j2]<<8;digits[j2]=carry%base;carry=carry/base|0}while(carry>0){digits.push(carry%base);carry=carry/base|0}}for(i=0;input[i]===0&&i<input.length-1;++i){output+=first}for(i=digits.length-1;i>=0;--i){output+=alphabet[digits[i]]}}if(maxline){var regex=new RegExp(".{1,"+maxline+"}","g");output=output.match(regex).join("\r\n")}return output};api.decode=function(input,alphabet){if(typeof input!=="string"){throw new TypeError('"input" must be a string.')}if(typeof alphabet!=="string"){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;var first=alphabet.charAt(0);var bytes=[0];for(var i=0;i<input.length;i++){var value=table[input.charCodeAt(i)];if(value===void 0){return}for(var j2=0,carry=value;j2<bytes.length;++j2){carry+=bytes[j2]*base;bytes[j2]=carry&255;carry>>=8}while(carry>0){bytes.push(carry&255);carry>>=8}}for(var k2=0;input[k2]===first&&k2<input.length-1;++k2){bytes.push(0)}if(typeof Buffer!=="undefined"){return Buffer.from(bytes.reverse())}return new Uint8Array(bytes.reverse())};function _encodeWithByteBuffer(input,alphabet){var i=0;var base=alphabet.length;var first=alphabet.charAt(0);var digits=[0];for(i=0;i<input.length();++i){for(var j2=0,carry=input.at(i);j2<digits.length;++j2){carry+=digits[j2]<<8;digits[j2]=carry%base;carry=carry/base|0}while(carry>0){digits.push(carry%base);carry=carry/base|0}}var output="";for(i=0;input.at(i)===0&&i<input.length()-1;++i){output+=first}for(i=digits.length-1;i>=0;--i){output+=alphabet[digits[i]]}return output}}});var require_util7=__commonJS({"node_modules/node-forge/lib/util.js"(exports,module){"use strict";var forge2=require_forge();var baseN=require_baseN();var util=module.exports=forge2.util=forge2.util||{};(function(){if(typeof process!=="undefined"&&process.nextTick&&!process.browser){util.nextTick=process.nextTick;if(typeof setImmediate==="function"){util.setImmediate=setImmediate}else{util.setImmediate=util.nextTick}return}if(typeof setImmediate==="function"){util.setImmediate=function(){return setImmediate.apply(void 0,arguments)};util.nextTick=function(callback){return setImmediate(callback)};return}util.setImmediate=function(callback){setTimeout(callback,0)};if(typeof window!=="undefined"&&typeof window.postMessage==="function"){let handler2=function(event){if(event.source===window&&event.data===msg){event.stopPropagation();var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}};var handler=handler2;var msg="forge.setImmediate";var callbacks=[];util.setImmediate=function(callback){callbacks.push(callback);if(callbacks.length===1){window.postMessage(msg,"*")}};window.addEventListener("message",handler2,true)}if(typeof MutationObserver!=="undefined"){var now=Date.now();var attr=true;var div=document.createElement("div");var callbacks=[];new MutationObserver(function(){var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}).observe(div,{attributes:true});var oldSetImmediate=util.setImmediate;util.setImmediate=function(callback){if(Date.now()-now>15){now=Date.now();oldSetImmediate(callback)}else{callbacks.push(callback);if(callbacks.length===1){div.setAttribute("a",attr=!attr)}}}}util.nextTick=util.setImmediate})();util.isNodejs=typeof process!=="undefined"&&process.versions&&process.versions.node;util.globalScope=(function(){if(util.isNodejs){return global}return typeof self==="undefined"?window:self})();util.isArray=Array.isArray||function(x){return Object.prototype.toString.call(x)==="[object Array]"};util.isArrayBuffer=function(x){return typeof ArrayBuffer!=="undefined"&&x instanceof ArrayBuffer};util.isArrayBufferView=function(x){return x&&util.isArrayBuffer(x.buffer)&&x.byteLength!==void 0};function _checkBitsParam(n){if(!(n===8||n===16||n===24||n===32)){throw new Error("Only 8, 16, 24, or 32 bits supported: "+n)}}util.ByteBuffer=ByteStringBuffer;function ByteStringBuffer(b2){this.data="";this.read=0;if(typeof b2==="string"){this.data=b2}else if(util.isArrayBuffer(b2)||util.isArrayBufferView(b2)){if(typeof Buffer!=="undefined"&&b2 instanceof Buffer){this.data=b2.toString("binary")}else{var arr=new Uint8Array(b2);try{this.data=String.fromCharCode.apply(null,arr)}catch(e){for(var i=0;i<arr.length;++i){this.putByte(arr[i])}}}}else if(b2 instanceof ByteStringBuffer||typeof b2==="object"&&typeof b2.data==="string"&&typeof b2.read==="number"){this.data=b2.data;this.read=b2.read}this._constructedStringLength=0}util.ByteStringBuffer=ByteStringBuffer;var _MAX_CONSTRUCTED_STRING_LENGTH=4096;util.ByteStringBuffer.prototype._optimizeConstructedString=function(x){this._constructedStringLength+=x;if(this._constructedStringLength>_MAX_CONSTRUCTED_STRING_LENGTH){this.data.substr(0,1);this._constructedStringLength=0}};util.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};util.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};util.ByteStringBuffer.prototype.putByte=function(b2){return this.putBytes(String.fromCharCode(b2))};util.ByteStringBuffer.prototype.fillWithByte=function(b2,n){b2=String.fromCharCode(b2);var d=this.data;while(n>0){if(n&1){d+=b2}n>>>=1;if(n>0){b2+=b2}}this.data=d;this._optimizeConstructedString(n);return this};util.ByteStringBuffer.prototype.putBytes=function(bytes){this.data+=bytes;this._optimizeConstructedString(bytes.length);return this};util.ByteStringBuffer.prototype.putString=function(str){return this.putBytes(util.encodeUtf8(str))};util.ByteStringBuffer.prototype.putInt16=function(i){return this.putBytes(String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt24=function(i){return this.putBytes(String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.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(i&255))};util.ByteStringBuffer.prototype.putInt16Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255))};util.ByteStringBuffer.prototype.putInt24Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255))};util.ByteStringBuffer.prototype.putInt32Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>24&255))};util.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.ByteStringBuffer.prototype.putSignedInt=function(i,n){if(i<0){i+=2<<n-1}return this.putInt(i,n)};util.ByteStringBuffer.prototype.putBuffer=function(buffer){return this.putBytes(buffer.getBytes())};util.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};util.ByteStringBuffer.prototype.getInt16=function(){var rval=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);this.read+=2;return rval};util.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);this.read+=3;return rval};util.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);this.read+=4;return rval};util.ByteStringBuffer.prototype.getInt16Le=function(){var rval=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;this.read+=2;return rval};util.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;this.read+=3;return rval};util.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;this.read+=4;return rval};util.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.ByteStringBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<<n-2;if(x>=max){x-=max<<1}return x};util.ByteStringBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.ByteStringBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.ByteStringBuffer.prototype.at=function(i){return this.data.charCodeAt(this.read+i)};util.ByteStringBuffer.prototype.setAt=function(i,b2){this.data=this.data.substr(0,this.read+i)+String.fromCharCode(b2)+this.data.substr(this.read+i+1);return this};util.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};util.ByteStringBuffer.prototype.copy=function(){var c=util.createBuffer(this.data);c.read=this.read;return c};util.ByteStringBuffer.prototype.compact=function(){if(this.read>0){this.data=this.data.slice(this.read);this.read=0}return this};util.ByteStringBuffer.prototype.clear=function(){this.data="";this.read=0;return this};util.ByteStringBuffer.prototype.truncate=function(count){var len=Math.max(0,this.length()-count);this.data=this.data.substr(this.read,len);this.read=0;return this};util.ByteStringBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i<this.data.length;++i){var b2=this.data.charCodeAt(i);if(b2<16){rval+="0"}rval+=b2.toString(16)}return rval};util.ByteStringBuffer.prototype.toString=function(){return util.decodeUtf8(this.bytes())};function DataBuffer(b2,options){options=options||{};this.read=options.readOffset||0;this.growSize=options.growSize||1024;var isArrayBuffer=util.isArrayBuffer(b2);var isArrayBufferView=util.isArrayBufferView(b2);if(isArrayBuffer||isArrayBufferView){if(isArrayBuffer){this.data=new DataView(b2)}else{this.data=new DataView(b2.buffer,b2.byteOffset,b2.byteLength)}this.write="writeOffset"in options?options.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0));this.write=0;if(b2!==null&&b2!==void 0){this.putBytes(b2)}if("writeOffset"in options){this.write=options.writeOffset}}util.DataBuffer=DataBuffer;util.DataBuffer.prototype.length=function(){return this.write-this.read};util.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};util.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);var dst=new Uint8Array(this.length()+growSize);dst.set(src);this.data=new DataView(dst.buffer);return this};util.DataBuffer.prototype.putByte=function(b2){this.accommodate(1);this.data.setUint8(this.write++,b2);return this};util.DataBuffer.prototype.fillWithByte=function(b2,n){this.accommodate(n);for(var i=0;i<n;++i){this.data.setUint8(b2)}return this};util.DataBuffer.prototype.putBytes=function(bytes,encoding){if(util.isArrayBufferView(bytes)){var src=new Uint8Array(bytes.buffer,bytes.byteOffset,bytes.byteLength);var len=src.byteLength-src.byteOffset;this.accommodate(len);var dst=new Uint8Array(this.data.buffer,this.write);dst.set(src);this.write+=len;return this}if(util.isArrayBuffer(bytes)){var src=new Uint8Array(bytes);this.accommodate(src.byteLength);var dst=new Uint8Array(this.data.buffer);dst.set(src,this.write);this.write+=src.byteLength;return this}if(bytes instanceof util.DataBuffer||typeof bytes==="object"&&typeof bytes.read==="number"&&typeof bytes.write==="number"&&util.isArrayBufferView(bytes.data)){var src=new Uint8Array(bytes.data.byteLength,bytes.read,bytes.length());this.accommodate(src.byteLength);var dst=new Uint8Array(bytes.data.byteLength,this.write);dst.set(src);this.write+=src.byteLength;return this}if(bytes instanceof util.ByteStringBuffer){bytes=bytes.data;encoding="binary"}encoding=encoding||"binary";if(typeof bytes==="string"){var view;if(encoding==="hex"){this.accommodate(Math.ceil(bytes.length/2));view=new Uint8Array(this.data.buffer,this.write);this.write+=util.binary.hex.decode(bytes,view,this.write);return this}if(encoding==="base64"){this.accommodate(Math.ceil(bytes.length/4)*3);view=new Uint8Array(this.data.buffer,this.write);this.write+=util.binary.base64.decode(bytes,view,this.write);return this}if(encoding==="utf8"){bytes=util.encodeUtf8(bytes);encoding="binary"}if(encoding==="binary"||encoding==="raw"){this.accommodate(bytes.length);view=new Uint8Array(this.data.buffer,this.write);this.write+=util.binary.raw.decode(view);return this}if(encoding==="utf16"){this.accommodate(bytes.length*2);view=new Uint16Array(this.data.buffer,this.write);this.write+=util.text.utf16.encode(view);return this}throw new Error("Invalid encoding: "+encoding)}throw Error("Invalid parameter: "+bytes)};util.DataBuffer.prototype.putBuffer=function(buffer){this.putBytes(buffer);buffer.clear();return this};util.DataBuffer.prototype.putString=function(str){return this.putBytes(str,"utf16")};util.DataBuffer.prototype.putInt16=function(i){this.accommodate(2);this.data.setInt16(this.write,i);this.write+=2;return this};util.DataBuffer.prototype.putInt24=function(i){this.accommodate(3);this.data.setInt16(this.write,i>>8&65535);this.data.setInt8(this.write,i>>16&255);this.write+=3;return this};util.DataBuffer.prototype.putInt32=function(i){this.accommodate(4);this.data.setInt32(this.write,i);this.write+=4;return this};util.DataBuffer.prototype.putInt16Le=function(i){this.accommodate(2);this.data.setInt16(this.write,i,true);this.write+=2;return this};util.DataBuffer.prototype.putInt24Le=function(i){this.accommodate(3);this.data.setInt8(this.write,i>>16&255);this.data.setInt16(this.write,i>>8&65535,true);this.write+=3;return this};util.DataBuffer.prototype.putInt32Le=function(i){this.accommodate(4);this.data.setInt32(this.write,i,true);this.write+=4;return this};util.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.DataBuffer.prototype.putSignedInt=function(i,n){_checkBitsParam(n);this.accommodate(n/8);if(i<0){i+=2<<n-1}return this.putInt(i,n)};util.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};util.DataBuffer.prototype.getInt16=function(){var rval=this.data.getInt16(this.read);this.read+=2;return rval};util.DataBuffer.prototype.getInt24=function(){var rval=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);this.read+=3;return rval};util.DataBuffer.prototype.getInt32=function(){var rval=this.data.getInt32(this.read);this.read+=4;return rval};util.DataBuffer.prototype.getInt16Le=function(){var rval=this.data.getInt16(this.read,true);this.read+=2;return rval};util.DataBuffer.prototype.getInt24Le=function(){var rval=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,true)<<8;this.read+=3;return rval};util.DataBuffer.prototype.getInt32Le=function(){var rval=this.data.getInt32(this.read,true);this.read+=4;return rval};util.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.DataBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<<n-2;if(x>=max){x-=max<<1}return x};util.DataBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.DataBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.DataBuffer.prototype.at=function(i){return this.data.getUint8(this.read+i)};util.DataBuffer.prototype.setAt=function(i,b2){this.data.setUint8(i,b2);return this};util.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};util.DataBuffer.prototype.copy=function(){return new util.DataBuffer(this)};util.DataBuffer.prototype.compact=function(){if(this.read>0){var src=new Uint8Array(this.data.buffer,this.read);var dst=new Uint8Array(src.byteLength);dst.set(src);this.data=new DataView(dst);this.write-=this.read;this.read=0}return this};util.DataBuffer.prototype.clear=function(){this.data=new DataView(new ArrayBuffer(0));this.read=this.write=0;return this};util.DataBuffer.prototype.truncate=function(count){this.write=Math.max(0,this.length()-count);this.read=Math.min(this.read,this.write);return this};util.DataBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i<this.data.byteLength;++i){var b2=this.data.getUint8(i);if(b2<16){rval+="0"}rval+=b2.toString(16)}return rval};util.DataBuffer.prototype.toString=function(encoding){var view=new Uint8Array(this.data,this.read,this.length());encoding=encoding||"utf8";if(encoding==="binary"||encoding==="raw"){return util.binary.raw.encode(view)}if(encoding==="hex"){return util.binary.hex.encode(view)}if(encoding==="base64"){return util.binary.base64.encode(view)}if(encoding==="utf8"){return util.text.utf8.decode(view)}if(encoding==="utf16"){return util.text.utf16.decode(view)}throw new Error("Invalid encoding: "+encoding)};util.createBuffer=function(input,encoding){encoding=encoding||"raw";if(input!==void 0&&encoding==="utf8"){input=util.encodeUtf8(input)}return new util.ByteBuffer(input)};util.fillString=function(c,n){var s3="";while(n>0){if(n&1){s3+=c}n>>>=1;if(n>0){c+=c}}return s3};util.xorBytes=function(s1,s22,n){var s3="";var b2="";var t="";var i=0;var c=0;for(;n>0;--n,++i){b2=s1.charCodeAt(i)^s22.charCodeAt(i);if(c>=10){s3+=t;t="";c=0}t+=String.fromCharCode(b2);++c}s3+=t;return s3};util.hexToBytes=function(hex){var rval="";var i=0;if(hex.length&true){i=1;rval+=String.fromCharCode(parseInt(hex[0],16))}for(;i<hex.length;i+=2){rval+=String.fromCharCode(parseInt(hex.substr(i,2),16))}return rval};util.bytesToHex=function(bytes){return util.createBuffer(bytes).toHex()};util.int32ToBytes=function(i){return String.fromCharCode(i>>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255)};var _base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var _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];var _base58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";util.encode64=function(input,maxline){var line="";var output="";var chr1,chr2,chr3;var i=0;while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);line+=_base64.charAt(chr1>>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.decode64=function(input){input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");var output="";var enc1,enc2,enc3,enc4;var i=0;while(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);if(enc3!==64){output+=String.fromCharCode((enc2&15)<<4|enc3>>2);if(enc4!==64){output+=String.fromCharCode((enc3&3)<<6|enc4)}}}return output};util.encodeUtf8=function(str){return unescape(encodeURIComponent(str))};util.decodeUtf8=function(str){return decodeURIComponent(escape(str))};util.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:baseN.encode,decode:baseN.decode}};util.binary.raw.encode=function(bytes){return String.fromCharCode.apply(null,bytes)};util.binary.raw.decode=function(str,output,offset){var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j2=offset;for(var i=0;i<str.length;++i){out[j2++]=str.charCodeAt(i)}return output?j2-offset:out};util.binary.hex.encode=util.bytesToHex;util.binary.hex.decode=function(hex,output,offset){var out=output;if(!out){out=new Uint8Array(Math.ceil(hex.length/2))}offset=offset||0;var i=0,j2=offset;if(hex.length&1){i=1;out[j2++]=parseInt(hex[0],16)}for(;i<hex.length;i+=2){out[j2++]=parseInt(hex.substr(i,2),16)}return output?j2-offset:out};util.binary.base64.encode=function(input,maxline){var line="";var output="";var chr1,chr2,chr3;var i=0;while(i<input.byteLength){chr1=input[i++];chr2=input[i++];chr3=input[i++];line+=_base64.charAt(chr1>>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.binary.base64.decode=function(input,output,offset){var out=output;if(!out){out=new Uint8Array(Math.ceil(input.length/4)*3)}input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");offset=offset||0;var enc1,enc2,enc3,enc4;var i=0,j2=offset;while(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[j2++]=enc1<<2|enc2>>4;if(enc3!==64){out[j2++]=(enc2&15)<<4|enc3>>2;if(enc4!==64){out[j2++]=(enc3&3)<<6|enc4}}}return output?j2-offset:out.subarray(0,j2)};util.binary.base58.encode=function(input,maxline){return util.binary.baseN.encode(input,_base58,maxline)};util.binary.base58.decode=function(input,maxline){return util.binary.baseN.decode(input,_base58,maxline)};util.text={utf8:{},utf16:{}};util.text.utf8.encode=function(str,output,offset){str=util.encodeUtf8(str);var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j2=offset;for(var i=0;i<str.length;++i){out[j2++]=str.charCodeAt(i)}return output?j2-offset:out};util.text.utf8.decode=function(bytes){return util.decodeUtf8(String.fromCharCode.apply(null,bytes))};util.text.utf16.encode=function(str,output,offset){var out=output;if(!out){out=new Uint8Array(str.length*2)}var view=new Uint16Array(out.buffer);offset=offset||0;var j2=offset;var k2=offset;for(var i=0;i<str.length;++i){view[k2++]=str.charCodeAt(i);j2+=2}return output?j2-offset:out};util.text.utf16.decode=function(bytes){return String.fromCharCode.apply(null,new Uint16Array(bytes.buffer))};util.deflate=function(api,bytes,raw){bytes=util.decode64(api.deflate(util.encode64(bytes)).rval);if(raw){var start=2;var flg=bytes.charCodeAt(1);if(flg&32){start=6}bytes=bytes.substring(start,bytes.length-4)}return bytes};util.inflate=function(api,bytes,raw){var rval=api.inflate(util.encode64(bytes)).rval;return rval===null?null:util.decode64(rval)};var _setStorageObject=function(api,id,obj){if(!api){throw new Error("WebStorage not available.")}var rval;if(obj===null){rval=api.removeItem(id)}else{obj=util.encode64(JSON.stringify(obj));rval=api.setItem(id,obj)}if(typeof rval!=="undefined"&&rval.rval!==true){var error=new Error(rval.error.message);error.id=rval.error.id;error.name=rval.error.name;throw error}};var _getStorageObject=function(api,id){if(!api){throw new Error("WebStorage not available.")}var rval=api.getItem(id);if(api.init){if(rval.rval===null){if(rval.error){var error=new Error(rval.error.message);error.id=rval.error.id;error.name=rval.error.name;throw error}rval=null}else{rval=rval.rval}}if(rval!==null){rval=JSON.parse(util.decode64(rval))}return rval};var _setItem=function(api,id,key,data){var obj=_getStorageObject(api,id);if(obj===null){obj={}}obj[key]=data;_setStorageObject(api,id,obj)};var _getItem=function(api,id,key){var rval=_getStorageObject(api,id);if(rval!==null){rval=key in rval?rval[key]:null}return rval};var _removeItem=function(api,id,key){var obj=_getStorageObject(api,id);if(obj!==null&&key in obj){delete obj[key];var empty=true;for(var prop in obj){empty=false;break}if(empty){obj=null}_setStorageObject(api,id,obj)}};var _clearItems=function(api,id){_setStorageObject(api,id,null)};var _callStorageFunction=function(func,args,location){var rval=null;if(typeof location==="undefined"){location=["web","flash"]}var type;var done=false;var exception=null;for(var idx in location){type=location[idx];try{if(type==="flash"||type==="both"){if(args[0]===null){throw new Error("Flash local storage not available.")}rval=func.apply(this,args);done=type==="flash"}if(type==="web"||type==="both"){args[0]=localStorage;rval=func.apply(this,args);done=true}}catch(ex){exception=ex}if(done){break}}if(!done){throw exception}return rval};util.setItem=function(api,id,key,data,location){_callStorageFunction(_setItem,arguments,location)};util.getItem=function(api,id,key,location){return _callStorageFunction(_getItem,arguments,location)};util.removeItem=function(api,id,key,location){_callStorageFunction(_removeItem,arguments,location)};util.clearItems=function(api,id,location){_callStorageFunction(_clearItems,arguments,location)};util.isEmpty=function(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){return false}}return true};util.format=function(format2){var re2=/%./g;var match;var part;var argi=0;var parts=[];var last=0;while(match=re2.exec(format2)){part=format2.substring(last,re2.lastIndex-2);if(part.length>0){parts.push(part)}last=re2.lastIndex;var code=match[0][1];switch(code){case"s":case"o":if(argi<arguments.length){parts.push(arguments[argi+++1])}else{parts.push("<?>")}break;case"%":parts.push("%");break;default:parts.push("<%"+code+"?>")}}parts.push(format2.substring(last));return parts.join("")};util.formatNumber=function(number,decimals,dec_point,thousands_sep){var n=number,c=isNaN(decimals=Math.abs(decimals))?2:decimals;var d=dec_point===void 0?",":dec_point;var t=thousands_sep===void 0?".":thousands_sep,s3=n<0?"-":"";var i=parseInt(n=Math.abs(+n||0).toFixed(c),10)+"";var j2=i.length>3?i.length%3:0;return s3+(j2?i.substr(0,j2)+t:"")+i.substr(j2).replace(/(\d{3})(?=\d)/g,"$1"+t)+(c?d+Math.abs(n-i).toFixed(c).slice(2):"")};util.formatSize=function(size){if(size>=1073741824){size=util.formatNumber(size/1073741824,2,".","")+" GiB"}else if(size>=1048576){size=util.formatNumber(size/1048576,2,".","")+" MiB"}else if(size>=1024){size=util.formatNumber(size/1024,0)+" KiB"}else{size=util.formatNumber(size,0)+" bytes"}return size};util.bytesFromIP=function(ip){if(ip.indexOf(".")!==-1){return util.bytesFromIPv4(ip)}if(ip.indexOf(":")!==-1){return util.bytesFromIPv6(ip)}return null};util.bytesFromIPv4=function(ip){ip=ip.split(".");if(ip.length!==4){return null}var b2=util.createBuffer();for(var i=0;i<ip.length;++i){var num=parseInt(ip[i],10);if(isNaN(num)){return null}b2.putByte(num)}return b2.getBytes()};util.bytesFromIPv6=function(ip){var blanks=0;ip=ip.split(":").filter(function(e){if(e.length===0)++blanks;return true});var zeros=(8-ip.length+blanks)*2;var b2=util.createBuffer();for(var i=0;i<8;++i){if(!ip[i]||ip[i].length===0){b2.fillWithByte(0,zeros);zeros=0;continue}var bytes=util.hexToBytes(ip[i]);if(bytes.length<2){b2.putByte(0)}b2.putBytes(bytes)}return b2.getBytes()};util.bytesToIP=function(bytes){if(bytes.length===4){return util.bytesToIPv4(bytes)}if(bytes.length===16){return util.bytesToIPv6(bytes)}return null};util.bytesToIPv4=function(bytes){if(bytes.length!==4){return null}var ip=[];for(var i=0;i<bytes.length;++i){ip.push(bytes.charCodeAt(i))}return ip.join(".")};util.bytesToIPv6=function(bytes){if(bytes.length!==16){return null}var ip=[];var zeroGroups=[];var zeroMaxGroup=0;for(var i=0;i<bytes.length;i+=2){var hex=util.bytesToHex(bytes[i]+bytes[i+1]);while(hex[0]==="0"&&hex!=="0"){hex=hex.substr(1)}if(hex==="0"){var last=zeroGroups[zeroGroups.length-1];var idx=ip.length;if(!last||idx!==last.end+1){zeroGroups.push({start:idx,end:idx})}else{last.end=idx;if(last.end-last.start>zeroGroups[zeroMaxGroup].end-zeroGroups[zeroMaxGroup].start){zeroMaxGroup=zeroGroups.length-1}}}ip.push(hex)}if(zeroGroups.length>0){var group=zeroGroups[zeroMaxGroup];if(group.end-group.start>0){ip.splice(group.start,group.end-group.start+1,"");if(group.start===0){ip.unshift("")}if(group.end===7){ip.push("")}}}return ip.join(":")};util.estimateCores=function(options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};if("cores"in util&&!options.update){return callback(null,util.cores)}if(typeof navigator!=="undefined"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0){util.cores=navigator.hardwareConcurrency;return callback(null,util.cores)}if(typeof Worker==="undefined"){util.cores=1;return callback(null,util.cores)}if(typeof Blob==="undefined"){util.cores=2;return callback(null,util.cores)}var blobUrl=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){var st2=Date.now();var et2=st2+4;while(Date.now()<et2);self.postMessage({st:st2,et:et2})})}.toString(),")()"],{type:"application/javascript"}));sample([],5,16);function sample(max,samples,numWorkers){if(samples===0){var avg=Math.floor(max.reduce(function(avg2,x){return avg2+x},0)/max.length);util.cores=Math.max(1,avg);URL.revokeObjectURL(blobUrl);return callback(null,util.cores)}map(numWorkers,function(err,results){max.push(reduce(numWorkers,results));sample(max,samples-1,numWorkers)})}function map(numWorkers,callback2){var workers=[];var results=[];for(var i=0;i<numWorkers;++i){var worker=new Worker(blobUrl);worker.addEventListener("message",function(e){results.push(e.data);if(results.length===numWorkers){for(var i2=0;i2<numWorkers;++i2){workers[i2].terminate()}callback2(null,results)}});workers.push(worker)}for(var i=0;i<numWorkers;++i){workers[i].postMessage(i)}}function reduce(numWorkers,results){var overlaps=[];for(var n=0;n<numWorkers;++n){var r1=results[n];var overlap=overlaps[n]=[];for(var i=0;i<numWorkers;++i){if(n===i){continue}var r2=results[i];if(r1.st>r2.st&&r1.st<r2.et||r2.st>r1.st&&r2.st<r1.et){overlap.push(i)}}}return overlaps.reduce(function(max,overlap2){return Math.max(max,overlap2.length)},0)}}}});var require_cipher=__commonJS({"node_modules/node-forge/lib/cipher.js"(exports,module){"use strict";var forge2=require_forge();require_util7();module.exports=forge2.cipher=forge2.cipher||{};forge2.cipher.algorithms=forge2.cipher.algorithms||{};forge2.cipher.createCipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge2.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge2.cipher.BlockCipher({algorithm:api,key,decrypt:false})};forge2.cipher.createDecipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge2.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge2.cipher.BlockCipher({algorithm:api,key,decrypt:true})};forge2.cipher.registerAlgorithm=function(name,algorithm){name=name.toUpperCase();forge2.cipher.algorithms[name]=algorithm};forge2.cipher.getAlgorithm=function(name){name=name.toUpperCase();if(name in forge2.cipher.algorithms){return forge2.cipher.algorithms[name]}return null};var BlockCipher=forge2.cipher.BlockCipher=function(options){this.algorithm=options.algorithm;this.mode=this.algorithm.mode;this.blockSize=this.mode.blockSize;this._finish=false;this._input=null;this.output=null;this._op=options.decrypt?this.mode.decrypt:this.mode.encrypt;this._decrypt=options.decrypt;this.algorithm.initialize(options)};BlockCipher.prototype.start=function(options){options=options||{};var opts={};for(var key in options){opts[key]=options[key]}opts.decrypt=this._decrypt;this._finish=false;this._input=forge2.util.createBuffer();this.output=options.output||forge2.util.createBuffer();this.mode.start(opts)};BlockCipher.prototype.update=function(input){if(input){this._input.putBuffer(input)}while(!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish){}this._input.compact()};BlockCipher.prototype.finish=function(pad){if(pad&&(this.mode.name==="ECB"||this.mode.name==="CBC")){this.mode.pad=function(input){return pad(this.blockSize,input,false)};this.mode.unpad=function(output){return pad(this.blockSize,output,true)}}var options={};options.decrypt=this._decrypt;options.overflow=this._input.length()%this.blockSize;if(!this._decrypt&&this.mode.pad){if(!this.mode.pad(this._input,options)){return false}}this._finish=true;this.update();if(this._decrypt&&this.mode.unpad){if(!this.mode.unpad(this.output,options)){return false}}if(this.mode.afterFinish){if(!this.mode.afterFinish(this.output,options)){return false}}return true}}});var require_cipherModes=__commonJS({"node_modules/node-forge/lib/cipherModes.js"(exports,module){"use strict";var forge2=require_forge();require_util7();forge2.cipher=forge2.cipher||{};var modes=module.exports=forge2.cipher.modes=forge2.cipher.modes||{};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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()}this.cipher.encrypt(this._inBlock,this._outBlock);for(var 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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()}this.cipher.decrypt(this._inBlock,this._outBlock);for(var 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();input.fillWithByte(padding,padding);return true};modes.ecb.prototype.unpad=function(output,options){if(options.overflow>0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};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(options.iv===null){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.")}else{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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=this._prev[i]^input.getInt32()}this.cipher.encrypt(this._inBlock,this._outBlock);for(var 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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()}this.cipher.decrypt(this._inBlock,this._outBlock);for(var 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();input.fillWithByte(padding,padding);return true};modes.cbc.prototype.unpad=function(output,options){if(options.overflow>0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};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=forge2.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(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()^this._outBlock[i];output.putInt32(this._inBlock[i])}return}var partialBytes=(this.blockSize-inputLength)%this.blockSize;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var 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(var i=0;i<this._ints;++i){this._inBlock[i]=this._partialBlock[i]}}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.cfb.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32();output.putInt32(this._inBlock[i]^this._outBlock[i])}return}var partialBytes=(this.blockSize-inputLength)%this.blockSize;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var 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(var i=0;i<this._ints;++i){this._inBlock[i]=this._partialBlock[i]}}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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=forge2.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(input.length()===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i<this._ints;++i){output.putInt32(input.getInt32()^this._outBlock[i]);this._inBlock[i]=this._outBlock[i]}return}var partialBytes=(this.blockSize-inputLength)%this.blockSize;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i<this._ints;++i){this._partialOutput.putInt32(input.getInt32()^this._outBlock[i])}if(partialBytes>0){input.read-=this.blockSize}else{for(var i=0;i<this._ints;++i){this._inBlock[i]=this._outBlock[i]}}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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=forge2.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(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&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;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i<this._ints;++i){this._partialOutput.putInt32(input.getInt32()^this._outBlock[i])}if(partialBytes>0){input.read-=this.blockSize}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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=forge2.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 iv=forge2.util.createBuffer(options.iv);this._cipherLength=0;var additionalData;if("additionalData"in options){additionalData=forge2.util.createBuffer(options.additionalData)}else{additionalData=forge2.util.createBuffer()}if("tagLength"in options){this._tagLength=options.tagLength}else{this._tagLength=128}this._tag=null;if(options.decrypt){this._tag=forge2.util.createBuffer(options.tag).getBytes();if(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(ivLength===12){this._j0=[iv.getInt32(),iv.getInt32(),iv.getInt32(),1]}else{this._j0=[0,0,0,0];while(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(ivLength*8)))}this._inBlock=this._j0.slice(0);inc32(this._inBlock);this._partialBytes=0;additionalData=forge2.util.createBuffer(additionalData);this._aDataLength=from64To32(additionalData.length()*8);var overflow=additionalData.length()%this.blockSize;if(overflow){additionalData.fillWithByte(0,this.blockSize-overflow)}this._s=[0,0,0,0];while(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(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&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;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var 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(var 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)}if(partialBytes>0&&!finish){input.read-=this.blockSize;output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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 true}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])}if(inputLength<this.blockSize){this._cipherLength+=inputLength%this.blockSize}else{this._cipherLength+=this.blockSize}};modes.gcm.prototype.afterFinish=function(output,options){var rval=true;if(options.decrypt&&options.overflow){output.truncate(this.blockSize-options.overflow)}this.tag=forge2.util.createBuffer();var lengths=this._aDataLength.concat(from64To32(this._cipherLength*8));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])}this.tag.truncate(this.tag.length()%(this._tagLength/8));if(options.decrypt&&this.tag.bytes()!==this._tag){rval=false}return rval};modes.gcm.prototype.multiply=function(x,y){var z_i=[0,0,0,0];var v_i=y.slice(0);for(var i=0;i<128;++i){var x_i=x[i/32|0]&1<<31-i%32;if(x_i){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){var lsb=x[3]&1;for(var i=3;i>0;--i){out[i]=x[i]>>>1|(x[i-1]&1)<<31}out[0]=x[0]>>>1;if(lsb){out[0]^=this._R}};modes.gcm.prototype.tableMultiply=function(x){var z2=[0,0,0,0];for(var i=0;i<32;++i){var idx=i/8|0;var x_i=x[idx]>>>(7-i%8)*4&15;var ah=this._m[i][x_i];z2[0]^=ah[0];z2[1]^=ah[1];z2[2]^=ah[2];z2[3]^=ah[3]}return z2};modes.gcm.prototype.ghash=function(h,y,x){y[0]^=x[0];y[1]^=x[1];y[2]^=x[2];y[3]^=x[3];return this.tableMultiply(y)};modes.gcm.prototype.generateHashTable=function(h,bits){var multiplier=8/bits;var perInt=4*multiplier;var size=16*multiplier;var m2=new Array(size);for(var i=0;i<size;++i){var tmp=[0,0,0,0];var idx=i/perInt|0;var shft=(perInt-1-i%perInt)*bits;tmp[idx]=1<<bits-1<<shft;m2[i]=this.generateSubHashTable(this.multiply(tmp,h),bits)}return m2};modes.gcm.prototype.generateSubHashTable=function(mid,bits){var size=1<<bits;var half=size>>>1;var m2=new Array(size);m2[half]=mid.slice(0);var i=half>>>1;while(i>0){this.pow(m2[2*i],m2[i]=[]);i>>=1}i=2;while(i<half){for(var j2=1;j2<i;++j2){var m_i=m2[i];var m_j=m2[j2];m2[i+j2]=[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}m2[0]=[0,0,0,0];for(i=half+1;i<size;++i){var c=m2[i^half];m2[i]=[mid[0]^c[0],mid[1]^c[1],mid[2]^c[2],mid[3]^c[3]]}return m2};function transformIV(iv,blockSize){if(typeof iv==="string"){iv=forge2.util.createBuffer(iv)}if(forge2.util.isArray(iv)&&iv.length>4){var tmp=iv;iv=forge2.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(!forge2.util.isArray(iv)){var ints=[];var blocks=blockSize/4;for(var 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,num&4294967295]}}});var require_aes=__commonJS({"node_modules/node-forge/lib/aes.js"(exports,module){"use strict";var forge2=require_forge();require_cipher();require_cipherModes();require_util7();module.exports=forge2.aes=forge2.aes||{};forge2.aes.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:false,mode});cipher.start(iv);return cipher};forge2.aes.createEncryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:false,mode})};forge2.aes.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:true,mode});cipher.start(iv);return cipher};forge2.aes.createDecryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:true,mode})};forge2.aes.Algorithm=function(name,mode){if(!init){initialize()}var self2=this;self2.name=name;self2.mode=new mode({blockSize:16,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self2._w,inBlock,outBlock,false)},decrypt:function(inBlock,outBlock){return _updateBlock(self2._w,inBlock,outBlock,true)}}});self2._init=false};forge2.aes.Algorithm.prototype.initialize=function(options){if(this._init){return}var key=options.key;var tmp;if(typeof key==="string"&&(key.length===16||key.length===24||key.length===32)){key=forge2.util.createBuffer(key)}else if(forge2.util.isArray(key)&&(key.length===16||key.length===24||key.length===32)){tmp=key;key=forge2.util.createBuffer();for(var i=0;i<tmp.length;++i){key.putByte(tmp[i])}}if(!forge2.util.isArray(key)){tmp=key;key=[];var len=tmp.length();if(len===16||len===24||len===32){len=len>>>2;for(var i=0;i<len;++i){key.push(tmp.getInt32())}}}if(!forge2.util.isArray(key)||!(key.length===4||key.length===6||key.length===8)){throw new Error("Invalid key parameter.")}var mode=this.mode.name;var encryptOp=["CFB","OFB","CTR","GCM"].indexOf(mode)!==-1;this._w=_expandKey(key,options.decrypt&&!encryptOp);this._init=true};forge2.aes._expandKey=function(key,decrypt){if(!init){initialize()}return _expandKey(key,decrypt)};forge2.aes._updateBlock=_updateBlock;registerAlgorithm("AES-ECB",forge2.cipher.modes.ecb);registerAlgorithm("AES-CBC",forge2.cipher.modes.cbc);registerAlgorithm("AES-CFB",forge2.cipher.modes.cfb);registerAlgorithm("AES-OFB",forge2.cipher.modes.ofb);registerAlgorithm("AES-CTR",forge2.cipher.modes.ctr);registerAlgorithm("AES-GCM",forge2.cipher.modes.gcm);function registerAlgorithm(name,mode){var factory=function(){return new forge2.aes.Algorithm(name,mode)};forge2.cipher.registerAlgorithm(name,factory)}var init=false;var Nb=4;var sbox;var isbox;var rcon;var mix;var imix;function initialize(){init=true;rcon=[0,1,2,4,8,16,32,64,128,27,54];var xtime=new Array(256);for(var 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(var i=0;i<4;++i){mix[i]=new Array(256);imix[i]=new Array(256)}var e=0,ei2=0,e2,e4,e8,sx,sx2,me2,ime;for(var i=0;i<256;++i){sx=ei2^ei2<<1^ei2<<2^ei2<<3^ei2<<4;sx=sx>>8^sx&255^99;sbox[e]=sx;isbox[sx]=e;sx2=xtime[sx];e2=xtime[e];e4=xtime[e2];e8=xtime[e4];me2=sx2<<24^sx<<16^sx<<8^(sx^sx2);ime=(e2^e4^e8)<<24^(e^e8)<<16^(e^e4^e8)<<8^(e^e2^e8);for(var n=0;n<4;++n){mix[n][e]=me2;imix[n][sx]=ime;me2=me2<<24|me2>>>8;ime=ime<<24|ime>>>8}if(e===0){e=ei2=1}else{e=e2^xtime[xtime[xtime[e2^e8]]];ei2^=xtime[xtime[ei2]]}}}function _expandKey(key,decrypt){var w2=key.slice(0);var temp,iNk=1;var Nk=w2.length;var Nr1=Nk+6+1;var end=Nb*Nr1;for(var i=Nk;i<end;++i){temp=w2[i-1];if(i%Nk===0){temp=sbox[temp>>>16&255]<<24^sbox[temp>>>8&255]<<16^sbox[temp&255]<<8^sbox[temp>>>24]^rcon[iNk]<<24;iNk++}else if(Nk>6&&i%Nk===4){temp=sbox[temp>>>24]<<24^sbox[temp>>>16&255]<<16^sbox[temp>>>8&255]<<8^sbox[temp&255]}w2[i]=w2[i-Nk]^temp}if(decrypt){var tmp;var m0=imix[0];var m1=imix[1];var m2=imix[2];var m3=imix[3];var wnew=w2.slice(0);end=w2.length;for(var i=0,wi2=end-Nb;i<end;i+=Nb,wi2-=Nb){if(i===0||i===end-Nb){wnew[i]=w2[wi2];wnew[i+1]=w2[wi2+3];wnew[i+2]=w2[wi2+2];wnew[i+3]=w2[wi2+1]}else{for(var n=0;n<Nb;++n){tmp=w2[wi2+n];wnew[i+(3&-n)]=m0[sbox[tmp>>>24]]^m1[sbox[tmp>>>16&255]]^m2[sbox[tmp>>>8&255]]^m3[sbox[tmp&255]]}}}w2=wnew}return w2}function _updateBlock(w2,input,output,decrypt){var Nr2=w2.length/4-1;var m0,m1,m2,m3,sub;if(decrypt){m0=imix[0];m1=imix[1];m2=imix[2];m3=imix[3];sub=isbox}else{m0=mix[0];m1=mix[1];m2=mix[2];m3=mix[3];sub=sbox}var a,b2,c,d,a2,b22,c2;a=input[0]^w2[0];b2=input[decrypt?3:1]^w2[1];c=input[2]^w2[2];d=input[decrypt?1:3]^w2[3];var i=3;for(var round=1;round<Nr2;++round){a2=m0[a>>>24]^m1[b2>>>16&255]^m2[c>>>8&255]^m3[d&255]^w2[++i];b22=m0[b2>>>24]^m1[c>>>16&255]^m2[d>>>8&255]^m3[a&255]^w2[++i];c2=m0[c>>>24]^m1[d>>>16&255]^m2[a>>>8&255]^m3[b2&255]^w2[++i];d=m0[d>>>24]^m1[a>>>16&255]^m2[b2>>>8&255]^m3[c&255]^w2[++i];a=a2;b2=b22;c=c2}output[0]=sub[a>>>24]<<24^sub[b2>>>16&255]<<16^sub[c>>>8&255]<<8^sub[d&255]^w2[++i];output[decrypt?3:1]=sub[b2>>>24]<<24^sub[c>>>16&255]<<16^sub[d>>>8&255]<<8^sub[a&255]^w2[++i];output[2]=sub[c>>>24]<<24^sub[d>>>16&255]<<16^sub[a>>>8&255]<<8^sub[b2&255]^w2[++i];output[decrypt?1:3]=sub[d>>>24]<<24^sub[a>>>16&255]<<16^sub[b2>>>8&255]<<8^sub[c&255]^w2[++i]}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="AES-"+mode;var cipher;if(options.decrypt){cipher=forge2.cipher.createDecipher(algorithm,options.key)}else{cipher=forge2.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options2){var output=null;if(options2 instanceof forge2.util.ByteBuffer){output=options2;options2={}}options2=options2||{};options2.output=output;options2.iv=iv;start.call(cipher,options2)};return cipher}}});var require_oids=__commonJS({"node_modules/node-forge/lib/oids.js"(exports,module){"use strict";var forge2=require_forge();forge2.pki=forge2.pki||{};var oids=module.exports=forge2.pki.oids=forge2.oids=forge2.oids||{};function _IN(id,name){oids[id]=name;oids[name]=id}function _I_(id,name){oids[id]=name}_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("2.5.4.65","pseudonym");_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")}});var require_asn1=__commonJS({"node_modules/node-forge/lib/asn1.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_oids();var asn1=module.exports=forge2.asn1=forge2.asn1||{};asn1.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};asn1.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.maxDepth=256;asn1.create=function(tagClass,type,constructed,value,options){if(forge2.util.isArray(value)){var tmp=[];for(var i=0;i<value.length;++i){if(value[i]!==void 0){tmp.push(value[i])}}value=tmp}var obj={tagClass,type,constructed,composed:constructed||forge2.util.isArray(value),value};if(options&&"bitStringContents"in options){obj.bitStringContents=options.bitStringContents;obj.original=asn1.copy(obj)}return obj};asn1.copy=function(obj,options){var copy;if(forge2.util.isArray(obj)){copy=[];for(var i=0;i<obj.length;++i){copy.push(asn1.copy(obj[i],options))}return copy}if(typeof obj==="string"){return obj}copy={tagClass:obj.tagClass,type:obj.type,constructed:obj.constructed,composed:obj.composed,value:asn1.copy(obj.value,options)};if(options&&!options.excludeBitStringContents){copy.bitStringContents=obj.bitStringContents}return copy};asn1.equals=function(obj1,obj2,options){if(forge2.util.isArray(obj1)){if(!forge2.util.isArray(obj2)){return false}if(obj1.length!==obj2.length){return false}for(var i=0;i<obj1.length;++i){if(!asn1.equals(obj1[i],obj2[i])){return false}}return true}if(typeof obj1!==typeof obj2){return false}if(typeof obj1==="string"){return obj1===obj2}var equal=obj1.tagClass===obj2.tagClass&&obj1.type===obj2.type&&obj1.constructed===obj2.constructed&&obj1.composed===obj2.composed&&asn1.equals(obj1.value,obj2.value);if(options&&options.includeBitStringContents){equal=equal&&obj1.bitStringContents===obj2.bitStringContents}return equal};asn1.getBerValueLength=function(b2){var b22=b2.getByte();if(b22===128){return void 0}var length;var longForm=b22&128;if(!longForm){length=b22}else{length=b2.getInt((b22&127)<<3)}return length};function _checkBufferLength(bytes,remaining,n){if(n>remaining){var error=new Error("Too few bytes to parse DER.");error.available=bytes.length();error.remaining=remaining;error.requested=n;throw error}}var _getValueLength=function(bytes,remaining){var b2=bytes.getByte();remaining--;if(b2===128){return void 0}var length;var longForm=b2&128;if(!longForm){length=b2}else{var longFormBytes=b2&127;_checkBufferLength(bytes,remaining,longFormBytes);length=bytes.getInt(longFormBytes<<3)}if(length<0){throw new Error("Negative length: "+length)}return length};asn1.fromDer=function(bytes,options){if(options===void 0){options={strict:true,parseAllBytes:true,decodeBitStrings:true}}if(typeof options==="boolean"){options={strict:options,parseAllBytes:true,decodeBitStrings:true}}if(!("strict"in options)){options.strict=true}if(!("parseAllBytes"in options)){options.parseAllBytes=true}if(!("decodeBitStrings"in options)){options.decodeBitStrings=true}if(!("maxDepth"in options)){options.maxDepth=asn1.maxDepth}if(typeof bytes==="string"){bytes=forge2.util.createBuffer(bytes)}var byteCount=bytes.length();var value=_fromDer(bytes,bytes.length(),0,options);if(options.parseAllBytes&&bytes.length()!==0){var error=new Error("Unparsed DER bytes remain after ASN.1 parsing.");error.byteCount=byteCount;error.remaining=bytes.length();throw error}return value};function _fromDer(bytes,remaining,depth,options){if(depth>=options.maxDepth){throw new Error("ASN.1 parsing error: Max depth exceeded.")}var start;_checkBufferLength(bytes,remaining,2);var b1=bytes.getByte();remaining--;var tagClass=b1&192;var type=b1&31;start=bytes.length();var length=_getValueLength(bytes,remaining);remaining-=start-bytes.length();if(length!==void 0&&length>remaining){if(options.strict){var error=new Error("Too few bytes to read ASN.1 value.");error.available=bytes.length();error.remaining=remaining;error.requested=length;throw error}length=remaining}var value;var bitStringContents;var constructed=(b1&32)===32;if(constructed){value=[];if(length===void 0){for(;;){_checkBufferLength(bytes,remaining,2);if(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{while(length>0){start=bytes.length();value.push(_fromDer(bytes,length,depth+1,options));remaining-=start-bytes.length();length-=start-bytes.length()}}}if(value===void 0&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING){bitStringContents=bytes.bytes(length)}if(value===void 0&&options.decodeBitStrings&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING&&length>1){var savedRead=bytes.read;var savedRemaining=remaining;var unused=0;if(type===asn1.Type.BITSTRING){_checkBufferLength(bytes,remaining,1);unused=bytes.getByte();remaining--}if(unused===0){try{start=bytes.length();var subOptions={strict:true,decodeBitStrings:true};var composed=_fromDer(bytes,remaining,depth+1,subOptions);var used=start-bytes.length();remaining-=used;if(type==asn1.Type.BITSTRING){used++}var tc=composed.tagClass;if(used===length&&(tc===asn1.Class.UNIVERSAL||tc===asn1.Class.CONTEXT_SPECIFIC)){value=[composed]}}catch(ex){}}if(value===void 0){bytes.read=savedRead;remaining=savedRemaining}}if(value===void 0){if(length===void 0){if(options.strict){throw new Error("Non-constructed ASN.1 object of indefinite length.")}length=remaining}if(type===asn1.Type.BMPSTRING){value="";for(;length>0;length-=2){_checkBufferLength(bytes,remaining,2);value+=String.fromCharCode(bytes.getInt16());remaining-=2}}else{value=bytes.getBytes(length);remaining-=length}}var asn1Options=bitStringContents===void 0?null:{bitStringContents};return asn1.create(tagClass,type,constructed,value,asn1Options)}asn1.toDer=function(obj){var bytes=forge2.util.createBuffer();var b1=obj.tagClass|obj.type;var value=forge2.util.createBuffer();var useBitStringContents=false;if("bitStringContents"in obj){useBitStringContents=true;if(obj.original){useBitStringContents=asn1.equals(obj,obj.original)}}if(useBitStringContents){value.putBytes(obj.bitStringContents)}else if(obj.composed){if(obj.constructed){b1|=32}else{value.putByte(0)}for(var i=0;i<obj.value.length;++i){if(obj.value[i]!==void 0){value.putBuffer(asn1.toDer(obj.value[i]))}}}else{if(obj.type===asn1.Type.BMPSTRING){for(var i=0;i<obj.value.length;++i){value.putInt16(obj.value.charCodeAt(i))}}else{if(obj.type===asn1.Type.INTEGER&&obj.value.length>1&&(obj.value.charCodeAt(0)===0&&(obj.value.charCodeAt(1)&128)===0||obj.value.charCodeAt(0)===255&&(obj.value.charCodeAt(1)&128)===128)){value.putBytes(obj.value.substr(1))}else{value.putBytes(obj.value)}}}bytes.putByte(b1);if(value.length()<=127){bytes.putByte(value.length()&127)}else{var len=value.length();var lenBytes="";do{lenBytes+=String.fromCharCode(len&255);len=len>>>8}while(len>0);bytes.putByte(lenBytes.length|128);for(var i=lenBytes.length-1;i>=0;--i){bytes.putByte(lenBytes.charCodeAt(i))}}bytes.putBuffer(value);return bytes};asn1.oidToDer=function(oid){var values=oid.split(".");var bytes=forge2.util.createBuffer();bytes.putByte(40*parseInt(values[0],10)+parseInt(values[1],10));var last,valueBytes,value,b2;for(var i=2;i<values.length;++i){last=true;valueBytes=[];value=parseInt(values[i],10);if(value>4294967295){throw new Error("OID value too large; max is 32-bits.")}do{b2=value&127;value=value>>>7;if(!last){b2|=128}valueBytes.push(b2);last=false}while(value>0);for(var n=valueBytes.length-1;n>=0;--n){bytes.putByte(valueBytes[n])}}return bytes};asn1.derToOid=function(bytes){var oid;if(typeof bytes==="string"){bytes=forge2.util.createBuffer(bytes)}var b2=bytes.getByte();oid=Math.floor(b2/40)+"."+b2%40;var value=0;while(bytes.length()>0){if(value>70368744177663){throw new Error("OID value too large; max is 53-bits.")}b2=bytes.getByte();value=value*128;if(b2&128){value+=b2&127}else{oid+="."+(value+b2);value=0}}return oid};asn1.utcTimeToDate=function(utc){var date=new Date;var year=parseInt(utc.substr(0,2),10);year=year>=50?1900+year:2e3+year;var MM=parseInt(utc.substr(2,2),10)-1;var DD=parseInt(utc.substr(4,2),10);var hh=parseInt(utc.substr(6,2),10);var mm=parseInt(utc.substr(8,2),10);var ss2=0;if(utc.length>11){var c=utc.charAt(10);var end=10;if(c!=="+"&&c!=="-"){ss2=parseInt(utc.substr(10,2),10);end+=2}}date.setUTCFullYear(year,MM,DD);date.setUTCHours(hh,mm,ss2,0);if(end){c=utc.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(utc.substr(end+1,2),10);var mmoffset=parseInt(utc.substr(end+4,2),10);var offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){date.setTime(+date-offset)}else{date.setTime(+date+offset)}}}return date};asn1.generalizedTimeToDate=function(gentime){var date=new Date;var YYYY=parseInt(gentime.substr(0,4),10);var MM=parseInt(gentime.substr(4,2),10)-1;var DD=parseInt(gentime.substr(6,2),10);var hh=parseInt(gentime.substr(8,2),10);var mm=parseInt(gentime.substr(10,2),10);var ss2=parseInt(gentime.substr(12,2),10);var fff=0;var offset=0;var isUTC=false;if(gentime.charAt(gentime.length-1)==="Z"){isUTC=true}var end=gentime.length-5,c=gentime.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(gentime.substr(end+1,2),10);var mmoffset=parseInt(gentime.substr(end+4,2),10);offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){offset*=-1}isUTC=true}if(gentime.charAt(14)==="."){fff=parseFloat(gentime.substr(14),10)*1e3}if(isUTC){date.setUTCFullYear(YYYY,MM,DD);date.setUTCHours(hh,mm,ss2,fff);date.setTime(+date+offset)}else{date.setFullYear(YYYY,MM,DD);date.setHours(hh,mm,ss2,fff)}return date};asn1.dateToUtcTime=function(date){if(typeof date==="string"){return date}var rval="";var format2=[];format2.push((""+date.getUTCFullYear()).substr(2));format2.push(""+(date.getUTCMonth()+1));format2.push(""+date.getUTCDate());format2.push(""+date.getUTCHours());format2.push(""+date.getUTCMinutes());format2.push(""+date.getUTCSeconds());for(var i=0;i<format2.length;++i){if(format2[i].length<2){rval+="0"}rval+=format2[i]}rval+="Z";return rval};asn1.dateToGeneralizedTime=function(date){if(typeof date==="string"){return date}var rval="";var format2=[];format2.push(""+date.getUTCFullYear());format2.push(""+(date.getUTCMonth()+1));format2.push(""+date.getUTCDate());format2.push(""+date.getUTCHours());format2.push(""+date.getUTCMinutes());format2.push(""+date.getUTCSeconds());for(var i=0;i<format2.length;++i){if(format2[i].length<2){rval+="0"}rval+=format2[i]}rval+="Z";return rval};asn1.integerToDer=function(x){var rval=forge2.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.");error.integer=x;throw error};asn1.derToInteger=function(bytes){if(typeof bytes==="string"){bytes=forge2.util.createBuffer(bytes)}var n=bytes.length()*8;if(n>32){throw new Error("Integer too large; max is 32-bits.")}return bytes.getSignedInt(n)};asn1.validate=function(obj,v2,capture2,errors){var rval=false;if((obj.tagClass===v2.tagClass||typeof v2.tagClass==="undefined")&&(obj.type===v2.type||typeof v2.type==="undefined")){if(obj.constructed===v2.constructed||typeof v2.constructed==="undefined"){rval=true;if(v2.value&&forge2.util.isArray(v2.value)){var j2=0;for(var i=0;rval&&i<v2.value.length;++i){var schemaItem=v2.value[i];rval=!!schemaItem.optional;var objChild=obj.value[j2];if(!objChild){if(!schemaItem.optional){rval=false;if(errors){errors.push("["+v2.name+'] Missing required element. Expected tag class "'+schemaItem.tagClass+'", type "'+schemaItem.type+'"')}}continue}var schemaHasTag=typeof schemaItem.tagClass!=="undefined"&&typeof schemaItem.type!=="undefined";if(schemaHasTag&&(objChild.tagClass!==schemaItem.tagClass||objChild.type!==schemaItem.type)){if(schemaItem.optional){rval=true;continue}else{rval=false;if(errors){errors.push("["+v2.name+"] Tag mismatch. Expected ("+schemaItem.tagClass+","+schemaItem.type+"), got ("+objChild.tagClass+","+objChild.type+")")}break}}var childRval=asn1.validate(objChild,schemaItem,capture2,errors);if(childRval){++j2;rval=true}else if(schemaItem.optional){rval=true}else{rval=false;break}}}if(rval&&capture2){if(v2.capture){capture2[v2.capture]=obj.value}if(v2.captureAsn1){capture2[v2.captureAsn1]=obj}if(v2.captureBitStringContents&&"bitStringContents"in obj){capture2[v2.captureBitStringContents]=obj.bitStringContents}if(v2.captureBitStringValue&&"bitStringContents"in obj){var value;if(obj.bitStringContents.length<2){capture2[v2.captureBitStringValue]=""}else{var unused=obj.bitStringContents.charCodeAt(0);if(unused!==0){throw new Error("captureBitStringValue only supported for zero unused bits")}capture2[v2.captureBitStringValue]=obj.bitStringContents.slice(1)}}}}else if(errors){errors.push("["+v2.name+'] Expected constructed "'+v2.constructed+'", got "'+obj.constructed+'"')}}else if(errors){if(obj.tagClass!==v2.tagClass){errors.push("["+v2.name+'] Expected tag class "'+v2.tagClass+'", got "'+obj.tagClass+'"')}if(obj.type!==v2.type){errors.push("["+v2.name+'] Expected type "'+v2.type+'", got "'+obj.type+'"')}}return rval};var _nonLatinRegex=/[^\\u0000-\\u00ff]/;asn1.prettyPrint=function(obj,level,indentation){var rval="";level=level||0;indentation=indentation||2;if(level>0){rval+="\n"}var indent="";for(var i=0;i<level*indentation;++i){indent+=" "}rval+=indent+"Tag: ";switch(obj.tagClass){case asn1.Class.UNIVERSAL:rval+="Universal:";break;case asn1.Class.APPLICATION:rval+="Application:";break;case asn1.Class.CONTEXT_SPECIFIC:rval+="Context-Specific:";break;case asn1.Class.PRIVATE:rval+="Private:";break}if(obj.tagClass===asn1.Class.UNIVERSAL){rval+=obj.type;switch(obj.type){case asn1.Type.NONE:rval+=" (None)";break;case asn1.Type.BOOLEAN:rval+=" (Boolean)";break;case asn1.Type.INTEGER:rval+=" (Integer)";break;case asn1.Type.BITSTRING:rval+=" (Bit string)";break;case asn1.Type.OCTETSTRING:rval+=" (Octet string)";break;case asn1.Type.NULL:rval+=" (Null)";break;case asn1.Type.OID:rval+=" (Object Identifier)";break;case asn1.Type.ODESC:rval+=" (Object Descriptor)";break;case asn1.Type.EXTERNAL:rval+=" (External or Instance of)";break;case asn1.Type.REAL:rval+=" (Real)";break;case asn1.Type.ENUMERATED:rval+=" (Enumerated)";break;case asn1.Type.EMBEDDED:rval+=" (Embedded PDV)";break;case asn1.Type.UTF8:rval+=" (UTF8)";break;case asn1.Type.ROID:rval+=" (Relative Object Identifier)";break;case asn1.Type.SEQUENCE:rval+=" (Sequence)";break;case asn1.Type.SET:rval+=" (Set)";break;case asn1.Type.PRINTABLESTRING:rval+=" (Printable String)";break;case asn1.Type.IA5String:rval+=" (IA5String (ASCII))";break;case asn1.Type.UTCTIME:rval+=" (UTC time)";break;case asn1.Type.GENERALIZEDTIME:rval+=" (Generalized time)";break;case asn1.Type.BMPSTRING:rval+=" (BMP String)";break}}else{rval+=obj.type}rval+="\n";rval+=indent+"Constructed: "+obj.constructed+"\n";if(obj.composed){var subvalues=0;var sub="";for(var i=0;i<obj.value.length;++i){if(obj.value[i]!==void 0){subvalues+=1;sub+=asn1.prettyPrint(obj.value[i],level+1,indentation);if(i+1<obj.value.length){sub+=","}}}rval+=indent+"Sub values: "+subvalues+sub}else{rval+=indent+"Value: ";if(obj.type===asn1.Type.OID){var oid=asn1.derToOid(obj.value);rval+=oid;if(forge2.pki&&forge2.pki.oids){if(oid in forge2.pki.oids){rval+=" ("+forge2.pki.oids[oid]+") "}}}if(obj.type===asn1.Type.INTEGER){try{rval+=asn1.derToInteger(obj.value)}catch(ex){rval+="0x"+forge2.util.bytesToHex(obj.value)}}else if(obj.type===asn1.Type.BITSTRING){if(obj.value.length>1){rval+="0x"+forge2.util.bytesToHex(obj.value.slice(1))}else{rval+="(none)"}if(obj.value.length>0){var unused=obj.value.charCodeAt(0);if(unused==1){rval+=" (1 unused bit shown)"}else if(unused>1){rval+=" ("+unused+" unused bits shown)"}}}else if(obj.type===asn1.Type.OCTETSTRING){if(!_nonLatinRegex.test(obj.value)){rval+="("+obj.value+") "}rval+="0x"+forge2.util.bytesToHex(obj.value)}else if(obj.type===asn1.Type.UTF8){try{rval+=forge2.util.decodeUtf8(obj.value)}catch(e){if(e.message==="URI malformed"){rval+="0x"+forge2.util.bytesToHex(obj.value)+" (malformed UTF8)"}else{throw e}}}else if(obj.type===asn1.Type.PRINTABLESTRING||obj.type===asn1.Type.IA5String){rval+=obj.value}else if(_nonLatinRegex.test(obj.value)){rval+="0x"+forge2.util.bytesToHex(obj.value)}else if(obj.value.length===0){rval+="[null]"}else{rval+=obj.value}}return rval}}});var require_md=__commonJS({"node_modules/node-forge/lib/md.js"(exports,module){"use strict";var forge2=require_forge();module.exports=forge2.md=forge2.md||{};forge2.md.algorithms=forge2.md.algorithms||{}}});var require_hmac=__commonJS({"node_modules/node-forge/lib/hmac.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var hmac=module.exports=forge2.hmac=forge2.hmac||{};hmac.create=function(){var _key=null;var _md=null;var _ipadding=null;var _opadding=null;var ctx={};ctx.start=function(md,key){if(md!==null){if(typeof md==="string"){md=md.toLowerCase();if(md in forge2.md.algorithms){_md=forge2.md.algorithms[md].create()}else{throw new Error('Unknown hash algorithm "'+md+'"')}}else{_md=md}}if(key===null){key=_key}else{if(typeof key==="string"){key=forge2.util.createBuffer(key)}else if(forge2.util.isArray(key)){var tmp=key;key=forge2.util.createBuffer();for(var i=0;i<tmp.length;++i){key.putByte(tmp[i])}}var keylen=key.length();if(keylen>_md.blockLength){_md.start();_md.update(key.bytes());key=_md.digest()}_ipadding=forge2.util.createBuffer();_opadding=forge2.util.createBuffer();keylen=key.length();for(var i=0;i<keylen;++i){var tmp=key.at(i);_ipadding.putByte(54^tmp);_opadding.putByte(92^tmp)}if(keylen<_md.blockLength){var tmp=_md.blockLength-keylen;for(var i=0;i<tmp;++i){_ipadding.putByte(54);_opadding.putByte(92)}}_key=key;_ipadding=_ipadding.bytes();_opadding=_opadding.bytes()}_md.start();_md.update(_ipadding)};ctx.update=function(bytes){_md.update(bytes)};ctx.getMac=function(){var inner=_md.digest().bytes();_md.start();_md.update(_opadding);_md.update(inner);return _md.digest()};ctx.digest=ctx.getMac;return ctx}}});var require_md5=__commonJS({"node_modules/node-forge/lib/md5.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var md5=module.exports=forge2.md5=forge2.md5||{};forge2.md.md5=forge2.md.algorithms.md5=md5;md5.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge2.util.createBuffer();var _w=new Array(16);var md={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_state={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878};return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var bits,carry=0;for(var i=md.fullMessageLength.length-1;i>=0;--i){bits=md.fullMessageLength[i]*8+carry;carry=bits/4294967296>>>0;finalBlock.putInt32Le(bits>>>0)}var s22={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3};_update(s22,_w,finalBlock);var rval=forge2.util.createBuffer();rval.putInt32Le(s22.h0);rval.putInt32Le(s22.h1);rval.putInt32Le(s22.h2);rval.putInt32Le(s22.h3);return rval};return md};var _padding=null;var _g=null;var _r2=null;var _k=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.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];_r2=[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(Math.abs(Math.sin(i+1))*4294967296)}_initialized=true}function _update(s3,w2,bytes){var t,a,b2,c,d,f2,r,i;var len=bytes.length();while(len>=64){a=s3.h0;b2=s3.h1;c=s3.h2;d=s3.h3;for(i=0;i<16;++i){w2[i]=bytes.getInt32Le();f2=d^b2&(c^d);t=a+f2+_k[i]+w2[i];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}for(;i<32;++i){f2=c^d&(b2^c);t=a+f2+_k[i]+w2[_g[i]];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}for(;i<48;++i){f2=b2^c^d;t=a+f2+_k[i]+w2[_g[i]];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}for(;i<64;++i){f2=c^(b2|~d);t=a+f2+_k[i]+w2[_g[i]];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}s3.h0=s3.h0+a|0;s3.h1=s3.h1+b2|0;s3.h2=s3.h2+c|0;s3.h3=s3.h3+d|0;len-=64}}}});var require_pem=__commonJS({"node_modules/node-forge/lib/pem.js"(exports,module){"use strict";var forge2=require_forge();require_util7();var pem=module.exports=forge2.pem=forge2.pem||{};pem.encode=function(msg,options){options=options||{};var rval="-----BEGIN "+msg.type+"-----\r\n";var header;if(msg.procType){header={name:"Proc-Type",values:[String(msg.procType.version),msg.procType.type]};rval+=foldHeader(header)}if(msg.contentDomain){header={name:"Content-Domain",values:[msg.contentDomain]};rval+=foldHeader(header)}if(msg.dekInfo){header={name:"DEK-Info",values:[msg.dekInfo.algorithm]};if(msg.dekInfo.parameters){header.values.push(msg.dekInfo.parameters)}rval+=foldHeader(header)}if(msg.headers){for(var i=0;i<msg.headers.length;++i){rval+=foldHeader(msg.headers[i])}}if(msg.procType){rval+="\r\n"}rval+=forge2.util.encode64(msg.body,options.maxline||64)+"\r\n";rval+="-----END "+msg.type+"-----\r\n";return rval};pem.decode=function(str){var rval=[];var rMessage=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;var rHeader=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;var rCRLF=/\r?\n/;var match;while(true){match=rMessage.exec(str);if(!match){break}var type=match[1];if(type==="NEW CERTIFICATE REQUEST"){type="CERTIFICATE REQUEST"}var msg={type,procType:null,contentDomain:null,dekInfo:null,headers:[],body:forge2.util.decode64(match[3])};rval.push(msg);if(!match[2]){continue}var lines=match[2].split(rCRLF);var li2=0;while(match&&li2<lines.length){var line=lines[li2].replace(/\s+$/,"");for(var nl=li2+1;nl<lines.length;++nl){var next=lines[nl];if(!/\s/.test(next[0])){break}line+=next;li2=nl}match=line.match(rHeader);if(match){var header={name:match[1],values:[]};var values=match[2].split(",");for(var vi2=0;vi2<values.length;++vi2){header.values.push(ltrim(values[vi2]))}if(!msg.procType){if(header.name!=="Proc-Type"){throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".')}else if(header.values.length!==2){throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.')}msg.procType={version:values[0],type:values[1]}}else if(!msg.contentDomain&&header.name==="Content-Domain"){msg.contentDomain=values[0]||""}else if(!msg.dekInfo&&header.name==="DEK-Info"){if(header.values.length===0){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.headers.push(header)}}++li2}if(msg.procType==="ENCRYPTED"&&!msg.dekInfo){throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(rval.length===0){throw new Error("Invalid PEM formatted message.")}return rval};function foldHeader(header){var rval=header.name+": ";var values=[];var insertSpace=function(match,$1){return" "+$1};for(var 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;var candidate=-1;for(var i=0;i<rval.length;++i,++length){if(length>65&&candidate!==-1){var insert=rval[candidate];if(insert===","){++candidate;rval=rval.substr(0,candidate)+"\r\n "+rval.substr(candidate)}else{rval=rval.substr(0,candidate)+"\r\n"+insert+rval.substr(candidate+1)}length=i-candidate-1;candidate=-1;++i}else if(rval[i]===" "||rval[i]===" "||rval[i]===","){candidate=i}}return rval}function ltrim(str){return str.replace(/^\s+/,"")}}});var require_des=__commonJS({"node_modules/node-forge/lib/des.js"(exports,module){"use strict";var forge2=require_forge();require_cipher();require_cipherModes();require_util7();module.exports=forge2.des=forge2.des||{};forge2.des.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:false,mode:mode||(iv===null?"ECB":"CBC")});cipher.start(iv);return cipher};forge2.des.createEncryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:false,mode})};forge2.des.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:true,mode:mode||(iv===null?"ECB":"CBC")});cipher.start(iv);return cipher};forge2.des.createDecryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:true,mode})};forge2.des.Algorithm=function(name,mode){var self2=this;self2.name=name;self2.mode=new mode({blockSize:8,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self2._keys,inBlock,outBlock,false)},decrypt:function(inBlock,outBlock){return _updateBlock(self2._keys,inBlock,outBlock,true)}}});self2._init=false};forge2.des.Algorithm.prototype.initialize=function(options){if(this._init){return}var key=forge2.util.createBuffer(options.key);if(this.name.indexOf("3DES")===0){if(key.length()!==24){throw new Error("Invalid Triple-DES key size: "+key.length()*8)}}this._keys=_createKeys(key);this._init=true};registerAlgorithm("DES-ECB",forge2.cipher.modes.ecb);registerAlgorithm("DES-CBC",forge2.cipher.modes.cbc);registerAlgorithm("DES-CFB",forge2.cipher.modes.cfb);registerAlgorithm("DES-OFB",forge2.cipher.modes.ofb);registerAlgorithm("DES-CTR",forge2.cipher.modes.ctr);registerAlgorithm("3DES-ECB",forge2.cipher.modes.ecb);registerAlgorithm("3DES-CBC",forge2.cipher.modes.cbc);registerAlgorithm("3DES-CFB",forge2.cipher.modes.cfb);registerAlgorithm("3DES-OFB",forge2.cipher.modes.ofb);registerAlgorithm("3DES-CTR",forge2.cipher.modes.ctr);function registerAlgorithm(name,mode){var factory=function(){return new forge2.des.Algorithm(name,mode)};forge2.cipher.registerAlgorithm(name,factory)}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];var 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];var 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];var 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];var 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];var 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];var 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];var 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 _createKeys(key){var 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];var iterations=key.length()>8?3:1;var keys=[];var shifts=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];var n=0,tmp;for(var j2=0;j2<iterations;j2++){var left=key.getInt32();var right=key.getInt32();tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>2^right)&858993459;right^=tmp;left^=tmp<<2;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=left<<8|right>>>20&240;left=right<<24|right<<8&16711680|right>>>8&65280|right>>>24&240;right=tmp;for(var i=0;i<shifts.length;++i){if(shifts[i]){left=left<<2|left>>>26;right=right<<2|right>>>26}else{left=left<<1|left>>>27;right=right<<1|right>>>27}left&=-15;right&=-15;var lefttmp=pc2bytes0[left>>>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];var 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=(righttmp>>>16^lefttmp)&65535;keys[n++]=lefttmp^tmp;keys[n++]=righttmp^tmp<<16}}return keys}function _updateBlock(keys,input,output,decrypt){var iterations=keys.length===32?3:9;var looping;if(iterations===3){looping=decrypt?[30,-2,-2]:[0,32,2]}else{looping=decrypt?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2]}var tmp;var left=input[0];var right=input[1];tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;left=left<<1|left>>>31;right=right<<1|right>>>31;for(var j2=0;j2<iterations;j2+=3){var endloop=looping[j2+1];var loopinc=looping[j2+2];for(var i=looping[j2];i!=endloop;i+=loopinc){var right1=right^keys[i];var 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[right1&63]|spfunction1[right2>>>24&63]|spfunction3[right2>>>16&63]|spfunction5[right2>>>8&63]|spfunction7[right2&63])}tmp=left;left=right;right=tmp}left=left>>>1|left<<31;right=right>>>1|right<<31;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;output[0]=left;output[1]=right}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="DES-"+mode;var cipher;if(options.decrypt){cipher=forge2.cipher.createDecipher(algorithm,options.key)}else{cipher=forge2.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options2){var output=null;if(options2 instanceof forge2.util.ByteBuffer){output=options2;options2={}}options2=options2||{};options2.output=output;options2.iv=iv;start.call(cipher,options2)};return cipher}}});var require_pbkdf2=__commonJS({"node_modules/node-forge/lib/pbkdf2.js"(exports,module){"use strict";var forge2=require_forge();require_hmac();require_md();require_util7();var pkcs5=forge2.pkcs5=forge2.pkcs5||{};var crypto5;if(forge2.util.isNodejs&&!forge2.options.usePureJavaScript){crypto5=__require("crypto")}module.exports=forge2.pbkdf2=pkcs5.pbkdf2=function(p2,s3,c,dkLen,md,callback){if(typeof md==="function"){callback=md;md=null}if(forge2.util.isNodejs&&!forge2.options.usePureJavaScript&&crypto5.pbkdf2&&(md===null||typeof md!=="object")&&(crypto5.pbkdf2Sync.length>4||(!md||md==="sha1"))){if(typeof md!=="string"){md="sha1"}p2=Buffer.from(p2,"binary");s3=Buffer.from(s3,"binary");if(!callback){if(crypto5.pbkdf2Sync.length===4){return crypto5.pbkdf2Sync(p2,s3,c,dkLen).toString("binary")}return crypto5.pbkdf2Sync(p2,s3,c,dkLen,md).toString("binary")}if(crypto5.pbkdf2Sync.length===4){return crypto5.pbkdf2(p2,s3,c,dkLen,function(err2,key){if(err2){return callback(err2)}callback(null,key.toString("binary"))})}return crypto5.pbkdf2(p2,s3,c,dkLen,md,function(err2,key){if(err2){return callback(err2)}callback(null,key.toString("binary"))})}if(typeof md==="undefined"||md===null){md="sha1"}if(typeof md==="string"){if(!(md in forge2.md.algorithms)){throw new Error("Unknown hash algorithm: "+md)}md=forge2.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);var r=dkLen-(len-1)*hLen;var prf=forge2.hmac.create();prf.start(md,p2);var dk="";var xor,u_c,u_c1;if(!callback){for(var i=1;i<=len;++i){prf.start(null,null);prf.update(s3);prf.update(forge2.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();for(var j2=2;j2<=c;++j2){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge2.util.xorBytes(xor,u_c,hLen);u_c1=u_c}dk+=i<len?xor:xor.substr(0,r)}return dk}var i=1,j2;function outer(){if(i>len){return callback(null,dk)}prf.start(null,null);prf.update(s3);prf.update(forge2.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();j2=2;inner()}function inner(){if(j2<=c){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge2.util.xorBytes(xor,u_c,hLen);u_c1=u_c;++j2;return forge2.util.setImmediate(inner)}dk+=i<len?xor:xor.substr(0,r);++i;outer()}outer()}}});var require_sha256=__commonJS({"node_modules/node-forge/lib/sha256.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var sha2562=module.exports=forge2.sha256=forge2.sha256||{};forge2.md.sha256=forge2.md.algorithms.sha256=sha2562;sha2562.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge2.util.createBuffer();var _w=new Array(64);var md={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_state={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225};return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i<md.fullMessageLength.length-1;++i){next=md.fullMessageLength[i+1]*8;carry=next/4294967296>>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s22={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(s22,_w,finalBlock);var rval=forge2.util.createBuffer();rval.putInt32(s22.h0);rval.putInt32(s22.h1);rval.putInt32(s22.h2);rval.putInt32(s22.h3);rval.putInt32(s22.h4);rval.putInt32(s22.h5);rval.putInt32(s22.h6);rval.putInt32(s22.h7);return rval};return md};var _padding=null;var _initialized=false;var _k=null;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.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=true}function _update(s3,w2,bytes){var t1,t2,s0,s1,ch,maj,i,a,b2,c,d,e,f2,g2,h;var len=bytes.length();while(len>=64){for(i=0;i<16;++i){w2[i]=bytes.getInt32()}for(;i<64;++i){t1=w2[i-2];t1=(t1>>>17|t1<<15)^(t1>>>19|t1<<13)^t1>>>10;t2=w2[i-15];t2=(t2>>>7|t2<<25)^(t2>>>18|t2<<14)^t2>>>3;w2[i]=t1+w2[i-7]+t2+w2[i-16]|0}a=s3.h0;b2=s3.h1;c=s3.h2;d=s3.h3;e=s3.h4;f2=s3.h5;g2=s3.h6;h=s3.h7;for(i=0;i<64;++i){s1=(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7);ch=g2^e&(f2^g2);s0=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10);maj=a&b2|c&(a^b2);t1=h+s1+ch+_k[i]+w2[i];t2=s0+maj;h=g2;g2=f2;f2=e;e=d+t1>>>0;d=c;c=b2;b2=a;a=t1+t2>>>0}s3.h0=s3.h0+a|0;s3.h1=s3.h1+b2|0;s3.h2=s3.h2+c|0;s3.h3=s3.h3+d|0;s3.h4=s3.h4+e|0;s3.h5=s3.h5+f2|0;s3.h6=s3.h6+g2|0;s3.h7=s3.h7+h|0;len-=64}}}});var require_prng=__commonJS({"node_modules/node-forge/lib/prng.js"(exports,module){"use strict";var forge2=require_forge();require_util7();var _crypto=null;if(forge2.util.isNodejs&&!forge2.options.usePureJavaScript&&!process.versions["node-webkit"]){_crypto=__require("crypto")}var prng=module.exports=forge2.prng=forge2.prng||{};prng.create=function(plugin){var ctx={plugin,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""};var md=plugin.md;var pools=new Array(32);for(var i=0;i<32;++i){pools[i]=md.create()}ctx.pools=pools;ctx.pool=0;ctx.generate=function(count,callback){if(!callback){return ctx.generateSync(count)}var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;var b2=forge2.util.createBuffer();ctx.key=null;generate();function generate(err){if(err){return callback(err)}if(b2.length()>=count){return callback(null,b2.getBytes(count))}if(ctx.generated>1048575){ctx.key=null}if(ctx.key===null){return forge2.util.nextTick(function(){_reseed(generate)})}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b2.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed));forge2.util.setImmediate(generate)}};ctx.generateSync=function(count){var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;ctx.key=null;var b2=forge2.util.createBuffer();while(b2.length()<count){if(ctx.generated>1048575){ctx.key=null}if(ctx.key===null){_reseedSync()}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b2.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed))}return b2.getBytes(count)};function _reseed(callback){if(ctx.pools[0].messageLength>=32){_seed();return 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()})}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=ctx.reseeds===4294967295?0:ctx.reseeds+1;var md2=ctx.plugin.md.create();md2.update(ctx.keyBytes);var _2powK=1;for(var k2=0;k2<32;++k2){if(ctx.reseeds%_2powK===0){md2.update(ctx.pools[k2].digest().getBytes());ctx.pools[k2].start()}_2powK=_2powK<<1}ctx.keyBytes=md2.digest().getBytes();md2.start();md2.update(ctx.keyBytes);var seedBytes=md2.digest().getBytes();ctx.key=ctx.plugin.formatKey(ctx.keyBytes);ctx.seed=ctx.plugin.formatSeed(seedBytes);ctx.generated=0}function defaultSeedFile(needed){var getRandomValues=null;var globalScope=forge2.util.globalScope;var _crypto2=globalScope.crypto||globalScope.msCrypto;if(_crypto2&&_crypto2.getRandomValues){getRandomValues=function(arr){return _crypto2.getRandomValues(arr)}}var b2=forge2.util.createBuffer();if(getRandomValues){while(b2.length()<needed){var count=Math.max(1,Math.min(needed-b2.length(),65536)/4);var entropy=new Uint32Array(Math.floor(count));try{getRandomValues(entropy);for(var i2=0;i2<entropy.length;++i2){b2.putInt32(entropy[i2])}}catch(e){if(!(typeof QuotaExceededError!=="undefined"&&e instanceof QuotaExceededError)){throw e}}}}if(b2.length()<needed){var hi2,lo2,next;var seed=Math.floor(Math.random()*65536);while(b2.length()<needed){lo2=16807*(seed&65535);hi2=16807*(seed>>16);lo2+=(hi2&32767)<<16;lo2+=hi2>>15;lo2=(lo2&2147483647)+(lo2>>31);seed=lo2&4294967295;for(var i2=0;i2<3;++i2){next=seed>>>(i2<<3);next^=Math.floor(Math.random()*256);b2.putByte(next&255)}}}return b2.getBytes(needed)}if(_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()}}else{ctx.seedFile=function(needed,callback){try{callback(null,defaultSeedFile(needed))}catch(e){callback(e)}};ctx.seedFileSync=defaultSeedFile}ctx.collect=function(bytes){var count=bytes.length;for(var i2=0;i2<count;++i2){ctx.pools[ctx.pool].update(bytes.substr(i2,1));ctx.pool=ctx.pool===31?0:ctx.pool+1}};ctx.collectInt=function(i2,n){var bytes="";for(var x=0;x<n;x+=8){bytes+=String.fromCharCode(i2>>x&255)}ctx.collect(bytes)};ctx.registerWorker=function(worker){if(worker===self){ctx.seedFile=function(needed,callback){function listener2(e){var data=e.data;if(data.forge&&data.forge.prng){self.removeEventListener("message",listener2);callback(data.forge.prng.err,data.forge.prng.bytes)}}self.addEventListener("message",listener2);self.postMessage({forge:{prng:{needed}}})}}else{var listener=function(e){var data=e.data;if(data.forge&&data.forge.prng){ctx.seedFile(data.forge.prng.needed,function(err,bytes){worker.postMessage({forge:{prng:{err,bytes}}})})}};worker.addEventListener("message",listener)}};return ctx}}});var require_random=__commonJS({"node_modules/node-forge/lib/random.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_sha256();require_prng();require_util7();(function(){if(forge2.random&&forge2.random.getBytes){module.exports=forge2.random;return}(function(jQuery2){var prng_aes={};var _prng_aes_output=new Array(4);var _prng_aes_buffer=forge2.util.createBuffer();prng_aes.formatKey=function(key2){var tmp=forge2.util.createBuffer(key2);key2=new Array(4);key2[0]=tmp.getInt32();key2[1]=tmp.getInt32();key2[2]=tmp.getInt32();key2[3]=tmp.getInt32();return forge2.aes._expandKey(key2,false)};prng_aes.formatSeed=function(seed){var tmp=forge2.util.createBuffer(seed);seed=new Array(4);seed[0]=tmp.getInt32();seed[1]=tmp.getInt32();seed[2]=tmp.getInt32();seed[3]=tmp.getInt32();return seed};prng_aes.cipher=function(key2,seed){forge2.aes._updateBlock(key2,seed,_prng_aes_output,false);_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]);return _prng_aes_buffer.getBytes()};prng_aes.increment=function(seed){++seed[3];return seed};prng_aes.md=forge2.md.sha256;function spawnPrng(){var ctx=forge2.prng.create(prng_aes);ctx.getBytes=function(count,callback){return ctx.generate(count,callback)};ctx.getBytesSync=function(count){return ctx.generate(count)};return ctx}var _ctx=spawnPrng();var getRandomValues=null;var globalScope=forge2.util.globalScope;var _crypto=globalScope.crypto||globalScope.msCrypto;if(_crypto&&_crypto.getRandomValues){getRandomValues=function(arr){return _crypto.getRandomValues(arr)}}if(forge2.options.usePureJavaScript||!forge2.util.isNodejs&&!getRandomValues){if(typeof window==="undefined"||window.document===void 0){}_ctx.collectInt(+new Date,32);if(typeof navigator!=="undefined"){var _navBytes="";for(var key in navigator){try{if(typeof navigator[key]=="string"){_navBytes+=navigator[key]}}catch(e){}}_ctx.collect(_navBytes);_navBytes=null}if(jQuery2){jQuery2().mousemove(function(e){_ctx.collectInt(e.clientX,16);_ctx.collectInt(e.clientY,16)});jQuery2().keypress(function(e){_ctx.collectInt(e.charCode,8)})}}if(!forge2.random){forge2.random=_ctx}else{for(var key in _ctx){forge2.random[key]=_ctx[key]}}forge2.random.createInstance=spawnPrng;module.exports=forge2.random})(typeof jQuery!=="undefined"?jQuery:null)})()}});var require_rc2=__commonJS({"node_modules/node-forge/lib/rc2.js"(exports,module){"use strict";var forge2=require_forge();require_util7();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];var s3=[1,2,3,5];var rol=function(word,bits){return word<<bits&65535|(word&65535)>>16-bits};var ror=function(word,bits){return(word&65535)>>bits|word<<16-bits&65535};module.exports=forge2.rc2=forge2.rc2||{};forge2.rc2.expandKey=function(key,effKeyBits){if(typeof key==="string"){key=forge2.util.createBuffer(key)}effKeyBits=effKeyBits||128;var L2=key;var T=key.length();var T1=effKeyBits;var T8=Math.ceil(T1/8);var TM=255>>(T1&7);var i;for(i=T;i<128;i++){L2.putByte(piTable[L2.at(i-1)+L2.at(i-T)&255])}L2.setAt(128-T8,piTable[L2.at(128-T8)&TM]);for(i=127-T8;i>=0;i--){L2.setAt(i,piTable[L2.at(i+1)^L2.at(i+T8)])}return L2};var createCipher=function(key,bits,encrypt){var _finish=false,_input=null,_output=null,_iv=null;var mixRound,mashRound;var i,j2,K2=[];key=forge2.rc2.expandKey(key,bits);for(i=0;i<64;i++){K2.push(key.getInt16Le())}if(encrypt){mixRound=function(R2){for(i=0;i<4;i++){R2[i]+=K2[j2]+(R2[(i+3)%4]&R2[(i+2)%4])+(~R2[(i+3)%4]&R2[(i+1)%4]);R2[i]=rol(R2[i],s3[i]);j2++}};mashRound=function(R2){for(i=0;i<4;i++){R2[i]+=K2[R2[(i+3)%4]&63]}}}else{mixRound=function(R2){for(i=3;i>=0;i--){R2[i]=ror(R2[i],s3[i]);R2[i]-=K2[j2]+(R2[(i+3)%4]&R2[(i+2)%4])+(~R2[(i+3)%4]&R2[(i+1)%4]);j2--}};mashRound=function(R2){for(i=3;i>=0;i--){R2[i]-=K2[R2[(i+3)%4]&63]}}}var runPlan=function(plan2){var R2=[];for(i=0;i<4;i++){var val=_input.getInt16Le();if(_iv!==null){if(encrypt){val^=_iv.getInt16Le()}else{_iv.putInt16Le(val)}}R2.push(val&65535)}j2=encrypt?0:63;for(var ptr=0;ptr<plan2.length;ptr++){for(var ctr=0;ctr<plan2[ptr][0];ctr++){plan2[ptr][1](R2)}}for(i=0;i<4;i++){if(_iv!==null){if(encrypt){_iv.putInt16Le(R2[i])}else{R2[i]^=_iv.getInt16Le()}}_output.putInt16Le(R2[i])}};var cipher=null;cipher={start:function(iv,output){if(iv){if(typeof iv==="string"){iv=forge2.util.createBuffer(iv)}}_finish=false;_input=forge2.util.createBuffer();_output=output||new forge2.util.createBuffer;_iv=iv;cipher.output=_output},update:function(input){if(!_finish){_input.putBuffer(input)}while(_input.length()>=8){runPlan([[5,mixRound],[1,mashRound],[6,mixRound],[1,mashRound],[5,mixRound]])}},finish:function(pad){var rval=true;if(encrypt){if(pad){rval=pad(8,_input,!encrypt)}else{var padding=_input.length()===8?8:8-_input.length();_input.fillWithByte(padding,padding)}}if(rval){_finish=true;cipher.update()}if(!encrypt){rval=_input.length()===0;if(rval){if(pad){rval=pad(8,_output,!encrypt)}else{var len=_output.length();var count=_output.at(len-1);if(count>len){rval=false}else{_output.truncate(count)}}}}return rval}};return cipher};forge2.rc2.startEncrypting=function(key,iv,output){var cipher=forge2.rc2.createEncryptionCipher(key,128);cipher.start(iv,output);return cipher};forge2.rc2.createEncryptionCipher=function(key,bits){return createCipher(key,bits,true)};forge2.rc2.startDecrypting=function(key,iv,output){var cipher=forge2.rc2.createDecryptionCipher(key,128);cipher.start(iv,output);return cipher};forge2.rc2.createDecryptionCipher=function(key,bits){return createCipher(key,bits,false)}}});var require_jsbn=__commonJS({"node_modules/node-forge/lib/jsbn.js"(exports,module){"use strict";var forge2=require_forge();module.exports=forge2.jsbn=forge2.jsbn||{};var dbits;var canary=0xdeadbeefcafe;var j_lm=(canary&16777215)==15715070;function BigInteger(a,b2,c){this.data=[];if(a!=null)if("number"==typeof a)this.fromNumber(a,b2,c);else if(b2==null&&"string"!=typeof a)this.fromString(a,256);else this.fromString(a,b2)}forge2.jsbn.BigInteger=BigInteger;function nbi(){return new BigInteger(null)}function am1(i,x,w2,j2,c,n){while(--n>=0){var v2=x*this.data[i++]+w2.data[j2]+c;c=Math.floor(v2/67108864);w2.data[j2++]=v2&67108863}return c}function am2(i,x,w2,j2,c,n){var xl=x&32767,xh=x>>15;while(--n>=0){var l=this.data[i]&32767;var h=this.data[i++]>>15;var m2=xh*l+h*xl;l=xl*l+((m2&32767)<<15)+w2.data[j2]+(c&1073741823);c=(l>>>30)+(m2>>>15)+xh*h+(c>>>30);w2.data[j2++]=l&1073741823}return c}function am3(i,x,w2,j2,c,n){var xl=x&16383,xh=x>>14;while(--n>=0){var l=this.data[i]&16383;var h=this.data[i++]>>14;var m2=xh*l+h*xl;l=xl*l+((m2&16383)<<14)+w2.data[j2]+c;c=(l>>28)+(m2>>14)+xh*h;w2.data[j2++]=l&268435455}return c}if(typeof navigator==="undefined"){BigInteger.prototype.am=am3;dbits=28}else if(j_lm&&navigator.appName=="Microsoft Internet Explorer"){BigInteger.prototype.am=am2;dbits=30}else if(j_lm&&navigator.appName!="Netscape"){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<<dbits)-1;BigInteger.prototype.DV=1<<dbits;var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";var BI_RC=new Array;var rr2;var vv;rr2="0".charCodeAt(0);for(vv=0;vv<=9;++vv)BI_RC[rr2++]=vv;rr2="a".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr2++]=vv;rr2="A".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr2++]=vv;function int2char(n){return BI_RM.charAt(n)}function intAt(s3,i){var c=BI_RC[s3.charCodeAt(i)];return c==null?-1:c}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}function bnpFromInt(x){this.t=1;this.s=x<0?-1:0;if(x>0)this.data[0]=x;else if(x<-1)this.data[0]=x+this.DV;else this.t=0}function nbv(i){var r=nbi();r.fromInt(i);return r}function bnpFromString(s3,b2){var k2;if(b2==16)k2=4;else if(b2==8)k2=3;else if(b2==256)k2=8;else if(b2==2)k2=1;else if(b2==32)k2=5;else if(b2==4)k2=2;else{this.fromRadix(s3,b2);return}this.t=0;this.s=0;var i=s3.length,mi2=false,sh=0;while(--i>=0){var x=k2==8?s3[i]&255:intAt(s3,i);if(x<0){if(s3.charAt(i)=="-")mi2=true;continue}mi2=false;if(sh==0)this.data[this.t++]=x;else if(sh+k2>this.DB){this.data[this.t-1]|=(x&(1<<this.DB-sh)-1)<<sh;this.data[this.t++]=x>>this.DB-sh}else this.data[this.t-1]|=x<<sh;sh+=k2;if(sh>=this.DB)sh-=this.DB}if(k2==8&&(s3[0]&128)!=0){this.s=-1;if(sh>0)this.data[this.t-1]|=(1<<this.DB-sh)-1<<sh}this.clamp();if(mi2)BigInteger.ZERO.subTo(this,this)}function bnpClamp(){var c=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==c)--this.t}function bnToString(b2){if(this.s<0)return"-"+this.negate().toString(b2);var k2;if(b2==16)k2=4;else if(b2==8)k2=3;else if(b2==2)k2=1;else if(b2==32)k2=5;else if(b2==4)k2=2;else return this.toRadix(b2);var km=(1<<k2)-1,d,m2=false,r="",i=this.t;var p2=this.DB-i*this.DB%k2;if(i-- >0){if(p2<this.DB&&(d=this.data[i]>>p2)>0){m2=true;r=int2char(d)}while(i>=0){if(p2<k2){d=(this.data[i]&(1<<p2)-1)<<k2-p2;d|=this.data[--i]>>(p2+=this.DB-k2)}else{d=this.data[i]>>(p2-=k2)&km;if(p2<=0){p2+=this.DB;--i}}if(d>0)m2=true;if(m2)r+=int2char(d)}}return m2?r:"0"}function bnNegate(){var r=nbi();BigInteger.ZERO.subTo(this,r);return r}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(a){var r=this.s-a.s;if(r!=0)return r;var i=this.t;r=i-a.t;if(r!=0)return this.s<0?-r:r;while(--i>=0)if((r=this.data[i]-a.data[i])!=0)return r;return 0}function nbits(x){var r=1,t;if((t=x>>>16)!=0){x=t;r+=16}if((t=x>>8)!=0){x=t;r+=8}if((t=x>>4)!=0){x=t;r+=4}if((t=x>>2)!=0){x=t;r+=2}if((t=x>>1)!=0){x=t;r+=1}return r}function bnBitLength(){if(this.t<=0)return 0;return this.DB*(this.t-1)+nbits(this.data[this.t-1]^this.s&this.DM)}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}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}function bnpLShiftTo(n,r){var bs2=n%this.DB;var cbs=this.DB-bs2;var bm=(1<<cbs)-1;var ds2=Math.floor(n/this.DB),c=this.s<<bs2&this.DM,i;for(i=this.t-1;i>=0;--i){r.data[i+ds2+1]=this.data[i]>>cbs|c;c=(this.data[i]&bm)<<bs2}for(i=ds2-1;i>=0;--i)r.data[i]=0;r.data[ds2]=c;r.t=this.t+ds2+1;r.s=this.s;r.clamp()}function bnpRShiftTo(n,r){r.s=this.s;var ds2=Math.floor(n/this.DB);if(ds2>=this.t){r.t=0;return}var bs2=n%this.DB;var cbs=this.DB-bs2;var bm=(1<<bs2)-1;r.data[0]=this.data[ds2]>>bs2;for(var i=ds2+1;i<this.t;++i){r.data[i-ds2-1]|=(this.data[i]&bm)<<cbs;r.data[i-ds2]=this.data[i]>>bs2}if(bs2>0)r.data[this.t-ds2-1]|=(this.s&bm)<<cbs;r.t=this.t-ds2;r.clamp()}function bnpSubTo(a,r){var i=0,c=0,m2=Math.min(a.t,this.t);while(i<m2){c+=this.data[i]-a.data[i];r.data[i++]=c&this.DM;c>>=this.DB}if(a.t<this.t){c-=a.s;while(i<this.t){c+=this.data[i];r.data[i++]=c&this.DM;c>>=this.DB}c+=this.s}else{c+=this.s;while(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;if(c<-1)r.data[i++]=this.DV+c;else if(c>0)r.data[i++]=c;r.t=i;r.clamp()}function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs();var i=x.t;r.t=i+y.t;while(--i>=0)r.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();if(this.s!=a.s)BigInteger.ZERO.subTo(r,r)}function bnpSquareTo(r){var x=this.abs();var i=r.t=2*x.t;while(--i>=0)r.data[i]=0;for(i=0;i<x.t-1;++i){var c=x.am(i,x.data[i],r,2*i,0,1);if((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}}if(r.t>0)r.data[r.t-1]+=x.am(i,x.data[i],r,2*i,0,1);r.s=0;r.clamp()}function bnpDivRemTo(m2,q2,r){var pm=m2.abs();if(pm.t<=0)return;var pt2=this.abs();if(pt2.t<pm.t){if(q2!=null)q2.fromInt(0);if(r!=null)this.copyTo(r);return}if(r==null)r=nbi();var y=nbi(),ts2=this.s,ms2=m2.s;var nsh=this.DB-nbits(pm.data[pm.t-1]);if(nsh>0){pm.lShiftTo(nsh,y);pt2.lShiftTo(nsh,r)}else{pm.copyTo(y);pt2.copyTo(r)}var ys2=y.t;var y0=y.data[ys2-1];if(y0==0)return;var yt2=y0*(1<<this.F1)+(ys2>1?y.data[ys2-2]>>this.F2:0);var d1=this.FV/yt2,d2=(1<<this.F1)/yt2,e=1<<this.F2;var i=r.t,j2=i-ys2,t=q2==null?nbi():q2;y.dlShiftTo(j2,t);if(r.compareTo(t)>=0){r.data[r.t++]=1;r.subTo(t,r)}BigInteger.ONE.dlShiftTo(ys2,t);t.subTo(y,y);while(y.t<ys2)y.data[y.t++]=0;while(--j2>=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,j2,0,ys2))<qd){y.dlShiftTo(j2,t);r.subTo(t,r);while(r.data[i]<--qd)r.subTo(t,r)}}if(q2!=null){r.drShiftTo(ys2,q2);if(ts2!=ms2)BigInteger.ZERO.subTo(q2,q2)}r.t=ys2;r.clamp();if(nsh>0)r.rShiftTo(nsh,r);if(ts2<0)BigInteger.ZERO.subTo(r,r)}function bnMod(a){var r=nbi();this.abs().divRemTo(a,null,r);if(this.s<0&&r.compareTo(BigInteger.ZERO)>0)a.subTo(r,r);return r}function Classic(m2){this.m=m2}function cConvert(x){if(x.s<0||x.compareTo(this.m)>=0)return x.mod(this.m);else return x}function cRevert(x){return x}function cReduce(x){x.divRemTo(this.m,null,x)}function cMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}function cSqrTo(x,r){x.squareTo(r);this.reduce(r)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1)return 0;var x=this.data[0];if((x&1)==0)return 0;var y=x&3;y=y*(2-(x&15)*y)&15;y=y*(2-(x&255)*y)&255;y=y*(2-((x&65535)*y&65535))&65535;y=y*(2-x*y%this.DV)%this.DV;return y>0?this.DV-y:-y}function Montgomery(m2){this.m=m2;this.mp=m2.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<m2.DB-15)-1;this.mt2=2*m2.t}function montConvert(x){var r=nbi();x.abs().dlShiftTo(this.m.t,r);r.divRemTo(this.m,null,r);if(x.s<0&&r.compareTo(BigInteger.ZERO)>0)this.m.subTo(r,r);return r}function montRevert(x){var r=nbi();x.copyTo(r);this.reduce(r);return r}function montReduce(x){while(x.t<=this.mt2)x.data[x.t++]=0;for(var i=0;i<this.m.t;++i){var j2=x.data[i]&32767;var u0=j2*this.mpl+((j2*this.mph+(x.data[i]>>15)*this.mpl&this.um)<<15)&x.DM;j2=i+this.m.t;x.data[j2]+=this.m.am(0,u0,x,i,0,this.m.t);while(x.data[j2]>=x.DV){x.data[j2]-=x.DV;x.data[++j2]++}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function montSqrTo(x,r){x.squareTo(r);this.reduce(r)}function montMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return(this.t>0?this.data[0]&1:this.s)==0}function bnpExp(e,z2){if(e>4294967295||e<1)return BigInteger.ONE;var r=nbi(),r2=nbi(),g2=z2.convert(this),i=nbits(e)-1;g2.copyTo(r);while(--i>=0){z2.sqrTo(r,r2);if((e&1<<i)>0)z2.mulTo(r2,g2,r);else{var t=r;r=r2;r2=t}}return z2.revert(r)}function bnModPowInt(e,m2){var z2;if(e<256||m2.isEven())z2=new Classic(m2);else z2=new Montgomery(m2);return this.exp(e,z2)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var r=nbi();this.copyTo(r);return r}function bnIntValue(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function bnByteValue(){return this.t==0?this.s:this.data[0]<<24>>24}function bnShortValue(){return this.t==0?this.s:this.data[0]<<16>>16}function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function bnSigNum(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function bnpToRadix(b2){if(b2==null)b2=10;if(this.signum()==0||b2<2||b2>36)return"0";var cs2=this.chunkSize(b2);var a=Math.pow(b2,cs2);var d=nbv(a),y=nbi(),z2=nbi(),r="";this.divRemTo(d,y,z2);while(y.signum()>0){r=(a+z2.intValue()).toString(b2).substr(1)+r;y.divRemTo(d,y,z2)}return z2.intValue().toString(b2)+r}function bnpFromRadix(s3,b2){this.fromInt(0);if(b2==null)b2=10;var cs2=this.chunkSize(b2);var d=Math.pow(b2,cs2),mi2=false,j2=0,w2=0;for(var i=0;i<s3.length;++i){var x=intAt(s3,i);if(x<0){if(s3.charAt(i)=="-"&&this.signum()==0)mi2=true;continue}w2=b2*w2+x;if(++j2>=cs2){this.dMultiply(d);this.dAddOffset(w2,0);j2=0;w2=0}}if(j2>0){this.dMultiply(Math.pow(b2,j2));this.dAddOffset(w2,0)}if(mi2)BigInteger.ZERO.subTo(this,this)}function bnpFromNumber(a,b2,c){if("number"==typeof b2){if(a<2)this.fromInt(1);else{this.fromNumber(a,c);if(!this.testBit(a-1))this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(b2)){this.dAddOffset(2,0);if(this.bitLength()>a)this.subTo(BigInteger.ONE.shiftLeft(a-1),this)}}}else{var x=new Array,t=a&7;x.length=(a>>3)+1;b2.nextBytes(x);if(t>0)x[0]&=(1<<t)-1;else x[0]=0;this.fromString(x,256)}}function bnToByteArray(){var i=this.t,r=new Array;r[0]=this.s;var p2=this.DB-i*this.DB%8,d,k2=0;if(i-- >0){if(p2<this.DB&&(d=this.data[i]>>p2)!=(this.s&this.DM)>>p2)r[k2++]=d|this.s<<this.DB-p2;while(i>=0){if(p2<8){d=(this.data[i]&(1<<p2)-1)<<8-p2;d|=this.data[--i]>>(p2+=this.DB-8)}else{d=this.data[i]>>(p2-=8)&255;if(p2<=0){p2+=this.DB;--i}}if((d&128)!=0)d|=-256;if(k2==0&&(this.s&128)!=(d&128))++k2;if(k2>0||d!=this.s)r[k2++]=d}}return r}function bnEquals(a){return this.compareTo(a)==0}function bnMin(a){return this.compareTo(a)<0?this:a}function bnMax(a){return this.compareTo(a)>0?this:a}function bnpBitwiseTo(a,op,r){var i,f2,m2=Math.min(a.t,this.t);for(i=0;i<m2;++i)r.data[i]=op(this.data[i],a.data[i]);if(a.t<this.t){f2=a.s&this.DM;for(i=m2;i<this.t;++i)r.data[i]=op(this.data[i],f2);r.t=this.t}else{f2=this.s&this.DM;for(i=m2;i<a.t;++i)r.data[i]=op(f2,a.data[i]);r.t=a.t}r.s=op(this.s,a.s);r.clamp()}function op_and(x,y){return x&y}function bnAnd(a){var r=nbi();this.bitwiseTo(a,op_and,r);return r}function op_or(x,y){return x|y}function bnOr(a){var r=nbi();this.bitwiseTo(a,op_or,r);return r}function op_xor(x,y){return x^y}function bnXor(a){var r=nbi();this.bitwiseTo(a,op_xor,r);return r}function op_andnot(x,y){return x&~y}function bnAndNot(a){var r=nbi();this.bitwiseTo(a,op_andnot,r);return r}function bnNot(){var r=nbi();for(var i=0;i<this.t;++i)r.data[i]=this.DM&~this.data[i];r.t=this.t;r.s=~this.s;return r}function bnShiftLeft(n){var r=nbi();if(n<0)this.rShiftTo(-n,r);else this.lShiftTo(n,r);return r}function bnShiftRight(n){var r=nbi();if(n<0)this.lShiftTo(-n,r);else this.rShiftTo(n,r);return r}function lbit(x){if(x==0)return-1;var r=0;if((x&65535)==0){x>>=16;r+=16}if((x&255)==0){x>>=8;r+=8}if((x&15)==0){x>>=4;r+=4}if((x&3)==0){x>>=2;r+=2}if((x&1)==0)++r;return r}function bnGetLowestSetBit(){for(var i=0;i<this.t;++i)if(this.data[i]!=0)return i*this.DB+lbit(this.data[i]);if(this.s<0)return this.t*this.DB;return-1}function cbit(x){var r=0;while(x!=0){x&=x-1;++r}return r}function bnBitCount(){var r=0,x=this.s&this.DM;for(var i=0;i<this.t;++i)r+=cbit(this.data[i]^x);return r}function bnTestBit(n){var j2=Math.floor(n/this.DB);if(j2>=this.t)return this.s!=0;return(this.data[j2]&1<<n%this.DB)!=0}function bnpChangeBit(n,op){var r=BigInteger.ONE.shiftLeft(n);this.bitwiseTo(r,op,r);return r}function bnSetBit(n){return this.changeBit(n,op_or)}function bnClearBit(n){return this.changeBit(n,op_andnot)}function bnFlipBit(n){return this.changeBit(n,op_xor)}function bnpAddTo(a,r){var i=0,c=0,m2=Math.min(a.t,this.t);while(i<m2){c+=this.data[i]+a.data[i];r.data[i++]=c&this.DM;c>>=this.DB}if(a.t<this.t){c+=a.s;while(i<this.t){c+=this.data[i];r.data[i++]=c&this.DM;c>>=this.DB}c+=this.s}else{c+=this.s;while(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;if(c>0)r.data[i++]=c;else if(c<-1)r.data[i++]=this.DV+c;r.t=i;r.clamp()}function bnAdd(a){var r=nbi();this.addTo(a,r);return r}function bnSubtract(a){var r=nbi();this.subTo(a,r);return r}function bnMultiply(a){var r=nbi();this.multiplyTo(a,r);return r}function bnSquare(){var r=nbi();this.squareTo(r);return r}function bnDivide(a){var r=nbi();this.divRemTo(a,r,null);return r}function bnRemainder(a){var r=nbi();this.divRemTo(a,null,r);return r}function bnDivideAndRemainder(a){var q2=nbi(),r=nbi();this.divRemTo(a,q2,r);return new Array(q2,r)}function bnpDMultiply(n){this.data[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(n,w2){if(n==0)return;while(this.t<=w2)this.data[this.t++]=0;this.data[w2]+=n;while(this.data[w2]>=this.DV){this.data[w2]-=this.DV;if(++w2>=this.t)this.data[this.t++]=0;++this.data[w2]}}function NullExp(){}function nNop(x){return x}function nMulTo(x,y,r){x.multiplyTo(y,r)}function nSqrTo(x,r){x.squareTo(r)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);r.s=0;r.t=i;while(i>0)r.data[--i]=0;var j2;for(j2=r.t-this.t;i<j2;++i)r.data[i+this.t]=this.am(0,a.data[i],r,i,0,this.t);for(j2=Math.min(a.t,n);i<j2;++i)this.am(0,a.data[i],r,i,0,n-i);r.clamp()}function bnpMultiplyUpperTo(a,n,r){--n;var i=r.t=this.t+a.t-n;r.s=0;while(--i>=0)r.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)}function Barrett(m2){this.r2=nbi();this.q3=nbi();BigInteger.ONE.dlShiftTo(2*m2.t,this.r2);this.mu=this.r2.divide(m2);this.m=m2}function barrettConvert(x){if(x.s<0||x.t>2*this.m.t)return x.mod(this.m);else if(x.compareTo(this.m)<0)return x;else{var r=nbi();x.copyTo(r);this.reduce(r);return r}}function barrettRevert(x){return x}function barrettReduce(x){x.drShiftTo(this.m.t-1,this.r2);if(x.t>this.m.t+1){x.t=this.m.t+1;x.clamp()}this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(x.compareTo(this.r2)<0)x.dAddOffset(1,this.m.t+1);x.subTo(this.r2,x);while(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function barrettSqrTo(x,r){x.squareTo(r);this.reduce(r)}function barrettMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(e,m2){var i=e.bitLength(),k2,r=nbv(1),z2;if(i<=0)return r;else if(i<18)k2=1;else if(i<48)k2=3;else if(i<144)k2=4;else if(i<768)k2=5;else k2=6;if(i<8)z2=new Classic(m2);else if(m2.isEven())z2=new Barrett(m2);else z2=new Montgomery(m2);var g2=new Array,n=3,k1=k2-1,km=(1<<k2)-1;g2[1]=z2.convert(this);if(k2>1){var g22=nbi();z2.sqrTo(g2[1],g22);while(n<=km){g2[n]=nbi();z2.mulTo(g22,g2[n-2],g2[n]);n+=2}}var j2=e.t-1,w2,is1=true,r2=nbi(),t;i=nbits(e.data[j2])-1;while(j2>=0){if(i>=k1)w2=e.data[j2]>>i-k1&km;else{w2=(e.data[j2]&(1<<i+1)-1)<<k1-i;if(j2>0)w2|=e.data[j2-1]>>this.DB+i-k1}n=k2;while((w2&1)==0){w2>>=1;--n}if((i-=n)<0){i+=this.DB;--j2}if(is1){g2[w2].copyTo(r);is1=false}else{while(n>1){z2.sqrTo(r,r2);z2.sqrTo(r2,r);n-=2}if(n>0)z2.sqrTo(r,r2);else{t=r;r=r2;r2=t}z2.mulTo(r2,g2[w2],r)}while(j2>=0&&(e.data[j2]&1<<i)==0){z2.sqrTo(r,r2);t=r;r=r2;r2=t;if(--i<0){i=this.DB-1;--j2}}}return z2.revert(r)}function bnGCD(a){var x=this.s<0?this.negate():this.clone();var y=a.s<0?a.negate():a.clone();if(x.compareTo(y)<0){var t=x;x=y;y=t}var i=x.getLowestSetBit(),g2=y.getLowestSetBit();if(g2<0)return x;if(i<g2)g2=i;if(g2>0){x.rShiftTo(g2,x);y.rShiftTo(g2,y)}while(x.signum()>0){if((i=x.getLowestSetBit())>0)x.rShiftTo(i,x);if((i=y.getLowestSetBit())>0)y.rShiftTo(i,y);if(x.compareTo(y)>=0){x.subTo(y,x);x.rShiftTo(1,x)}else{y.subTo(x,y);y.rShiftTo(1,y)}}if(g2>0)y.lShiftTo(g2,y);return y}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(d==0)r=this.data[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this.data[i])%n;return r}function bnModInverse(m2){if(this.signum()==0){return BigInteger.ZERO}var ac=m2.isEven();if(this.isEven()&&ac||m2.signum()==0)return BigInteger.ZERO;var u2=m2.clone(),v2=this.clone();var a=nbv(1),b2=nbv(0),c=nbv(0),d=nbv(1);while(u2.signum()!=0){while(u2.isEven()){u2.rShiftTo(1,u2);if(ac){if(!a.isEven()||!b2.isEven()){a.addTo(this,a);b2.subTo(m2,b2)}a.rShiftTo(1,a)}else if(!b2.isEven())b2.subTo(m2,b2);b2.rShiftTo(1,b2)}while(v2.isEven()){v2.rShiftTo(1,v2);if(ac){if(!c.isEven()||!d.isEven()){c.addTo(this,c);d.subTo(m2,d)}c.rShiftTo(1,c)}else if(!d.isEven())d.subTo(m2,d);d.rShiftTo(1,d)}if(u2.compareTo(v2)>=0){u2.subTo(v2,u2);if(ac)a.subTo(c,a);b2.subTo(d,b2)}else{v2.subTo(u2,v2);if(ac)c.subTo(a,c);d.subTo(b2,d)}}if(v2.compareTo(BigInteger.ONE)!=0)return BigInteger.ZERO;if(d.compareTo(m2)>=0)return d.subtract(m2);if(d.signum()<0)d.addTo(m2,d);else return d;if(d.signum()<0)return d.add(m2);else return d}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,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(t){var i,x=this.abs();if(x.t==1&&x.data[0]<=lowprimes[lowprimes.length-1]){for(i=0;i<lowprimes.length;++i)if(x.data[0]==lowprimes[i])return true;return false}if(x.isEven())return false;i=1;while(i<lowprimes.length){var m2=lowprimes[i],j2=i+1;while(j2<lowprimes.length&&m2<lplim)m2*=lowprimes[j2++];m2=x.modInt(m2);while(i<j2)if(m2%lowprimes[i++]==0)return false}return x.millerRabin(t)}function bnpMillerRabin(t){var n1=this.subtract(BigInteger.ONE);var k2=n1.getLowestSetBit();if(k2<=0)return false;var r=n1.shiftRight(k2);var prng=bnGetPrng();var a;for(var 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(y.compareTo(BigInteger.ONE)!=0&&y.compareTo(n1)!=0){var j2=1;while(j2++<k2&&y.compareTo(n1)!=0){y=y.modPowInt(2,this);if(y.compareTo(BigInteger.ONE)==0)return false}if(y.compareTo(n1)!=0)return false}}return true}function bnGetPrng(){return{nextBytes:function(x){for(var i=0;i<x.length;++i){x[i]=Math.floor(Math.random()*256)}}}}BigInteger.prototype.chunkSize=bnpChunkSize;BigInteger.prototype.toRadix=bnpToRadix;BigInteger.prototype.fromRadix=bnpFromRadix;BigInteger.prototype.fromNumber=bnpFromNumber;BigInteger.prototype.bitwiseTo=bnpBitwiseTo;BigInteger.prototype.changeBit=bnpChangeBit;BigInteger.prototype.addTo=bnpAddTo;BigInteger.prototype.dMultiply=bnpDMultiply;BigInteger.prototype.dAddOffset=bnpDAddOffset;BigInteger.prototype.multiplyLowerTo=bnpMultiplyLowerTo;BigInteger.prototype.multiplyUpperTo=bnpMultiplyUpperTo;BigInteger.prototype.modInt=bnpModInt;BigInteger.prototype.millerRabin=bnpMillerRabin;BigInteger.prototype.clone=bnClone;BigInteger.prototype.intValue=bnIntValue;BigInteger.prototype.byteValue=bnByteValue;BigInteger.prototype.shortValue=bnShortValue;BigInteger.prototype.signum=bnSigNum;BigInteger.prototype.toByteArray=bnToByteArray;BigInteger.prototype.equals=bnEquals;BigInteger.prototype.min=bnMin;BigInteger.prototype.max=bnMax;BigInteger.prototype.and=bnAnd;BigInteger.prototype.or=bnOr;BigInteger.prototype.xor=bnXor;BigInteger.prototype.andNot=bnAndNot;BigInteger.prototype.not=bnNot;BigInteger.prototype.shiftLeft=bnShiftLeft;BigInteger.prototype.shiftRight=bnShiftRight;BigInteger.prototype.getLowestSetBit=bnGetLowestSetBit;BigInteger.prototype.bitCount=bnBitCount;BigInteger.prototype.testBit=bnTestBit;BigInteger.prototype.setBit=bnSetBit;BigInteger.prototype.clearBit=bnClearBit;BigInteger.prototype.flipBit=bnFlipBit;BigInteger.prototype.add=bnAdd;BigInteger.prototype.subtract=bnSubtract;BigInteger.prototype.multiply=bnMultiply;BigInteger.prototype.divide=bnDivide;BigInteger.prototype.remainder=bnRemainder;BigInteger.prototype.divideAndRemainder=bnDivideAndRemainder;BigInteger.prototype.modPow=bnModPow;BigInteger.prototype.modInverse=bnModInverse;BigInteger.prototype.pow=bnPow;BigInteger.prototype.gcd=bnGCD;BigInteger.prototype.isProbablePrime=bnIsProbablePrime;BigInteger.prototype.square=bnSquare}});var require_sha1=__commonJS({"node_modules/node-forge/lib/sha1.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var sha1=module.exports=forge2.sha1=forge2.sha1||{};forge2.md.sha1=forge2.md.algorithms.sha1=sha1;sha1.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge2.util.createBuffer();var _w=new Array(80);var md={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_state={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520};return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i<md.fullMessageLength.length-1;++i){next=md.fullMessageLength[i+1]*8;carry=next/4294967296>>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s22={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4};_update(s22,_w,finalBlock);var rval=forge2.util.createBuffer();rval.putInt32(s22.h0);rval.putInt32(s22.h1);rval.putInt32(s22.h2);rval.putInt32(s22.h3);rval.putInt32(s22.h4);return rval};return md};var _padding=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.util.fillString(String.fromCharCode(0),64);_initialized=true}function _update(s3,w2,bytes){var t,a,b2,c,d,e,f2,i;var len=bytes.length();while(len>=64){a=s3.h0;b2=s3.h1;c=s3.h2;d=s3.h3;e=s3.h4;for(i=0;i<16;++i){t=bytes.getInt32();w2[i]=t;f2=d^b2&(c^d);t=(a<<5|a>>>27)+f2+e+1518500249+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<20;++i){t=w2[i-3]^w2[i-8]^w2[i-14]^w2[i-16];t=t<<1|t>>>31;w2[i]=t;f2=d^b2&(c^d);t=(a<<5|a>>>27)+f2+e+1518500249+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<32;++i){t=w2[i-3]^w2[i-8]^w2[i-14]^w2[i-16];t=t<<1|t>>>31;w2[i]=t;f2=b2^c^d;t=(a<<5|a>>>27)+f2+e+1859775393+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<40;++i){t=w2[i-6]^w2[i-16]^w2[i-28]^w2[i-32];t=t<<2|t>>>30;w2[i]=t;f2=b2^c^d;t=(a<<5|a>>>27)+f2+e+1859775393+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<60;++i){t=w2[i-6]^w2[i-16]^w2[i-28]^w2[i-32];t=t<<2|t>>>30;w2[i]=t;f2=b2&c|d&(b2^c);t=(a<<5|a>>>27)+f2+e+2400959708+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<80;++i){t=w2[i-6]^w2[i-16]^w2[i-28]^w2[i-32];t=t<<2|t>>>30;w2[i]=t;f2=b2^c^d;t=(a<<5|a>>>27)+f2+e+3395469782+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}s3.h0=s3.h0+a|0;s3.h1=s3.h1+b2|0;s3.h2=s3.h2+c|0;s3.h3=s3.h3+d|0;s3.h4=s3.h4+e|0;len-=64}}}});var require_pkcs1=__commonJS({"node_modules/node-forge/lib/pkcs1.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_random();require_sha1();var pkcs1=module.exports=forge2.pkcs1=forge2.pkcs1||{};pkcs1.encode_rsa_oaep=function(key,message,options){var label;var seed;var md;var mgf1Md;if(typeof options==="string"){label=options;seed=arguments[3]||void 0;md=arguments[4]||void 0}else if(options){label=options.label||void 0;seed=options.seed||void 0;md=options.md||void 0;if(options.mgf1&&options.mgf1.md){mgf1Md=options.mgf1.md}}if(!md){md=forge2.md.sha1.create()}else{md.start()}if(!mgf1Md){mgf1Md=md}var keyLength=Math.ceil(key.n.bitLength()/8);var maxLength=keyLength-2*md.digestLength-2;if(message.length>maxLength){var error=new Error("RSAES-OAEP input message length is too long.");error.length=message.length;error.maxLength=maxLength;throw error}if(!label){label=""}md.update(label,"raw");var lHash=md.digest();var PS="";var PS_length=maxLength-message.length;for(var i=0;i<PS_length;i++){PS+="\0"}var DB=lHash.getBytes()+PS+""+message;if(!seed){seed=forge2.random.getBytes(md.digestLength)}else if(seed.length!==md.digestLength){var error=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");error.seedLength=seed.length;error.digestLength=md.digestLength;throw error}var dbMask=rsa_mgf1(seed,keyLength-md.digestLength-1,mgf1Md);var maskedDB=forge2.util.xorBytes(DB,dbMask,DB.length);var seedMask=rsa_mgf1(maskedDB,md.digestLength,mgf1Md);var maskedSeed=forge2.util.xorBytes(seed,seedMask,seed.length);return"\0"+maskedSeed+maskedDB};pkcs1.decode_rsa_oaep=function(key,em,options){var label;var md;var mgf1Md;if(typeof options==="string"){label=options;md=arguments[3]||void 0}else if(options){label=options.label||void 0;md=options.md||void 0;if(options.mgf1&&options.mgf1.md){mgf1Md=options.mgf1.md}}var keyLength=Math.ceil(key.n.bitLength()/8);if(em.length!==keyLength){var error=new Error("RSAES-OAEP encoded message length is invalid.");error.length=em.length;error.expectedLength=keyLength;throw error}if(md===void 0){md=forge2.md.sha1.create()}else{md.start()}if(!mgf1Md){mgf1Md=md}if(keyLength<2*md.digestLength+2){throw new Error("RSAES-OAEP key is too short for the hash function.")}if(!label){label=""}md.update(label,"raw");var lHash=md.digest().getBytes();var y=em.charAt(0);var maskedSeed=em.substring(1,md.digestLength+1);var maskedDB=em.substring(1+md.digestLength);var seedMask=rsa_mgf1(maskedDB,md.digestLength,mgf1Md);var seed=forge2.util.xorBytes(maskedSeed,seedMask,maskedSeed.length);var dbMask=rsa_mgf1(seed,keyLength-md.digestLength-1,mgf1Md);var db=forge2.util.xorBytes(maskedDB,dbMask,maskedDB.length);var lHashPrime=db.substring(0,md.digestLength);var error=y!=="\0";for(var i=0;i<md.digestLength;++i){error|=lHash.charAt(i)!==lHashPrime.charAt(i)}var in_ps=1;var index=md.digestLength;for(var j2=md.digestLength;j2<db.length;j2++){var code=db.charCodeAt(j2);var is_0=code&1^1;var error_mask=in_ps?65534:0;error|=code&error_mask;in_ps=in_ps&is_0;index+=in_ps}if(error||db.charCodeAt(index)!==1){throw new Error("Invalid RSAES-OAEP padding.")}return db.substring(index+1)};function rsa_mgf1(seed,maskLength,hash){if(!hash){hash=forge2.md.sha1.create()}var t="";var count=Math.ceil(maskLength/hash.digestLength);for(var i=0;i<count;++i){var c=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,i&255);hash.start();hash.update(seed+c);t+=hash.digest().getBytes()}return t.substring(0,maskLength)}}});var require_prime=__commonJS({"node_modules/node-forge/lib/prime.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_jsbn();require_random();(function(){if(forge2.prime){module.exports=forge2.prime;return}var prime=module.exports=forge2.prime=forge2.prime||{};var BigInteger=forge2.jsbn.BigInteger;var GCD_30_DELTA=[6,4,2,4,2,4,6,2];var THIRTY=new BigInteger(null);THIRTY.fromInt(30);var op_or=function(x,y){return x|y};prime.generateProbablePrime=function(bits,options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};var algorithm=options.algorithm||"PRIMEINC";if(typeof algorithm==="string"){algorithm={name:algorithm}}algorithm.options=algorithm.options||{};var prng=options.prng||forge2.random;var rng={nextBytes:function(x){var b2=prng.getBytesSync(x.length);for(var i=0;i<x.length;++i){x[i]=b2.charCodeAt(i)}}};if(algorithm.name==="PRIMEINC"){return primeincFindPrime(bits,rng,algorithm.options,callback)}throw new Error("Invalid prime generation algorithm: "+algorithm.name)};function primeincFindPrime(bits,rng,options,callback){if("workers"in options){return primeincFindPrimeWithWorkers(bits,rng,options,callback)}return primeincFindPrimeWithoutWorkers(bits,rng,options,callback)}function primeincFindPrimeWithoutWorkers(bits,rng,options,callback){var num=generateRandom(bits,rng);var deltaIdx=0;var mrTests=getMillerRabinTests(num.bitLength());if("millerRabinTests"in options){mrTests=options.millerRabinTests}var maxBlockTime=10;if("maxBlockTime"in options){maxBlockTime=options.maxBlockTime}_primeinc(num,bits,rng,deltaIdx,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)}if(num.isProbablePrime(mrTests)){return callback(null,num)}num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}while(maxBlockTime<0||+new Date-start<maxBlockTime);forge2.util.setImmediate(function(){_primeinc(num,bits,rng,deltaIdx,mrTests,maxBlockTime,callback)})}function primeincFindPrimeWithWorkers(bits,rng,options,callback){if(typeof Worker==="undefined"){return primeincFindPrimeWithoutWorkers(bits,rng,options,callback)}var num=generateRandom(bits,rng);var numWorkers=options.workers;var workLoad=options.workLoad||100;var range=workLoad*30/8;var workerScript=options.workerScript||"forge/prime.worker.js";if(numWorkers===-1){return forge2.util.estimateCores(function(err,cores){if(err){cores=2}numWorkers=cores-1;generate()})}generate();function generate(){numWorkers=Math.max(1,numWorkers);var workers=[];for(var i=0;i<numWorkers;++i){workers[i]=new Worker(workerScript)}var running=numWorkers;for(var i=0;i<numWorkers;++i){workers[i].addEventListener("message",workerMessage)}var found=false;function workerMessage(e){if(found){return}--running;var data=e.data;if(data.found){for(var i2=0;i2<workers.length;++i2){workers[i2].terminate()}found=true;return callback(null,new BigInteger(data.prime,16))}if(num.bitLength()>bits){num=generateRandom(bits,rng)}var hex=num.toString(16);e.target.postMessage({hex,workLoad});num.dAddOffset(range,0)}}}function generateRandom(bits,rng){var num=new BigInteger(bits,rng);var bits1=bits-1;if(!num.testBit(bits1)){num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,num)}num.dAddOffset(31-num.mod(THIRTY).byteValue(),0);return num}function getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}})()}});var require_rsa=__commonJS({"node_modules/node-forge/lib/rsa.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_jsbn();require_oids();require_pkcs1();require_prime();require_random();require_util7();if(typeof BigInteger==="undefined"){BigInteger=forge2.jsbn.BigInteger}var BigInteger;var _crypto=forge2.util.isNodejs?__require("crypto"):null;var asn1=forge2.asn1;var util=forge2.util;forge2.pki=forge2.pki||{};module.exports=forge2.pki.rsa=forge2.rsa=forge2.rsa||{};var pki=forge2.pki;var GCD_30_DELTA=[6,4,2,4,2,4,6,2];var privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"privateKey"}]};var rsaPrivateKeyValidator={name:"RSAPrivateKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPrivateKey.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyCoefficient"}]};var rsaPublicKeyValidator={name:"RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPublicKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyExponent"}]};var publicKeyValidator=forge2.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"rsaPublicKey"}]}]};var digestInfoValidator={name:"DigestInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.NULL,capture:"parameters",optional:true,constructed:false}]},{name:"DigestInfo.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"digest"}]};var emsaPkcs1v15encode=function(md){var oid;if(md.algorithm in pki.oids){oid=pki.oids[md.algorithm]}else{var error=new Error("Unknown message digest algorithm.");error.algorithm=md.algorithm;throw error}var oidBytes=asn1.oidToDer(oid).getBytes();var digestInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var digestAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,oidBytes));digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,""));var digest=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,md.digest().getBytes());digestInfo.value.push(digestAlgorithm);digestInfo.value.push(digest);return asn1.toDer(digestInfo).getBytes()};var _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)}if(!key.dP){key.dP=key.d.mod(key.p.subtract(BigInteger.ONE))}if(!key.dQ){key.dQ=key.d.mod(key.q.subtract(BigInteger.ONE))}if(!key.qInv){key.qInv=key.q.modInverse(key.p)}var r;do{r=new BigInteger(forge2.util.bytesToHex(forge2.random.getBytes(key.n.bitLength()/8)),16)}while(r.compareTo(key.n)>=0||!r.gcd(key.n).equals(BigInteger.ONE));x=x.multiply(r.modPow(key.e,key.n)).mod(key.n);var xp=x.mod(key.p).modPow(key.dP,key.p);var xq=x.mod(key.q).modPow(key.dQ,key.q);while(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);y=y.multiply(r.modInverse(key.n)).mod(key.n);return y};pki.rsa.encrypt=function(m2,key,bt2){var pub=bt2;var eb;var k2=Math.ceil(key.n.bitLength()/8);if(bt2!==false&&bt2!==true){pub=bt2===2;eb=_encodePkcs1_v1_5(m2,key,bt2)}else{eb=forge2.util.createBuffer();eb.putBytes(m2)}var x=new BigInteger(eb.toHex(),16);var y=_modPow(x,key,pub);var yhex=y.toString(16);var ed=forge2.util.createBuffer();var zeros=k2-Math.ceil(yhex.length/2);while(zeros>0){ed.putByte(0);--zeros}ed.putBytes(forge2.util.hexToBytes(yhex));return ed.getBytes()};pki.rsa.decrypt=function(ed,key,pub,ml){var k2=Math.ceil(key.n.bitLength()/8);if(ed.length!==k2){var error=new Error("Encrypted message length is invalid.");error.length=ed.length;error.expected=k2;throw error}var y=new BigInteger(forge2.util.createBuffer(ed).toHex(),16);if(y.compareTo(key.n)>=0){throw new Error("Encrypted message is invalid.")}var x=_modPow(y,key,pub);var xhex=x.toString(16);var eb=forge2.util.createBuffer();var zeros=k2-Math.ceil(xhex.length/2);while(zeros>0){eb.putByte(0);--zeros}eb.putBytes(forge2.util.hexToBytes(xhex));if(ml!==false){return _decodePkcs1_v1_5(eb.getBytes(),key,pub)}return eb.getBytes()};pki.rsa.createKeyPairGenerationState=function(bits,e,options){if(typeof bits==="string"){bits=parseInt(bits,10)}bits=bits||2048;options=options||{};var prng=options.prng||forge2.random;var rng={nextBytes:function(x){var b2=prng.getBytesSync(x.length);for(var i=0;i<x.length;++i){x[i]=b2.charCodeAt(i)}}};var algorithm=options.algorithm||"PRIMEINC";var rval;if(algorithm==="PRIMEINC"){rval={algorithm,state:0,bits,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};rval.e.fromInt(rval.eInt)}else{throw new Error("Invalid key generation algorithm: "+algorithm)}return rval};pki.rsa.stepKeyPairGenerationState=function(state3,n){if(!("algorithm"in state3)){state3.algorithm="PRIMEINC"}var THIRTY=new BigInteger(null);THIRTY.fromInt(30);var deltaIdx=0;var op_or=function(x,y){return x|y};var t1=+new Date;var t2;var total=0;while(state3.keys===null&&(n<=0||total<n)){if(state3.state===0){var bits=state3.p===null?state3.pBits:state3.qBits;var bits1=bits-1;if(state3.pqState===0){state3.num=new BigInteger(bits,state3.rng);if(!state3.num.testBit(bits1)){state3.num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,state3.num)}state3.num.dAddOffset(31-state3.num.mod(THIRTY).byteValue(),0);deltaIdx=0;++state3.pqState}else if(state3.pqState===1){if(state3.num.bitLength()>bits){state3.pqState=0}else if(state3.num.isProbablePrime(_getMillerRabinTests(state3.num.bitLength()))){++state3.pqState}else{state3.num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}}else if(state3.pqState===2){state3.pqState=state3.num.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE)===0?3:0}else if(state3.pqState===3){state3.pqState=0;if(state3.p===null){state3.p=state3.num}else{state3.q=state3.num}if(state3.p!==null&&state3.q!==null){++state3.state}state3.num=null}}else if(state3.state===1){if(state3.p.compareTo(state3.q)<0){state3.num=state3.p;state3.p=state3.q;state3.q=state3.num}++state3.state}else if(state3.state===2){state3.p1=state3.p.subtract(BigInteger.ONE);state3.q1=state3.q.subtract(BigInteger.ONE);state3.phi=state3.p1.multiply(state3.q1);++state3.state}else if(state3.state===3){if(state3.phi.gcd(state3.e).compareTo(BigInteger.ONE)===0){++state3.state}else{state3.p=null;state3.q=null;state3.state=0}}else if(state3.state===4){state3.n=state3.p.multiply(state3.q);if(state3.n.bitLength()===state3.bits){++state3.state}else{state3.q=null;state3.state=0}}else if(state3.state===5){var d=state3.e.modInverse(state3.phi);state3.keys={privateKey:pki.rsa.setPrivateKey(state3.n,state3.e,d,state3.p,state3.q,d.mod(state3.p1),d.mod(state3.q1),state3.q.modInverse(state3.p)),publicKey:pki.rsa.setPublicKey(state3.n,state3.e)}}t2=+new Date;total+=t2-t1;t1=t2}return state3.keys!==null};pki.rsa.generateKeyPair=function(bits,e,options,callback){if(arguments.length===1){if(typeof bits==="object"){options=bits;bits=void 0}else if(typeof bits==="function"){callback=bits;bits=void 0}}else if(arguments.length===2){if(typeof bits==="number"){if(typeof e==="function"){callback=e;e=void 0}else if(typeof e!=="number"){options=e;e=void 0}}else{options=bits;callback=e;bits=void 0;e=void 0}}else if(arguments.length===3){if(typeof e==="number"){if(typeof options==="function"){callback=options;options=void 0}}else{callback=options;options=e;e=void 0}}options=options||{};if(bits===void 0){bits=options.bits||2048}if(e===void 0){e=options.e||65537}if(!forge2.options.usePureJavaScript&&!options.prng&&bits>=256&&bits<=16384&&(e===65537||e===3)){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"}},true,["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(forge2.util.createBuffer(pkcs8)));callback(null,{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"}},true,["sign","verify"]);genOp.oncomplete=function(e2){var pair=e2.target.result;var exportOp=util.globalScope.msCrypto.subtle.exportKey("pkcs8",pair.privateKey);exportOp.oncomplete=function(e3){var pkcs8=e3.target.result;var privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge2.util.createBuffer(pkcs8)));callback(null,{privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})};exportOp.onerror=function(err){callback(err)}};genOp.onerror=function(err){callback(err)};return}}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 state3=pki.rsa.createKeyPairGenerationState(bits,e,options);if(!callback){pki.rsa.stepKeyPairGenerationState(state3,0);return state3.keys}_generateKeyPair(state3,options,callback)};pki.setRsaPublicKey=pki.rsa.setPublicKey=function(n,e){var key={n,e};key.encrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===void 0){scheme="RSAES-PKCS1-V1_5"}if(scheme==="RSAES-PKCS1-V1_5"){scheme={encode:function(m2,key2,pub){return _encodePkcs1_v1_5(m2,key2,2).getBytes()}}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={encode:function(m2,key2){return forge2.pkcs1.encode_rsa_oaep(key2,m2,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={encode:function(e3){return e3}}}else if(typeof scheme==="string"){throw new Error('Unsupported encryption scheme: "'+scheme+'".')}var e2=scheme.encode(data,key,true);return pki.rsa.encrypt(e2,key,true)};key.verify=function(digest,signature,scheme,options){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===void 0){scheme="RSASSA-PKCS1-V1_5"}if(options===void 0){options={_parseAllDigestBytes:true,_skipPaddingChecks:false}}if(!("_parseAllDigestBytes"in options)){options._parseAllDigestBytes=true}if(!("_skipPaddingChecks"in options)){options._skipPaddingChecks=false}if(scheme==="RSASSA-PKCS1-V1_5"){scheme={verify:function(digest2,d2){d2=_decodePkcs1_v1_5(d2,key,true,void 0,options);var obj=asn1.fromDer(d2,{parseAllBytes:options._parseAllDigestBytes});var capture2={};var errors=[];if(!asn1.validate(obj,digestInfoValidator,capture2,errors)||obj.value.length!==2){var error=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.algorithmIdentifier);if(!(oid===forge2.oids.md2||oid===forge2.oids.md5||oid===forge2.oids.sha1||oid===forge2.oids.sha224||oid===forge2.oids.sha256||oid===forge2.oids.sha384||oid===forge2.oids.sha512||oid===forge2.oids["sha512-224"]||oid===forge2.oids["sha512-256"])){var error=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");error.oid=oid;throw error}if(oid===forge2.oids.md2||oid===forge2.oids.md5){if(!("parameters"in capture2)){throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}}return digest2===capture2.digest}}}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={verify:function(digest2,d2){d2=_decodePkcs1_v1_5(d2,key,true,void 0,options);return digest2===d2}}}var d=pki.rsa.decrypt(signature,key,true,false);return scheme.verify(digest,d,key.n.bitLength())};return key};pki.setRsaPrivateKey=pki.rsa.setPrivateKey=function(n,e,d,p2,q2,dP,dQ,qInv){var key={n,e,d,p:p2,q:q2,dP,dQ,qInv};key.decrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===void 0){scheme="RSAES-PKCS1-V1_5"}var d2=pki.rsa.decrypt(data,key,false,false);if(scheme==="RSAES-PKCS1-V1_5"){scheme={decode:_decodePkcs1_v1_5}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={decode:function(d3,key2){return forge2.pkcs1.decode_rsa_oaep(key2,d3,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={decode:function(d3){return d3}}}else{throw new Error('Unsupported encryption scheme: "'+scheme+'".')}return scheme.decode(d2,key,false)};key.sign=function(md,scheme){var bt2=false;if(typeof scheme==="string"){scheme=scheme.toUpperCase()}if(scheme===void 0||scheme==="RSASSA-PKCS1-V1_5"){scheme={encode:emsaPkcs1v15encode};bt2=1}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={encode:function(){return md}};bt2=1}var d2=scheme.encode(md,key.n.bitLength());return pki.rsa.encrypt(d2,key,bt2)};return key};pki.wrapRsaPrivateKey=function(rsaKey){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(rsaKey).getBytes())])};pki.privateKeyFromAsn1=function(obj){var capture2={};var errors=[];if(asn1.validate(obj,privateKeyValidator,capture2,errors)){obj=asn1.fromDer(forge2.util.createBuffer(capture2.privateKey))}capture2={};errors=[];if(!asn1.validate(obj,rsaPrivateKeyValidator,capture2,errors)){var error=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");error.errors=errors;throw error}var n,e,d,p2,q2,dP,dQ,qInv;n=forge2.util.createBuffer(capture2.privateKeyModulus).toHex();e=forge2.util.createBuffer(capture2.privateKeyPublicExponent).toHex();d=forge2.util.createBuffer(capture2.privateKeyPrivateExponent).toHex();p2=forge2.util.createBuffer(capture2.privateKeyPrime1).toHex();q2=forge2.util.createBuffer(capture2.privateKeyPrime2).toHex();dP=forge2.util.createBuffer(capture2.privateKeyExponent1).toHex();dQ=forge2.util.createBuffer(capture2.privateKeyExponent2).toHex();qInv=forge2.util.createBuffer(capture2.privateKeyCoefficient).toHex();return pki.setRsaPrivateKey(new BigInteger(n,16),new BigInteger(e,16),new BigInteger(d,16),new BigInteger(p2,16),new BigInteger(q2,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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.d)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.p)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.q)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dP)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dQ)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.qInv))])};pki.publicKeyFromAsn1=function(obj){var capture2={};var errors=[];if(asn1.validate(obj,publicKeyValidator,capture2,errors)){var oid=asn1.derToOid(capture2.publicKeyOid);if(oid!==pki.oids.rsaEncryption){var error=new Error("Cannot read public key. Unknown OID.");error.oid=oid;throw error}obj=capture2.rsaPublicKey}errors=[];if(!asn1.validate(obj,rsaPublicKeyValidator,capture2,errors)){var error=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");error.errors=errors;throw error}var n=forge2.util.createBuffer(capture2.publicKeyModulus).toHex();var e=forge2.util.createBuffer(capture2.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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,[pki.publicKeyToRSAPublicKey(key)])])};pki.publicKeyToRSAPublicKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e))])};function _encodePkcs1_v1_5(m2,key,bt2){var eb=forge2.util.createBuffer();var k2=Math.ceil(key.n.bitLength()/8);if(m2.length>k2-11){var error=new Error("Message is too long for PKCS#1 v1.5 padding.");error.length=m2.length;error.max=k2-11;throw error}eb.putByte(0);eb.putByte(bt2);var padNum=k2-3-m2.length;var padByte;if(bt2===0||bt2===1){padByte=bt2===0?0:255;for(var i=0;i<padNum;++i){eb.putByte(padByte)}}else{while(padNum>0){var numZeros=0;var padBytes=forge2.random.getBytes(padNum);for(var i=0;i<padNum;++i){padByte=padBytes.charCodeAt(i);if(padByte===0){++numZeros}else{eb.putByte(padByte)}}padNum=numZeros}}eb.putByte(0);eb.putBytes(m2);return eb}function _decodePkcs1_v1_5(em,key,pub,ml,options){var k2=Math.ceil(key.n.bitLength()/8);var eb=forge2.util.createBuffer(em);var first=eb.getByte();var bt2=eb.getByte();if(first!==0||pub&&bt2!==0&&bt2!==1||!pub&&bt2!==2||pub&&bt2===0&&typeof ml==="undefined"){throw new Error("Encryption block is invalid.")}var padNum=0;if(bt2===0){padNum=k2-3-ml;for(var i=0;i<padNum;++i){if(eb.getByte()!==0){throw new Error("Encryption block is invalid.")}}}else if(bt2===1){padNum=0;while(eb.length()>1){if(eb.getByte()!==255){--eb.read;break}++padNum}if(padNum<8&&!(options?options._skipPaddingChecks:false)){throw new Error("Encryption block is invalid.")}}else if(bt2===2){padNum=0;while(eb.length()>1){if(eb.getByte()===0){--eb.read;break}++padNum}if(padNum<8&&!(options?options._skipPaddingChecks:false)){throw new Error("Encryption block is invalid.")}}var zero=eb.getByte();if(zero!==0||padNum!==k2-3-eb.length()){throw new Error("Encryption block is invalid.")}return eb.getBytes()}function _generateKeyPair(state3,options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};var opts={algorithm:{name:options.algorithm||"PRIMEINC",options:{workers:options.workers||2,workLoad:options.workLoad||100,workerScript:options.workerScript}}};if("prng"in options){opts.prng=options.prng}generate();function generate(){getPrime(state3.pBits,function(err,num){if(err){return callback(err)}state3.p=num;if(state3.q!==null){return finish(err,state3.q)}getPrime(state3.qBits,finish)})}function getPrime(bits,callback2){forge2.prime.generateProbablePrime(bits,opts,callback2)}function finish(err,num){if(err){return callback(err)}state3.q=num;if(state3.p.compareTo(state3.q)<0){var tmp=state3.p;state3.p=state3.q;state3.q=tmp}if(state3.p.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE)!==0){state3.p=null;generate();return}if(state3.q.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE)!==0){state3.q=null;getPrime(state3.qBits,finish);return}state3.p1=state3.p.subtract(BigInteger.ONE);state3.q1=state3.q.subtract(BigInteger.ONE);state3.phi=state3.p1.multiply(state3.q1);if(state3.phi.gcd(state3.e).compareTo(BigInteger.ONE)!==0){state3.p=state3.q=null;generate();return}state3.n=state3.p.multiply(state3.q);if(state3.n.bitLength()!==state3.bits){state3.q=null;getPrime(state3.qBits,finish);return}var d=state3.e.modInverse(state3.phi);state3.keys={privateKey:pki.rsa.setPrivateKey(state3.n,state3.e,d,state3.p,state3.q,d.mod(state3.p1),d.mod(state3.q1),state3.q.modInverse(state3.p)),publicKey:pki.rsa.setPublicKey(state3.n,state3.e)};callback(null,state3.keys)}}function _bnToBytes(b2){var hex=b2.toString(16);if(hex[0]>="8"){hex="00"+hex}var bytes=forge2.util.hexToBytes(hex);if(bytes.length>1&&(bytes.charCodeAt(0)===0&&(bytes.charCodeAt(1)&128)===0||bytes.charCodeAt(0)===255&&(bytes.charCodeAt(1)&128)===128)){return bytes.substr(1)}return bytes}function _getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}function _detectNodeCrypto(fn){return forge2.util.isNodejs&&typeof _crypto[fn]==="function"}function _detectSubtleCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.crypto==="object"&&typeof util.globalScope.crypto.subtle==="object"&&typeof util.globalScope.crypto.subtle[fn]==="function"}function _detectSubtleMsCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.msCrypto==="object"&&typeof util.globalScope.msCrypto.subtle==="object"&&typeof util.globalScope.msCrypto.subtle[fn]==="function"}function _intToUint8Array(x){var bytes=forge2.util.hexToBytes(x.toString(16));var buffer=new Uint8Array(bytes.length);for(var i=0;i<bytes.length;++i){buffer[i]=bytes.charCodeAt(i)}return buffer}}});var require_pbe=__commonJS({"node_modules/node-forge/lib/pbe.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_asn1();require_des();require_md();require_oids();require_pbkdf2();require_pem();require_random();require_rc2();require_rsa();require_util7();if(typeof BigInteger==="undefined"){BigInteger=forge2.jsbn.BigInteger}var BigInteger;var asn1=forge2.asn1;var pki=forge2.pki=forge2.pki||{};module.exports=pki.pbe=forge2.pbe=forge2.pbe||{};var oids=pki.oids;var encryptedPrivateKeyValidator={name:"EncryptedPrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"encryptedData"}]};var PBES2AlgorithmsValidator={name:"PBES2Algorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.params.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,optional:true,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"encIv"}]}]};var pkcs12PbeParamsValidator={name:"pkcs-12PbeParams",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"pkcs-12PbeParams.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"iterations"}]};pki.encryptPrivateKeyInfo=function(obj,password,options){options=options||{};options.saltSize=options.saltSize||8;options.count=options.count||2048;options.algorithm=options.algorithm||"aes128";options.prfAlgorithm=options.prfAlgorithm||"sha1";var salt=forge2.random.getBytesSync(options.saltSize);var count=options.count;var countBytes=asn1.integerToDer(count);var dkLen;var encryptionAlgorithm;var encryptedData;if(options.algorithm.indexOf("aes")===0||options.algorithm==="des"){var ivLen,encOid,cipherFn;switch(options.algorithm){case"aes128":dkLen=16;ivLen=16;encOid=oids["aes128-CBC"];cipherFn=forge2.aes.createEncryptionCipher;break;case"aes192":dkLen=24;ivLen=16;encOid=oids["aes192-CBC"];cipherFn=forge2.aes.createEncryptionCipher;break;case"aes256":dkLen=32;ivLen=16;encOid=oids["aes256-CBC"];cipherFn=forge2.aes.createEncryptionCipher;break;case"des":dkLen=8;ivLen=8;encOid=oids["desCBC"];cipherFn=forge2.des.createEncryptionCipher;break;default:var error=new Error("Cannot encrypt private key. Unknown encryption algorithm.");error.algorithm=options.algorithm;throw error}var prfAlgorithm="hmacWith"+options.prfAlgorithm.toUpperCase();var md=prfAlgorithmToMessageDigest(prfAlgorithm);var dk=forge2.pkcs5.pbkdf2(password,salt,count,dkLen,md);var iv=forge2.random.getBytesSync(ivLen);var cipher=cipherFn(dk);cipher.start(iv);cipher.update(asn1.toDer(obj));cipher.finish();encryptedData=cipher.output.getBytes();var params=createPbkdf2Params(salt,countBytes,dkLen,prfAlgorithm);encryptionAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids["pkcs5PBES2"]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes()),params]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(encOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,iv)])])])}else if(options.algorithm==="3des"){dkLen=24;var saltBytes=new forge2.util.ByteBuffer(salt);var dk=pki.pbe.generatePkcs12Key(password,saltBytes,1,count,dkLen);var iv=pki.pbe.generatePkcs12Key(password,saltBytes,2,count,dkLen);var cipher=forge2.des.createEncryptionCipher(dk);cipher.start(iv);cipher.update(asn1.toDer(obj));cipher.finish();encryptedData=cipher.output.getBytes();encryptionAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,salt),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,countBytes.getBytes())])])}else{var error=new Error("Cannot encrypt private key. Unknown encryption algorithm.");error.algorithm=options.algorithm;throw error}var rval=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[encryptionAlgorithm,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,encryptedData)]);return rval};pki.decryptPrivateKeyInfo=function(obj,password){var rval=null;var capture2={};var errors=[];if(!asn1.validate(obj,encryptedPrivateKeyValidator,capture2,errors)){var error=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.encryptionOid);var cipher=pki.pbe.getCipher(oid,capture2.encryptionParams,password);var encrypted=forge2.util.createBuffer(capture2.encryptedData);cipher.update(encrypted);if(cipher.finish()){rval=asn1.fromDer(cipher.output)}return rval};pki.encryptedPrivateKeyToPem=function(epki,maxline){var msg={type:"ENCRYPTED PRIVATE KEY",body:asn1.toDer(epki).getBytes()};return forge2.pem.encode(msg,{maxline})};pki.encryptedPrivateKeyFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="ENCRYPTED PRIVATE KEY"){var error=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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){options=options||{};if(!options.legacy){var rval=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));rval=pki.encryptPrivateKeyInfo(rval,password,options);return pki.encryptedPrivateKeyToPem(rval)}var algorithm;var iv;var dkLen;var cipherFn;switch(options.algorithm){case"aes128":algorithm="AES-128-CBC";dkLen=16;iv=forge2.random.getBytesSync(16);cipherFn=forge2.aes.createEncryptionCipher;break;case"aes192":algorithm="AES-192-CBC";dkLen=24;iv=forge2.random.getBytesSync(16);cipherFn=forge2.aes.createEncryptionCipher;break;case"aes256":algorithm="AES-256-CBC";dkLen=32;iv=forge2.random.getBytesSync(16);cipherFn=forge2.aes.createEncryptionCipher;break;case"3des":algorithm="DES-EDE3-CBC";dkLen=24;iv=forge2.random.getBytesSync(8);cipherFn=forge2.des.createEncryptionCipher;break;case"des":algorithm="DES-CBC";dkLen=8;iv=forge2.random.getBytesSync(8);cipherFn=forge2.des.createEncryptionCipher;break;default:var error=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+options.algorithm+'".');error.algorithm=options.algorithm;throw error}var dk=forge2.pbe.opensslDeriveBytes(password,iv.substr(0,8),dkLen);var cipher=cipherFn(dk);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,parameters:forge2.util.bytesToHex(iv).toUpperCase()},body:cipher.output.getBytes()};return forge2.pem.encode(msg)};pki.decryptRsaPrivateKey=function(pem,password){var rval=null;var msg=forge2.pem.decode(pem)[0];if(msg.type!=="ENCRYPTED PRIVATE KEY"&&msg.type!=="PRIVATE KEY"&&msg.type!=="RSA PRIVATE KEY"){var error=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');error.headerType=error;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){var dkLen;var cipherFn;switch(msg.dekInfo.algorithm){case"DES-CBC":dkLen=8;cipherFn=forge2.des.createDecryptionCipher;break;case"DES-EDE3-CBC":dkLen=24;cipherFn=forge2.des.createDecryptionCipher;break;case"AES-128-CBC":dkLen=16;cipherFn=forge2.aes.createDecryptionCipher;break;case"AES-192-CBC":dkLen=24;cipherFn=forge2.aes.createDecryptionCipher;break;case"AES-256-CBC":dkLen=32;cipherFn=forge2.aes.createDecryptionCipher;break;case"RC2-40-CBC":dkLen=5;cipherFn=function(key){return forge2.rc2.createDecryptionCipher(key,40)};break;case"RC2-64-CBC":dkLen=8;cipherFn=function(key){return forge2.rc2.createDecryptionCipher(key,64)};break;case"RC2-128-CBC":dkLen=16;cipherFn=function(key){return forge2.rc2.createDecryptionCipher(key,128)};break;default:var error=new Error('Could not decrypt private key; unsupported encryption algorithm "'+msg.dekInfo.algorithm+'".');error.algorithm=msg.dekInfo.algorithm;throw error}var iv=forge2.util.hexToBytes(msg.dekInfo.parameters);var dk=forge2.pbe.opensslDeriveBytes(password,iv.substr(0,8),dkLen);var cipher=cipherFn(dk);cipher.start(iv);cipher.update(forge2.util.createBuffer(msg.body));if(cipher.finish()){rval=cipher.output.getBytes()}else{return rval}}else{rval=msg.body}if(msg.type==="ENCRYPTED PRIVATE KEY"){rval=pki.decryptPrivateKeyInfo(asn1.fromDer(rval),password)}else{rval=asn1.fromDer(rval)}if(rval!==null){rval=pki.privateKeyFromAsn1(rval)}return rval};pki.pbe.generatePkcs12Key=function(password,salt,id,iter,n,md){var j2,l;if(typeof md==="undefined"||md===null){if(!("sha1"in forge2.md)){throw new Error('"sha1" hash algorithm unavailable.')}md=forge2.md.sha1.create()}var u2=md.digestLength;var v2=md.blockLength;var result=new forge2.util.ByteBuffer;var passBuf=new forge2.util.ByteBuffer;if(password!==null&&password!==void 0){for(l=0;l<password.length;l++){passBuf.putInt16(password.charCodeAt(l))}passBuf.putInt16(0)}var p2=passBuf.length();var s3=salt.length();var D=new forge2.util.ByteBuffer;D.fillWithByte(id,v2);var Slen=v2*Math.ceil(s3/v2);var S2=new forge2.util.ByteBuffer;for(l=0;l<Slen;l++){S2.putByte(salt.at(l%s3))}var Plen=v2*Math.ceil(p2/v2);var P2=new forge2.util.ByteBuffer;for(l=0;l<Plen;l++){P2.putByte(passBuf.at(l%p2))}var I2=S2;I2.putBuffer(P2);var c=Math.ceil(n/u2);for(var i=1;i<=c;i++){var buf=new forge2.util.ByteBuffer;buf.putBytes(D.bytes());buf.putBytes(I2.bytes());for(var round=0;round<iter;round++){md.start();md.update(buf.getBytes());buf=md.digest()}var B2=new forge2.util.ByteBuffer;for(l=0;l<v2;l++){B2.putByte(buf.at(l%u2))}var k2=Math.ceil(s3/v2)+Math.ceil(p2/v2);var Inew=new forge2.util.ByteBuffer;for(j2=0;j2<k2;j2++){var chunk=new forge2.util.ByteBuffer(I2.getBytes(v2));var x=511;for(l=B2.length()-1;l>=0;l--){x=x>>8;x+=B2.at(l)+chunk.at(l);chunk.setAt(l,x&255)}Inew.putBuffer(chunk)}I2=Inew;result.putBuffer(buf)}result.truncate(result.length()-n);return 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.");error.oid=oid;error.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"];throw error}};pki.pbe.getCipherForPBES2=function(oid,params,password){var capture2={};var errors=[];if(!asn1.validate(params,PBES2AlgorithmsValidator,capture2,errors)){var error=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}oid=asn1.derToOid(capture2.kdfOid);if(oid!==pki.oids["pkcs5PBKDF2"]){var error=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");error.oid=oid;error.supportedOids=["pkcs5PBKDF2"];throw error}oid=asn1.derToOid(capture2.encOid);if(oid!==pki.oids["aes128-CBC"]&&oid!==pki.oids["aes192-CBC"]&&oid!==pki.oids["aes256-CBC"]&&oid!==pki.oids["des-EDE3-CBC"]&&oid!==pki.oids["desCBC"]){var error=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");error.oid=oid;error.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"];throw error}var salt=capture2.kdfSalt;var count=forge2.util.createBuffer(capture2.kdfIterationCount);count=count.getInt(count.length()<<3);var dkLen;var cipherFn;switch(pki.oids[oid]){case"aes128-CBC":dkLen=16;cipherFn=forge2.aes.createDecryptionCipher;break;case"aes192-CBC":dkLen=24;cipherFn=forge2.aes.createDecryptionCipher;break;case"aes256-CBC":dkLen=32;cipherFn=forge2.aes.createDecryptionCipher;break;case"des-EDE3-CBC":dkLen=24;cipherFn=forge2.des.createDecryptionCipher;break;case"desCBC":dkLen=8;cipherFn=forge2.des.createDecryptionCipher;break}var md=prfOidToMessageDigest(capture2.prfOid);var dk=forge2.pkcs5.pbkdf2(password,salt,count,dkLen,md);var iv=capture2.encIv;var cipher=cipherFn(dk);cipher.start(iv);return cipher};pki.pbe.getCipherForPKCS12PBE=function(oid,params,password){var capture2={};var errors=[];if(!asn1.validate(params,pkcs12PbeParamsValidator,capture2,errors)){var error=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}var salt=forge2.util.createBuffer(capture2.salt);var count=forge2.util.createBuffer(capture2.iterations);count=count.getInt(count.length()<<3);var dkLen,dIvLen,cipherFn;switch(oid){case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:dkLen=24;dIvLen=8;cipherFn=forge2.des.startDecrypting;break;case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:dkLen=5;dIvLen=8;cipherFn=function(key2,iv2){var cipher=forge2.rc2.createDecryptionCipher(key2,40);cipher.start(iv2,null);return cipher};break;default:var error=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");error.oid=oid;throw error}var md=prfOidToMessageDigest(capture2.prfOid);var key=pki.pbe.generatePkcs12Key(password,salt,1,count,dkLen,md);md.start();var iv=pki.pbe.generatePkcs12Key(password,salt,2,count,dIvLen,md);return cipherFn(key,iv)};pki.pbe.opensslDeriveBytes=function(password,salt,dkLen,md){if(typeof md==="undefined"||md===null){if(!("md5"in forge2.md)){throw new Error('"md5" hash algorithm unavailable.')}md=forge2.md.md5.create()}if(salt===null){salt=""}var digests=[hash(md,password+salt)];for(var length=16,i=1;length<dkLen;++i,length+=16){digests.push(hash(md,digests[i-1]+password+salt))}return digests.join("").substr(0,dkLen)};function hash(md,bytes){return md.start().update(bytes).digest().getBytes()}function prfOidToMessageDigest(prfOid){var prfAlgorithm;if(!prfOid){prfAlgorithm="hmacWithSHA1"}else{prfAlgorithm=pki.oids[asn1.derToOid(prfOid)];if(!prfAlgorithm){var error=new Error("Unsupported PRF OID.");error.oid=prfOid;error.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"];throw error}}return prfAlgorithmToMessageDigest(prfAlgorithm)}function prfAlgorithmToMessageDigest(prfAlgorithm){var factory=forge2.md;switch(prfAlgorithm){case"hmacWithSHA224":factory=forge2.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":prfAlgorithm=prfAlgorithm.substr(8).toLowerCase();break;default:var error=new Error("Unsupported PRF algorithm.");error.algorithm=prfAlgorithm;error.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"];throw error}if(!factory||!(prfAlgorithm in factory)){throw new Error("Unknown hash algorithm: "+prfAlgorithm)}return factory[prfAlgorithm].create()}function createPbkdf2Params(salt,countBytes,dkLen,prfAlgorithm){var params=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,salt),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,countBytes.getBytes())]);if(prfAlgorithm!=="hmacWithSHA1"){params.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(dkLen.toString(16))),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]))}return params}}});var require_pkcs7asn1=__commonJS({"node_modules/node-forge/lib/pkcs7asn1.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_util7();var asn1=forge2.asn1;var p7v=module.exports=forge2.pkcs7asn1=forge2.pkcs7asn1||{};forge2.pkcs7=forge2.pkcs7||{};forge2.pkcs7.asn1=p7v;var contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"ContentInfo.ContentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,captureAsn1:"content"}]};p7v.contentInfoValidator=contentInfoValidator;var encryptedContentInfoValidator={name:"EncryptedContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,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:true,value:[{name:"EnvelopedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,captureAsn1:"recipientInfos"}].concat(encryptedContentInfoValidator)};p7v.encryptedDataValidator={name:"EncryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"}].concat(encryptedContentInfoValidator)};var signerValidator={name:"SignerInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignerInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false},{name:"SignerInfo.issuerAndSerialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:asn1.Class.UNIVERSAL,constructed:false,captureAsn1:"digestParameter",optional:true}]},{name:"SignerInfo.authenticatedAttributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:true,optional:true,capture:"unauthenticatedAttributes"}]};p7v.signedDataValidator={name:"SignedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,captureAsn1:"digestAlgorithms"},contentInfoValidator,{name:"SignedData.Certificates",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,optional:true,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,optional:true,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,capture:"signerInfos",optional:true,value:[signerValidator]}]};p7v.recipientInfoValidator={name:"RecipientInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RecipientInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:asn1.Class.UNIVERSAL,constructed:false,captureAsn1:"encParameter",optional:true}]},{name:"RecipientInfo.encryptedKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"encKey"}]}}});var require_mgf1=__commonJS({"node_modules/node-forge/lib/mgf1.js"(exports,module){"use strict";var forge2=require_forge();require_util7();forge2.mgf=forge2.mgf||{};var mgf1=module.exports=forge2.mgf.mgf1=forge2.mgf1=forge2.mgf1||{};mgf1.create=function(md){var mgf={generate:function(seed,maskLen){var t=new forge2.util.ByteBuffer;var len=Math.ceil(maskLen/md.digestLength);for(var i=0;i<len;i++){var c=new forge2.util.ByteBuffer;c.putInt32(i);md.start();md.update(seed+c.getBytes());t.putBuffer(md.digest())}t.truncate(t.length()-maskLen);return t.getBytes()}};return mgf}}});var require_mgf=__commonJS({"node_modules/node-forge/lib/mgf.js"(exports,module){"use strict";var forge2=require_forge();require_mgf1();module.exports=forge2.mgf=forge2.mgf||{};forge2.mgf.mgf1=forge2.mgf1}});var require_pss=__commonJS({"node_modules/node-forge/lib/pss.js"(exports,module){"use strict";var forge2=require_forge();require_random();require_util7();var pss=module.exports=forge2.pss=forge2.pss||{};pss.create=function(options){if(arguments.length===3){options={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]}}var hash=options.md;var mgf=options.mgf;var hLen=hash.digestLength;var salt_=options.salt||null;if(typeof salt_==="string"){salt_=forge2.util.createBuffer(salt_)}var sLen;if("saltLength"in options){sLen=options.saltLength}else if(salt_!==null){sLen=salt_.length()}else{throw new Error("Salt length not specified or specific salt not given.")}if(salt_!==null&&salt_.length()!==sLen){throw new Error("Given salt length does not match length of given salt.")}var prng=options.prng||forge2.random;var pssobj={};pssobj.encode=function(md,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);var mHash=md.digest().getBytes();if(emLen<hLen+sLen+2){throw new Error("Message is too long to encrypt.")}var salt;if(salt_===null){salt=prng.getBytesSync(sLen)}else{salt=salt_.bytes()}var m_=new forge2.util.ByteBuffer;m_.fillWithByte(0,8);m_.putBytes(mHash);m_.putBytes(salt);hash.start();hash.update(m_.getBytes());var h=hash.digest().getBytes();var ps2=new forge2.util.ByteBuffer;ps2.fillWithByte(0,emLen-sLen-hLen-2);ps2.putByte(1);ps2.putBytes(salt);var db=ps2.getBytes();var maskLen=emLen-hLen-1;var dbMask=mgf.generate(h,maskLen);var maskedDB="";for(i=0;i<maskLen;i++){maskedDB+=String.fromCharCode(db.charCodeAt(i)^dbMask.charCodeAt(i))}var mask=65280>>8*emLen-emBits&255;maskedDB=String.fromCharCode(maskedDB.charCodeAt(0)&~mask)+maskedDB.substr(1);return maskedDB+h+String.fromCharCode(188)};pssobj.verify=function(mHash,em,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);em=em.substr(-emLen);if(emLen<hLen+sLen+2){throw new Error("Inconsistent parameters to PSS signature verification.")}if(em.charCodeAt(emLen-1)!==188){throw new Error("Encoded message does not end in 0xBC.")}var maskLen=emLen-hLen-1;var maskedDB=em.substr(0,maskLen);var h=em.substr(maskLen,hLen);var mask=65280>>8*emLen-emBits&255;if((maskedDB.charCodeAt(0)&mask)!==0){throw new Error("Bits beyond keysize not zero as expected.")}var dbMask=mgf.generate(h,maskLen);var 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(db.charCodeAt(i)!==0){throw new Error("Leftmost octets not zero as expected")}}if(db.charCodeAt(checkLen)!==1){throw new Error("Inconsistent PSS signature, 0x01 marker not found")}var salt=db.substr(-sLen);var m_=new forge2.util.ByteBuffer;m_.fillWithByte(0,8);m_.putBytes(mHash);m_.putBytes(salt);hash.start();hash.update(m_.getBytes());var h_=hash.digest().getBytes();return h===h_};return pssobj}}});var require_x509=__commonJS({"node_modules/node-forge/lib/x509.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_asn1();require_des();require_md();require_mgf();require_oids();require_pem();require_pss();require_rsa();require_util7();var asn1=forge2.asn1;var pki=module.exports=forge2.pki=forge2.pki||{};var oids=pki.oids;var _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=forge2.pki.rsa.publicKeyValidator;var x509CertificateValidator={name:"Certificate",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.TBSCertificate",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:asn1.Class.UNIVERSAL,optional:true,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.UTCTIME,constructed:false,optional:true,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.GENERALIZEDTIME,constructed:false,optional:true,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.UTCTIME,constructed:false,optional:true,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.GENERALIZEDTIME,constructed:false,optional:true,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certSubject"},publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:true,optional:true,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:2,constructed:true,optional:true,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:3,constructed:true,captureAsn1:"certExtensions",optional:true}]},{name:"Certificate.signatureAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:asn1.Class.UNIVERSAL,optional:true,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"certSignature"}]};var rsassaPssParameterValidator={name:"rsapss",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"rsapss.hashAlgorithm",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.SEQUENCE,constructed:true,optional:true,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:true,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.SEQUENCE,constructed:true,optional:true,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:2,optional:true,value:[{name:"rsapss.saltLength.saltLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.INTEGER,constructed:false,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:3,optional:true,value:[{name:"rsapss.trailer.trailer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.INTEGER,constructed:false,capture:"trailer"}]}]};var certificationRequestInfoValidator={name:"CertificationRequestInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certificationRequestInfoSubject"},publicKeyValidator,{name:"CertificationRequestInfo.attributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false},{name:"CertificationRequestInfo.attributes.value",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true}]}]}]};var certificationRequestValidator={name:"CertificationRequest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"csr",value:[certificationRequestInfoValidator,{name:"CertificationRequest.signatureAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,optional:true,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"csrSignature"}]};pki.RDNAttributesAsArray=function(rdn,md){var rval=[];var set,attr,obj;for(var si2=0;si2<rdn.value.length;++si2){set=rdn.value[si2];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;if(obj.type in oids){obj.name=oids[obj.type];if(obj.name in _shortNames){obj.shortName=_shortNames[obj.name]}}if(md){md.update(obj.type);md.update(obj.value)}rval.push(obj)}}return rval};pki.CRIAttributesAsArray=function(attributes){var rval=[];for(var si2=0;si2<attributes.length;++si2){var seq=attributes[si2];var type=asn1.derToOid(seq.value[0].value);var values=seq.value[1].value;for(var vi2=0;vi2<values.length;++vi2){var obj={};obj.type=type;obj.value=values[vi2].value;obj.valueTagClass=values[vi2].type;if(obj.type in oids){obj.name=oids[obj.type];if(obj.name in _shortNames){obj.shortName=_shortNames[obj.name]}}if(obj.type===oids.extensionRequest){obj.extensions=[];for(var ei2=0;ei2<obj.value.length;++ei2){obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei2]))}}rval.push(obj)}}return rval};function _getAttribute(obj,options){if(typeof options==="string"){options={shortName:options}}var rval=null;var attr;for(var i=0;rval===null&&i<obj.attributes.length;++i){attr=obj.attributes[i];if(options.type&&options.type===attr.type){rval=attr}else if(options.name&&options.name===attr.name){rval=attr}else if(options.shortName&&options.shortName===attr.shortName){rval=attr}}return rval}var _readSignatureParameters=function(oid,obj,fillDefaults){var params={};if(oid!==oids["RSASSA-PSS"]){return params}if(fillDefaults){params={hash:{algorithmOid:oids["sha1"]},mgf:{algorithmOid:oids["mgf1"],hash:{algorithmOid:oids["sha1"]}},saltLength:20}}var capture2={};var errors=[];if(!asn1.validate(obj,rsassaPssParameterValidator,capture2,errors)){var error=new Error("Cannot read RSASSA-PSS parameter block.");error.errors=errors;throw error}if(capture2.hashOid!==void 0){params.hash=params.hash||{};params.hash.algorithmOid=asn1.derToOid(capture2.hashOid)}if(capture2.maskGenOid!==void 0){params.mgf=params.mgf||{};params.mgf.algorithmOid=asn1.derToOid(capture2.maskGenOid);params.mgf.hash=params.mgf.hash||{};params.mgf.hash.algorithmOid=asn1.derToOid(capture2.maskGenHashOid)}if(capture2.saltLength!==void 0){params.saltLength=capture2.saltLength.charCodeAt(0)}return params};var _createSignatureDigest=function(options){switch(oids[options.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return forge2.md.sha1.create();case"md5WithRSAEncryption":return forge2.md.md5.create();case"sha256WithRSAEncryption":return forge2.md.sha256.create();case"sha384WithRSAEncryption":return forge2.md.sha384.create();case"sha512WithRSAEncryption":return forge2.md.sha512.create();case"RSASSA-PSS":return forge2.md.sha256.create();default:var error=new Error("Could not compute "+options.type+" digest. Unknown signature OID.");error.signatureOid=options.signatureOid;throw error}};var _verifySignature=function(options){var cert=options.certificate;var scheme;switch(cert.signatureOid){case oids.sha1WithRSAEncryption:case oids.sha1WithRSASignature:break;case oids["RSASSA-PSS"]:var hash,mgf;hash=oids[cert.signatureParameters.mgf.hash.algorithmOid];if(hash===void 0||forge2.md[hash]===void 0){var error=new Error("Unsupported MGF hash function.");error.oid=cert.signatureParameters.mgf.hash.algorithmOid;error.name=hash;throw error}mgf=oids[cert.signatureParameters.mgf.algorithmOid];if(mgf===void 0||forge2.mgf[mgf]===void 0){var error=new Error("Unsupported MGF function.");error.oid=cert.signatureParameters.mgf.algorithmOid;error.name=mgf;throw error}mgf=forge2.mgf[mgf].create(forge2.md[hash].create());hash=oids[cert.signatureParameters.hash.algorithmOid];if(hash===void 0||forge2.md[hash]===void 0){var error=new Error("Unsupported RSASSA-PSS hash function.");error.oid=cert.signatureParameters.hash.algorithmOid;error.name=hash;throw error}scheme=forge2.pss.create(forge2.md[hash].create(),mgf,cert.signatureParameters.saltLength);break}return cert.publicKey.verify(options.md.digest().getBytes(),options.signature,scheme)};pki.certificateFromPem=function(pem,computeHash,strict){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="CERTIFICATE"&&msg.type!=="X509 CERTIFICATE"&&msg.type!=="TRUSTED CERTIFICATE"){var error=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(msg,{maxline})};pki.publicKeyFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="PUBLIC KEY"&&msg.type!=="RSA PUBLIC KEY"){var error=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(msg,{maxline})};pki.publicKeyToRSAPublicKeyPem=function(key,maxline){var msg={type:"RSA PUBLIC KEY",body:asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()};return forge2.pem.encode(msg,{maxline})};pki.getPublicKeyFingerprint=function(key,options){options=options||{};var md=options.md||forge2.md.sha1.create();var type=options.type||"RSAPublicKey";var bytes;switch(type){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(options.encoding==="hex"){var hex=digest.toHex();if(options.delimiter){return hex.match(/.{2}/g).join(options.delimiter)}return hex}else if(options.encoding==="binary"){return digest.getBytes()}else if(options.encoding){throw new Error('Unknown encoding "'+options.encoding+'".')}return digest};pki.certificationRequestFromPem=function(pem,computeHash,strict){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="CERTIFICATE REQUEST"){var error=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(msg,{maxline})};pki.createCertificate=function(){var cert={};cert.version=2;cert.serialNumber="00";cert.signatureOid=null;cert.signature=null;cert.siginfo={};cert.siginfo.algorithmOid=null;cert.validity={};cert.validity.notBefore=new Date;cert.validity.notAfter=new Date;cert.issuer={};cert.issuer.getField=function(sn2){return _getAttribute(cert.issuer,sn2)};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(sn2){return _getAttribute(cert.subject,sn2)};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;if(uniqueId){cert.subject.uniqueId=uniqueId}cert.subject.hash=null};cert.setIssuer=function(attrs,uniqueId){_fillMissingFields(attrs);cert.issuer.attributes=attrs;delete cert.issuer.uniqueId;if(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.extensions=exts};cert.getExtension=function(options){if(typeof options==="string"){options={name:options}}var rval=null;var ext;for(var i=0;rval===null&&i<cert.extensions.length;++i){ext=cert.extensions[i];if(options.id&&ext.id===options.id){rval=ext}else if(options.name&&ext.name===options.name){rval=ext}}return rval};cert.sign=function(key,md){cert.md=md||forge2.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.");error.algorithm=cert.md.algorithm;throw 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=false;if(!cert.issued(child)){var issuer=child.issuer;var subject=cert.subject;var 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.");error.expectedIssuer=subject.attributes;error.actualIssuer=issuer.attributes;throw error}var md=child.md;if(md===null){md=_createSignatureDigest({signatureOid:child.signatureOid,type:"certificate"});var tbsCertificate=child.tbsCertificate||pki.getTBSCertificate(child);var bytes=asn1.toDer(tbsCertificate);md.update(bytes.getBytes())}if(md!==null){rval=_verifySignature({certificate:cert,md,signature:child.signature})}return rval};cert.isIssuer=function(parent){var rval=false;var i=cert.issuer;var s3=parent.subject;if(i.hash&&s3.hash){rval=i.hash===s3.hash}else if(i.attributes.length===s3.attributes.length){rval=true;var iattr,sattr;for(var n=0;rval&&n<i.attributes.length;++n){iattr=i.attributes[n];sattr=s3.attributes[n];if(iattr.type!==sattr.type||iattr.value!==sattr.value){rval=false}}}return rval};cert.issued=function(child){return child.isIssuer(cert)};cert.generateSubjectKeyIdentifier=function(){return pki.getPublicKeyFingerprint(cert.publicKey,{type:"RSAPublicKey"})};cert.verifySubjectKeyIdentifier=function(){var oid=oids["subjectKeyIdentifier"];for(var i=0;i<cert.extensions.length;++i){var ext=cert.extensions[i];if(ext.id===oid){var ski=cert.generateSubjectKeyIdentifier().getBytes();return forge2.util.hexToBytes(ext.subjectKeyIdentifier)===ski}}return false};return cert};pki.certificateFromAsn1=function(obj,computeHash){var capture2={};var errors=[];if(!asn1.validate(obj,x509CertificateValidator,capture2,errors)){var error=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.publicKeyOid);if(oid!==pki.oids.rsaEncryption){throw new Error("Cannot read public key. OID is not RSA.")}var cert=pki.createCertificate();cert.version=capture2.certVersion?capture2.certVersion.charCodeAt(0):0;var serial=forge2.util.createBuffer(capture2.certSerialNumber);cert.serialNumber=serial.toHex();cert.signatureOid=forge2.asn1.derToOid(capture2.certSignatureOid);cert.signatureParameters=_readSignatureParameters(cert.signatureOid,capture2.certSignatureParams,true);cert.siginfo.algorithmOid=forge2.asn1.derToOid(capture2.certinfoSignatureOid);cert.siginfo.parameters=_readSignatureParameters(cert.siginfo.algorithmOid,capture2.certinfoSignatureParams,false);cert.signature=capture2.certSignature;var validity=[];if(capture2.certValidity1UTCTime!==void 0){validity.push(asn1.utcTimeToDate(capture2.certValidity1UTCTime))}if(capture2.certValidity2GeneralizedTime!==void 0){validity.push(asn1.generalizedTimeToDate(capture2.certValidity2GeneralizedTime))}if(capture2.certValidity3UTCTime!==void 0){validity.push(asn1.utcTimeToDate(capture2.certValidity3UTCTime))}if(capture2.certValidity4GeneralizedTime!==void 0){validity.push(asn1.generalizedTimeToDate(capture2.certValidity4GeneralizedTime))}if(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.")}cert.validity.notBefore=validity[0];cert.validity.notAfter=validity[1];cert.tbsCertificate=capture2.tbsCertificate;if(computeHash){cert.md=_createSignatureDigest({signatureOid:cert.signatureOid,type:"certificate"});var bytes=asn1.toDer(cert.tbsCertificate);cert.md.update(bytes.getBytes())}var imd=forge2.md.sha1.create();var ibytes=asn1.toDer(capture2.certIssuer);imd.update(ibytes.getBytes());cert.issuer.getField=function(sn2){return _getAttribute(cert.issuer,sn2)};cert.issuer.addField=function(attr){_fillMissingFields([attr]);cert.issuer.attributes.push(attr)};cert.issuer.attributes=pki.RDNAttributesAsArray(capture2.certIssuer);if(capture2.certIssuerUniqueId){cert.issuer.uniqueId=capture2.certIssuerUniqueId}cert.issuer.hash=imd.digest().toHex();var smd=forge2.md.sha1.create();var sbytes=asn1.toDer(capture2.certSubject);smd.update(sbytes.getBytes());cert.subject.getField=function(sn2){return _getAttribute(cert.subject,sn2)};cert.subject.addField=function(attr){_fillMissingFields([attr]);cert.subject.attributes.push(attr)};cert.subject.attributes=pki.RDNAttributesAsArray(capture2.certSubject);if(capture2.certSubjectUniqueId){cert.subject.uniqueId=capture2.certSubjectUniqueId}cert.subject.hash=smd.digest().toHex();if(capture2.certExtensions){cert.extensions=pki.certificateExtensionsFromAsn1(capture2.certExtensions)}else{cert.extensions=[]}cert.publicKey=pki.publicKeyFromAsn1(capture2.subjectPublicKeyInfo);return cert};pki.certificateExtensionsFromAsn1=function(exts){var rval=[];for(var i=0;i<exts.value.length;++i){var extseq=exts.value[i];for(var ei2=0;ei2<extseq.value.length;++ei2){rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei2]))}}return rval};pki.certificateExtensionFromAsn1=function(ext){var e={};e.id=asn1.derToOid(ext.value[0].value);e.critical=false;if(ext.value[1].type===asn1.Type.BOOLEAN){e.critical=ext.value[1].value.charCodeAt(0)!==0;e.value=ext.value[2].value}else{e.value=ext.value[1].value}if(e.id in oids){e.name=oids[e.id];if(e.name==="keyUsage"){var ev=asn1.fromDer(e.value);var b2=0;var b3=0;if(ev.value.length>1){b2=ev.value.charCodeAt(1);b3=ev.value.length>2?ev.value.charCodeAt(2):0}e.digitalSignature=(b2&128)===128;e.nonRepudiation=(b2&64)===64;e.keyEncipherment=(b2&32)===32;e.dataEncipherment=(b2&16)===16;e.keyAgreement=(b2&8)===8;e.keyCertSign=(b2&4)===4;e.cRLSign=(b2&2)===2;e.encipherOnly=(b2&1)===1;e.decipherOnly=(b3&128)===128}else if(e.name==="basicConstraints"){var ev=asn1.fromDer(e.value);if(ev.value.length>0&&ev.value[0].type===asn1.Type.BOOLEAN){e.cA=ev.value[0].value.charCodeAt(0)!==0}else{e.cA=false}var value=null;if(ev.value.length>0&&ev.value[0].type===asn1.Type.INTEGER){value=ev.value[0].value}else if(ev.value.length>1){value=ev.value[1].value}if(value!==null){e.pathLenConstraint=asn1.derToInteger(value)}}else if(e.name==="extKeyUsage"){var ev=asn1.fromDer(e.value);for(var vi2=0;vi2<ev.value.length;++vi2){var oid=asn1.derToOid(ev.value[vi2].value);if(oid in oids){e[oids[oid]]=true}else{e[oid]=true}}}else if(e.name==="nsCertType"){var ev=asn1.fromDer(e.value);var b2=0;if(ev.value.length>1){b2=ev.value.charCodeAt(1)}e.client=(b2&128)===128;e.server=(b2&64)===64;e.email=(b2&32)===32;e.objsign=(b2&16)===16;e.reserved=(b2&8)===8;e.sslCA=(b2&4)===4;e.emailCA=(b2&2)===2;e.objCA=(b2&1)===1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];var gn2;var ev=asn1.fromDer(e.value);for(var n=0;n<ev.value.length;++n){gn2=ev.value[n];var altName={type:gn2.type,value:gn2.value};e.altNames.push(altName);switch(gn2.type){case 1:case 2:case 6:break;case 7:altName.ip=forge2.util.bytesToIP(gn2.value);break;case 8:altName.oid=asn1.derToOid(gn2.value);break;default:}}}else if(e.name==="subjectKeyIdentifier"){var ev=asn1.fromDer(e.value);e.subjectKeyIdentifier=forge2.util.bytesToHex(ev.value)}}return e};pki.certificationRequestFromAsn1=function(obj,computeHash){var capture2={};var errors=[];if(!asn1.validate(obj,certificationRequestValidator,capture2,errors)){var error=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.publicKeyOid);if(oid!==pki.oids.rsaEncryption){throw new Error("Cannot read public key. OID is not RSA.")}var csr=pki.createCertificationRequest();csr.version=capture2.csrVersion?capture2.csrVersion.charCodeAt(0):0;csr.signatureOid=forge2.asn1.derToOid(capture2.csrSignatureOid);csr.signatureParameters=_readSignatureParameters(csr.signatureOid,capture2.csrSignatureParams,true);csr.siginfo.algorithmOid=forge2.asn1.derToOid(capture2.csrSignatureOid);csr.siginfo.parameters=_readSignatureParameters(csr.siginfo.algorithmOid,capture2.csrSignatureParams,false);csr.signature=capture2.csrSignature;csr.certificationRequestInfo=capture2.certificationRequestInfo;if(computeHash){csr.md=_createSignatureDigest({signatureOid:csr.signatureOid,type:"certification request"});var bytes=asn1.toDer(csr.certificationRequestInfo);csr.md.update(bytes.getBytes())}var smd=forge2.md.sha1.create();csr.subject.getField=function(sn2){return _getAttribute(csr.subject,sn2)};csr.subject.addField=function(attr){_fillMissingFields([attr]);csr.subject.attributes.push(attr)};csr.subject.attributes=pki.RDNAttributesAsArray(capture2.certificationRequestInfoSubject,smd);csr.subject.hash=smd.digest().toHex();csr.publicKey=pki.publicKeyFromAsn1(capture2.subjectPublicKeyInfo);csr.getAttribute=function(sn2){return _getAttribute(csr,sn2)};csr.addAttribute=function(attr){_fillMissingFields([attr]);csr.attributes.push(attr)};csr.attributes=pki.CRIAttributesAsArray(capture2.certificationRequestInfoAttributes||[]);return csr};pki.createCertificationRequest=function(){var csr={};csr.version=0;csr.signatureOid=null;csr.signature=null;csr.siginfo={};csr.siginfo.algorithmOid=null;csr.subject={};csr.subject.getField=function(sn2){return _getAttribute(csr.subject,sn2)};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(sn2){return _getAttribute(csr,sn2)};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||forge2.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.");error.algorithm=csr.md.algorithm;throw 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=false;var md=csr.md;if(md===null){md=_createSignatureDigest({signatureOid:csr.signatureOid,type:"certification request"});var cri=csr.certificationRequestInfo||pki.getCertificationRequestInfo(csr);var bytes=asn1.toDer(cri);md.update(bytes.getBytes())}if(md!==null){rval=_verifySignature({certificate:csr,md,signature:csr.signature})}return rval};return csr};function _dnToAsn1(obj){var rval=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var attr,set;var attrs=obj.attributes;for(var i=0;i<attrs.length;++i){attr=attrs[i];var value=attr.value;var valueTagClass=asn1.Type.PRINTABLESTRING;if("valueTagClass"in attr){valueTagClass=attr.valueTagClass;if(valueTagClass===asn1.Type.UTF8){value=forge2.util.encodeUtf8(value)}}set=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,valueTagClass,false,value)])]);rval.value.push(set)}return rval}function _fillMissingFields(attrs){var attr;for(var i=0;i<attrs.length;++i){attr=attrs[i];if(typeof attr.name==="undefined"){if(attr.type&&attr.type in pki.oids){attr.name=pki.oids[attr.type]}else if(attr.shortName&&attr.shortName in _shortNames){attr.name=pki.oids[_shortNames[attr.shortName]]}}if(typeof attr.type==="undefined"){if(attr.name&&attr.name in pki.oids){attr.type=pki.oids[attr.name]}else{var error=new Error("Attribute type not specified.");error.attribute=attr;throw error}}if(typeof attr.shortName==="undefined"){if(attr.name&&attr.name in _shortNames){attr.shortName=_shortNames[attr.name]}}if(attr.type===oids.extensionRequest){attr.valueConstructed=true;attr.valueTagClass=asn1.Type.SEQUENCE;if(!attr.value&&attr.extensions){attr.value=[];for(var ei2=0;ei2<attr.extensions.length;++ei2){attr.value.push(pki.certificateExtensionToAsn1(_fillMissingExtensionFields(attr.extensions[ei2])))}}}if(typeof attr.value==="undefined"){var error=new Error("Attribute value not specified.");error.attribute=attr;throw error}}}function _fillMissingExtensionFields(e,options){options=options||{};if(typeof e.name==="undefined"){if(e.id&&e.id in pki.oids){e.name=pki.oids[e.id]}}if(typeof e.id==="undefined"){if(e.name&&e.name in pki.oids){e.id=pki.oids[e.name]}else{var error=new Error("Extension ID not specified.");error.extension=e;throw error}}if(typeof e.value!=="undefined"){return e}if(e.name==="keyUsage"){var unused=0;var b2=0;var b3=0;if(e.digitalSignature){b2|=128;unused=7}if(e.nonRepudiation){b2|=64;unused=6}if(e.keyEncipherment){b2|=32;unused=5}if(e.dataEncipherment){b2|=16;unused=4}if(e.keyAgreement){b2|=8;unused=3}if(e.keyCertSign){b2|=4;unused=2}if(e.cRLSign){b2|=2;unused=1}if(e.encipherOnly){b2|=1;unused=0}if(e.decipherOnly){b3|=128;unused=7}var value=String.fromCharCode(unused);if(b3!==0){value+=String.fromCharCode(b2)+String.fromCharCode(b3)}else if(b2!==0){value+=String.fromCharCode(b2)}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,value)}else if(e.name==="basicConstraints"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);if(e.cA){e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BOOLEAN,false,String.fromCharCode(255)))}if("pathLenConstraint"in e){e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(e.pathLenConstraint).getBytes()))}}else if(e.name==="extKeyUsage"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;for(var key in e){if(e[key]!==true){continue}if(key in oids){seq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids[key]).getBytes()))}else if(key.indexOf(".")!==-1){seq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(key).getBytes()))}}}else if(e.name==="nsCertType"){var unused=0;var b2=0;if(e.client){b2|=128;unused=7}if(e.server){b2|=64;unused=6}if(e.email){b2|=32;unused=5}if(e.objsign){b2|=16;unused=4}if(e.reserved){b2|=8;unused=3}if(e.sslCA){b2|=4;unused=2}if(e.emailCA){b2|=2;unused=1}if(e.objCA){b2|=1;unused=0}var value=String.fromCharCode(unused);if(b2!==0){value+=String.fromCharCode(b2)}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,value)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var altName;for(var n=0;n<e.altNames.length;++n){altName=e.altNames[n];var value=altName.value;if(altName.type===7&&altName.ip){value=forge2.util.bytesFromIP(altName.ip);if(value===null){var error=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');error.extension=e;throw error}}else if(altName.type===8){if(altName.oid){value=asn1.oidToDer(asn1.oidToDer(altName.oid))}else{value=asn1.oidToDer(value)}}e.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,false,value))}}else if(e.name==="nsComment"&&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,false,e.comment)}else if(e.name==="subjectKeyIdentifier"&&options.cert){var ski=options.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=ski.toHex();e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ski.getBytes())}else if(e.name==="authorityKeyIdentifier"&&options.cert){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;if(e.keyIdentifier){var keyIdentifier=e.keyIdentifier===true?options.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,false,keyIdentifier))}if(e.authorityCertIssuer){var authorityCertIssuer=[asn1.create(asn1.Class.CONTEXT_SPECIFIC,4,true,[_dnToAsn1(e.authorityCertIssuer===true?options.cert.issuer:e.authorityCertIssuer)])];seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,authorityCertIssuer))}if(e.serialNumber){var serialNumber=forge2.util.hexToBytes(e.serialNumber===true?options.cert.serialNumber:e.serialNumber);seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,false,serialNumber))}}else if(e.name==="cRLDistributionPoints"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;var subSeq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var fullNameGeneralNames=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[]);var altName;for(var n=0;n<e.altNames.length;++n){altName=e.altNames[n];var value=altName.value;if(altName.type===7&&altName.ip){value=forge2.util.bytesFromIP(altName.ip);if(value===null){var error=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');error.extension=e;throw error}}else if(altName.type===8){if(altName.oid){value=asn1.oidToDer(asn1.oidToDer(altName.oid))}else{value=asn1.oidToDer(value)}}fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,false,value))}subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[fullNameGeneralNames]));seq.push(subSeq)}if(typeof e.value==="undefined"){var error=new Error("Extension value not specified.");error.extension=e;throw error}return e}function _signatureParametersToAsn1(oid,params){switch(oid){case oids["RSASSA-PSS"]:var parts=[];if(params.hash.algorithmOid!==void 0){parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(params.hash.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")])]))}if(params.mgf.algorithmOid!==void 0){parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(params.mgf.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")])])]))}if(params.saltLength!==void 0){parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(params.saltLength).getBytes())]))}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,parts);default:return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")}}function _CRIAttributesToAsn1(csr){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[]);if(csr.attributes.length===0){return rval}var attrs=csr.attributes;for(var i=0;i<attrs.length;++i){var attr=attrs[i];var value=attr.value;var valueTagClass=asn1.Type.UTF8;if("valueTagClass"in attr){valueTagClass=attr.valueTagClass}if(valueTagClass===asn1.Type.UTF8){value=forge2.util.encodeUtf8(value)}var valueConstructed=false;if("valueConstructed"in attr){valueConstructed=attr.valueConstructed}var seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,valueTagClass,valueConstructed,value)])]);rval.value.push(seq)}return rval}var jan_1_1950=new Date("1950-01-01T00:00:00Z");var jan_1_2050=new Date("2050-01-01T00:00:00Z");function _dateToAsn1(date){if(date>=jan_1_1950&&date<jan_1_2050){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.UTCTIME,false,asn1.dateToUtcTime(date))}else{return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.GENERALIZEDTIME,false,asn1.dateToGeneralizedTime(date))}}pki.getTBSCertificate=function(cert){var notBefore=_dateToAsn1(cert.validity.notBefore);var notAfter=_dateToAsn1(cert.validity.notAfter);var tbs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(cert.version).getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(cert.serialNumber)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),_signatureParametersToAsn1(cert.siginfo.algorithmOid,cert.siginfo.parameters)]),_dnToAsn1(cert.issuer),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[notBefore,notAfter]),_dnToAsn1(cert.subject),pki.publicKeyToAsn1(cert.publicKey)]);if(cert.issuer.uniqueId){tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.issuer.uniqueId)]))}if(cert.subject.uniqueId){tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.subject.uniqueId)]))}if(cert.extensions.length>0){tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions))}return tbs};pki.getCertificationRequestInfo=function(csr){var cri=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(csr.version).getBytes()),_dnToAsn1(csr.subject),pki.publicKeyToAsn1(csr.publicKey),_CRIAttributesToAsn1(csr)]);return cri};pki.distinguishedNameToAsn1=function(dn2){return _dnToAsn1(dn2)};pki.certificateToAsn1=function(cert){var tbsCertificate=cert.tbsCertificate||pki.getTBSCertificate(cert);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[tbsCertificate,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(cert.signatureOid).getBytes()),_signatureParametersToAsn1(cert.signatureOid,cert.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.signature)])};pki.certificateExtensionsToAsn1=function(exts){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,3,true,[]);var seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);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,true,[]);extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(ext.id).getBytes()));if(ext.critical){extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BOOLEAN,false,String.fromCharCode(255)))}var value=ext.value;if(typeof ext.value!=="string"){value=asn1.toDer(value).getBytes()}extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,value));return extseq};pki.certificationRequestToAsn1=function(csr){var cri=csr.certificationRequestInfo||pki.getCertificationRequestInfo(csr);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[cri,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(csr.signatureOid).getBytes()),_signatureParametersToAsn1(csr.signatureOid,csr.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+csr.signature)])};pki.createCaStore=function(certs){var caStore={certs:{}};caStore.getIssuer=function(cert2){var rval=getBySubject(cert2.issuer);return rval};caStore.addCertificate=function(cert2){if(typeof cert2==="string"){cert2=forge2.pki.certificateFromPem(cert2)}ensureSubjectHasHash(cert2.subject);if(!caStore.hasCertificate(cert2)){if(cert2.subject.hash in caStore.certs){var tmp=caStore.certs[cert2.subject.hash];if(!forge2.util.isArray(tmp)){tmp=[tmp]}tmp.push(cert2);caStore.certs[cert2.subject.hash]=tmp}else{caStore.certs[cert2.subject.hash]=cert2}}};caStore.hasCertificate=function(cert2){if(typeof cert2==="string"){cert2=forge2.pki.certificateFromPem(cert2)}var match=getBySubject(cert2.subject);if(!match){return false}if(!forge2.util.isArray(match)){match=[match]}var der1=asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();for(var i2=0;i2<match.length;++i2){var der2=asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes();if(der1===der2){return true}}return false};caStore.listAllCertificates=function(){var certList=[];for(var hash in caStore.certs){if(caStore.certs.hasOwnProperty(hash)){var value=caStore.certs[hash];if(!forge2.util.isArray(value)){certList.push(value)}else{for(var i2=0;i2<value.length;++i2){certList.push(value[i2])}}}}return certList};caStore.removeCertificate=function(cert2){var result;if(typeof cert2==="string"){cert2=forge2.pki.certificateFromPem(cert2)}ensureSubjectHasHash(cert2.subject);if(!caStore.hasCertificate(cert2)){return null}var match=getBySubject(cert2.subject);if(!forge2.util.isArray(match)){result=caStore.certs[cert2.subject.hash];delete caStore.certs[cert2.subject.hash];return result}var der1=asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();for(var i2=0;i2<match.length;++i2){var der2=asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes();if(der1===der2){result=match[i2];match.splice(i2,1)}}if(match.length===0){delete caStore.certs[cert2.subject.hash]}return result};function getBySubject(subject){ensureSubjectHasHash(subject);return caStore.certs[subject.hash]||null}function ensureSubjectHasHash(subject){if(!subject.hash){var md=forge2.md.sha1.create();subject.attributes=pki.RDNAttributesAsArray(_dnToAsn1(subject),md);subject.hash=md.digest().toHex()}}if(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){if(typeof options==="function"){options={verify:options}}options=options||{};chain=chain.slice(0);var certs=chain.slice(0);var validityCheckDate=options.validityCheckDate;if(typeof validityCheckDate==="undefined"){validityCheckDate=new Date}var first=true;var error=null;var depth=0;do{var cert=chain.shift();var parent=null;var selfSigned=false;if(validityCheckDate){if(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}}}if(error===null){parent=chain[0]||caStore.getIssuer(cert);if(parent===null){if(cert.isIssuer(cert)){selfSigned=true;parent=cert}}if(parent){var parents=parent;if(!forge2.util.isArray(parents)){parents=[parents]}var verified=false;while(!verified&&parents.length>0){parent=parents.shift();try{verified=parent.verify(cert)}catch(ex){}}if(!verified){error={message:"Certificate signature is invalid.",error:pki.certificateError.bad_certificate}}}if(error===null&&(!parent||selfSigned)&&!caStore.hasCertificate(cert)){error={message:"Certificate is not trusted.",error:pki.certificateError.unknown_ca}}}if(error===null&&parent&&!cert.isIssuer(parent)){error={message:"Certificate issuer is invalid.",error:pki.certificateError.bad_certificate}}if(error===null){var se2={keyUsage:true,basicConstraints:true};for(var i=0;error===null&&i<cert.extensions.length;++i){var ext=cert.extensions[i];if(ext.critical&&!(ext.name in se2)){error={message:"Certificate has an unsupported critical extension.",error:pki.certificateError.unsupported_certificate}}}}if(error===null&&(!first||chain.length===0&&(!parent||selfSigned))){var bcExt=cert.getExtension("basicConstraints");var keyUsageExt=cert.getExtension("keyUsage");if(keyUsageExt!==null){if(!keyUsageExt.keyCertSign||bcExt===null){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}}}if(error===null&&bcExt===null){error={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:pki.certificateError.bad_certificate}}if(error===null&&bcExt!==null&&!bcExt.cA){error={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:pki.certificateError.bad_certificate}}if(error===null&&keyUsageExt!==null&&"pathLenConstraint"in bcExt){var pathLen=depth-1;if(pathLen>bcExt.pathLenConstraint){error={message:"Certificate basicConstraints pathLenConstraint violated.",error:pki.certificateError.bad_certificate}}}}var vfd=error===null?true:error.error;var ret=options.verify?options.verify(vfd,depth,certs):vfd;if(ret===true){error=null}else{if(vfd===true){error={message:"The application rejected the certificate.",error:pki.certificateError.bad_certificate}}if(ret||ret===0){if(typeof ret==="object"&&!forge2.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.error){error.error=ret.error}}else if(typeof ret==="string"){error.error=ret}}throw error}first=false;++depth}while(chain.length>0);return true}}});var require_pkcs12=__commonJS({"node_modules/node-forge/lib/pkcs12.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_hmac();require_oids();require_pkcs7asn1();require_pbe();require_random();require_rsa();require_sha1();require_util7();require_x509();var asn1=forge2.asn1;var pki=forge2.pki;var p12=module.exports=forge2.pkcs12=forge2.pkcs12||{};var contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"ContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"content"}]};var pfxValidator={name:"PFX",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},contentInfoValidator,{name:"PFX.macData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:true,tagClass:asn1.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,optional:true,capture:"macIterations"}]}]};var safeBagValidator={name:"SafeBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SafeBag.bagId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,optional:true,capture:"bagAttributes"}]};var attributeValidator={name:"Attribute",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Attribute.attrId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"oid"},{name:"Attribute.attrValues",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,capture:"values"}]};var certBagValidator={name:"CertBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertBag.certId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certId"},{name:"CertBag.certValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,value:[{name:"CertBag.certValue[0]",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.OCTETSTRING,constructed:false,capture:"cert"}]}]};function _getBagsByAttribute(safeContents,attrName,attrValue,bagType){var result=[];for(var i=0;i<safeContents.length;i++){for(var j2=0;j2<safeContents[i].safeBags.length;j2++){var bag=safeContents[i].safeBags[j2];if(bagType!==void 0&&bag.type!==bagType){continue}if(attrName===null){result.push(bag);continue}if(bag.attributes[attrName]!==void 0&&bag.attributes[attrName].indexOf(attrValue)>=0){result.push(bag)}}}return result}p12.pkcs12FromAsn1=function(obj,strict,password){if(typeof strict==="string"){password=strict;strict=true}else if(strict===void 0){strict=true}var capture2={};var errors=[];if(!asn1.validate(obj,pfxValidator,capture2,errors)){var error=new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");error.errors=error;throw error}var pfx={version:capture2.version.charCodeAt(0),safeContents:[],getBags:function(filter){var rval={};var localKeyId;if("localKeyId"in filter){localKeyId=filter.localKeyId}else if("localKeyIdHex"in filter){localKeyId=forge2.util.hexToBytes(filter.localKeyIdHex)}if(localKeyId===void 0&&!("friendlyName"in filter)&&"bagType"in filter){rval[filter.bagType]=_getBagsByAttribute(pfx.safeContents,null,null,filter.bagType)}if(localKeyId!==void 0){rval.localKeyId=_getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,filter.bagType)}if("friendlyName"in filter){rval.friendlyName=_getBagsByAttribute(pfx.safeContents,"friendlyName",filter.friendlyName,filter.bagType)}return rval},getBagsByFriendlyName:function(friendlyName,bagType){return _getBagsByAttribute(pfx.safeContents,"friendlyName",friendlyName,bagType)},getBagsByLocalKeyId:function(localKeyId,bagType){return _getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,bagType)}};if(capture2.version.charCodeAt(0)!==3){var error=new Error("PKCS#12 PFX of version other than 3 not supported.");error.version=capture2.version.charCodeAt(0);throw error}if(asn1.derToOid(capture2.contentType)!==pki.oids.data){var error=new Error("Only PKCS#12 PFX in password integrity mode supported.");error.oid=asn1.derToOid(capture2.contentType);throw error}var data=capture2.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.")}data=_decodePkcs7Data(data);if(capture2.mac){var md=null;var macKeyBytes=0;var macAlgorithm=asn1.derToOid(capture2.macAlgorithm);switch(macAlgorithm){case pki.oids.sha1:md=forge2.md.sha1.create();macKeyBytes=20;break;case pki.oids.sha256:md=forge2.md.sha256.create();macKeyBytes=32;break;case pki.oids.sha384:md=forge2.md.sha384.create();macKeyBytes=48;break;case pki.oids.sha512:md=forge2.md.sha512.create();macKeyBytes=64;break;case pki.oids.md5:md=forge2.md.md5.create();macKeyBytes=16;break}if(md===null){throw new Error("PKCS#12 uses unsupported MAC algorithm: "+macAlgorithm)}var macSalt=new forge2.util.ByteBuffer(capture2.macSalt);var macIterations="macIterations"in capture2?parseInt(forge2.util.bytesToHex(capture2.macIterations),16):1;var macKey=p12.generateKey(password,macSalt,3,macIterations,macKeyBytes,md);var mac=forge2.hmac.create();mac.start(md,macKey);mac.update(data.value);var macValue=mac.getMac();if(macValue.getBytes()!==capture2.macDigest){throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}}else if(Array.isArray(obj.value)&&obj.value.length>2){throw new Error("Invalid PKCS#12. macData field present but MAC was not validated.")}_decodeAuthenticatedSafe(pfx,data.value,strict,password);return pfx};function _decodePkcs7Data(data){if(data.composed||data.constructed){var value=forge2.util.createBuffer();for(var i=0;i<data.value.length;++i){value.putBytes(data.value[i].value)}data.composed=data.constructed=false;data.value=value.getBytes()}return data}function _decodeAuthenticatedSafe(pfx,authSafe,strict,password){authSafe=asn1.fromDer(authSafe,strict);if(authSafe.tagClass!==asn1.Class.UNIVERSAL||authSafe.type!==asn1.Type.SEQUENCE||authSafe.constructed!==true){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];var capture2={};var errors=[];if(!asn1.validate(contentInfo,contentInfoValidator,capture2,errors)){var error=new Error("Cannot read ContentInfo.");error.errors=errors;throw error}var obj={encrypted:false};var safeContents=null;var data=capture2.content.value[0];switch(asn1.derToOid(capture2.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=true;break;default:var error=new Error("Unsupported PKCS#12 contentType.");error.contentType=asn1.derToOid(capture2.contentType);throw error}obj.safeBags=_decodeSafeContents(safeContents,strict,password);pfx.safeContents.push(obj)}}function _decryptSafeContents(data,password){var capture2={};var errors=[];if(!asn1.validate(data,forge2.pkcs7.asn1.encryptedDataValidator,capture2,errors)){var error=new Error("Cannot read EncryptedContentInfo.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.contentType);if(oid!==pki.oids.data){var error=new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");error.oid=oid;throw error}oid=asn1.derToOid(capture2.encAlgorithm);var cipher=pki.pbe.getCipher(oid,capture2.encParameter,password);var encryptedContentAsn1=_decodePkcs7Data(capture2.encryptedContentAsn1);var encrypted=forge2.util.createBuffer(encryptedContentAsn1.value);cipher.update(encrypted);if(!cipher.finish()){throw new Error("Failed to decrypt PKCS#12 SafeContents.")}return cipher.output.getBytes()}function _decodeSafeContents(safeContents,strict,password){if(!strict&&safeContents.length===0){return[]}safeContents=asn1.fromDer(safeContents,strict);if(safeContents.tagClass!==asn1.Class.UNIVERSAL||safeContents.type!==asn1.Type.SEQUENCE||safeContents.constructed!==true){throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.")}var res=[];for(var i=0;i<safeContents.value.length;i++){var safeBag=safeContents.value[i];var capture2={};var errors=[];if(!asn1.validate(safeBag,safeBagValidator,capture2,errors)){var error=new Error("Cannot read SafeBag.");error.errors=errors;throw error}var bag={type:asn1.derToOid(capture2.bagId),attributes:_decodeBagAttributes(capture2.bagAttributes)};res.push(bag);var validator,decoder;var bagAsn1=capture2.bagValue.value[0];switch(bag.type){case pki.oids.pkcs8ShroudedKeyBag:bagAsn1=pki.decryptPrivateKeyInfo(bagAsn1,password);if(bagAsn1===null){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(capture2.certId)!==pki.oids.x509Certificate){var error2=new Error("Unsupported certificate type, only X.509 supported.");error2.oid=asn1.derToOid(capture2.certId);throw error2}var certAsn1=asn1.fromDer(capture2.cert,strict);try{bag.cert=pki.certificateFromAsn1(certAsn1,true)}catch(e){bag.cert=null;bag.asn1=certAsn1}};break;default:var error=new Error("Unsupported PKCS#12 SafeBag type.");error.oid=bag.type;throw error}if(validator!==void 0&&!asn1.validate(bagAsn1,validator,capture2,errors)){var error=new Error("Cannot read PKCS#12 "+validator.name);error.errors=errors;throw error}decoder()}return res}function _decodeBagAttributes(attributes){var decodedAttrs={};if(attributes!==void 0){for(var i=0;i<attributes.length;++i){var capture2={};var errors=[];if(!asn1.validate(attributes[i],attributeValidator,capture2,errors)){var error=new Error("Cannot read PKCS#12 BagAttribute.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.oid);if(pki.oids[oid]===void 0){continue}decodedAttrs[pki.oids[oid]]=[];for(var j2=0;j2<capture2.values.length;++j2){decodedAttrs[pki.oids[oid]].push(capture2.values[j2].value)}}}return decodedAttrs}p12.toPkcs12Asn1=function(key,cert,password,options){options=options||{};options.saltSize=options.saltSize||8;options.count=options.count||2048;options.algorithm=options.algorithm||options.encAlgorithm||"aes128";if(!("useMac"in options)){options.useMac=true}if(!("localKeyId"in options)){options.localKeyId=null}if(!("generateLocalKeyId"in options)){options.generateLocalKeyId=true}var localKeyId=options.localKeyId;var bagAttrs;if(localKeyId!==null){localKeyId=forge2.util.hexToBytes(localKeyId)}else if(options.generateLocalKeyId){if(cert){var pairedCert=forge2.util.isArray(cert)?cert[0]:cert;if(typeof pairedCert==="string"){pairedCert=pki.certificateFromPem(pairedCert)}var sha1=forge2.md.sha1.create();sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());localKeyId=sha1.digest().getBytes()}else{localKeyId=forge2.random.getBytes(20)}}var attrs=[];if(localKeyId!==null){attrs.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.localKeyId).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,localKeyId)])]))}if("friendlyName"in options){attrs.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.friendlyName).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BMPSTRING,false,options.friendlyName)])]))}if(attrs.length>0){bagAttrs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,attrs)}var contents=[];var chain=[];if(cert!==null){if(forge2.util.isArray(cert)){chain=cert}else{chain=[cert]}}var certSafeBags=[];for(var i=0;i<chain.length;++i){cert=chain[i];if(typeof cert==="string"){cert=pki.certificateFromPem(cert)}var certBagAttrs=i===0?bagAttrs:void 0;var certAsn1=pki.certificateToAsn1(cert);var certSafeBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.certBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.x509Certificate).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(certAsn1).getBytes())])])]),certBagAttrs]);certSafeBags.push(certSafeBag)}if(certSafeBags.length>0){var certSafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,certSafeBags);var certCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(certSafeContents).getBytes())])]);contents.push(certCI)}var keyBag=null;if(key!==null){var pkAsn1=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));if(password===null){keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.keyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pkAsn1]),bagAttrs])}else{keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pki.encryptPrivateKeyInfo(pkAsn1,password,options)]),bagAttrs])}var keySafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[keyBag]);var keyCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(keySafeContents).getBytes())])]);contents.push(keyCI)}var safe=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,contents);var macData;if(options.useMac){var sha1=forge2.md.sha1.create();var macSalt=new forge2.util.ByteBuffer(forge2.random.getBytes(options.saltSize));var count=options.count;var key=p12.generateKey(password,macSalt,3,count,20);var mac=forge2.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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.sha1).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macValue.getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macSalt.getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(count).getBytes())])}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(3).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(safe).getBytes())])]),macData])};p12.generateKey=forge2.pbe.generatePkcs12Key}});var require_pki=__commonJS({"node_modules/node-forge/lib/pki.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_oids();require_pbe();require_pem();require_pbkdf2();require_pkcs12();require_pss();require_rsa();require_util7();require_x509();var asn1=forge2.asn1;var pki=module.exports=forge2.pki=forge2.pki||{};pki.pemToDer=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert PEM to DER; PEM is encrypted.")}return forge2.util.createBuffer(msg.body)};pki.privateKeyFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="PRIVATE KEY"&&msg.type!=="RSA PRIVATE KEY"){var error=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert private key from PEM; PEM is encrypted.")}var obj=asn1.fromDer(msg.body);return pki.privateKeyFromAsn1(obj)};pki.privateKeyToPem=function(key,maxline){var msg={type:"RSA PRIVATE KEY",body:asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()};return forge2.pem.encode(msg,{maxline})};pki.privateKeyInfoToPem=function(pki2,maxline){var msg={type:"PRIVATE KEY",body:asn1.toDer(pki2).getBytes()};return forge2.pem.encode(msg,{maxline})}}});var require_tls=__commonJS({"node_modules/node-forge/lib/tls.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_hmac();require_md5();require_pem();require_pki();require_random();require_sha1();require_util7();var prf_TLS1=function(secret,label,seed,length){var rval=forge2.util.createBuffer();var idx=secret.length>>1;var slen=idx+(secret.length&1);var s1=secret.substr(0,slen);var s22=secret.substr(idx,slen);var ai2=forge2.util.createBuffer();var hmac=forge2.hmac.create();seed=label+seed;var md5itr=Math.ceil(length/16);var sha1itr=Math.ceil(length/20);hmac.start("MD5",s1);var md5bytes=forge2.util.createBuffer();ai2.putBytes(seed);for(var i=0;i<md5itr;++i){hmac.start(null,null);hmac.update(ai2.getBytes());ai2.putBuffer(hmac.digest());hmac.start(null,null);hmac.update(ai2.bytes()+seed);md5bytes.putBuffer(hmac.digest())}hmac.start("SHA1",s22);var sha1bytes=forge2.util.createBuffer();ai2.clear();ai2.putBytes(seed);for(var i=0;i<sha1itr;++i){hmac.start(null,null);hmac.update(ai2.getBytes());ai2.putBuffer(hmac.digest());hmac.start(null,null);hmac.update(ai2.bytes()+seed);sha1bytes.putBuffer(hmac.digest())}rval.putBytes(forge2.util.xorBytes(md5bytes.getBytes(),sha1bytes.getBytes(),length));return rval};var hmac_sha1=function(key2,seqNum,record){var hmac=forge2.hmac.create();hmac.start("SHA1",key2);var b2=forge2.util.createBuffer();b2.putInt32(seqNum[0]);b2.putInt32(seqNum[1]);b2.putByte(record.type);b2.putByte(record.version.major);b2.putByte(record.version.minor);b2.putInt16(record.length);b2.putBytes(record.fragment.bytes());hmac.update(b2.getBytes());return hmac.digest().getBytes()};var deflate=function(c,record,s3){var rval=false;try{var bytes=c.deflate(record.fragment.getBytes());record.fragment=forge2.util.createBuffer(bytes);record.length=bytes.length;rval=true}catch(ex){}return rval};var inflate=function(c,record,s3){var rval=false;try{var bytes=c.inflate(record.fragment.getBytes());record.fragment=forge2.util.createBuffer(bytes);record.length=bytes.length;rval=true}catch(ex){}return rval};var readVector=function(b2,lenBytes){var len=0;switch(lenBytes){case 1:len=b2.getByte();break;case 2:len=b2.getInt16();break;case 3:len=b2.getInt24();break;case 4:len=b2.getInt32();break}return forge2.util.createBuffer(b2.getBytes(len))};var writeVector=function(b2,lenBytes,v2){b2.putInt(v2.length(),lenBytes<<3);b2.putBuffer(v2)};var tls5={};tls5.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};tls5.SupportedVersions=[tls5.Versions.TLS_1_1,tls5.Versions.TLS_1_0];tls5.Version=tls5.SupportedVersions[0];tls5.MaxFragment=16384-1024;tls5.ConnectionEnd={server:0,client:1};tls5.PRFAlgorithm={tls_prf_sha256:0};tls5.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};tls5.CipherType={stream:0,block:1,aead:2};tls5.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};tls5.CompressionMethod={none:0,deflate:1};tls5.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};tls5.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};tls5.Alert={};tls5.Alert.Level={warning:1,fatal:2};tls5.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};tls5.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};tls5.CipherSuites={};tls5.getCipherSuite=function(twoBytes){var rval=null;for(var key2 in tls5.CipherSuites){var cs2=tls5.CipherSuites[key2];if(cs2.id[0]===twoBytes.charCodeAt(0)&&cs2.id[1]===twoBytes.charCodeAt(1)){rval=cs2;break}}return rval};tls5.handleUnexpected=function(c,record){var ignore=!c.open&&c.entity===tls5.ConnectionEnd.client;if(!ignore){c.error(c,{message:"Unexpected message. Received TLS record out of order.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unexpected_message}})}};tls5.handleHelloRequest=function(c,record,length){if(!c.handshaking&&c.handshakes>0){tls5.queue(c,tls5.createAlert(c,{level:tls5.Alert.Level.warning,description:tls5.Alert.Description.no_renegotiation}));tls5.flush(c)}c.process()};tls5.parseHelloMessage=function(c,record,length){var msg=null;var client=c.entity===tls5.ConnectionEnd.client;if(length<38){c.error(c,{message:client?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}else{var b2=record.fragment;var remaining=b2.length();msg={version:{major:b2.getByte(),minor:b2.getByte()},random:forge2.util.createBuffer(b2.getBytes(32)),session_id:readVector(b2,1),extensions:[]};if(client){msg.cipher_suite=b2.getBytes(2);msg.compression_method=b2.getByte()}else{msg.cipher_suites=readVector(b2,2);msg.compression_methods=readVector(b2,1)}remaining=length-(remaining-b2.length());if(remaining>0){var exts=readVector(b2,2);while(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(ext.type[0]===0&&ext.type[1]===0){var snl=readVector(ext.data,2);while(snl.length()>0){var snType=snl.getByte();if(snType!==0){break}c.session.extensions.server_name.serverNameList.push(readVector(snl,2).getBytes())}}}}}if(c.session.version){if(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:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.protocol_version}})}}if(client){c.session.cipherSuite=tls5.getCipherSuite(msg.cipher_suite)}else{var tmp=forge2.util.createBuffer(msg.cipher_suites.bytes());while(tmp.length()>0){c.session.cipherSuite=tls5.getCipherSuite(tmp.getBytes(2));if(c.session.cipherSuite!==null){break}}}if(c.session.cipherSuite===null){return c.error(c,{message:"No cipher suites in common.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.handshake_failure},cipherSuite:forge2.util.bytesToHex(msg.cipher_suite)})}if(client){c.session.compressionMethod=msg.compression_method}else{c.session.compressionMethod=tls5.CompressionMethod.none}}return msg};tls5.createSecurityParameters=function(c,msg){var client=c.entity===tls5.ConnectionEnd.client;var msgRandom=msg.random.bytes();var cRandom=client?c.session.sp.client_random:msgRandom;var sRandom=client?msgRandom:tls5.createRandom().getBytes();c.session.sp={entity:c.entity,prf_algorithm:tls5.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}};tls5.handleServerHello=function(c,record,length){var msg=tls5.parseHelloMessage(c,record,length);if(c.fail){return}if(msg.version.minor<=c.version.minor){c.version.minor=msg.version.minor}else{return c.error(c,{message:"Incompatible TLS version.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.protocol_version}})}c.session.version=c.version;var sessionId=msg.session_id.bytes();if(sessionId.length>0&&sessionId===c.session.id){c.expect=SCC;c.session.resuming=true;c.session.sp.server_random=msg.random.bytes()}else{c.expect=SCE;c.session.resuming=false;tls5.createSecurityParameters(c,msg)}c.session.id=sessionId;c.process()};tls5.handleClientHello=function(c,record,length){var msg=tls5.parseHelloMessage(c,record,length);if(c.fail){return}var sessionId=msg.session_id.bytes();var session=null;if(c.sessionCache){session=c.sessionCache.getSession(sessionId);if(session===null){sessionId=""}else if(session.version.major!==msg.version.major||session.version.minor>msg.version.minor){session=null;sessionId=""}}if(sessionId.length===0){sessionId=forge2.random.getBytes(32)}c.session.id=sessionId;c.session.clientHelloVersion=msg.version;c.session.sp={};if(session){c.version=c.session.version=session.version;c.session.sp=session.sp}else{var version;for(var i=1;i<tls5.SupportedVersions.length;++i){version=tls5.SupportedVersions[i];if(version.minor<=msg.version.minor){break}}c.version={major:version.major,minor:version.minor};c.session.version=c.version}if(session!==null){c.expect=CCC;c.session.resuming=true;c.session.sp.client_random=msg.random.bytes()}else{c.expect=c.verifyClient!==false?CCE:CKE;c.session.resuming=false;tls5.createSecurityParameters(c,msg)}c.open=true;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createServerHello(c)}));if(c.session.resuming){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.change_cipher_spec,data:tls5.createChangeCipherSpec()}));c.state.pending=tls5.createConnectionState(c);c.state.current.write=c.state.pending.write;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createFinished(c)}))}else{tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createCertificate(c)}));if(!c.fail){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createServerKeyExchange(c)}));if(c.verifyClient!==false){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createCertificateRequest(c)}))}tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createServerHelloDone(c)}))}}tls5.flush(c);c.process()};tls5.handleCertificate=function(c,record,length){if(length<3){return c.error(c,{message:"Invalid Certificate message. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var b2=record.fragment;var msg={certificate_list:readVector(b2,3)};var cert,asn1;var certs=[];try{while(msg.certificate_list.length()>0){cert=readVector(msg.certificate_list,3);asn1=forge2.asn1.fromDer(cert);cert=forge2.pki.certificateFromAsn1(asn1,true);certs.push(cert)}}catch(ex){return c.error(c,{message:"Could not parse certificate list.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_certificate}})}var client=c.entity===tls5.ConnectionEnd.client;if((client||c.verifyClient===true)&&certs.length===0){c.error(c,{message:client?"No server certificate provided.":"No client certificate provided.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}else if(certs.length===0){c.expect=client?SKE:CKE}else{if(client){c.session.serverCertificate=certs[0]}else{c.session.clientCertificate=certs[0]}if(tls5.verifyCertificateChain(c,certs)){c.expect=client?SKE:CKE}}c.process()};tls5.handleServerKeyExchange=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unsupported_certificate}})}c.expect=SCR;c.process()};tls5.handleClientKeyExchange=function(c,record,length){if(length<48){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unsupported_certificate}})}var b2=record.fragment;var msg={enc_pre_master_secret:readVector(b2,2).getBytes()};var privateKey=null;if(c.getPrivateKey){try{privateKey=c.getPrivateKey(c,c.session.serverCertificate);privateKey=forge2.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}}if(privateKey===null){return c.error(c,{message:"No private key set.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.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=forge2.random.getBytes(48)}c.expect=CCC;if(c.session.clientCertificate!==null){c.expect=CCV}c.process()};tls5.handleCertificateRequest=function(c,record,length){if(length<3){return c.error(c,{message:"Invalid CertificateRequest. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var b2=record.fragment;var msg={certificate_types:readVector(b2,1),certificate_authorities:readVector(b2,2)};c.session.certificateRequest=msg;c.expect=SHD;c.process()};tls5.handleCertificateVerify=function(c,record,length){if(length<2){return c.error(c,{message:"Invalid CertificateVerify. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var b2=record.fragment;b2.read-=4;var msgBytes=b2.bytes();b2.read+=4;var msg={signature:readVector(b2,2).getBytes()};var verify=forge2.util.createBuffer();verify.putBuffer(c.session.md5.digest());verify.putBuffer(c.session.sha1.digest());verify=verify.getBytes();try{var cert=c.session.clientCertificate;if(!cert.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:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.handshake_failure}})}c.expect=CCC;c.process()};tls5.handleServerHelloDone=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid ServerHelloDone message. Invalid length.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.record_overflow}})}if(c.serverCertificate===null){var error={message:"No server certificate provided. Not enough security.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.insufficient_security}};var depth=0;var ret=c.verify(c,error.alert.description,depth,[]);if(ret!==true){if(ret||ret===0){if(typeof ret==="object"&&!forge2.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.alert){error.alert.description=ret.alert}}else if(typeof ret==="number"){error.alert.description=ret}}return c.error(c,error)}}if(c.session.certificateRequest!==null){record=tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createCertificate(c)});tls5.queue(c,record)}record=tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createClientKeyExchange(c)});tls5.queue(c,record);c.expect=SER;var callback=function(c2,signature){if(c2.session.certificateRequest!==null&&c2.session.clientCertificate!==null){tls5.queue(c2,tls5.createRecord(c2,{type:tls5.ContentType.handshake,data:tls5.createCertificateVerify(c2,signature)}))}tls5.queue(c2,tls5.createRecord(c2,{type:tls5.ContentType.change_cipher_spec,data:tls5.createChangeCipherSpec()}));c2.state.pending=tls5.createConnectionState(c2);c2.state.current.write=c2.state.pending.write;tls5.queue(c2,tls5.createRecord(c2,{type:tls5.ContentType.handshake,data:tls5.createFinished(c2)}));c2.expect=SCC;tls5.flush(c2);c2.process()};if(c.session.certificateRequest===null||c.session.clientCertificate===null){return callback(c,null)}tls5.getClientSignature(c,callback)};tls5.handleChangeCipherSpec=function(c,record){if(record.fragment.getByte()!==1){return c.error(c,{message:"Invalid ChangeCipherSpec message received.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var client=c.entity===tls5.ConnectionEnd.client;if(c.session.resuming&&client||!c.session.resuming&&!client){c.state.pending=tls5.createConnectionState(c)}c.state.current.read=c.state.pending.read;if(!c.session.resuming&&client||c.session.resuming&&!client){c.state.pending=null}c.expect=client?SFI:CFI;c.process()};tls5.handleFinished=function(c,record,length){var b2=record.fragment;b2.read-=4;var msgBytes=b2.bytes();b2.read+=4;var vd=record.fragment.getBytes();b2=forge2.util.createBuffer();b2.putBuffer(c.session.md5.digest());b2.putBuffer(c.session.sha1.digest());var client=c.entity===tls5.ConnectionEnd.client;var label=client?"server finished":"client finished";var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;b2=prf(sp.master_secret,label,b2.getBytes(),vdl);if(b2.getBytes()!==vd){return c.error(c,{message:"Invalid verify_data in Finished message.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.decrypt_error}})}c.session.md5.update(msgBytes);c.session.sha1.update(msgBytes);if(c.session.resuming&&client||!c.session.resuming&&!client){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.change_cipher_spec,data:tls5.createChangeCipherSpec()}));c.state.current.write=c.state.pending.write;c.state.pending=null;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createFinished(c)}))}c.expect=client?SAD:CAD;c.handshaking=false;++c.handshakes;c.peerCertificate=client?c.session.serverCertificate:c.session.clientCertificate;tls5.flush(c);c.isConnected=true;c.connected(c);c.process()};tls5.handleAlert=function(c,record){var b2=record.fragment;var alert={level:b2.getByte(),description:b2.getByte()};var msg;switch(alert.description){case tls5.Alert.Description.close_notify:msg="Connection closed.";break;case tls5.Alert.Description.unexpected_message:msg="Unexpected message.";break;case tls5.Alert.Description.bad_record_mac:msg="Bad record MAC.";break;case tls5.Alert.Description.decryption_failed:msg="Decryption failed.";break;case tls5.Alert.Description.record_overflow:msg="Record overflow.";break;case tls5.Alert.Description.decompression_failure:msg="Decompression failed.";break;case tls5.Alert.Description.handshake_failure:msg="Handshake failure.";break;case tls5.Alert.Description.bad_certificate:msg="Bad certificate.";break;case tls5.Alert.Description.unsupported_certificate:msg="Unsupported certificate.";break;case tls5.Alert.Description.certificate_revoked:msg="Certificate revoked.";break;case tls5.Alert.Description.certificate_expired:msg="Certificate expired.";break;case tls5.Alert.Description.certificate_unknown:msg="Certificate unknown.";break;case tls5.Alert.Description.illegal_parameter:msg="Illegal parameter.";break;case tls5.Alert.Description.unknown_ca:msg="Unknown certificate authority.";break;case tls5.Alert.Description.access_denied:msg="Access denied.";break;case tls5.Alert.Description.decode_error:msg="Decode error.";break;case tls5.Alert.Description.decrypt_error:msg="Decrypt error.";break;case tls5.Alert.Description.export_restriction:msg="Export restriction.";break;case tls5.Alert.Description.protocol_version:msg="Unsupported protocol version.";break;case tls5.Alert.Description.insufficient_security:msg="Insufficient security.";break;case tls5.Alert.Description.internal_error:msg="Internal error.";break;case tls5.Alert.Description.user_canceled:msg="User canceled.";break;case tls5.Alert.Description.no_renegotiation:msg="Renegotiation not supported.";break;default:msg="Unknown error.";break}if(alert.description===tls5.Alert.Description.close_notify){return c.close()}c.error(c,{message:msg,send:false,origin:c.entity===tls5.ConnectionEnd.client?"server":"client",alert});c.process()};tls5.handleHandshake=function(c,record){var b2=record.fragment;var type=b2.getByte();var length=b2.getInt24();if(length>b2.length()){c.fragmented=record;record.fragment=forge2.util.createBuffer();b2.read-=4;return c.process()}c.fragmented=null;b2.read-=4;var bytes=b2.bytes(length+4);b2.read+=4;if(type in hsTable[c.entity][c.expect]){if(c.entity===tls5.ConnectionEnd.server&&!c.open&&!c.fail){c.handshaking=true;c.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:forge2.md.md5.create(),sha1:forge2.md.sha1.create()}}if(type!==tls5.HandshakeType.hello_request&&type!==tls5.HandshakeType.certificate_verify&&type!==tls5.HandshakeType.finished){c.session.md5.update(bytes);c.session.sha1.update(bytes)}hsTable[c.entity][c.expect][type](c,record,length)}else{tls5.handleUnexpected(c,record)}};tls5.handleApplicationData=function(c,record){c.data.putBuffer(record.fragment);c.dataReady(c);c.process()};tls5.handleHeartbeat=function(c,record){var b2=record.fragment;var type=b2.getByte();var length=b2.getInt16();var payload=b2.getBytes(length);if(type===tls5.HeartbeatMessageType.heartbeat_request){if(c.handshaking||length>payload.length){return c.process()}tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.heartbeat,data:tls5.createHeartbeat(tls5.HeartbeatMessageType.heartbeat_response,payload)}));tls5.flush(c)}else if(type===tls5.HeartbeatMessageType.heartbeat_response){if(payload!==c.expectedHeartbeatPayload){return c.process()}if(c.heartbeatReceived){c.heartbeatReceived(c,forge2.util.createBuffer(payload))}}c.process()};var SHE=0;var SCE=1;var SKE=2;var SCR=3;var SHD=4;var SCC=5;var SFI=6;var SAD=7;var SER=8;var CHE=0;var CCE=1;var CKE=2;var CCV=3;var CCC=4;var CFI=5;var CAD=6;var __=tls5.handleUnexpected;var R0=tls5.handleChangeCipherSpec;var R1=tls5.handleAlert;var R2=tls5.handleHandshake;var R3=tls5.handleApplicationData;var R4=tls5.handleHeartbeat;var ctTable=[];ctTable[tls5.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[tls5.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=tls5.handleHelloRequest;var H1=tls5.handleServerHello;var H2=tls5.handleCertificate;var H3=tls5.handleServerKeyExchange;var H4=tls5.handleCertificateRequest;var H5=tls5.handleServerHelloDone;var H6=tls5.handleFinished;var hsTable=[];hsTable[tls5.ConnectionEnd.client]=[[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];var H7=tls5.handleClientHello;var H8=tls5.handleClientKeyExchange;var H9=tls5.handleCertificateVerify;hsTable[tls5.ConnectionEnd.server]=[[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];tls5.generateKeys=function(c,sp){var prf=prf_TLS1;var random=sp.client_random+sp.server_random;if(!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;var tls10=c.version.major===tls5.Versions.TLS_1_0.major&&c.version.minor===tls5.Versions.TLS_1_0.minor;if(tls10){length+=2*sp.fixed_iv_length}var km=prf(sp.master_secret,"key expansion",random,length);var 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)};if(tls10){rval.client_write_IV=km.getBytes(sp.fixed_iv_length);rval.server_write_IV=km.getBytes(sp.fixed_iv_length)}return rval};tls5.createConnectionState=function(c){var client=c.entity===tls5.ConnectionEnd.client;var createMode=function(){var mode={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(record){return true},compressionState:null,compressFunction:function(record){return true},updateSequenceNumber:function(){if(mode.sequenceNumber[1]===4294967295){mode.sequenceNumber[1]=0;++mode.sequenceNumber[0]}else{++mode.sequenceNumber[1]}}};return mode};var state3={read:createMode(),write:createMode()};state3.read.update=function(c2,record){if(!state3.read.cipherFunction(record,state3.read)){c2.error(c2,{message:"Could not decrypt record or bad MAC.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_record_mac}})}else if(!state3.read.compressFunction(c2,record,state3.read)){c2.error(c2,{message:"Could not decompress record.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.decompression_failure}})}return!c2.fail};state3.write.update=function(c2,record){if(!state3.write.compressFunction(c2,record,state3.write)){c2.error(c2,{message:"Could not compress record.",send:false,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}else if(!state3.write.cipherFunction(record,state3.write)){c2.error(c2,{message:"Could not encrypt record.",send:false,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}return!c2.fail};if(c.session){var sp=c.session.sp;c.session.cipherSuite.initSecurityParameters(sp);sp.keys=tls5.generateKeys(c,sp);state3.read.macKey=client?sp.keys.server_write_MAC_key:sp.keys.client_write_MAC_key;state3.write.macKey=client?sp.keys.client_write_MAC_key:sp.keys.server_write_MAC_key;c.session.cipherSuite.initConnectionState(state3,c,sp);switch(sp.compression_algorithm){case tls5.CompressionMethod.none:break;case tls5.CompressionMethod.deflate:state3.read.compressFunction=inflate;state3.write.compressFunction=deflate;break;default:throw new Error("Unsupported compression algorithm.")}}return state3};tls5.createRandom=function(){var d=new Date;var utc=+d+d.getTimezoneOffset()*6e4;var rval=forge2.util.createBuffer();rval.putInt32(utc);rval.putBytes(forge2.random.getBytes(28));return rval};tls5.createRecord=function(c,options){if(!options.data){return null}var record={type:options.type,version:{major:c.version.major,minor:c.version.minor},length:options.data.length(),fragment:options.data};return record};tls5.createAlert=function(c,alert){var b2=forge2.util.createBuffer();b2.putByte(alert.level);b2.putByte(alert.description);return tls5.createRecord(c,{type:tls5.ContentType.alert,data:b2})};tls5.createClientHello=function(c){c.session.clientHelloVersion={major:c.version.major,minor:c.version.minor};var cipherSuites=forge2.util.createBuffer();for(var i=0;i<c.cipherSuites.length;++i){var cs2=c.cipherSuites[i];cipherSuites.putByte(cs2.id[0]);cipherSuites.putByte(cs2.id[1])}var cSuites=cipherSuites.length();var compressionMethods=forge2.util.createBuffer();compressionMethods.putByte(tls5.CompressionMethod.none);var cMethods=compressionMethods.length();var extensions=forge2.util.createBuffer();if(c.virtualHost){var ext=forge2.util.createBuffer();ext.putByte(0);ext.putByte(0);var serverName=forge2.util.createBuffer();serverName.putByte(0);writeVector(serverName,2,forge2.util.createBuffer(c.virtualHost));var snList=forge2.util.createBuffer();writeVector(snList,2,serverName);writeVector(ext,2,snList);extensions.putBuffer(ext)}var extLength=extensions.length();if(extLength>0){extLength+=2}var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+cSuites+1+cMethods+extLength;var rval=forge2.util.createBuffer();rval.putByte(tls5.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,forge2.util.createBuffer(sessionId));writeVector(rval,2,cipherSuites);writeVector(rval,1,compressionMethods);if(extLength>0){writeVector(rval,2,extensions)}return rval};tls5.createServerHello=function(c){var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+1;var rval=forge2.util.createBuffer();rval.putByte(tls5.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,forge2.util.createBuffer(sessionId));rval.putByte(c.session.cipherSuite.id[0]);rval.putByte(c.session.cipherSuite.id[1]);rval.putByte(c.session.compressionMethod);return rval};tls5.createCertificate=function(c){var client=c.entity===tls5.ConnectionEnd.client;var cert=null;if(c.getCertificate){var hint;if(client){hint=c.session.certificateRequest}else{hint=c.session.extensions.server_name.serverNameList}cert=c.getCertificate(c,hint)}var certList=forge2.util.createBuffer();if(cert!==null){try{if(!forge2.util.isArray(cert)){cert=[cert]}var asn1=null;for(var i=0;i<cert.length;++i){var msg=forge2.pem.decode(cert[i])[0];if(msg.type!=="CERTIFICATE"&&msg.type!=="X509 CERTIFICATE"&&msg.type!=="TRUSTED CERTIFICATE"){var error=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert certificate from PEM; PEM is encrypted.")}var der=forge2.util.createBuffer(msg.body);if(asn1===null){asn1=forge2.asn1.fromDer(der.bytes(),false)}var certBuffer=forge2.util.createBuffer();writeVector(certBuffer,3,der);certList.putBuffer(certBuffer)}cert=forge2.pki.certificateFromAsn1(asn1);if(client){c.session.clientCertificate=cert}else{c.session.serverCertificate=cert}}catch(ex){return c.error(c,{message:"Could not send certificate list.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_certificate}})}}var length=3+certList.length();var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.certificate);rval.putInt24(length);writeVector(rval,3,certList);return rval};tls5.createClientKeyExchange=function(c){var b2=forge2.util.createBuffer();b2.putByte(c.session.clientHelloVersion.major);b2.putByte(c.session.clientHelloVersion.minor);b2.putBytes(forge2.random.getBytes(46));var sp=c.session.sp;sp.pre_master_secret=b2.getBytes();var key2=c.session.serverCertificate.publicKey;b2=key2.encrypt(sp.pre_master_secret);var length=b2.length+2;var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.client_key_exchange);rval.putInt24(length);rval.putInt16(b2.length);rval.putBytes(b2);return rval};tls5.createServerKeyExchange=function(c){var length=0;var rval=forge2.util.createBuffer();if(length>0){rval.putByte(tls5.HandshakeType.server_key_exchange);rval.putInt24(length)}return rval};tls5.getClientSignature=function(c,callback){var b2=forge2.util.createBuffer();b2.putBuffer(c.session.md5.digest());b2.putBuffer(c.session.sha1.digest());b2=b2.getBytes();c.getSignature=c.getSignature||function(c2,b3,callback2){var privateKey=null;if(c2.getPrivateKey){try{privateKey=c2.getPrivateKey(c2,c2.session.clientCertificate);privateKey=forge2.pki.privateKeyFromPem(privateKey)}catch(ex){c2.error(c2,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}}if(privateKey===null){c2.error(c2,{message:"No private key set.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}else{b3=privateKey.sign(b3,null)}callback2(c2,b3)};c.getSignature(c,b2,callback)};tls5.createCertificateVerify=function(c,signature){var length=signature.length+2;var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.certificate_verify);rval.putInt24(length);rval.putInt16(signature.length);rval.putBytes(signature);return rval};tls5.createCertificateRequest=function(c){var certTypes=forge2.util.createBuffer();certTypes.putByte(1);var cAs=forge2.util.createBuffer();for(var key2 in c.caStore.certs){var cert=c.caStore.certs[key2];var dn2=forge2.pki.distinguishedNameToAsn1(cert.subject);var byteBuffer=forge2.asn1.toDer(dn2);cAs.putInt16(byteBuffer.length());cAs.putBuffer(byteBuffer)}var length=1+certTypes.length()+2+cAs.length();var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.certificate_request);rval.putInt24(length);writeVector(rval,1,certTypes);writeVector(rval,2,cAs);return rval};tls5.createServerHelloDone=function(c){var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.server_hello_done);rval.putInt24(0);return rval};tls5.createChangeCipherSpec=function(){var rval=forge2.util.createBuffer();rval.putByte(1);return rval};tls5.createFinished=function(c){var b2=forge2.util.createBuffer();b2.putBuffer(c.session.md5.digest());b2.putBuffer(c.session.sha1.digest());var client=c.entity===tls5.ConnectionEnd.client;var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;var label=client?"client finished":"server finished";b2=prf(sp.master_secret,label,b2.getBytes(),vdl);var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.finished);rval.putInt24(b2.length());rval.putBuffer(b2);return rval};tls5.createHeartbeat=function(type,payload,payloadLength){if(typeof payloadLength==="undefined"){payloadLength=payload.length}var rval=forge2.util.createBuffer();rval.putByte(type);rval.putInt16(payloadLength);rval.putBytes(payload);var plaintextLength=rval.length();var paddingLength=Math.max(16,plaintextLength-payloadLength-3);rval.putBytes(forge2.random.getBytes(paddingLength));return rval};tls5.queue=function(c,record){if(!record){return}if(record.fragment.length()===0){if(record.type===tls5.ContentType.handshake||record.type===tls5.ContentType.alert||record.type===tls5.ContentType.change_cipher_spec){return}}if(record.type===tls5.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()<=tls5.MaxFragment){records=[record]}else{records=[];var data=record.fragment.bytes();while(data.length>tls5.MaxFragment){records.push(tls5.createRecord(c,{type:record.type,data:forge2.util.createBuffer(data.slice(0,tls5.MaxFragment))}));data=data.slice(tls5.MaxFragment)}if(data.length>0){records.push(tls5.createRecord(c,{type:record.type,data:forge2.util.createBuffer(data)}))}}for(var i=0;i<records.length&&!c.fail;++i){var rec=records[i];var s3=c.state.current.write;if(s3.update(c,rec)){c.records.push(rec)}}};tls5.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)}c.records=[];return c.tlsDataReady(c)};var _certErrorToAlertDesc=function(error){switch(error){case true:return true;case forge2.pki.certificateError.bad_certificate:return tls5.Alert.Description.bad_certificate;case forge2.pki.certificateError.unsupported_certificate:return tls5.Alert.Description.unsupported_certificate;case forge2.pki.certificateError.certificate_revoked:return tls5.Alert.Description.certificate_revoked;case forge2.pki.certificateError.certificate_expired:return tls5.Alert.Description.certificate_expired;case forge2.pki.certificateError.certificate_unknown:return tls5.Alert.Description.certificate_unknown;case forge2.pki.certificateError.unknown_ca:return tls5.Alert.Description.unknown_ca;default:return tls5.Alert.Description.bad_certificate}};var _alertDescToCertError=function(desc){switch(desc){case true:return true;case tls5.Alert.Description.bad_certificate:return forge2.pki.certificateError.bad_certificate;case tls5.Alert.Description.unsupported_certificate:return forge2.pki.certificateError.unsupported_certificate;case tls5.Alert.Description.certificate_revoked:return forge2.pki.certificateError.certificate_revoked;case tls5.Alert.Description.certificate_expired:return forge2.pki.certificateError.certificate_expired;case tls5.Alert.Description.certificate_unknown:return forge2.pki.certificateError.certificate_unknown;case tls5.Alert.Description.unknown_ca:return forge2.pki.certificateError.unknown_ca;default:return forge2.pki.certificateError.bad_certificate}};tls5.verifyCertificateChain=function(c,chain){try{var options={};for(var key2 in c.verifyOptions){options[key2]=c.verifyOptions[key2]}options.verify=function(vfd,depth,chain2){var desc=_certErrorToAlertDesc(vfd);var ret=c.verify(c,vfd,depth,chain2);if(ret!==true){if(typeof ret==="object"&&!forge2.util.isArray(ret)){var error=new Error("The application rejected the certificate.");error.send=true;error.alert={level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_certificate};if(ret.message){error.message=ret.message}if(ret.alert){error.alert.description=ret.alert}throw error}if(ret!==vfd){ret=_alertDescToCertError(ret)}}return ret};forge2.pki.verifyCertificateChain(c.caStore,chain,options)}catch(ex){var err=ex;if(typeof err!=="object"||forge2.util.isArray(err)){err={send:true,alert:{level:tls5.Alert.Level.fatal,description:_certErrorToAlertDesc(ex)}}}if(!("send"in err)){err.send=true}if(!("alert"in err)){err.alert={level:tls5.Alert.Level.fatal,description:_certErrorToAlertDesc(err.error)}}c.error(c,err)}return!c.fail};tls5.createSessionCache=function(cache3,capacity){var rval=null;if(cache3&&cache3.getSession&&cache3.setSession&&cache3.order){rval=cache3}else{rval={};rval.cache=cache3||{};rval.capacity=Math.max(capacity||100,1);rval.order=[];for(var key2 in cache3){if(rval.order.length<=capacity){rval.order.push(key2)}else{delete cache3[key2]}}rval.getSession=function(sessionId){var session=null;var key3=null;if(sessionId){key3=forge2.util.bytesToHex(sessionId)}else if(rval.order.length>0){key3=rval.order[0]}if(key3!==null&&key3 in rval.cache){session=rval.cache[key3];delete rval.cache[key3];for(var i in rval.order){if(rval.order[i]===key3){rval.order.splice(i,1);break}}}return session};rval.setSession=function(sessionId,session){if(rval.order.length===rval.capacity){var key3=rval.order.shift();delete rval.cache[key3]}var key3=forge2.util.bytesToHex(sessionId);rval.order.push(key3);rval.cache[key3]=session}}return rval};tls5.createConnection=function(options){var caStore=null;if(options.caStore){if(forge2.util.isArray(options.caStore)){caStore=forge2.pki.createCaStore(options.caStore)}else{caStore=options.caStore}}else{caStore=forge2.pki.createCaStore()}var cipherSuites=options.cipherSuites||null;if(cipherSuites===null){cipherSuites=[];for(var key2 in tls5.CipherSuites){cipherSuites.push(tls5.CipherSuites[key2])}}var entity=options.server||false?tls5.ConnectionEnd.server:tls5.ConnectionEnd.client;var sessionCache=options.sessionCache?tls5.createSessionCache(options.sessionCache):null;var c={version:{major:tls5.Version.major,minor:tls5.Version.minor},entity,sessionId:options.sessionId,caStore,sessionCache,cipherSuites,connected:options.connected,virtualHost:options.virtualHost||null,verifyClient:options.verifyClient||false,verify:options.verify||function(cn2,vfd,dpth,cts){return vfd},verifyOptions:options.verifyOptions||{},getCertificate:options.getCertificate||null,getPrivateKey:options.getPrivateKey||null,getSignature:options.getSignature||null,input:forge2.util.createBuffer(),tlsData:forge2.util.createBuffer(),data:forge2.util.createBuffer(),tlsDataReady:options.tlsDataReady,dataReady:options.dataReady,heartbeatReceived:options.heartbeatReceived,closed:options.closed,error:function(c2,ex){ex.origin=ex.origin||(c2.entity===tls5.ConnectionEnd.client?"client":"server");if(ex.send){tls5.queue(c2,tls5.createAlert(c2,ex.alert));tls5.flush(c2)}var fatal=ex.fatal!==false;if(fatal){c2.fail=true}options.error(c2,ex);if(fatal){c2.close(false)}},deflate:options.deflate||null,inflate:options.inflate||null};c.reset=function(clearFail){c.version={major:tls5.Version.major,minor:tls5.Version.minor};c.record=null;c.session=null;c.peerCertificate=null;c.state={pending:null,current:null};c.expect=c.entity===tls5.ConnectionEnd.client?SHE:CHE;c.fragmented=null;c.records=[];c.open=false;c.handshakes=0;c.handshaking=false;c.isConnected=false;c.fail=!(clearFail||typeof clearFail==="undefined");c.input.clear();c.tlsData.clear();c.data.clear();c.state.current=tls5.createConnectionState(c)};c.reset();var _update=function(c2,record){var aligned=record.type-tls5.ContentType.change_cipher_spec;var handlers=ctTable[c2.entity][c2.expect];if(aligned in handlers){handlers[aligned](c2,record)}else{tls5.handleUnexpected(c2,record)}};var _readRecordHeader=function(c2){var rval=0;var b2=c2.input;var len=b2.length();if(len<5){rval=5-len}else{c2.record={type:b2.getByte(),version:{major:b2.getByte(),minor:b2.getByte()},length:b2.getInt16(),fragment:forge2.util.createBuffer(),ready:false};var compatibleVersion=c2.record.version.major===c2.version.major;if(compatibleVersion&&c2.session&&c2.session.version){compatibleVersion=c2.record.version.minor===c2.version.minor}if(!compatibleVersion){c2.error(c2,{message:"Incompatible TLS version.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.protocol_version}})}}return rval};var _readRecord=function(c2){var rval=0;var b2=c2.input;var len=b2.length();if(len<c2.record.length){rval=c2.record.length-len}else{c2.record.fragment.putBytes(b2.getBytes(c2.record.length));b2.compact();var s3=c2.state.current.read;if(s3.update(c2,c2.record)){if(c2.fragmented!==null){if(c2.fragmented.type===c2.record.type){c2.fragmented.fragment.putBuffer(c2.record.fragment);c2.record=c2.fragmented}else{c2.error(c2,{message:"Invalid fragmented record.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unexpected_message}})}}c2.record.ready=true}}return rval};c.handshake=function(sessionId){if(c.entity!==tls5.ConnectionEnd.client){c.error(c,{message:"Cannot initiate handshake as a server.",fatal:false})}else if(c.handshaking){c.error(c,{message:"Handshake already in progress.",fatal:false})}else{if(c.fail&&!c.open&&c.handshakes===0){c.fail=false}c.handshaking=true;sessionId=sessionId||"";var session=null;if(sessionId.length>0){if(c.sessionCache){session=c.sessionCache.getSession(sessionId)}if(session===null){sessionId=""}}if(sessionId.length===0&&c.sessionCache){session=c.sessionCache.getSession();if(session!==null){sessionId=session.id}}c.session={id:sessionId,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:forge2.md.md5.create(),sha1:forge2.md.sha1.create()};if(session){c.version=session.version;c.session.sp=session.sp}c.session.sp.client_random=tls5.createRandom().getBytes();c.open=true;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createClientHello(c)}));tls5.flush(c)}};c.process=function(data){var rval=0;if(data){c.input.putBytes(data)}if(!c.fail){if(c.record!==null&&c.record.ready&&c.record.fragment.isEmpty()){c.record=null}if(c.record===null){rval=_readRecordHeader(c)}if(!c.fail&&c.record!==null&&!c.record.ready){rval=_readRecord(c)}if(!c.fail&&c.record!==null&&c.record.ready){_update(c,c.record)}}return rval};c.prepare=function(data){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.application_data,data:forge2.util.createBuffer(data)}));return tls5.flush(c)};c.prepareHeartbeatRequest=function(payload,payloadLength){if(payload instanceof forge2.util.ByteBuffer){payload=payload.bytes()}if(typeof payloadLength==="undefined"){payloadLength=payload.length}c.expectedHeartbeatPayload=payload;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.heartbeat,data:tls5.createHeartbeat(tls5.HeartbeatMessageType.heartbeat_request,payload,payloadLength)}));return tls5.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)}if(c.open){c.open=false;c.input.clear();if(c.isConnected||c.handshaking){c.isConnected=c.handshaking=false;tls5.queue(c,tls5.createAlert(c,{level:tls5.Alert.Level.warning,description:tls5.Alert.Description.close_notify}));tls5.flush(c)}c.closed(c)}c.reset(clearFail)};return c};module.exports=forge2.tls=forge2.tls||{};for(key in tls5){if(typeof tls5[key]!=="function"){forge2.tls[key]=tls5[key]}}var key;forge2.tls.prf_tls1=prf_TLS1;forge2.tls.hmac_sha1=hmac_sha1;forge2.tls.createSessionCache=tls5.createSessionCache;forge2.tls.createConnection=tls5.createConnection}});var require_aesCipherSuites=__commonJS({"node_modules/node-forge/lib/aesCipherSuites.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_tls();var tls5=module.exports=forge2.tls;tls5.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=tls5.BulkCipherAlgorithm.aes;sp.cipher_type=tls5.CipherType.block;sp.enc_key_length=16;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls5.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState};tls5.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=tls5.BulkCipherAlgorithm.aes;sp.cipher_type=tls5.CipherType.block;sp.enc_key_length=32;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls5.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState};function initConnectionState(state3,c,sp){var client=c.entity===forge2.tls.ConnectionEnd.client;state3.read.cipherState={init:false,cipher:forge2.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};state3.write.cipherState={init:false,cipher:forge2.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};state3.read.cipherFunction=decrypt_aes_cbc_sha1;state3.write.cipherFunction=encrypt_aes_cbc_sha1;state3.read.macLength=state3.write.macLength=sp.mac_length;state3.read.macFunction=state3.write.macFunction=tls5.hmac_sha1}function encrypt_aes_cbc_sha1(record,s3){var rval=false;var mac=s3.macFunction(s3.macKey,s3.sequenceNumber,record);record.fragment.putBytes(mac);s3.updateSequenceNumber();var iv;if(record.version.minor===tls5.Versions.TLS_1_0.minor){iv=s3.cipherState.init?null:s3.cipherState.iv}else{iv=forge2.random.getBytesSync(16)}s3.cipherState.init=true;var cipher=s3.cipherState.cipher;cipher.start({iv});if(record.version.minor>=tls5.Versions.TLS_1_1.minor){cipher.output.putBytes(iv)}cipher.update(record.fragment);if(cipher.finish(encrypt_aes_cbc_sha1_padding)){record.fragment=cipher.output;record.length=record.fragment.length();rval=true}return rval}function encrypt_aes_cbc_sha1_padding(blockSize,input,decrypt){if(!decrypt){var padding=blockSize-input.length()%blockSize;input.fillWithByte(padding-1,padding)}return true}function decrypt_aes_cbc_sha1_padding(blockSize,output,decrypt){var rval=true;if(decrypt){var len=output.length();var paddingLength=output.last();for(var i=len-1-paddingLength;i<len-1;++i){rval=rval&&output.at(i)==paddingLength}if(rval){output.truncate(paddingLength+1)}}return rval}function decrypt_aes_cbc_sha1(record,s3){var rval=false;var iv;if(record.version.minor===tls5.Versions.TLS_1_0.minor){iv=s3.cipherState.init?null:s3.cipherState.iv}else{iv=record.fragment.getBytes(16)}s3.cipherState.init=true;var cipher=s3.cipherState.cipher;cipher.start({iv});cipher.update(record.fragment);rval=cipher.finish(decrypt_aes_cbc_sha1_padding);var macLen=s3.macLength;var mac=forge2.random.getBytesSync(macLen);var len=cipher.output.length();if(len>=macLen){record.fragment=cipher.output.getBytes(len-macLen);mac=cipher.output.getBytes(macLen)}else{record.fragment=cipher.output.getBytes()}record.fragment=forge2.util.createBuffer(record.fragment);record.length=record.fragment.length();var mac2=s3.macFunction(s3.macKey,s3.sequenceNumber,record);s3.updateSequenceNumber();rval=compareMacs(s3.macKey,mac,mac2)&&rval;return rval}function compareMacs(key,mac1,mac2){var hmac=forge2.hmac.create();hmac.start("SHA1",key);hmac.update(mac1);mac1=hmac.digest().getBytes();hmac.start(null,null);hmac.update(mac2);mac2=hmac.digest().getBytes();return mac1===mac2}}});var require_sha512=__commonJS({"node_modules/node-forge/lib/sha512.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var sha512=module.exports=forge2.sha512=forge2.sha512||{};forge2.md.sha512=forge2.md.algorithms.sha512=sha512;var sha384=forge2.sha384=forge2.sha512.sha384=forge2.sha512.sha384||{};sha384.create=function(){return sha512.create("SHA-384")};forge2.md.sha384=forge2.md.algorithms.sha384=sha384;forge2.sha512.sha256=forge2.sha512.sha256||{create:function(){return sha512.create("SHA-512/256")}};forge2.md["sha512/256"]=forge2.md.algorithms["sha512/256"]=forge2.sha512.sha256;forge2.sha512.sha224=forge2.sha512.sha224||{create:function(){return sha512.create("SHA-512/224")}};forge2.md["sha512/224"]=forge2.md.algorithms["sha512/224"]=forge2.sha512.sha224;sha512.create=function(algorithm){if(!_initialized){_init()}if(typeof algorithm==="undefined"){algorithm="SHA-512"}if(!(algorithm in _states)){throw new Error("Invalid SHA-512 algorithm: "+algorithm)}var _state=_states[algorithm];var _h=null;var _input=forge2.util.createBuffer();var _w=new Array(80);for(var wi2=0;wi2<80;++wi2){_w[wi2]=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;break}var md={algorithm:algorithm.replace("-","").toLowerCase(),blockLength:128,digestLength,messageLength:0,fullMessageLength:null,messageLengthSize:16};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength128=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_h=new Array(_state.length);for(var i=0;i<_state.length;++i){_h[i]=_state[i].slice(0)}return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_h,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i<md.fullMessageLength.length-1;++i){next=md.fullMessageLength[i+1]*8;carry=next/4294967296>>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var h=new Array(_h.length);for(var i=0;i<_h.length;++i){h[i]=_h[i].slice(0)}_update(h,_w,finalBlock);var rval=forge2.util.createBuffer();var hlen;if(algorithm==="SHA-512"){hlen=h.length}else if(algorithm==="SHA-384"){hlen=h.length-2}else{hlen=h.length-4}for(var i=0;i<hlen;++i){rval.putInt32(h[i][0]);if(i!==hlen-1||algorithm!=="SHA-512/224"){rval.putInt32(h[i][1])}}return rval};return md};var _padding=null;var _initialized=false;var _k=null;var _states=null;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.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={};_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=true}function _update(s3,w2,bytes){var t1_hi,t1_lo;var t2_hi,t2_lo;var s0_hi,s0_lo;var s1_hi,s1_lo;var ch_hi,ch_lo;var maj_hi,maj_lo;var a_hi,a_lo;var b_hi,b_lo;var c_hi,c_lo;var d_hi,d_lo;var e_hi,e_lo;var f_hi,f_lo;var g_hi,g_lo;var h_hi,h_lo;var i,hi2,lo2,w22,w7,w15,w16;var len=bytes.length();while(len>=128){for(i=0;i<16;++i){w2[i][0]=bytes.getInt32()>>>0;w2[i][1]=bytes.getInt32()>>>0}for(;i<80;++i){w22=w2[i-2];hi2=w22[0];lo2=w22[1];t1_hi=((hi2>>>19|lo2<<13)^(lo2>>>29|hi2<<3)^hi2>>>6)>>>0;t1_lo=((hi2<<13|lo2>>>19)^(lo2<<3|hi2>>>29)^(hi2<<26|lo2>>>6))>>>0;w15=w2[i-15];hi2=w15[0];lo2=w15[1];t2_hi=((hi2>>>1|lo2<<31)^(hi2>>>8|lo2<<24)^hi2>>>7)>>>0;t2_lo=((hi2<<31|lo2>>>1)^(hi2<<24|lo2>>>8)^(hi2<<25|lo2>>>7))>>>0;w7=w2[i-7];w16=w2[i-16];lo2=t1_lo+w7[1]+t2_lo+w16[1];w2[i][0]=t1_hi+w7[0]+t2_hi+w16[0]+(lo2/4294967296>>>0)>>>0;w2[i][1]=lo2>>>0}a_hi=s3[0][0];a_lo=s3[0][1];b_hi=s3[1][0];b_lo=s3[1][1];c_hi=s3[2][0];c_lo=s3[2][1];d_hi=s3[3][0];d_lo=s3[3][1];e_hi=s3[4][0];e_lo=s3[4][1];f_hi=s3[5][0];f_lo=s3[5][1];g_hi=s3[6][0];g_lo=s3[6][1];h_hi=s3[7][0];h_lo=s3[7][1];for(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;s1_lo=((e_hi<<18|e_lo>>>14)^(e_hi<<14|e_lo>>>18)^(e_lo<<23|e_hi>>>9))>>>0;ch_hi=(g_hi^e_hi&(f_hi^g_hi))>>>0;ch_lo=(g_lo^e_lo&(f_lo^g_lo))>>>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;lo2=h_lo+s1_lo+ch_lo+_k[i][1]+w2[i][1];t1_hi=h_hi+s1_hi+ch_hi+_k[i][0]+w2[i][0]+(lo2/4294967296>>>0)>>>0;t1_lo=lo2>>>0;lo2=s0_lo+maj_lo;t2_hi=s0_hi+maj_hi+(lo2/4294967296>>>0)>>>0;t2_lo=lo2>>>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;lo2=d_lo+t1_lo;e_hi=d_hi+t1_hi+(lo2/4294967296>>>0)>>>0;e_lo=lo2>>>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;lo2=t1_lo+t2_lo;a_hi=t1_hi+t2_hi+(lo2/4294967296>>>0)>>>0;a_lo=lo2>>>0}lo2=s3[0][1]+a_lo;s3[0][0]=s3[0][0]+a_hi+(lo2/4294967296>>>0)>>>0;s3[0][1]=lo2>>>0;lo2=s3[1][1]+b_lo;s3[1][0]=s3[1][0]+b_hi+(lo2/4294967296>>>0)>>>0;s3[1][1]=lo2>>>0;lo2=s3[2][1]+c_lo;s3[2][0]=s3[2][0]+c_hi+(lo2/4294967296>>>0)>>>0;s3[2][1]=lo2>>>0;lo2=s3[3][1]+d_lo;s3[3][0]=s3[3][0]+d_hi+(lo2/4294967296>>>0)>>>0;s3[3][1]=lo2>>>0;lo2=s3[4][1]+e_lo;s3[4][0]=s3[4][0]+e_hi+(lo2/4294967296>>>0)>>>0;s3[4][1]=lo2>>>0;lo2=s3[5][1]+f_lo;s3[5][0]=s3[5][0]+f_hi+(lo2/4294967296>>>0)>>>0;s3[5][1]=lo2>>>0;lo2=s3[6][1]+g_lo;s3[6][0]=s3[6][0]+g_hi+(lo2/4294967296>>>0)>>>0;s3[6][1]=lo2>>>0;lo2=s3[7][1]+h_lo;s3[7][0]=s3[7][0]+h_hi+(lo2/4294967296>>>0)>>>0;s3[7][1]=lo2>>>0;len-=128}}}});var require_asn1_validator=__commonJS({"node_modules/node-forge/lib/asn1-validator.js"(exports){"use strict";var forge2=require_forge();require_asn1();var asn1=forge2.asn1;exports.privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"privateKey"}]};exports.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"publicKeyOid"}]},{tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,composed:true,captureBitStringValue:"ed25519PublicKey"}]}}});var require_ed25519=__commonJS({"node_modules/node-forge/lib/ed25519.js"(exports,module){"use strict";var forge2=require_forge();require_jsbn();require_random();require_sha512();require_util7();var asn1Validator=require_asn1_validator();var publicKeyValidator=asn1Validator.publicKeyValidator;var privateKeyValidator=asn1Validator.privateKeyValidator;if(typeof BigInteger==="undefined"){BigInteger=forge2.jsbn.BigInteger}var BigInteger;var ByteBuffer=forge2.util.ByteBuffer;var NativeBuffer=typeof Buffer==="undefined"?Uint8Array:Buffer;forge2.pki=forge2.pki||{};module.exports=forge2.pki.ed25519=forge2.ed25519=forge2.ed25519||{};var ed25519=forge2.ed25519;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){options=options||{};var seed=options.seed;if(seed===void 0){seed=forge2.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH)}else if(typeof seed==="string"){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"});var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);var sk=new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i){sk[i]=seed[i]}crypto_sign_keypair(pk,sk);return{publicKey:pk,privateKey:sk}};ed25519.privateKeyFromAsn1=function(obj){var capture2={};var errors=[];var valid=forge2.asn1.validate(obj,privateKeyValidator,capture2,errors);if(!valid){var error=new Error("Invalid Key.");error.errors=errors;throw error}var oid=forge2.asn1.derToOid(capture2.privateKeyOid);var ed25519Oid=forge2.oids.EdDSA25519;if(oid!==ed25519Oid){throw new Error('Invalid OID "'+oid+'"; OID must be "'+ed25519Oid+'".')}var privateKey=capture2.privateKey;var privateKeyBytes=messageToNativeBuffer({message:forge2.asn1.fromDer(privateKey).value,encoding:"binary"});return{privateKeyBytes}};ed25519.publicKeyFromAsn1=function(obj){var capture2={};var errors=[];var valid=forge2.asn1.validate(obj,publicKeyValidator,capture2,errors);if(!valid){var error=new Error("Invalid Key.");error.errors=errors;throw error}var oid=forge2.asn1.derToOid(capture2.publicKeyOid);var ed25519Oid=forge2.oids.EdDSA25519;if(oid!==ed25519Oid){throw new Error('Invalid OID "'+oid+'"; OID must be "'+ed25519Oid+'".')}var publicKeyBytes=capture2.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){options=options||{};var privateKey=messageToNativeBuffer({message: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)}var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);for(var i=0;i<pk.length;++i){pk[i]=privateKey[32+i]}return pk};ed25519.sign=function(options){options=options||{};var msg=messageToNativeBuffer(options);var privateKey=messageToNativeBuffer({message:options.privateKey,encoding:"binary"});if(privateKey.length===ed25519.constants.SEED_BYTE_LENGTH){var keyPair=ed25519.generateKeyPair({seed:privateKey});privateKey=keyPair.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);crypto_sign(signedMsg,msg,msg.length,privateKey);var sig=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);for(var i=0;i<sig.length;++i){sig[i]=signedMsg[i]}return sig};ed25519.verify=function(options){options=options||{};var msg=messageToNativeBuffer(options);if(options.signature===void 0){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 sm=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH+msg.length);var m2=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH+msg.length);var i;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 crypto_sign_open(m2,sm,sm.length,publicKey)>=0};function messageToNativeBuffer(options){var message=options.message;if(message instanceof Uint8Array||message instanceof NativeBuffer){return message}var encoding=options.encoding;if(message===void 0){if(options.md){message=options.md.digest().getBytes();encoding="binary"}else{throw new TypeError('"options.message" or "options.md" not specified.')}}if(typeof message==="string"&&!encoding){throw new TypeError('"options.encoding" must be "binary" or "utf8".')}if(typeof message==="string"){if(typeof Buffer!=="undefined"){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.')}var buffer=new NativeBuffer(message.length());for(var i=0;i<buffer.length;++i){buffer[i]=message.at(i)}return buffer}var gf0=gf();var gf1=gf([1]);var D=gf([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]);var D2=gf([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]);var X2=gf([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]);var Y2=gf([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]);var L2=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]);var I2=gf([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function sha512(msg,msgLen){var md=forge2.md.sha512.create();var buffer=new ByteBuffer(msg);md.update(buffer.getBytes(msgLen),"binary");var hash=md.digest().getBytes();if(typeof Buffer!=="undefined"){return Buffer.from(hash,"binary")}var out=new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);for(var i=0;i<64;++i){out[i]=hash.charCodeAt(i)}return out}function crypto_sign_keypair(pk,sk){var p2=[gf(),gf(),gf(),gf()];var i;var d=sha512(sk,32);d[0]&=248;d[31]&=127;d[31]|=64;scalarbase(p2,d);pack(pk,p2);for(i=0;i<32;++i){sk[i+32]=pk[i]}return 0}function crypto_sign(sm,m2,n,sk){var i,j2,x=new Float64Array(64);var p2=[gf(),gf(),gf(),gf()];var 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]=m2[i]}for(i=0;i<32;++i){sm[32+i]=d[32+i]}var r=sha512(sm.subarray(32),n+32);reduce(r);scalarbase(p2,r);pack(sm,p2);for(i=32;i<64;++i){sm[i]=sk[i]}var h=sha512(sm,n+64);reduce(h);for(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(j2=0;j2<32;j2++){x[i+j2]+=h[i]*d[j2]}}modL(sm.subarray(32),x);return smlen}function crypto_sign_open(m2,sm,n,pk){var i,mlen;var t=new NativeBuffer(32);var p2=[gf(),gf(),gf(),gf()],q2=[gf(),gf(),gf(),gf()];mlen=-1;if(n<64){return-1}if(unpackneg(q2,pk)){return-1}if(!_isCanonicalSignatureScalar(sm,32)){return-1}for(i=0;i<n;++i){m2[i]=sm[i]}for(i=0;i<32;++i){m2[i+32]=pk[i]}var h=sha512(m2,n);reduce(h);scalarmult(p2,q2,h);scalarbase(q2,sm.subarray(32));add(p2,q2);pack(t,p2);n-=64;if(crypto_verify_32(sm,0,t,0)){for(i=0;i<n;++i){m2[i]=0}return-1}for(i=0;i<n;++i){m2[i]=sm[i+64]}mlen=n;return mlen}function _isCanonicalSignatureScalar(bytes,offset){var i;for(i=31;i>=0;--i){if(bytes[offset+i]<L2[i]){return true}if(bytes[offset+i]>L2[i]){return false}}return false}function modL(r,x){var carry,i,j2,k2;for(i=63;i>=32;--i){carry=0;for(j2=i-32,k2=i-12;j2<k2;++j2){x[j2]+=carry-16*x[i]*L2[j2-(i-32)];carry=x[j2]+128>>8;x[j2]-=carry*256}x[j2]+=carry;x[i]=0}carry=0;for(j2=0;j2<32;++j2){x[j2]+=carry-(x[31]>>4)*L2[j2];carry=x[j2]>>8;x[j2]&=255}for(j2=0;j2<32;++j2){x[j2]-=carry*L2[j2]}for(i=0;i<32;++i){x[i+1]+=x[i]>>8;r[i]=x[i]&255}}function reduce(r){var x=new Float64Array(64);for(var i=0;i<64;++i){x[i]=r[i];r[i]=0}modL(r,x)}function add(p2,q2){var a=gf(),b2=gf(),c=gf(),d=gf(),e=gf(),f2=gf(),g2=gf(),h=gf(),t=gf();Z2(a,p2[1],p2[0]);Z2(t,q2[1],q2[0]);M2(a,a,t);A2(b2,p2[0],p2[1]);A2(t,q2[0],q2[1]);M2(b2,b2,t);M2(c,p2[3],q2[3]);M2(c,c,D2);M2(d,p2[2],q2[2]);A2(d,d,d);Z2(e,b2,a);Z2(f2,d,c);A2(g2,d,c);A2(h,b2,a);M2(p2[0],e,f2);M2(p2[1],h,g2);M2(p2[2],g2,f2);M2(p2[3],e,h)}function cswap(p2,q2,b2){for(var i=0;i<4;++i){sel25519(p2[i],q2[i],b2)}}function pack(r,p2){var tx=gf(),ty=gf(),zi2=gf();inv25519(zi2,p2[2]);M2(tx,p2[0],zi2);M2(ty,p2[1],zi2);pack25519(r,ty);r[31]^=par25519(tx)<<7}function pack25519(o,n){var i,j2,b2;var m2=gf(),t=gf();for(i=0;i<16;++i){t[i]=n[i]}car25519(t);car25519(t);car25519(t);for(j2=0;j2<2;++j2){m2[0]=t[0]-65517;for(i=1;i<15;++i){m2[i]=t[i]-65535-(m2[i-1]>>16&1);m2[i-1]&=65535}m2[15]=t[15]-32767-(m2[14]>>16&1);b2=m2[15]>>16&1;m2[14]&=65535;sel25519(t,m2,1-b2)}for(i=0;i<16;i++){o[2*i]=t[i]&255;o[2*i+1]=t[i]>>8}}function unpackneg(r,p2){var t=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r[2],gf1);unpack25519(r[1],p2);S2(num,r[1]);M2(den,num,D);Z2(num,num,r[2]);A2(den,r[2],den);S2(den2,den);S2(den4,den2);M2(den6,den4,den2);M2(t,den6,num);M2(t,t,den);pow2523(t,t);M2(t,t,num);M2(t,t,den);M2(t,t,den);M2(r[0],t,den);S2(chk,r[0]);M2(chk,chk,den);if(neq25519(chk,num)){M2(r[0],r[0],I2)}S2(chk,r[0]);M2(chk,chk,den);if(neq25519(chk,num)){return-1}if(par25519(r[0])===p2[31]>>7){Z2(r[0],gf0,r[0])}M2(r[3],r[0],r[1]);return 0}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}function pow2523(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=250;a>=0;--a){S2(c,c);if(a!==1){M2(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function neq25519(a,b2){var c=new NativeBuffer(32);var d=new NativeBuffer(32);pack25519(c,a);pack25519(d,b2);return crypto_verify_32(c,0,d,0)}function crypto_verify_32(x,xi2,y,yi2){return vn2(x,xi2,y,yi2,32)}function vn2(x,xi2,y,yi2,n){var i,d=0;for(i=0;i<n;++i){d|=x[xi2+i]^y[yi2+i]}return(1&d-1>>>8)-1}function par25519(a){var d=new NativeBuffer(32);pack25519(d,a);return d[0]&1}function scalarmult(p2,q2,s3){var b2,i;set25519(p2[0],gf0);set25519(p2[1],gf1);set25519(p2[2],gf1);set25519(p2[3],gf0);for(i=255;i>=0;--i){b2=s3[i/8|0]>>(i&7)&1;cswap(p2,q2,b2);add(q2,p2);add(p2,p2);cswap(p2,q2,b2)}}function scalarbase(p2,s3){var q2=[gf(),gf(),gf(),gf()];set25519(q2[0],X2);set25519(q2[1],Y2);set25519(q2[2],gf1);M2(q2[3],X2,Y2);scalarmult(p2,q2,s3)}function set25519(r,a){var i;for(i=0;i<16;i++){r[i]=a[i]|0}}function inv25519(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=253;a>=0;--a){S2(c,c);if(a!==2&&a!==4){M2(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function car25519(o){var i,v2,c=1;for(i=0;i<16;++i){v2=o[i]+c+65535;c=Math.floor(v2/65536);o[i]=v2-c*65536}o[0]+=c-1+37*(c-1)}function sel25519(p2,q2,b2){var t,c=~(b2-1);for(var i=0;i<16;++i){t=c&(p2[i]^q2[i]);p2[i]^=t;q2[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 A2(o,a,b2){for(var i=0;i<16;++i){o[i]=a[i]+b2[i]}}function Z2(o,a,b2){for(var i=0;i<16;++i){o[i]=a[i]-b2[i]}}function S2(o,a){M2(o,a,a)}function M2(o,a,b2){var v2,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=b2[0],b1=b2[1],b22=b2[2],b3=b2[3],b4=b2[4],b5=b2[5],b6=b2[6],b7=b2[7],b8=b2[8],b9=b2[9],b10=b2[10],b11=b2[11],b12=b2[12],b13=b2[13],b14=b2[14],b15=b2[15];v2=a[0];t0+=v2*b0;t1+=v2*b1;t2+=v2*b22;t3+=v2*b3;t4+=v2*b4;t5+=v2*b5;t6+=v2*b6;t7+=v2*b7;t8+=v2*b8;t9+=v2*b9;t10+=v2*b10;t11+=v2*b11;t12+=v2*b12;t13+=v2*b13;t14+=v2*b14;t15+=v2*b15;v2=a[1];t1+=v2*b0;t2+=v2*b1;t3+=v2*b22;t4+=v2*b3;t5+=v2*b4;t6+=v2*b5;t7+=v2*b6;t8+=v2*b7;t9+=v2*b8;t10+=v2*b9;t11+=v2*b10;t12+=v2*b11;t13+=v2*b12;t14+=v2*b13;t15+=v2*b14;t16+=v2*b15;v2=a[2];t2+=v2*b0;t3+=v2*b1;t4+=v2*b22;t5+=v2*b3;t6+=v2*b4;t7+=v2*b5;t8+=v2*b6;t9+=v2*b7;t10+=v2*b8;t11+=v2*b9;t12+=v2*b10;t13+=v2*b11;t14+=v2*b12;t15+=v2*b13;t16+=v2*b14;t17+=v2*b15;v2=a[3];t3+=v2*b0;t4+=v2*b1;t5+=v2*b22;t6+=v2*b3;t7+=v2*b4;t8+=v2*b5;t9+=v2*b6;t10+=v2*b7;t11+=v2*b8;t12+=v2*b9;t13+=v2*b10;t14+=v2*b11;t15+=v2*b12;t16+=v2*b13;t17+=v2*b14;t18+=v2*b15;v2=a[4];t4+=v2*b0;t5+=v2*b1;t6+=v2*b22;t7+=v2*b3;t8+=v2*b4;t9+=v2*b5;t10+=v2*b6;t11+=v2*b7;t12+=v2*b8;t13+=v2*b9;t14+=v2*b10;t15+=v2*b11;t16+=v2*b12;t17+=v2*b13;t18+=v2*b14;t19+=v2*b15;v2=a[5];t5+=v2*b0;t6+=v2*b1;t7+=v2*b22;t8+=v2*b3;t9+=v2*b4;t10+=v2*b5;t11+=v2*b6;t12+=v2*b7;t13+=v2*b8;t14+=v2*b9;t15+=v2*b10;t16+=v2*b11;t17+=v2*b12;t18+=v2*b13;t19+=v2*b14;t20+=v2*b15;v2=a[6];t6+=v2*b0;t7+=v2*b1;t8+=v2*b22;t9+=v2*b3;t10+=v2*b4;t11+=v2*b5;t12+=v2*b6;t13+=v2*b7;t14+=v2*b8;t15+=v2*b9;t16+=v2*b10;t17+=v2*b11;t18+=v2*b12;t19+=v2*b13;t20+=v2*b14;t21+=v2*b15;v2=a[7];t7+=v2*b0;t8+=v2*b1;t9+=v2*b22;t10+=v2*b3;t11+=v2*b4;t12+=v2*b5;t13+=v2*b6;t14+=v2*b7;t15+=v2*b8;t16+=v2*b9;t17+=v2*b10;t18+=v2*b11;t19+=v2*b12;t20+=v2*b13;t21+=v2*b14;t22+=v2*b15;v2=a[8];t8+=v2*b0;t9+=v2*b1;t10+=v2*b22;t11+=v2*b3;t12+=v2*b4;t13+=v2*b5;t14+=v2*b6;t15+=v2*b7;t16+=v2*b8;t17+=v2*b9;t18+=v2*b10;t19+=v2*b11;t20+=v2*b12;t21+=v2*b13;t22+=v2*b14;t23+=v2*b15;v2=a[9];t9+=v2*b0;t10+=v2*b1;t11+=v2*b22;t12+=v2*b3;t13+=v2*b4;t14+=v2*b5;t15+=v2*b6;t16+=v2*b7;t17+=v2*b8;t18+=v2*b9;t19+=v2*b10;t20+=v2*b11;t21+=v2*b12;t22+=v2*b13;t23+=v2*b14;t24+=v2*b15;v2=a[10];t10+=v2*b0;t11+=v2*b1;t12+=v2*b22;t13+=v2*b3;t14+=v2*b4;t15+=v2*b5;t16+=v2*b6;t17+=v2*b7;t18+=v2*b8;t19+=v2*b9;t20+=v2*b10;t21+=v2*b11;t22+=v2*b12;t23+=v2*b13;t24+=v2*b14;t25+=v2*b15;v2=a[11];t11+=v2*b0;t12+=v2*b1;t13+=v2*b22;t14+=v2*b3;t15+=v2*b4;t16+=v2*b5;t17+=v2*b6;t18+=v2*b7;t19+=v2*b8;t20+=v2*b9;t21+=v2*b10;t22+=v2*b11;t23+=v2*b12;t24+=v2*b13;t25+=v2*b14;t26+=v2*b15;v2=a[12];t12+=v2*b0;t13+=v2*b1;t14+=v2*b22;t15+=v2*b3;t16+=v2*b4;t17+=v2*b5;t18+=v2*b6;t19+=v2*b7;t20+=v2*b8;t21+=v2*b9;t22+=v2*b10;t23+=v2*b11;t24+=v2*b12;t25+=v2*b13;t26+=v2*b14;t27+=v2*b15;v2=a[13];t13+=v2*b0;t14+=v2*b1;t15+=v2*b22;t16+=v2*b3;t17+=v2*b4;t18+=v2*b5;t19+=v2*b6;t20+=v2*b7;t21+=v2*b8;t22+=v2*b9;t23+=v2*b10;t24+=v2*b11;t25+=v2*b12;t26+=v2*b13;t27+=v2*b14;t28+=v2*b15;v2=a[14];t14+=v2*b0;t15+=v2*b1;t16+=v2*b22;t17+=v2*b3;t18+=v2*b4;t19+=v2*b5;t20+=v2*b6;t21+=v2*b7;t22+=v2*b8;t23+=v2*b9;t24+=v2*b10;t25+=v2*b11;t26+=v2*b12;t27+=v2*b13;t28+=v2*b14;t29+=v2*b15;v2=a[15];t15+=v2*b0;t16+=v2*b1;t17+=v2*b22;t18+=v2*b3;t19+=v2*b4;t20+=v2*b5;t21+=v2*b6;t22+=v2*b7;t23+=v2*b8;t24+=v2*b9;t25+=v2*b10;t26+=v2*b11;t27+=v2*b12;t28+=v2*b13;t29+=v2*b14;t30+=v2*b15;t0+=38*t16;t1+=38*t17;t2+=38*t18;t3+=38*t19;t4+=38*t20;t5+=38*t21;t6+=38*t22;t7+=38*t23;t8+=38*t24;t9+=38*t25;t10+=38*t26;t11+=38*t27;t12+=38*t28;t13+=38*t29;t14+=38*t30;c=1;v2=t0+c+65535;c=Math.floor(v2/65536);t0=v2-c*65536;v2=t1+c+65535;c=Math.floor(v2/65536);t1=v2-c*65536;v2=t2+c+65535;c=Math.floor(v2/65536);t2=v2-c*65536;v2=t3+c+65535;c=Math.floor(v2/65536);t3=v2-c*65536;v2=t4+c+65535;c=Math.floor(v2/65536);t4=v2-c*65536;v2=t5+c+65535;c=Math.floor(v2/65536);t5=v2-c*65536;v2=t6+c+65535;c=Math.floor(v2/65536);t6=v2-c*65536;v2=t7+c+65535;c=Math.floor(v2/65536);t7=v2-c*65536;v2=t8+c+65535;c=Math.floor(v2/65536);t8=v2-c*65536;v2=t9+c+65535;c=Math.floor(v2/65536);t9=v2-c*65536;v2=t10+c+65535;c=Math.floor(v2/65536);t10=v2-c*65536;v2=t11+c+65535;c=Math.floor(v2/65536);t11=v2-c*65536;v2=t12+c+65535;c=Math.floor(v2/65536);t12=v2-c*65536;v2=t13+c+65535;c=Math.floor(v2/65536);t13=v2-c*65536;v2=t14+c+65535;c=Math.floor(v2/65536);t14=v2-c*65536;v2=t15+c+65535;c=Math.floor(v2/65536);t15=v2-c*65536;t0+=c-1+37*(c-1);c=1;v2=t0+c+65535;c=Math.floor(v2/65536);t0=v2-c*65536;v2=t1+c+65535;c=Math.floor(v2/65536);t1=v2-c*65536;v2=t2+c+65535;c=Math.floor(v2/65536);t2=v2-c*65536;v2=t3+c+65535;c=Math.floor(v2/65536);t3=v2-c*65536;v2=t4+c+65535;c=Math.floor(v2/65536);t4=v2-c*65536;v2=t5+c+65535;c=Math.floor(v2/65536);t5=v2-c*65536;v2=t6+c+65535;c=Math.floor(v2/65536);t6=v2-c*65536;v2=t7+c+65535;c=Math.floor(v2/65536);t7=v2-c*65536;v2=t8+c+65535;c=Math.floor(v2/65536);t8=v2-c*65536;v2=t9+c+65535;c=Math.floor(v2/65536);t9=v2-c*65536;v2=t10+c+65535;c=Math.floor(v2/65536);t10=v2-c*65536;v2=t11+c+65535;c=Math.floor(v2/65536);t11=v2-c*65536;v2=t12+c+65535;c=Math.floor(v2/65536);t12=v2-c*65536;v2=t13+c+65535;c=Math.floor(v2/65536);t13=v2-c*65536;v2=t14+c+65535;c=Math.floor(v2/65536);t14=v2-c*65536;v2=t15+c+65535;c=Math.floor(v2/65536);t15=v2-c*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}}});var require_kem=__commonJS({"node_modules/node-forge/lib/kem.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_random();require_jsbn();module.exports=forge2.kem=forge2.kem||{};var BigInteger=forge2.jsbn.BigInteger;forge2.kem.rsa={};forge2.kem.rsa.create=function(kdf,options){options=options||{};var prng=options.prng||forge2.random;var kem={};kem.encrypt=function(publicKey,keyLength){var byteLength=Math.ceil(publicKey.n.bitLength()/8);var r;do{r=new BigInteger(forge2.util.bytesToHex(prng.getBytesSync(byteLength)),16).mod(publicKey.n)}while(r.compareTo(BigInteger.ONE)<=0);r=forge2.util.hexToBytes(r.toString(16));var zeros=byteLength-r.length;if(zeros>0){r=forge2.util.fillString(String.fromCharCode(0),zeros)+r}var encapsulation=publicKey.encrypt(r,"NONE");var key=kdf.generate(r,keyLength);return{encapsulation,key}};kem.decrypt=function(privateKey,encapsulation,keyLength){var r=privateKey.decrypt(encapsulation,"NONE");return kdf.generate(r,keyLength)};return kem};forge2.kem.kdf1=function(md,digestLength){_createKDF(this,md,0,digestLength||md.digestLength)};forge2.kem.kdf2=function(md,digestLength){_createKDF(this,md,1,digestLength||md.digestLength)};function _createKDF(kdf,md,counterStart,digestLength){kdf.generate=function(x,length){var key=new forge2.util.ByteBuffer;var k2=Math.ceil(length/digestLength)+counterStart;var c=new forge2.util.ByteBuffer;for(var i=counterStart;i<k2;++i){c.putInt32(i);md.start();md.update(x+c.getBytes());var hash=md.digest();key.putBytes(hash.getBytes(digestLength))}key.truncate(key.length()-length);return key.getBytes()}}}});var require_log=__commonJS({"node_modules/node-forge/lib/log.js"(exports,module){"use strict";var forge2=require_forge();require_util7();module.exports=forge2.log=forge2.log||{};forge2.log.levels=["none","error","warning","info","debug","verbose","max"];var sLevelInfo={};var sLoggers=[];var sConsoleLogger=null;forge2.log.LEVEL_LOCKED=1<<1;forge2.log.NO_LEVEL_CHECK=1<<2;forge2.log.INTERPOLATE=1<<3;for(i=0;i<forge2.log.levels.length;++i){level=forge2.log.levels[i];sLevelInfo[level]={index:i,name:level.toUpperCase()}}var level;var i;forge2.log.logMessage=function(message){var messageLevelIndex=sLevelInfo[message.level].index;for(var i2=0;i2<sLoggers.length;++i2){var logger2=sLoggers[i2];if(logger2.flags&forge2.log.NO_LEVEL_CHECK){logger2.f(message)}else{var loggerLevelIndex=sLevelInfo[logger2.level].index;if(messageLevelIndex<=loggerLevelIndex){logger2.f(logger2,message)}}}};forge2.log.prepareStandard=function(message){if(!("standard"in message)){message.standard=sLevelInfo[message.level].name+" ["+message.category+"] "+message.message}};forge2.log.prepareFull=function(message){if(!("full"in message)){var args=[message.message];args=args.concat([]);message.full=forge2.util.format.apply(this,args)}};forge2.log.prepareStandardFull=function(message){if(!("standardFull"in message)){forge2.log.prepareStandard(message);message.standardFull=message.standard}};if(true){levels=["error","warning","info","debug","verbose"];for(i=0;i<levels.length;++i){(function(level2){forge2.log[level2]=function(category,message){var args=Array.prototype.slice.call(arguments).slice(2);var msg={timestamp:new Date,level:level2,category,message,"arguments":args};forge2.log.logMessage(msg)}})(levels[i])}}var levels;var i;forge2.log.makeLogger=function(logFunction){var logger2={flags:0,f:logFunction};forge2.log.setLevel(logger2,"none");return logger2};forge2.log.setLevel=function(logger2,level2){var rval=false;if(logger2&&!(logger2.flags&forge2.log.LEVEL_LOCKED)){for(var i2=0;i2<forge2.log.levels.length;++i2){var aValidLevel=forge2.log.levels[i2];if(level2==aValidLevel){logger2.level=level2;rval=true;break}}}return rval};forge2.log.lock=function(logger2,lock2){if(typeof lock2==="undefined"||lock2){logger2.flags|=forge2.log.LEVEL_LOCKED}else{logger2.flags&=~forge2.log.LEVEL_LOCKED}};forge2.log.addLogger=function(logger2){sLoggers.push(logger2)};if(typeof console!=="undefined"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug){levelHandlers={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug};f2=function(logger2,message){forge2.log.prepareStandard(message);var handler=levelHandlers[message.level];var args=[message.standard];args=args.concat(message["arguments"].slice());handler.apply(console,args)};logger=forge2.log.makeLogger(f2)}else{f2=function(logger2,message){forge2.log.prepareStandardFull(message);console.log(message.standardFull)};logger=forge2.log.makeLogger(f2)}forge2.log.setLevel(logger,"debug");forge2.log.addLogger(logger);sConsoleLogger=logger}else{console={log:function(){}}}var logger;var levelHandlers;var f2;if(sConsoleLogger!==null&&typeof window!=="undefined"&&window.location){query=new URL(window.location.href).searchParams;if(query.has("console.level")){forge2.log.setLevel(sConsoleLogger,query.get("console.level").slice(-1)[0])}if(query.has("console.lock")){lock=query.get("console.lock").slice(-1)[0];if(lock=="true"){forge2.log.lock(sConsoleLogger)}}}var query;var lock;forge2.log.consoleLogger=sConsoleLogger}});var require_md_all=__commonJS({"node_modules/node-forge/lib/md.all.js"(exports,module){"use strict";module.exports=require_md();require_md5();require_sha1();require_sha256();require_sha512()}});var require_pkcs7=__commonJS({"node_modules/node-forge/lib/pkcs7.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_asn1();require_des();require_oids();require_pem();require_pkcs7asn1();require_random();require_util7();require_x509();var asn1=forge2.asn1;var p7=module.exports=forge2.pkcs7=forge2.pkcs7||{};p7.messageFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="PKCS7"){var error=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(pemObj,{maxline})};p7.messageFromAsn1=function(obj){var capture2={};var errors=[];if(!asn1.validate(obj,p7.asn1.contentInfoValidator,capture2,errors)){var error=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");error.errors=errors;throw error}var contentType=asn1.derToOid(capture2.contentType);var msg;switch(contentType){case forge2.pki.oids.envelopedData:msg=p7.createEnvelopedData();break;case forge2.pki.oids.encryptedData:msg=p7.createEncryptedData();break;case forge2.pki.oids.signedData:msg=p7.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+contentType+" is not (yet) supported.")}msg.fromAsn1(capture2.content.value[0]);return msg};p7.createSignedData=function(){var msg=null;msg={type:forge2.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(obj){_fromAsn1(msg,obj,p7.asn1.signedDataValidator);msg.certificates=[];msg.crls=[];msg.digestAlgorithmIdentifiers=[];msg.contentInfo=null;msg.signerInfos=[];if(msg.rawCapture.certificates){var certs=msg.rawCapture.certificates.value;for(var i=0;i<certs.length;++i){msg.certificates.push(forge2.pki.certificateFromAsn1(certs[i]))}}},toAsn1:function(){if(!msg.contentInfo){msg.sign()}var certs=[];for(var i=0;i<msg.certificates.length;++i){certs.push(forge2.pki.certificateToAsn1(msg.certificates[i]))}var crls=[];var signedData=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(msg.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,msg.digestAlgorithmIdentifiers),msg.contentInfo])]);if(certs.length>0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,certs))}if(crls.length>0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,crls))}signedData.value[0].value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,msg.signerInfos));return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(msg.type).getBytes()),signedData])},addSigner:function(signer){var issuer=signer.issuer;var serialNumber=signer.serialNumber;if(signer.certificate){var cert=signer.certificate;if(typeof cert==="string"){cert=forge2.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.")}if(typeof key==="string"){key=forge2.pki.privateKeyFromPem(key)}var digestAlgorithm=signer.digestAlgorithm||forge2.pki.oids.sha1;switch(digestAlgorithm){case forge2.pki.oids.sha1:case forge2.pki.oids.sha256:case forge2.pki.oids.sha384:case forge2.pki.oids.sha512:case forge2.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){var contentType=false;var messageDigest=false;for(var i=0;i<authenticatedAttributes.length;++i){var attr=authenticatedAttributes[i];if(!contentType&&attr.type===forge2.pki.oids.contentType){contentType=true;if(messageDigest){break}continue}if(!messageDigest&&attr.type===forge2.pki.oids.messageDigest){messageDigest=true;if(contentType){break}continue}}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,version:1,issuer,serialNumber,digestAlgorithm,signatureAlgorithm:forge2.pki.oids.rsaEncryption,signature:null,authenticatedAttributes,unauthenticatedAttributes:[]})},sign:function(options){options=options||{};if(typeof msg.content!=="object"||msg.contentInfo===null){msg.contentInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(forge2.pki.oids.data).getBytes())]);if("content"in msg){var content;if(msg.content instanceof forge2.util.ByteBuffer){content=msg.content.bytes()}else if(typeof msg.content==="string"){content=forge2.util.encodeUtf8(msg.content)}if(options.detached){msg.detachedContent=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,content)}else{msg.contentInfo.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,content)]))}}}if(msg.signers.length===0){return}var mds=addDigestAlgorithmIds();addSignerInfos(mds)},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(cert){if(typeof cert==="string"){cert=forge2.pki.certificateFromPem(cert)}msg.certificates.push(cert)},addCertificateRevokationList:function(crl){throw new Error("PKCS#7 CRL support not yet implemented.")}};return msg;function addDigestAlgorithmIds(){var mds={};for(var i=0;i<msg.signers.length;++i){var signer=msg.signers[i];var oid=signer.digestAlgorithm;if(!(oid in mds)){mds[oid]=forge2.md[forge2.pki.oids[oid]].create()}if(signer.authenticatedAttributes.length===0){signer.md=mds[oid]}else{signer.md=forge2.md[forge2.pki.oids[oid]].create()}}msg.digestAlgorithmIdentifiers=[];for(var oid in mds){msg.digestAlgorithmIdentifiers.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]))}return mds}function addSignerInfos(mds){var content;if(msg.detachedContent){content=msg.detachedContent}else{content=msg.contentInfo.value[1];content=content.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);var bytes=asn1.toDer(content);bytes.getByte();asn1.getBerValueLength(bytes);bytes=bytes.getBytes();for(var oid in mds){mds[oid].start().update(bytes)}var signingTime=new Date;for(var i=0;i<msg.signers.length;++i){var signer=msg.signers[i];if(signer.authenticatedAttributes.length===0){if(contentType!==forge2.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,true,[]);var attrsAsn1=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[]);for(var ai2=0;ai2<signer.authenticatedAttributes.length;++ai2){var attr=signer.authenticatedAttributes[ai2];if(attr.type===forge2.pki.oids.messageDigest){attr.value=mds[signer.digestAlgorithm].digest()}else if(attr.type===forge2.pki.oids.signingTime){if(!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=_signersToAsn1(msg.signers)}};p7.createEncryptedData=function(){var msg=null;msg={type:forge2.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:forge2.pki.oids["aes256-CBC"]},fromAsn1:function(obj){_fromAsn1(msg,obj,p7.asn1.encryptedDataValidator)},decrypt:function(key){if(key!==void 0){msg.encryptedContent.key=key}_decryptContent(msg)}};return msg};p7.createEnvelopedData=function(){var msg=null;msg={type:forge2.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:forge2.pki.oids["aes256-CBC"]},fromAsn1:function(obj){var capture2=_fromAsn1(msg,obj,p7.asn1.envelopedDataValidator);msg.recipients=_recipientsFromAsn1(capture2.recipientInfos.value)},toAsn1:function(){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(msg.type).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(msg.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,_recipientsToAsn1(msg.recipients)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,_encryptedContentToAsn1(msg.encryptedContent))])])])},findRecipient:function(cert){var sAttr=cert.issuer.attributes;for(var i=0;i<msg.recipients.length;++i){var r=msg.recipients[i];var rAttr=r.issuer;if(r.serialNumber!==cert.serialNumber){continue}if(rAttr.length!==sAttr.length){continue}var match=true;for(var j2=0;j2<sAttr.length;++j2){if(rAttr[j2].type!==sAttr[j2].type||rAttr[j2].value!==sAttr[j2].value){match=false;break}}if(match){return r}}return null},decrypt:function(recipient,privKey){if(msg.encryptedContent.key===void 0&&recipient!==void 0&&privKey!==void 0){switch(recipient.encryptedContent.algorithm){case forge2.pki.oids.rsaEncryption:case forge2.pki.oids.desCBC:var key=privKey.decrypt(recipient.encryptedContent.content);msg.encryptedContent.key=forge2.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:forge2.pki.oids.rsaEncryption,key:cert.publicKey}})},encrypt:function(key,cipher){if(msg.encryptedContent.content===void 0){cipher=cipher||msg.encryptedContent.algorithm;key=key||msg.encryptedContent.key;var keyLen,ivLen,ciphFn;switch(cipher){case forge2.pki.oids["aes128-CBC"]:keyLen=16;ivLen=16;ciphFn=forge2.aes.createEncryptionCipher;break;case forge2.pki.oids["aes192-CBC"]:keyLen=24;ivLen=16;ciphFn=forge2.aes.createEncryptionCipher;break;case forge2.pki.oids["aes256-CBC"]:keyLen=32;ivLen=16;ciphFn=forge2.aes.createEncryptionCipher;break;case forge2.pki.oids["des-EDE3-CBC"]:keyLen=24;ivLen=8;ciphFn=forge2.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+cipher)}if(key===void 0){key=forge2.util.createBuffer(forge2.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=forge2.util.createBuffer(forge2.random.getBytes(ivLen));var ciph=ciphFn(key);ciph.start(msg.encryptedContent.parameter.copy());ciph.update(msg.content);if(!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(recipient.encryptedContent.content!==void 0){continue}switch(recipient.encryptedContent.algorithm){case forge2.pki.oids.rsaEncryption:recipient.encryptedContent.content=recipient.encryptedContent.key.encrypt(msg.encryptedContent.key.data);break;default:throw new Error("Unsupported asymmetric cipher, OID "+recipient.encryptedContent.algorithm)}}}};return msg};function _recipientFromAsn1(obj){var capture2={};var errors=[];if(!asn1.validate(obj,p7.asn1.recipientInfoValidator,capture2,errors)){var error=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");error.errors=errors;throw error}return{version:capture2.version.charCodeAt(0),issuer:forge2.pki.RDNAttributesAsArray(capture2.issuer),serialNumber:forge2.util.createBuffer(capture2.serial).toHex(),encryptedContent:{algorithm:asn1.derToOid(capture2.encAlgorithm),parameter:capture2.encParameter?capture2.encParameter.value:void 0,content:capture2.encKey}}}function _recipientToAsn1(obj){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(obj.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[forge2.pki.distinguishedNameToAsn1({attributes:obj.issuer}),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(obj.serialNumber))]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,obj.encryptedContent.content)])}function _recipientsFromAsn1(infos){var ret=[];for(var i=0;i<infos.length;++i){ret.push(_recipientFromAsn1(infos[i]))}return ret}function _recipientsToAsn1(recipients){var ret=[];for(var 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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(obj.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[forge2.pki.distinguishedNameToAsn1({attributes:obj.issuer}),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(obj.serialNumber))]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(obj.digestAlgorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")])]);if(obj.authenticatedAttributesAsn1){rval.value.push(obj.authenticatedAttributesAsn1)}rval.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(obj.signatureAlgorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]));rval.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,obj.signature));if(obj.unauthenticatedAttributes.length>0){var attrsAsn1=asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[]);for(var i=0;i<obj.unauthenticatedAttributes.length;++i){var attr=obj.unauthenticatedAttributes[i];attrsAsn1.values.push(_attributeToAsn1(attr))}rval.value.push(attrsAsn1)}return rval}function _signersToAsn1(signers){var ret=[];for(var i=0;i<signers.length;++i){ret.push(_signerToAsn1(signers[i]))}return ret}function _attributeToAsn1(attr){var value;if(attr.type===forge2.pki.oids.contentType){value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.value).getBytes())}else if(attr.type===forge2.pki.oids.messageDigest){value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,attr.value.bytes())}else if(attr.type===forge2.pki.oids.signingTime){var jan_1_1950=new Date("1950-01-01T00:00:00Z");var jan_1_2050=new Date("2050-01-01T00:00:00Z");var date=attr.value;if(typeof date==="string"){var timestamp=Date.parse(date);if(!isNaN(timestamp)){date=new Date(timestamp)}else if(date.length===13){date=asn1.utcTimeToDate(date)}else{date=asn1.generalizedTimeToDate(date)}}if(date>=jan_1_1950&&date<jan_1_2050){value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.UTCTIME,false,asn1.dateToUtcTime(date))}else{value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.GENERALIZEDTIME,false,asn1.dateToGeneralizedTime(date))}}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[value])])}function _encryptedContentToAsn1(ec){return[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(forge2.pki.oids.data).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(ec.algorithm).getBytes()),!ec.parameter?void 0:asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ec.parameter.getBytes())]),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ec.content.getBytes())])]}function _fromAsn1(msg,obj,validator){var capture2={};var errors=[];if(!asn1.validate(obj,validator,capture2,errors)){var error=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");error.errors=error;throw error}var contentType=asn1.derToOid(capture2.contentType);if(contentType!==forge2.pki.oids.data){throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.")}if(capture2.encryptedContent){var content="";if(forge2.util.isArray(capture2.encryptedContent)){for(var i=0;i<capture2.encryptedContent.length;++i){if(capture2.encryptedContent[i].type!==asn1.Type.OCTETSTRING){throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.")}content+=capture2.encryptedContent[i].value}}else{content=capture2.encryptedContent}msg.encryptedContent={algorithm:asn1.derToOid(capture2.encAlgorithm),parameter:forge2.util.createBuffer(capture2.encParameter.value),content:forge2.util.createBuffer(content)}}if(capture2.content){var content="";if(forge2.util.isArray(capture2.content)){for(var i=0;i<capture2.content.length;++i){if(capture2.content[i].type!==asn1.Type.OCTETSTRING){throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.")}content+=capture2.content[i].value}}else{content=capture2.content}msg.content=forge2.util.createBuffer(content)}msg.version=capture2.version.charCodeAt(0);msg.rawCapture=capture2;return capture2}function _decryptContent(msg){if(msg.encryptedContent.key===void 0){throw new Error("Symmetric key not available.")}if(msg.content===void 0){var ciph;switch(msg.encryptedContent.algorithm){case forge2.pki.oids["aes128-CBC"]:case forge2.pki.oids["aes192-CBC"]:case forge2.pki.oids["aes256-CBC"]:ciph=forge2.aes.createDecryptionCipher(msg.encryptedContent.key);break;case forge2.pki.oids["desCBC"]:case forge2.pki.oids["des-EDE3-CBC"]:ciph=forge2.des.createDecryptionCipher(msg.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+msg.encryptedContent.algorithm)}ciph.start(msg.encryptedContent.parameter);ciph.update(msg.encryptedContent.content);if(!ciph.finish()){throw new Error("Symmetric decryption failed.")}msg.content=ciph.output}}}});var require_ssh=__commonJS({"node_modules/node-forge/lib/ssh.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_hmac();require_md5();require_sha1();require_util7();var ssh=module.exports=forge2.ssh=forge2.ssh||{};ssh.privateKeyToPutty=function(privateKey,passphrase,comment){comment=comment||"";passphrase=passphrase||"";var algorithm="ssh-rsa";var encryptionAlgorithm=passphrase===""?"none":"aes256-cbc";var ppk="PuTTY-User-Key-File-2: "+algorithm+"\r\n";ppk+="Encryption: "+encryptionAlgorithm+"\r\n";ppk+="Comment: "+comment+"\r\n";var pubbuffer=forge2.util.createBuffer();_addStringToBuffer(pubbuffer,algorithm);_addBigIntegerToBuffer(pubbuffer,privateKey.e);_addBigIntegerToBuffer(pubbuffer,privateKey.n);var pub=forge2.util.encode64(pubbuffer.bytes(),64);var length=Math.floor(pub.length/66)+1;ppk+="Public-Lines: "+length+"\r\n";ppk+=pub;var privbuffer=forge2.util.createBuffer();_addBigIntegerToBuffer(privbuffer,privateKey.d);_addBigIntegerToBuffer(privbuffer,privateKey.p);_addBigIntegerToBuffer(privbuffer,privateKey.q);_addBigIntegerToBuffer(privbuffer,privateKey.qInv);var priv;if(!passphrase){priv=forge2.util.encode64(privbuffer.bytes(),64)}else{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=forge2.util.createBuffer();aeskey.putBuffer(_sha1("\0\0\0\0",passphrase));aeskey.putBuffer(_sha1("\0\0\0",passphrase));var cipher=forge2.aes.createEncryptionCipher(aeskey.truncate(8),"CBC");cipher.start(forge2.util.createBuffer().fillWithByte(0,16));cipher.update(privbuffer.copy());cipher.finish();var encrypted=cipher.output;encrypted.truncate(16);priv=forge2.util.encode64(encrypted.bytes(),64)}length=Math.floor(priv.length/66)+1;ppk+="\r\nPrivate-Lines: "+length+"\r\n";ppk+=priv;var mackey=_sha1("putty-private-key-file-mac-key",passphrase);var macbuffer=forge2.util.createBuffer();_addStringToBuffer(macbuffer,algorithm);_addStringToBuffer(macbuffer,encryptionAlgorithm);_addStringToBuffer(macbuffer,comment);macbuffer.putInt32(pubbuffer.length());macbuffer.putBuffer(pubbuffer);macbuffer.putInt32(privbuffer.length());macbuffer.putBuffer(privbuffer);var hmac=forge2.hmac.create();hmac.start("sha1",mackey);hmac.update(macbuffer.bytes());ppk+="\r\nPrivate-MAC: "+hmac.digest().toHex()+"\r\n";return ppk};ssh.publicKeyToOpenSSH=function(key,comment){var type="ssh-rsa";comment=comment||"";var buffer=forge2.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);return type+" "+forge2.util.encode64(buffer.bytes())+" "+comment};ssh.privateKeyToOpenSSH=function(privateKey,passphrase){if(!passphrase){return forge2.pki.privateKeyToPem(privateKey)}return forge2.pki.encryptRsaPrivateKey(privateKey,passphrase,{legacy:true,algorithm:"aes128"})};ssh.getPublicKeyFingerprint=function(key,options){options=options||{};var md=options.md||forge2.md.md5.create();var type="ssh-rsa";var buffer=forge2.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);md.start();md.update(buffer.getBytes());var digest=md.digest();if(options.encoding==="hex"){var hex=digest.toHex();if(options.delimiter){return hex.match(/.{2}/g).join(options.delimiter)}return hex}else if(options.encoding==="binary"){return digest.getBytes()}else if(options.encoding){throw new Error('Unknown encoding "'+options.encoding+'".')}return digest};function _addBigIntegerToBuffer(buffer,val){var hexVal=val.toString(16);if(hexVal[0]>="8"){hexVal="00"+hexVal}var bytes=forge2.util.hexToBytes(hexVal);buffer.putInt32(bytes.length);buffer.putBytes(bytes)}function _addStringToBuffer(buffer,val){buffer.putInt32(val.length);buffer.putString(val)}function _sha1(){var sha=forge2.md.sha1.create();var num=arguments.length;for(var i=0;i<num;++i){sha.update(arguments[i])}return sha.digest()}}});var require_lib=__commonJS({"node_modules/node-forge/lib/index.js"(exports,module){"use strict";module.exports=require_forge();require_aes();require_aesCipherSuites();require_asn1();require_cipher();require_des();require_ed25519();require_hmac();require_kem();require_log();require_md_all();require_mgf1();require_pbkdf2();require_pem();require_pkcs1();require_pkcs12();require_pkcs7();require_pki();require_prime();require_prng();require_pss();require_random();require_rc2();require_ssh();require_tls();require_util7()}});var init_vertex=__esm({"src/vertex.ts"(){"use strict"}});import fs2 from"fs";import os2 from"os";import path6 from"path";var TOML_KEY_PART_RE;var init_client_config=__esm({"src/client-config.ts"(){"use strict";init_main();init_vertex();TOML_KEY_PART_RE=new RegExp(String.raw`^(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*')(?:\.(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*'))*$`)}});import{createHash as createHash5,randomUUID}from"crypto";import fs4 from"fs";import os4 from"os";import path8 from"path";function isProxyInstanceFile(v2){return v2!==void 0&&"instanceId"in v2}function readProxyInstanceFile(file){let raw;try{raw=fs4.readFileSync(file??instanceFilePath(),"utf8").trim()}catch{return void 0}if(raw.startsWith("{")){try{const parsed=JSON.parse(raw);if(typeof parsed.origin==="string"&&/^https?:\/\/\S+$/.test(parsed.origin)){const windows={};if(parsed.modelWindows&&typeof parsed.modelWindows==="object"){for(const[k2,v2]of Object.entries(parsed.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(parsed.modelMaxOutputs&&typeof parsed.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(parsed.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{origin:parsed.origin,instanceId:typeof parsed.instanceId==="string"?parsed.instanceId:"",pid:typeof parsed.pid==="number"?parsed.pid:0,startedAt:typeof parsed.startedAt==="number"?parsed.startedAt:0,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,passthrough:Boolean(parsed.passthrough),mitmDomains:Array.isArray(parsed.mitmDomains)?parsed.mitmDomains.map(String):[],modelWindows:windows,modelMaxOutputs:Object.keys(maxOutputs).length>0?maxOutputs:void 0,launchToken:typeof parsed.launchToken==="string"?parsed.launchToken:void 0,lane:typeof parsed.lane==="string"&&parsed.lane!==""?parsed.lane:void 0,codeFingerprint:typeof parsed.codeFingerprint==="string"&&parsed.codeFingerprint!==""?parsed.codeFingerprint:void 0}}}catch{}}if(/^https?:\/\/\S+$/.test(raw))return{origin:raw};return void 0}function instanceFilePath(){return path8.join(stateDir(),"proxy-origin")}function portZoneFilePath(){return path8.join(stateDir(),"port-zone.json")}function readZonePort(lane,file=portZoneFilePath()){let raw;try{raw=fs4.readFileSync(file,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);const v2=parsed?.lanes?.[lane];if(typeof v2==="number"&&Number.isInteger(v2)&&v2>0&&v2<65536)return v2;return void 0}catch{return void 0}}function writeZonePort(lane,port,file=portZoneFilePath()){if(!Number.isInteger(port)||port<=0||port>=65536)return;let cur={};try{const parsed=JSON.parse(fs4.readFileSync(file,"utf8"));if(parsed!==null&&typeof parsed==="object"&&parsed.lanes!==null&&typeof parsed.lanes==="object")cur=parsed}catch{}atomicWriteJson({lanes:{...cur.lanes??{},[lane]:port}},file)}function lanePreferredPort(lane,env=process.env,file=portZoneFilePath()){return readZonePort(lane,file)??resolveZonePortBase(env)}function entryScriptFingerprint(scriptPath){if(!scriptPath)return void 0;const resolved=path8.resolve(scriptPath);const cached=scriptFingerprints.get(resolved);if(cached!==void 0)return cached;let digest;try{digest=createHash5("sha256").update(fs4.readFileSync(resolved)).digest("hex")}catch{return void 0}scriptFingerprints.set(resolved,digest);return digest}function atomicWriteJson(obj,filePath){fs4.mkdirSync(path8.dirname(filePath),{recursive:true});const tempPath=`${filePath}.${process.pid}.${randomUUID()}.tmp`;let descriptor;try{descriptor=fs4.openSync(tempPath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(obj)+"\n",null,"utf8");fs4.fsyncSync(descriptor);fs4.closeSync(descriptor);descriptor=void 0;fs4.renameSync(tempPath,filePath)}catch(error){if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}try{fs4.unlinkSync(tempPath)}catch{}throw error}}function startingMarkerPath(){return path8.join(stateDir(),"proxy-starting")}function readStartingMarker(file){let raw;try{raw=fs4.readFileSync(file??startingMarkerPath(),"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed.token!=="string"||parsed.token==="")return void 0;if(typeof parsed.pid!=="number"||!Number.isInteger(parsed.pid)||parsed.pid<=0)return void 0;if(typeof parsed.startedAt!=="number")return void 0;return{token:parsed.token,pid:parsed.pid,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,startedAt:parsed.startedAt,...typeof parsed.lane==="string"&&parsed.lane!==""?{lane:parsed.lane}:{}}}catch{return void 0}}function claimStartingMarker(marker,file){const filePath=file??startingMarkerPath();let descriptor;try{fs4.mkdirSync(path8.dirname(filePath),{recursive:true});descriptor=fs4.openSync(filePath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(marker)+"\n",null,"utf8");fs4.fsyncSync(descriptor);descriptor=void 0;return true}catch{if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}return false}}function clearStartingMarker(token,file){const filePath=file??startingMarkerPath();const current=readStartingMarker(filePath);if(current&&current.token===token){try{fs4.unlinkSync(filePath)}catch{}}}function removeStartingMarker(file){try{fs4.unlinkSync(file??startingMarkerPath())}catch{}}function isPidAlive(pid){if(!Number.isInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err){return err.code==="EPERM"}}function registryDirPath(){return path8.join(stateDir(),"instances")}function legacyRegistryFilePath(){return path8.join(stateDir(),"instances.json")}function safeReadJson(file){try{return JSON.parse(fs4.readFileSync(file,"utf8"))}catch{return void 0}}function coerceEntry(value){if(!value||typeof value!=="object")return void 0;const o=value;if(typeof o.instanceId!=="string"||o.instanceId==="")return void 0;const windows={};if(o.modelWindows&&typeof o.modelWindows==="object"){for(const[k2,v2]of Object.entries(o.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(o.modelMaxOutputs&&typeof o.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(o.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{instanceId:o.instanceId,pid:typeof o.pid==="number"?o.pid:0,port:typeof o.port==="number"?o.port:0,origin:typeof o.origin==="string"?o.origin:"",startedAt:typeof o.startedAt==="number"?o.startedAt:0,...typeof o.host==="string"&&o.host!==""?{host:o.host}:{},...typeof o.passthrough==="boolean"?{passthrough:o.passthrough}:{},...Array.isArray(o.mitmDomains)?{mitmDomains:o.mitmDomains.map(String)}:{},...Object.keys(windows).length>0?{modelWindows:windows}:{},...Object.keys(maxOutputs).length>0?{modelMaxOutputs:maxOutputs}:{},...typeof o.lane==="string"&&o.lane!==""?{lane:o.lane}:{},...typeof o.codeFingerprint==="string"&&o.codeFingerprint!==""?{codeFingerprint:o.codeFingerprint}:{}}}function readMarkerNames(){try{return fs4.readdirSync(registryDirPath())}catch{return[]}}function readAllRegistryEntries(){const seen=new Set;const out=[];for(const name of readMarkerNames()){if(!name.endsWith(".json"))continue;const entry=coerceEntry(safeReadJson(path8.join(registryDirPath(),name)));if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}const legacy=safeReadJson(legacyRegistryFilePath());if(legacy&&Array.isArray(legacy.instances)){for(const raw of legacy.instances){const entry=coerceEntry(raw);if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}}return out}function discoverLiveInstances(){const out=[];for(const e of readAllRegistryEntries()){if(!isPidAlive(e.pid))continue;out.push({origin:e.origin,instanceId:e.instanceId,pid:e.pid,startedAt:e.startedAt,host:e.host??"",port:e.port,passthrough:Boolean(e.passthrough),mitmDomains:e.mitmDomains??[],modelWindows:e.modelWindows??{},modelMaxOutputs:e.modelMaxOutputs,lane:e.lane,codeFingerprint:e.codeFingerprint})}return out}var scriptFingerprints;var init_instance=__esm({"src/instance.ts"(){"use strict";init_config();init_paths();scriptFingerprints=new Map}});var init_win_cmd=__esm({"src/win-cmd.ts"(){"use strict"}});import fs5 from"fs";import path9 from"path";import{execFile,spawnSync}from"child_process";import{promisify}from"util";var DSH_PACKAGE,DSH_EXEC_TIMEOUT_MS,pExecFile;var init_dsh_channel=__esm({"src/dsh-channel.ts"(){"use strict";init_client_config();init_win_cmd();DSH_PACKAGE="billion-context";DSH_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile=promisify(execFile)}});import fs6 from"fs";import path10 from"path";import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";var PI_NPM_SPEC,PI_EXEC_TIMEOUT_MS,pExecFile2;var init_pi_channel=__esm({"src/pi-channel.ts"(){"use strict";init_client_config();init_dsh_channel();PI_NPM_SPEC="npm:billion-context";PI_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile2=promisify2(execFile2)}});import Qr from"events";import I from"fs";import{EventEmitter as Di}from"events";import Cs from"stream";import{StringDecoder as Hr}from"string_decoder";import cr from"path";import Kt from"fs";import{dirname as Fn,parse as kn}from"path";import{EventEmitter as Dn}from"events";import zi from"assert";import{Buffer as Ot}from"buffer";import*as Ps from"zlib";import en from"zlib";import{posix as Zt}from"path";import{basename as _n}from"path";import mi from"fs";import X from"fs";import js from"path";import{win32 as Pn}from"path";import ar from"path";import Br from"fs";import co from"assert";import{randomBytes as Mr}from"crypto";import u from"fs";import R from"path";import pr from"fs";import wi from"fs";import we from"path";import k from"fs";import ro from"fs/promises";import Si from"path";import{join as xr}from"path";import v from"fs";import Pr from"path";function Zn(s3,t,e){let i=t,r=t?t.next:s3.head,n=new ue(e,i,r,s3);return n.next===void 0&&(s3.tail=n),n.prev===void 0&&(s3.head=n),s3.length++,n}function Yn(s3,t){s3.tail=new ue(t,s3.tail,void 0,s3),s3.head||(s3.head=s3.tail),s3.length++}function Kn(s3,t){s3.head=new ue(t,void 0,s3.head,s3),s3.tail||(s3.tail=s3.head),s3.length++}var zr,Ur,Ds,Wr,Gr,Zr,Q,J,nt,De,qt,Ne,Ns,Ae,As,z,Mt,g,Qt,Bt,b,N,_,bi,Ie,L,S,_i,Oi,Is,Ti,Z,xi,Ce,Jt,Rt,C,jt,Yr,Kr,Vr,$r,Fe,Li,Xr,qr,A,Jr,ht,H,te,m,Ni,tt,Ai,ki,vi,ie,ke,Ut,Ht,Ii,Pt,at,U,ot,Y,zt,Ci,j,ee,Fi,ve,gt,Me,bt,_t,Be,et,Wt,jr,Fs,ks,vs,Ms,Bs,tn,se,K,sn,M,rn,zs,nn,Bi,Tt,Gt,Pi,re,Pe,ze,Ue,He,We,Ge,Ze,Ye,Ke,Us,hn,an,Hs,ln,cn,Ws,Gs,Hi,ne,dn,Ui,oe,Ve,un,F,mn,xt,Wi,pn,lt,En,wn,Sn,ct,yn,Rn,gn,Gi,bn,Lt,ft,On,Tn,xn,Ln,f,$e,Dt,Nn,Xi,qi,An,B,Nt,it,Zi,Zs,V,he,dt,Ys,p,st,ut,Yi,At,w,Xe,qe,Ki,Ks,Vs,ae,Vi,Qe,Yt,$,Je,It,je,ti,$s,In,le,$i,Xs,Cn,rt,mt,vn,Qi,Mn,Bn,Ct,Ji,zn,qs,ce,ei,ji,Un,Hn,ts,Qs,rr,Wn,tr,er,ir,is,sr,fe,ii,ss,si,rs,ns,os5,hs,pt,ri,as,es,q,de,ni,oi,Gn,hi,ue,pi,nr,li,me,W,pe,Et,Ft,Ee,ai,G,ls,ci,or,ds,us,fi,di,hr,cs,ui,lr,fs7,wt,kt,Vn,$n,fr,dr,Xn,qn,Qn,Jn,Er,wr,ur,Sr,yr,Rr,jn,to,eo,mr,ms,ps,Ei,io,Es,so,ws,Se,St,no,gr,Ss,br,oo,_r,ys,Or,Vt,Tr,ho,ao,lo,yi,Lr,Dr,_s,Nr,Os,P,Ts,xs,gi,Ar,Ir,Re,Cr,Fr,Rs,yt,O,Ri,kr,$t,gs,bs,Ls,ge,be,_e,Oe,fo,Te,uo,mo,po,vr,Xt,ye,xe,Eo,wo,So,yo,Ro,go,bo,_o,vt,Oo,To;var init_index_min=__esm({"node_modules/tar/dist/esm/index.min.js"(){"use strict";zr=Object.defineProperty;Ur=(s3,t)=>{for(var e in t)zr(s3,e,{get:t[e],enumerable:true})};Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null};Wr=s3=>!!s3&&typeof s3=="object"&&(s3 instanceof A||s3 instanceof Cs||Gr(s3)||Zr(s3));Gr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.pipe=="function"&&s3.pipe!==Cs.Writable.prototype.pipe;Zr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.write=="function"&&typeof s3.end=="function";Q=Symbol("EOF");J=Symbol("maybeEmitEnd");nt=Symbol("emittedEnd");De=Symbol("emittingEnd");qt=Symbol("emittedError");Ne=Symbol("closed");Ns=Symbol("read");Ae=Symbol("flush");As=Symbol("flushChunk");z=Symbol("encoding");Mt=Symbol("decoder");g=Symbol("flowing");Qt=Symbol("paused");Bt=Symbol("resume");b=Symbol("buffer");N=Symbol("pipes");_=Symbol("bufferLength");bi=Symbol("bufferPush");Ie=Symbol("bufferShift");L=Symbol("objectMode");S=Symbol("destroyed");_i=Symbol("error");Oi=Symbol("emitData");Is=Symbol("emitEnd");Ti=Symbol("emitEnd2");Z=Symbol("async");xi=Symbol("abort");Ce=Symbol("aborted");Jt=Symbol("signal");Rt=Symbol("dataListeners");C=Symbol("discarded");jt=s3=>Promise.resolve().then(s3);Yr=s3=>s3();Kr=s3=>s3==="end"||s3==="finish"||s3==="prefinish";Vr=s3=>s3 instanceof ArrayBuffer||!!s3&&typeof s3=="object"&&s3.constructor&&s3.constructor.name==="ArrayBuffer"&&s3.byteLength>=0;$r=s3=>!Buffer.isBuffer(s3)&&ArrayBuffer.isView(s3);Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}};Li=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}};Xr=s3=>!!s3.objectMode;qr=s3=>!s3.objectMode&&!!s3.encoding&&s3.encoding!=="buffer";A=class extends Di{[g]=false;[Qt]=false;[N]=[];[b]=[];[L];[z];[Z];[Mt];[Q]=false;[nt]=false;[De]=false;[Ne]=false;[qt]=null;[_]=0;[S]=false;[Jt];[Ce]=false;[Rt]=0;[C]=false;writable=true;readable=true;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Xr(e)?(this[L]=true,this[z]=null):qr(e)?(this[z]=e.encoding,this[L]=false):(this[L]=false,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Hr(this[z]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[N]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[xi](){this[Ce]=true,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ce]}set aborted(t){}write(t,e,i){if(this[Ce])return false;if(this[Q])throw new Error("write after end");if(this[S])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Yr;if(!this[L]&&!Buffer.isBuffer(t)){if($r(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[S])return null;if(this[C]=false,this[_]===0||t===0||t&&t>this[_])return this[J](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ns](t||null,this[b][0]);return this[J](),e}[Ns](t,e){if(this[L])this[Ie]();else{let i=e;t===i.length||t===null?this[Ie]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[Q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Q]=true,this.writable=false,(this[g]||!this[Qt])&&this[J](),this}[Bt](){this[S]||(!this[Rt]&&!this[N].length&&(this[C]=true),this[Qt]=false,this[g]=true,this.emit("resume"),this[b].length?this[Ae]():this[Q]?this[J]():this.emit("drain"))}resume(){return this[Bt]()}pause(){this[g]=false,this[Qt]=true,this[C]=false}get destroyed(){return this[S]}get flowing(){return this[g]}get paused(){return this[Qt]}[bi](t){this[L]?this[_]+=1:this[_]+=t.length,this[b].push(t)}[Ie](){return this[L]?this[_]-=1:this[_]-=this[b][0].length,this[b].shift()}[Ae](t=false){do;while(this[As](this[Ie]())&&this[b].length);!t&&!this[b].length&&!this[Q]&&this.emit("drain")}[As](t){return this.emit("data",t),this[g]}pipe(t,e){if(this[S])return t;this[C]=false;let i=this[nt];return e=e||{},t===Ds.stdout||t===Ds.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[N].push(e.proxyErrors?new Li(this,t,e):new Fe(this,t,e)),this[Z]?jt(()=>this[Bt]()):this[Bt]()),t}unpipe(t){let e=this[N].find(i=>i.dest===t);e&&(this[N].length===1?(this[g]&&this[Rt]===0&&(this[g]=false),this[N]=[]):this[N].splice(this[N].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[C]=false,this[Rt]++,!this[N].length&&!this[g]&&this[Bt]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(Kr(t)&&this[nt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[qt]){let r=e;this[Z]?jt(()=>r.call(this,this[qt])):r.call(this,this[qt])}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[Rt]=this.listeners("data").length,this[Rt]===0&&!this[C]&&!this[N].length&&(this[g]=false)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Rt]=0,!this[C]&&!this[N].length&&(this[g]=false)),e}get emittedEnd(){return this[nt]}[J](){!this[De]&&!this[nt]&&!this[S]&&this[b].length===0&&this[Q]&&(this[De]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ne]&&this.emit("close"),this[De]=false)}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==S&&this[S])return false;if(t==="data")return!this[L]&&!i?false:this[Z]?(jt(()=>this[Oi](i)),true):this[Oi](i);if(t==="end")return this[Is]();if(t==="close"){if(this[Ne]=true,!this[nt]&&!this[S])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[qt]=i,super.emit(_i,i);let n=!this[Jt]||this.listeners("error").length?super.emit("error",i):false;return this[J](),n}else if(t==="resume"){let n=super.emit("resume");return this[J](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[J](),r}[Oi](t){for(let i of this[N])i.dest.write(t)===false&&this.pause();let e=this[C]?false:super.emit("data",t);return this[J](),e}[Is](){return this[nt]?false:(this[nt]=true,this.readable=false,this[Z]?(jt(()=>this[Ti]()),true):this[Ti]())}[Ti](){if(this[Mt]){let e=this[Mt].end();if(e){for(let i of this[N])i.dest.write(e);this[C]||super.emit("data",e)}}for(let e of this[N])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[L]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[L]||(t.dataLength+=i.length)}),await e,t}async concat(){if(this[L])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(S,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[C]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:false,value:r});if(this[Q])return e();let n,o,h=d=>{this.off("data",a),this.off("end",l),this.off(S,c),e(),o(d)},a=d=>{this.off("error",h),this.off("end",l),this.off(S,c),this.pause(),n({value:d,done:!!this[Q]})},l=()=>{this.off("error",h),this.off("data",a),this.off(S,c),e(),n({done:true,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((d,y)=>{o=y,n=d,this.once(S,c),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[C]=false;let t=false,e=()=>(this.pause(),this.off(_i,e),this.off(S,e),this.off("end",e),t=true,{done:true,value:void 0}),i=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(_i,e),this.once(S,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[S])return t?this.emit("error",t):this.emit(S),this;this[S]=true,this[C]=true,this[b].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Ne]&&e.close(),t?this.emit("error",t):this.emit(S),this}static get isStream(){return Wr}};Jr=I.writev;ht=Symbol("_autoClose");H=Symbol("_close");te=Symbol("_ended");m=Symbol("_fd");Ni=Symbol("_finished");tt=Symbol("_flags");Ai=Symbol("_flush");ki=Symbol("_handleChunk");vi=Symbol("_makeBuf");ie=Symbol("_mode");ke=Symbol("_needDrain");Ut=Symbol("_onerror");Ht=Symbol("_onopen");Ii=Symbol("_onread");Pt=Symbol("_onwrite");at=Symbol("_open");U=Symbol("_path");ot=Symbol("_pos");Y=Symbol("_queue");zt=Symbol("_read");Ci=Symbol("_readSize");j=Symbol("_reading");ee=Symbol("_remain");Fi=Symbol("_size");ve=Symbol("_write");gt=Symbol("_writing");Me=Symbol("_defaultFlag");bt=Symbol("_errored");_t=class extends A{[bt]=false;[m];[U];[Ci];[j]=false;[Fi];[ee];[ht];constructor(t,e){if(e=e||{},super(e),this.readable=true,this.writable=false,typeof t!="string")throw new TypeError("path must be a string");this[bt]=false,this[m]=typeof e.fd=="number"?e.fd:void 0,this[U]=t,this[Ci]=e.readSize||16*1024*1024,this[j]=false,this[Fi]=typeof e.size=="number"?e.size:1/0,this[ee]=this[Fi],this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true,typeof this[m]=="number"?this[zt]():this[at]()}get fd(){return this[m]}get path(){return this[U]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[at](){I.open(this[U],"r",(t,e)=>this[Ht](t,e))}[Ht](t,e){t?this[Ut](t):(this[m]=e,this.emit("open",e),this[zt]())}[vi](){return Buffer.allocUnsafe(Math.min(this[Ci],this[ee]))}[zt](){if(!this[j]){this[j]=true;let t=this[vi]();if(t.length===0)return process.nextTick(()=>this[Ii](null,0,t));I.read(this[m],t,0,t.length,null,(e,i,r)=>this[Ii](e,i,r))}}[Ii](t,e,i){this[j]=false,t?this[Ut](t):this[ki](e,i)&&this[zt]()}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ut](t){this[j]=true,this[H](),this.emit("error",t)}[ki](t,e){let i=false;return this[ee]-=t,t>0&&(i=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[ee]<=0)&&(i=false,this[H](),super.end()),i}emit(t,...e){switch(t){case"prefinish":case"finish":return false;case"drain":return typeof this[m]=="number"&&this[zt](),false;case"error":return this[bt]?false:(this[bt]=true,super.emit(t,...e));default:return super.emit(t,...e)}}};Be=class extends _t{[at](){let t=true;try{this[Ht](null,I.openSync(this[U],"r")),t=false}finally{t&&this[H]()}}[zt](){let t=true;try{if(!this[j]){this[j]=true;do{let e=this[vi](),i=e.length===0?0:I.readSync(this[m],e,0,e.length,null);if(!this[ki](i,e))break}while(true);this[j]=false}t=false}finally{t&&this[H]()}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}};et=class extends Qr{readable=false;writable=true;[bt]=false;[gt]=false;[te]=false;[Y]=[];[ke]=false;[U];[ie];[ht];[m];[Me];[tt];[Ni]=false;[ot];constructor(t,e){e=e||{},super(e),this[U]=t,this[m]=typeof e.fd=="number"?e.fd:void 0,this[ie]=e.mode===void 0?438:e.mode,this[ot]=typeof e.start=="number"?e.start:void 0,this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true;let i=this[ot]!==void 0?"r+":"w";this[Me]=e.flags===void 0,this[tt]=e.flags===void 0?i:e.flags,this[m]===void 0&&this[at]()}emit(t,...e){if(t==="error"){if(this[bt])return false;this[bt]=true}return super.emit(t,...e)}get fd(){return this[m]}get path(){return this[U]}[Ut](t){this[H](),this[gt]=true,this.emit("error",t)}[at](){I.open(this[U],this[tt],this[ie],(t,e)=>this[Ht](t,e))}[Ht](t,e){this[Me]&&this[tt]==="r+"&&t&&t.code==="ENOENT"?(this[tt]="w",this[at]()):t?this[Ut](t):(this[m]=e,this.emit("open",e),this[gt]||this[Ai]())}end(t,e){return t&&this.write(t,e),this[te]=true,!this[gt]&&!this[Y].length&&typeof this[m]=="number"&&this[Pt](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[te]?(this.emit("error",new Error("write() after end()")),false):this[m]===void 0||this[gt]||this[Y].length?(this[Y].push(t),this[ke]=true,false):(this[gt]=true,this[ve](t),true)}[ve](t){I.write(this[m],t,0,t.length,this[ot],(e,i)=>this[Pt](e,i))}[Pt](t,e){t?this[Ut](t):(this[ot]!==void 0&&typeof e=="number"&&(this[ot]+=e),this[Y].length?this[Ai]():(this[gt]=false,this[te]&&!this[Ni]?(this[Ni]=true,this[H](),this.emit("finish")):this[ke]&&(this[ke]=false,this.emit("drain"))))}[Ai](){if(this[Y].length===0)this[te]&&this[Pt](null,0);else if(this[Y].length===1)this[ve](this[Y].pop());else{let t=this[Y];this[Y]=[],Jr(this[m],t,this[ot],(e,i)=>this[Pt](e,i))}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}};Wt=class extends et{[at](){let t;if(this[Me]&&this[tt]==="r+")try{t=I.openSync(this[U],this[tt],this[ie])}catch(e){if(e?.code==="ENOENT")return this[tt]="w",this[at]();throw e}else t=I.openSync(this[U],this[tt],this[ie]);this[Ht](null,t)}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}[ve](t){let e=true;try{this[Pt](null,I.writeSync(this[m],t,0,t.length,this[ot])),e=false}finally{if(e)try{this[H]()}catch{}}}};jr=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]);Fs=s3=>!!s3.sync&&!!s3.file;ks=s3=>!s3.sync&&!!s3.file;vs=s3=>!!s3.sync&&!s3.file;Ms=s3=>!s3.sync&&!s3.file;Bs=s3=>!!s3.file;tn=s3=>{let t=jr.get(s3);return t||s3};se=(s3={})=>{if(!s3)return{};let t={};for(let[e,i]of Object.entries(s3)){let r=tn(e);t[r]=i}return t.chmod===void 0&&t.noChmod===false&&(t.chmod=true),delete t.noChmod,t};K=(s3,t,e,i,r)=>Object.assign((n=[],o,h)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(h=o,o=void 0),o=o?Array.from(o):[];let a=se(n);if(r?.(a,o),Fs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return s3(a,o)}else if(ks(a)){let l=t(a,o);return h?l.then(()=>h(),h):l}else if(vs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return e(a,o)}else if(Ms(a)){if(typeof h=="function")throw new TypeError("callback only supported with file option");return i(a,o)}throw new Error("impossible options??")},{syncFile:s3,asyncFile:t,syncNoFile:e,asyncNoFile:i,validate:r});sn=en.constants||{ZLIB_VERNUM:4736};M=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,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_VERSION_ERROR:-6,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,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},sn));rn=Ot.concat;zs=Object.getOwnPropertyDescriptor(Ot,"concat");nn=s3=>s3;Bi=zs?.writable===true||zs?.set!==void 0?s3=>{Ot.concat=s3?nn:rn}:s3=>{};Tt=Symbol("_superWrite");Gt=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}};Pi=Symbol("flushFlag");re=class extends A{#t=false;#i=false;#s;#n;#r;#e;#o;get sawError(){return this.#t}get handle(){return this.#e}get flushFlag(){return this.#s}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#s=t.flush??0,this.#n=t.finishFlush??0,this.#r=t.fullFlushFlag??0,typeof Ps[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#e=new Ps[e](t)}catch(i){throw new Gt(i,this.constructor)}this.#o=i=>{this.#t||(this.#t=true,this.close(),this.emit("error",i))},this.#e?.on("error",i=>this.#o(new Gt(i))),this.once("end",()=>this.close)}close(){this.#e&&(this.#e.close(),this.#e=void 0,this.emit("close"))}reset(){if(!this.#t)return zi(this.#e,"zlib binding closed"),this.#e.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#r),this.write(Object.assign(Ot.alloc(0),{[Pi]:t})))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#n),this.#i=true,super.end(i)}get ended(){return this.#i}[Tt](t){return super.write(t)}write(t,e,i){if(typeof e=="function"&&(i=e,e="utf8"),typeof t=="string"&&(t=Ot.from(t,e)),this.#t)return;zi(this.#e,"zlib binding closed");let r=this.#e._handle,n=r.close;r.close=()=>{};let o=this.#e.close;this.#e.close=()=>{},Bi(true);let h;try{let l=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l),Bi(false)}catch(l){Bi(false),this.#o(new Gt(l,this.write))}finally{this.#e&&(this.#e._handle=r,r.close=n,this.#e.close=o,this.#e.removeAllListeners("error"))}this.#e&&this.#e.on("error",l=>this.#o(new Gt(l,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l=h[0];a=this[Tt](Ot.from(l));for(let c=1;c<h.length;c++)a=this[Tt](h[c])}else a=this[Tt](Ot.from(h));return i&&i(),a}};Pe=class extends re{#t;#i;constructor(t,e){t=t||{},t.flush=t.flush||M.Z_NO_FLUSH,t.finishFlush=t.finishFlush||M.Z_FINISH,t.fullFlushFlag=M.Z_FULL_FLUSH,super(t,e),this.#t=t.level,this.#i=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#t!==t||this.#i!==e){this.flush(M.Z_SYNC_FLUSH),zi(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(r,n)=>{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(t,e)}finally{this.handle.flush=i}this.handle&&(this.#t=t,this.#i=e)}}}};ze=class extends Pe{#t;constructor(t){super(t,"Gzip"),this.#t=t&&!!t.portable}[Tt](t){return this.#t?(this.#t=false,t[9]=255,super[Tt](t)):super[Tt](t)}};Ue=class extends Pe{constructor(t){super(t,"Unzip")}};He=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||M.BROTLI_OPERATION_FINISH,t.fullFlushFlag=M.BROTLI_OPERATION_FLUSH,super(t,e)}};We=class extends He{constructor(t){super(t,"BrotliCompress")}};Ge=class extends He{constructor(t){super(t,"BrotliDecompress")}};Ze=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.ZSTD_e_continue,t.finishFlush=t.finishFlush||M.ZSTD_e_end,t.fullFlushFlag=M.ZSTD_e_flush,super(t,e)}};Ye=class extends Ze{constructor(t){super(t,"ZstdCompress")}};Ke=class extends Ze{constructor(t){super(t,"ZstdDecompress")}};Us=(s3,t)=>{if(Number.isSafeInteger(s3))s3<0?an(s3,t):hn(s3,t);else throw Error("cannot encode number outside of javascript safe integer range");return t};hn=(s3,t)=>{t[0]=128;for(var e=t.length;e>1;e--)t[e-1]=s3&255,s3=Math.floor(s3/256)};an=(s3,t)=>{t[0]=255;var e=false;s3=s3*-1;for(var i=t.length;i>1;i--){var r=s3&255;s3=Math.floor(s3/256),e?t[i-1]=Ws(r):r===0?t[i-1]=0:(e=true,t[i-1]=Gs(r))}};Hs=s3=>{let t=s3[0],e=t===128?cn(s3.subarray(1,s3.length)):t===255?ln(s3):null;if(e===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(e))throw Error("parsed number outside of javascript safe integer range");return e};ln=s3=>{for(var t=s3.length,e=0,i=false,r=t-1;r>-1;r--){var n=Number(s3[r]),o;i?o=Ws(n):n===0?o=n:(i=true,o=Gs(n)),o!==0&&(e-=o*Math.pow(256,t-r-1))}return e};cn=s3=>{for(var t=s3.length,e=0,i=t-1;i>-1;i--){var r=Number(s3[i]);r!==0&&(e+=r*Math.pow(256,t-i-1))}return e};Ws=s3=>(255^s3)&255;Gs=s3=>(255^s3)+1&255;Hi={};Ur(Hi,{code:()=>Ve,isCode:()=>ne,isName:()=>dn,name:()=>oe,normalFsTypes:()=>Ui});ne=s3=>oe.has(s3);dn=s3=>Ve.has(s3);Ui=new Set(["0","","1","2","3","4","5","6","7","D"]);oe=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Ve=new Map(Array.from(oe).map(s3=>[s3[1],s3[0]]));un=s3=>s3===void 0||s3<0?void 0:s3;F=class{cksumValid=false;needPax=false;nullBlock=false;block;path;mode;uid;gid;size;cksum;#t="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,i,r){Buffer.isBuffer(t)?this.decode(t,e||0,i,r):t&&this.#i(t)}decode(t,e,i,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=xt(t,e+156,1),o=Ui.has(n),h=o?i:void 0,a=o?r:void 0;if(this.path=h?.path??xt(t,e,100),this.mode=h?.mode??a?.mode??lt(t,e+100,8),this.uid=h?.uid??a?.uid??lt(t,e+108,8),this.gid=h?.gid??a?.gid??lt(t,e+116,8),this.size=un(h?.size??a?.size??lt(t,e+124,12)),this.mtime=h?.mtime??a?.mtime??Wi(t,e+136,12),this.cksum=lt(t,e+148,12),a&&this.#i(a,true),h&&this.#i(h),ne(n)&&(this.#t=n||"0"),this.#t==="0"&&this.path.slice(-1)==="/"&&(this.#t="5"),this.#t==="5"&&(this.size=0),this.linkpath=xt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=h?.uname??a?.uname??xt(t,e+265,32),this.gname=h?.gname??a?.gname??xt(t,e+297,32),this.devmaj=h?.devmaj??a?.devmaj??lt(t,e+329,8)??0,this.devmin=h?.devmin??a?.devmin??lt(t,e+337,8)??0,t[e+475]!==0){let c=xt(t,e+345,155);this.path=c+"/"+this.path}else{let c=xt(t,e+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??r?.atime??Wi(t,e+476,12),this.ctime=i?.ctime??r?.ctime??Wi(t,e+488,12)}let l=256;for(let c=e;c<e+148;c++)l+=t[c];for(let c=e+156;c<e+512;c++)l+=t[c];this.cksumValid=l===this.cksum,this.cksum===void 0&&l===256&&(this.nullBlock=true)}#i(t,e=false){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="size"&&Number(r)<0||i==="path"&&e||i==="linkpath"&&e||i==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#t==="Unsupported"&&(this.#t="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=mn(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Lt(t,e,100,n)||this.needPax,this.needPax=ct(t,e+100,8,this.mode)||this.needPax,this.needPax=ct(t,e+108,8,this.uid)||this.needPax,this.needPax=ct(t,e+116,8,this.gid)||this.needPax,this.needPax=ct(t,e+124,12,this.size)||this.needPax,this.needPax=Gi(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#t.codePointAt(0)),this.needPax=Lt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Lt(t,e+265,32,this.uname)||this.needPax,this.needPax=Lt(t,e+297,32,this.gname)||this.needPax,this.needPax=ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Lt(t,e+345,i,o)||this.needPax,t[e+475]!==0?this.needPax=Lt(t,e+345,155,o)||this.needPax:(this.needPax=Lt(t,e+345,130,o)||this.needPax,this.needPax=Gi(t,e+476,12,this.atime)||this.needPax,this.needPax=Gi(t,e+488,12,this.ctime)||this.needPax);let h=256;for(let a=e;a<e+148;a++)h+=t[a];for(let a=e+156;a<e+512;a++)h+=t[a];return this.cksum=h,ct(t,e+148,8,this.cksum),this.cksumValid=true,this.needPax}get type(){return this.#t==="Unsupported"?this.#t:oe.get(this.#t)}get typeKey(){return this.#t}set type(t){let e=String(Ve.get(t));if(ne(e)||e==="Unsupported")this.#t=e;else if(ne(t))this.#t=t;else throw new TypeError("invalid entry type: "+t)}};mn=(s3,t)=>{let i=s3,r="",n,o=Zt.parse(s3).root||".";if(Buffer.byteLength(i)<100)n=[i,r,false];else{r=Zt.dirname(i),i=Zt.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=t?n=[i,r,false]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=t?n=[i.slice(0,99),r,true]:(i=Zt.join(Zt.basename(r),i),r=Zt.dirname(r));while(r!==o&&n===void 0);n||(n=[s3.slice(0,99),"",true])}return n};xt=(s3,t,e)=>s3.subarray(t,t+e).toString("utf8").replace(/\0.*/,"");Wi=(s3,t,e)=>pn(lt(s3,t,e));pn=s3=>s3===void 0?void 0:new Date(s3*1e3);lt=(s3,t,e)=>Number(s3[t])&128?Hs(s3.subarray(t,t+e)):wn(s3,t,e);En=s3=>isNaN(s3)?void 0:s3;wn=(s3,t,e)=>En(parseInt(s3.subarray(t,t+e).toString("utf8").replace(/\0.*$/,"").trim(),8));Sn={12:8589934591,8:2097151};ct=(s3,t,e,i)=>i===void 0?false:i>Sn[e]||i<0?(Us(i,s3.subarray(t,t+e)),true):(yn(s3,t,e,i),false);yn=(s3,t,e,i)=>s3.write(Rn(i,e),t,e,"ascii");Rn=(s3,t)=>gn(Math.floor(s3).toString(8),t);gn=(s3,t)=>(s3.length===t-1?s3:new Array(t-s3.length-1).join("0")+s3+" ")+"\0";Gi=(s3,t,e,i)=>i===void 0?false:ct(s3,t,e,i.getTime()/1e3);bn=new Array(156).join("\0");Lt=(s3,t,e,i)=>i===void 0?false:(s3.write(i+bn,t,e,"utf8"),i.length!==Buffer.byteLength(i)||i.length>e);ft=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,e=false){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=e,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let e=Buffer.byteLength(t),i=512*Math.ceil(1+e/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new F({path:("PaxHeader/"+_n(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:e,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(r),r.write(t,512,e,"utf8");for(let n=e+512;n<r.length;n++)r[n]=0;return r}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let e=this[t],i=e instanceof Date?e.getTime()/1e3:e,r=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
309
+ ${captureLines}`:capture2.stack}module.exports.fetch=function fetch2(init,options=void 0){return fetchImpl(init,options).catch(err=>{if(currentFilename){appendFetchStackTrace(err,currentFilename)}else if(err&&typeof err==="object"){Error.captureStackTrace(err,module.exports.fetch)}throw err})};module.exports.Headers=require_headers().Headers;module.exports.Response=require_response().Response;module.exports.Request=require_request2().Request;module.exports.FormData=require_formdata().FormData;var{setGlobalOrigin,getGlobalOrigin}=require_global();module.exports.setGlobalOrigin=setGlobalOrigin;module.exports.getGlobalOrigin=getGlobalOrigin;var{CacheStorage}=require_cachestorage();var{kConstruct}=require_symbols();module.exports.caches=new CacheStorage(kConstruct);var{deleteCookie,getCookies,getSetCookies,setCookie,parseCookie}=require_cookies();module.exports.deleteCookie=deleteCookie;module.exports.getCookies=getCookies;module.exports.getSetCookies=getSetCookies;module.exports.setCookie=setCookie;module.exports.parseCookie=parseCookie;var{parseMIMEType,serializeAMimeType}=require_data_url();module.exports.parseMIMEType=parseMIMEType;module.exports.serializeAMimeType=serializeAMimeType;var{CloseEvent,ErrorEvent,MessageEvent}=require_events();var{WebSocket,ping}=require_websocket();module.exports.WebSocket=WebSocket;module.exports.CloseEvent=CloseEvent;module.exports.ErrorEvent=ErrorEvent;module.exports.MessageEvent=MessageEvent;module.exports.ping=ping;module.exports.WebSocketStream=require_websocketstream().WebSocketStream;module.exports.WebSocketError=require_websocketerror().WebSocketError;module.exports.request=makeDispatcher(api.request);module.exports.stream=makeDispatcher(api.stream);module.exports.pipeline=makeDispatcher(api.pipeline);module.exports.connect=makeDispatcher(api.connect);module.exports.upgrade=makeDispatcher(api.upgrade);module.exports.MockClient=MockClient;module.exports.MockCallHistory=MockCallHistory;module.exports.MockCallHistoryLog=MockCallHistoryLog;module.exports.MockPool=MockPool;module.exports.MockAgent=MockAgent;module.exports.SnapshotAgent=SnapshotAgent;module.exports.mockErrors=mockErrors;var{EventSource}=require_eventsource();module.exports.EventSource=EventSource;function install(){globalThis.fetch=module.exports.fetch;globalThis.Headers=module.exports.Headers;globalThis.Response=module.exports.Response;globalThis.Request=module.exports.Request;globalThis.FormData=module.exports.FormData;globalThis.WebSocket=module.exports.WebSocket;globalThis.CloseEvent=module.exports.CloseEvent;globalThis.ErrorEvent=module.exports.ErrorEvent;globalThis.MessageEvent=module.exports.MessageEvent;globalThis.EventSource=module.exports.EventSource}module.exports.install=install}});import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";var transports;var init_fetch_transport=__esm({"src/fetch-transport.ts"(){"use strict";transports=new AsyncLocalStorage2}});var init_upstream_fail=__esm({"src/upstream-fail.ts"(){"use strict"}});import{homedir}from"os";import path3 from"path";function xdg(envVar,fallback){const v2=process.env[envVar];if(v2&&v2.length>0)return path3.resolve(v2);return path3.join(homedir(),fallback)}function configDir(){return path3.join(xdg("XDG_CONFIG_HOME",".config"),"billion-context")}function configFile(){const env=process.env.BILI_CONFIG_FILE;if(env&&env.length>0)return path3.resolve(env);return path3.join(configDir(),"billion-context.json")}function cacheDir(){return path3.join(xdg("XDG_CACHE_HOME",".cache"),"billion-context")}function stateDir(){return path3.join(xdg("XDG_STATE_HOME",".local/state"),"billion-context")}function defaultLogFile(){return path3.join(stateDir(),"bili.log")}var init_paths=__esm({"src/paths.ts"(){"use strict"}});function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}return{setPosition,getPosition:()=>pos,scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:()=>token,getTokenValue:()=>value,getTokenOffset:()=>tokenOffset,getTokenLength:()=>pos-tokenOffset,getTokenStartLine:()=>lineStartOffset,getTokenStartCharacter:()=>tokenOffset-prevTokenLineStartOffset,getTokenError:()=>scanError}}function isWhiteSpace(ch){return ch===32||ch===9}function isLineBreak(ch){return ch===10||ch===13}function isDigit(ch){return ch>=48&&ch<=57}var CharacterCodes;var init_scanner=__esm({"node_modules/jsonc-parser/lib/esm/impl/scanner.js"(){"use strict";(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}))}});var cachedSpaces,maxCachedValues,cachedBreakLinesWithSpaces;var init_string_intern=__esm({"node_modules/jsonc-parser/lib/esm/impl/string-intern.js"(){"use strict";cachedSpaces=new Array(20).fill(0).map((_2,index)=>{return" ".repeat(index)});maxCachedValues=200;cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_2,index)=>{return"\r\n"+" ".repeat(index)})}}}});var init_format=__esm({"node_modules/jsonc-parser/lib/esm/impl/format.js"(){"use strict";init_scanner();init_string_intern()}});function parse(text,errors=[],options=ParseOptions.DEFAULT){let currentProperty=null;let currentParent=[];const previousParents=[];function onValue(value){if(Array.isArray(currentParent)){currentParent.push(value)}else if(currentProperty!==null){currentParent[currentProperty]=value}}const visitor={onObjectBegin:()=>{const object={};onValue(object);previousParents.push(currentParent);currentParent=object;currentProperty=null},onObjectProperty:name=>{currentProperty=name},onObjectEnd:()=>{currentParent=previousParents.pop()},onArrayBegin:()=>{const array=[];onValue(array);previousParents.push(currentParent);currentParent=array;currentProperty=null},onArrayEnd:()=>{currentParent=previousParents.pop()},onLiteralValue:onValue,onError:(error,offset,length)=>{errors.push({error,offset,length})}};visit(text,visitor,options);return currentParent[0]}function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}var ParseOptions;var init_parser=__esm({"node_modules/jsonc-parser/lib/esm/impl/parser.js"(){"use strict";init_scanner();(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}))}});var init_edit=__esm({"node_modules/jsonc-parser/lib/esm/impl/edit.js"(){"use strict";init_format();init_parser()}});function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}var ScanError,SyntaxKind,parse2,ParseErrorCode;var init_main=__esm({"node_modules/jsonc-parser/lib/esm/main.js"(){"use strict";init_format();init_edit();init_scanner();init_parser();(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));parse2=parse;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}))}});import{execFileSync as execFileSync2}from"child_process";import net from"net";import tls from"tls";var import_undici;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs()}});import{createHash as createHash2}from"crypto";function hashId(s3){return createHash2("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var BILI_PASSTHROUGH_HEADER;var init_util=__esm({"src/util.ts"(){"use strict";BILI_PASSTHROUGH_HEADER="x-bili-passthrough"}});var DEFAULT_MITM_DOMAINS;var init_mitm_domains=__esm({"src/mitm-domains.ts"(){"use strict";DEFAULT_MITM_DOMAINS=["api.anthropic.com","api.openai.com","chatgpt.com"]}});var init_compat_roles=__esm({"src/compat-roles.ts"(){"use strict";init_config()}});var init_compat_drop=__esm({"src/compat-drop.ts"(){"use strict";init_config()}});var init_private_host=__esm({"src/private-host.ts"(){"use strict"}});var SUMMARY_DEFAULT_BUDGET;var init_external_summary_settings=__esm({"src/external-summary-settings.ts"(){"use strict";init_logger();init_private_host();init_knobs();SUMMARY_DEFAULT_BUDGET={totalTimeoutMs:5e4,targetTimeoutMs:25e3,maxSummaryBytes:64*1024}}});import{readFileSync as readFileSync2,existsSync,mkdirSync as mkdirSync2,writeFileSync}from"fs";import{createHash as createHash3}from"crypto";import{dirname}from"path";function resolveRecordedMitmDomains(passed,env=process.env){const fileConfig=loadConfigFile();const enabled=(env.BILI_MITM??(fileConfig.mitm?.enabled===false?"0":"1"))!=="0";if(!enabled)return[];const effective=passed&&passed.length>0?passed.join(","):env.BILI_MITM_DOMAINS;return dedupeDomains([...fileConfig.mitm?.domains??[],...splitCsv(effective)])}function splitCsv(value){if(!value)return[];return value.split(",").map(s3=>s3.trim()).filter(s3=>s3.length>0)}function dedupeDomains(list){const seen=new Set;const out=[];for(const d of list){if(!seen.has(d)){seen.add(d);out.push(d)}}return out}function warnUnknownTopLevelKeys(obj){const unknown=Object.keys(obj).filter(key=>!KNOWN_TOP_LEVEL_KEYS.has(key)&&key!=="allowDshCompaction");if(unknown.length===0)return;const signature=[...unknown].sort().join("\0");if(seenUnknownTopLevelKeySignatures.has(signature))return;seenUnknownTopLevelKeySignatures.add(signature);const misplaced=unknown.filter(key=>COMPRESS_SETTING_FIELDS.has(key));const hint=misplaced.length>0?` \u2014 ${misplaced.map(k2=>`"${k2}" belongs under "compress" (did you mean "compress.${k2}"?)`).join("; ")}`:"";log("warn",`[acp-config] ignoring unknown top-level config key(s): ${unknown.join(", ")}${hint}`)}function parseBiliConfig(raw){try{return JSON.parse(raw)}catch{const errors=[];const value=parse2(raw,errors,{allowTrailingComma:true});if(errors.length===0)return value;const first=errors[0];throw new SyntaxError(`invalid JSON/JSONC at ${lineColumnOf(raw,first.offset)}: ${printParseErrorCode(first.error)}`)}}function lineColumnOf(text,offset){let line=1;let column=1;for(let i=0;i<offset&&i<text.length;i++){if(text.charAt(i)==="\n"){line++;column=1}else column++}return`line ${line} column ${column}`}function loadConfigFile(){const path29=configFile();let raw;let value;try{raw=readFileSync2(path29,"utf8").replace(/^\uFEFF/,"");const cached=configFileCache;if(cached&&cached.raw===raw)return cached.value;const parsed=parseBiliConfig(raw);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){const obj=parsed;warnRemovedDshAllowKey(obj);warnUnknownTopLevelKeys(obj);warnInertResignPassthrough(obj);warnInertStripImages(obj);warnInertRemovedCompressKeys(obj);value=obj}else{value={}}}catch(e){if(e.code!=="ENOENT"){log("error",`[acp-config] failed to parse ${path29}: ${String(e)}`)}if(raw!==void 0)value={}}if(raw===void 0||value===void 0)return{};configFileCache={raw,value};return value}function warnRemovedDshAllowKey(obj){const hits=[];if(Object.prototype.hasOwnProperty.call(obj,"allowDshCompaction")&&obj.allowDshCompaction!==null&&obj.allowDshCompaction!==void 0){hits.push('top-level "allowDshCompaction"')}const d=obj.dsh;if(d!==null&&typeof d==="object"&&!Array.isArray(d)){const live=new Set(["authoredCompaction","contextTab","contextTabLabel"]);for(const key of Object.keys(d))if(!live.has(key))hits.push(`dsh.${key}`)}hits.sort();const sig=hits.join(",");if(sig===""||sig===removedDshAllowKeySignature)return;removedDshAllowKeySignature=sig;log("warn",`[acp-config] ${hits.join(", ")} was removed (#3651, superseding #2028) \u2014 value(s) ignored: dsh native compaction is now refused unconditionally by the wire guard on every lane. Delete it from your config to silence this.`)}function resolveResignSettings(env=process.env,provider={},scheme=RESIGN_BUILTIN_SCHEME){const key=scheme.trim().toLowerCase();const file=loadConfigFile().resign?.[key]??{};const providerBlock=provider?.[key]??{};const enabled=env.BILI_RESIGN!==void 0?env.BILI_RESIGN!=="0":providerBlock.enabled!==void 0?providerBlock.enabled:file.enabled!==false;const passthrough=env.BILI_RESIGN_PASSTHROUGH!==void 0?env.BILI_RESIGN_PASSTHROUGH==="1"||env.BILI_RESIGN_PASSTHROUGH==="true":providerBlock.passthrough!==void 0?providerBlock.passthrough:file.passthrough===true;const credentialRef=env.BILI_CODEARTS_REF?.trim()||providerBlock.credentialRef||file.credentialRef||void 0;return{enabled,passthrough,credentialRef}}function warnInertStripImages(obj){const compress=obj.compress;if(!compress||typeof compress!=="object"||Array.isArray(compress))return;const hit=["stripImages","stripImagesKeepRecent"].filter(k2=>compress[k2]!==void 0);const sig=hit.join(",");if(sig===""||sig===seenInertStripImagesSignature)return;seenInertStripImagesSignature=sig;log("warn",`[acp-config] compress.${hit.join("/compress.")} is INERT \u2014 compress.stripImages was removed: media now folds by default (#2640) and decompress({ imageRef }) recovers folded pixels; nothing is stripped from the wire anymore. Remove the key(s) from the config.`)}function warnInertRemovedCompressKeys(obj){const hits=[];const scanBlock=(block,pathPrefix)=>{if(!block||typeof block!=="object"||Array.isArray(block))return;for(const key of INERT_REMOVED_COMPRESS_KEYS){if(block[key]!==void 0)hits.push(`${pathPrefix}.${key}`)}};scanBlock(obj.compress,"compress");const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const[url,entry]of Object.entries(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const p2=entry;scanBlock(p2.compress,`providers["${url}"].compress`);const models=p2.models;if(models&&typeof models==="object"&&!Array.isArray(models)){for(const[model,mEntry]of Object.entries(models)){if(!mEntry||typeof mEntry!=="object"||Array.isArray(mEntry))continue;scanBlock(mEntry.compress,`providers["${url}"].models["${model}"].compress`)}}}}hits.sort();const sig=hits.join(",");if(sig===""||sig===seenInertRemovedCompressKeysSignature)return;seenInertRemovedCompressKeysSignature=sig;log("warn",`[acp-config] ${hits.join(", ")} is INERT \u2014 compress.imageCompression was removed and no longer does anything at any level (image pre-compression + image_full restore channel, #3266). Remove it from the config; images pass through byte-identical.`)}function warnInertResignPassthrough(obj){const inert=[];const consider=(map,providerBlockFor)=>{if(!map||typeof map!=="object"||Array.isArray(map))return;for(const[key,val]of Object.entries(map)){if(key===RESIGN_BUILTIN_SCHEME)continue;const block=val!==null&&typeof val==="object"&&!Array.isArray(val)?val:{};if(block["passthrough"]!==true)continue;const fileBlock=(obj.resign??{})[key];const providerBlock=providerBlockFor(key);const enabled=process.env.BILI_RESIGN!==void 0?process.env.BILI_RESIGN!=="0":providerBlock?.enabled!==void 0?providerBlock.enabled:fileBlock?.enabled!==false;if(enabled)inert.push(key)}};consider(obj.resign,()=>void 0);const providers=obj.providers;if(providers&&typeof providers==="object"&&!Array.isArray(providers)){for(const entry of Object.values(providers)){if(!entry||typeof entry!=="object"||Array.isArray(entry))continue;const pmap=entry.resign;if(pmap===void 0)continue;consider(pmap,key=>(pmap??{})[key])}}inert.sort();const sig=inert.join(",");if(sig===""||sig===inertResignPassthroughSignature)return;inertResignPassthroughSignature=sig;const list=inert.map(k2=>`resign["${k2}"].passthrough`).join(", ");log("warn",`[acp-config] ${list}=true is INERT \u2014 since the #2090 compress-or-refuse contract, unsigned pass-through exists ONLY for the built-in scheme "${RESIGN_BUILTIN_SCHEME}"; those signed requests stay REFUSED until bili ships a re-signer for them. Restore pre-resign handling with resign["<scheme>"].enabled=false or BILI_RESIGN=0 (the upstream will then reject the rewritten bodies).`)}function resolveZonePortBase(env=process.env){const fromEnv=Number.parseInt(env.BILI_ZONE_PORT??"",10);if(Number.isInteger(fromEnv)&&fromEnv>0&&fromEnv<65536)return fromEnv;return ZONE_PORT_BASE}function resolveNativeAttachExternal(env=process.env){const fromEnv=(env.BILI_NATIVE_ATTACH_EXTERNAL??"").trim().toLowerCase();if(fromEnv==="1"||fromEnv==="true")return true;if(fromEnv==="0"||fromEnv==="false")return false;return loadConfigFile().native?.attachExternal===true}function resolveNativeAttachLanePriority(){const raw=loadConfigFile().native?.attachLanePriority;if(!Array.isArray(raw))return[];const out=[];for(const item of raw){if(typeof item!=="string")continue;const t=item.trim();if(t.length>0&&!out.includes(t))out.push(t)}return out}function resolveNativeAttachPolicy(env=process.env){const norm=v2=>(v2??"").trim().toLowerCase();const fromEnv=norm(env.BILI_NATIVE_ATTACH_POLICY);if(fromEnv==="global-fallback"||fromEnv==="global")return"global-fallback";if(fromEnv==="own-lane"||fromEnv==="ownlane"||fromEnv==="strict")return"own-lane";const file=norm(loadConfigFile().native?.attachPolicy);if(file==="global-fallback"||file==="global")return"global-fallback";return"own-lane"}function resolveNativeAttachUrl(env=process.env){const fromEnv=(env.BILI_MCP_PROXY??"").trim();if(fromEnv.length>0)return fromEnv;const file=(loadConfigFile().native?.attachUrl??"").trim();return file.length>0?file:void 0}var KNOWN_TOP_LEVEL_KEYS,COMPRESS_SETTING_FIELDS,seenUnknownTopLevelKeySignatures,configFileCache,removedDshAllowKeySignature,RESIGN_BUILTIN_SCHEME,inertResignPassthroughSignature,seenInertStripImagesSignature,INERT_REMOVED_COMPRESS_KEYS,seenInertRemovedCompressKeysSignature,ZONE_PORT_BASE;var init_config=__esm({"src/config.ts"(){"use strict";init_main();init_paths();init_logger();init_upstream_proxy();init_log_mask();init_util();init_mitm_domains();init_compat_roles();init_compat_drop();init_external_summary_settings();KNOWN_TOP_LEVEL_KEYS=new Set(["port","host","upstream","providersPath","providers","proxy","modelContextLimit","sessionHeader","log","debug","dumpSse","passthrough","autoUpdate","autoRestartOnUpdate","updateTag","advisoryCheck","advisoryUrl","releaseNotesCheck","releaseNotesUrl","upstreamProxy","upstreamProxyMode","logFile","compress","promptCache","mitm","maskHosts","subagentSplit","forkAdoption","affinitySimhash","resumeInheritance","chainContentDetection","chainEgressStamp","stableSystemAnchor","rollout","dsh","compat","imageBilling","imageTokenCap","claude","native","resign","pi","storage","security","network","persist","sessions","plugin","update","diagnostics","fakeCompletion","codexCompact","ccrRetrievalTtlMs","decompressTmpCap","autoModeForge","imageRescale","guardrails","cacheKeepalive"]);COMPRESS_SETTING_FIELDS=new Set(["modelContextLimit","maxContextLimit","emergencyThresholdPercent","nudgeGrowthTokens","minPressureBenefitTokens","tierNudgeTokens","nudgeModelDecided","nudgeDecisionMaxTokens","preserveRecentMessages","preserveRecentTokens","minCompressRange","minCompressRangeChars","outputHeadroomMaxPct","tiers","protectedLatestTools","protectedTools","neverPreserveRecentTools","preserveRecentTools","visibilityMarkers","rules","injectTool","injectNudge","acknowledgePromptsRisk","absorb","ccr","search","prompts","promptPack","reasoningGuard","outputSteering","priceProfile","reconcile","streamSummary"]);seenUnknownTopLevelKeySignatures=new Set;configFileCache=null;removedDshAllowKeySignature="";RESIGN_BUILTIN_SCHEME="sdk-hmac-sha256";inertResignPassthroughSignature=null;seenInertStripImagesSignature="";INERT_REMOVED_COMPRESS_KEYS=["imageCompression"];seenInertRemovedCompressKeysSignature="";ZONE_PORT_BASE=18787}});var init_duration=__esm({"src/duration.ts"(){"use strict"}});import{createHash as createHash4}from"crypto";var MIN_MEDIA_URL_SPLIT_BYTES,MEDIA_URL_MARKER_RE;var init_identity=__esm({"src/storage/identity.ts"(){"use strict";MIN_MEDIA_URL_SPLIT_BYTES=2048;MEDIA_URL_MARKER_RE=new RegExp(`data:([a-zA-Z0-9.+\\/-]+);base64,([A-Za-z0-9+/=]{${MIN_MEDIA_URL_SPLIT_BYTES},})`,"g")}});function storagePragmas(walJournalSizeLimitBytes){return["PRAGMA journal_mode = WAL","PRAGMA synchronous = NORMAL","PRAGMA busy_timeout = 5000","PRAGMA foreign_keys = ON",`PRAGMA journal_size_limit = ${walJournalSizeLimitBytes}`,"PRAGMA auto_vacuum = INCREMENTAL"]}var WAL_JOURNAL_SIZE_LIMIT,STORAGE_PRAGMAS;var init_schema=__esm({"src/storage/schema.ts"(){"use strict";init_identity();init_logger();WAL_JOURNAL_SIZE_LIMIT=8*1024*1024;STORAGE_PRAGMAS=storagePragmas(WAL_JOURNAL_SIZE_LIMIT)}});import path4 from"path";function tNumLoose(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0&&envRaw!=="")return Number(envRaw);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function tInt(envName,fileValue){const envRaw=process.env[envName];if(envRaw!==void 0)return Number.parseInt(envRaw,10);return typeof fileValue==="number"&&Number.isFinite(fileValue)?fileValue:NaN}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v2=envRaw!==void 0?Number.parseInt(envRaw,10):(()=>{const f2=loadConfigFile().sessions?.max;return typeof f2==="number"&&Number.isFinite(f2)?f2:NaN})();return Math.max(1,v2||256)}function sessionResidentMaxBytes(){const v2=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v2)&&v2>=0?Math.floor(v2):512*1024*1024}function updateRegistryBase(){const envRaw=process.env.BILI_UPDATE_REGISTRY;if(envRaw!==void 0&&envRaw.trim().length>0)return envRaw.trim();const f2=loadConfigFile().update?.registry;return typeof f2==="string"&&f2.trim().length>0?f2.trim():void 0}function updateCheckIntervalMs(){const v2=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v2)&&v2>0?Math.floor(v2):3*60*1e3}var DEFAULT_LIMITS_RECEIVE_BYTES,DEFAULT_LIMITS_DECODED_BYTES,DEFAULT_LIMITS_OUTBOUND_BYTES,DEFAULT_WS_OUTBOUND_BYTES;var init_knobs=__esm({"src/knobs.ts"(){"use strict";init_paths();init_config();init_duration();init_fetch_util();init_upstream_proxy();init_schema();DEFAULT_LIMITS_RECEIVE_BYTES=5*1024*1024*1024;DEFAULT_LIMITS_DECODED_BYTES=10*1024*1024*1024;DEFAULT_LIMITS_OUTBOUND_BYTES=5*1024*1024*1024;DEFAULT_WS_OUTBOUND_BYTES=10*1024*1024}});import{readFileSync as readFileSync3,statSync as statSync2}from"fs";import*as tls2 from"tls";var init_upstream_ca=__esm({"src/upstream-ca.ts"(){"use strict";init_logger();init_knobs()}});var MAX_REQUEST_BYTES,MAX_DECODED_REQUEST_BYTES;var init_request_body_budget=__esm({"src/request-body-budget.ts"(){"use strict";init_knobs();MAX_REQUEST_BYTES=100*1024*1024;MAX_DECODED_REQUEST_BYTES=2*MAX_REQUEST_BYTES}});var import_undici2,UPSTREAM_TIMEOUT_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_fetch_transport();init_upstream_fail();init_upstream_ca();init_knobs();init_request_body_budget();init_request_body_budget();UPSTREAM_TIMEOUT_MS=12*60*1e3}});var require_forge=__commonJS({"node_modules/node-forge/lib/forge.js"(exports,module){"use strict";module.exports={options:{usePureJavaScript:false}}}});var require_baseN=__commonJS({"node_modules/node-forge/lib/baseN.js"(exports,module){"use strict";var api={};module.exports=api;var _reverseAlphabets={};api.encode=function(input,alphabet,maxline){if(typeof alphabet!=="string"){throw new TypeError('"alphabet" must be a string.')}if(maxline!==void 0&&typeof maxline!=="number"){throw new TypeError('"maxline" must be a number.')}var output="";if(!(input instanceof Uint8Array)){output=_encodeWithByteBuffer(input,alphabet)}else{var i=0;var base=alphabet.length;var first=alphabet.charAt(0);var digits=[0];for(i=0;i<input.length;++i){for(var j2=0,carry=input[i];j2<digits.length;++j2){carry+=digits[j2]<<8;digits[j2]=carry%base;carry=carry/base|0}while(carry>0){digits.push(carry%base);carry=carry/base|0}}for(i=0;input[i]===0&&i<input.length-1;++i){output+=first}for(i=digits.length-1;i>=0;--i){output+=alphabet[digits[i]]}}if(maxline){var regex=new RegExp(".{1,"+maxline+"}","g");output=output.match(regex).join("\r\n")}return output};api.decode=function(input,alphabet){if(typeof input!=="string"){throw new TypeError('"input" must be a string.')}if(typeof alphabet!=="string"){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;var first=alphabet.charAt(0);var bytes=[0];for(var i=0;i<input.length;i++){var value=table[input.charCodeAt(i)];if(value===void 0){return}for(var j2=0,carry=value;j2<bytes.length;++j2){carry+=bytes[j2]*base;bytes[j2]=carry&255;carry>>=8}while(carry>0){bytes.push(carry&255);carry>>=8}}for(var k2=0;input[k2]===first&&k2<input.length-1;++k2){bytes.push(0)}if(typeof Buffer!=="undefined"){return Buffer.from(bytes.reverse())}return new Uint8Array(bytes.reverse())};function _encodeWithByteBuffer(input,alphabet){var i=0;var base=alphabet.length;var first=alphabet.charAt(0);var digits=[0];for(i=0;i<input.length();++i){for(var j2=0,carry=input.at(i);j2<digits.length;++j2){carry+=digits[j2]<<8;digits[j2]=carry%base;carry=carry/base|0}while(carry>0){digits.push(carry%base);carry=carry/base|0}}var output="";for(i=0;input.at(i)===0&&i<input.length()-1;++i){output+=first}for(i=digits.length-1;i>=0;--i){output+=alphabet[digits[i]]}return output}}});var require_util7=__commonJS({"node_modules/node-forge/lib/util.js"(exports,module){"use strict";var forge2=require_forge();var baseN=require_baseN();var util=module.exports=forge2.util=forge2.util||{};(function(){if(typeof process!=="undefined"&&process.nextTick&&!process.browser){util.nextTick=process.nextTick;if(typeof setImmediate==="function"){util.setImmediate=setImmediate}else{util.setImmediate=util.nextTick}return}if(typeof setImmediate==="function"){util.setImmediate=function(){return setImmediate.apply(void 0,arguments)};util.nextTick=function(callback){return setImmediate(callback)};return}util.setImmediate=function(callback){setTimeout(callback,0)};if(typeof window!=="undefined"&&typeof window.postMessage==="function"){let handler2=function(event){if(event.source===window&&event.data===msg){event.stopPropagation();var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}};var handler=handler2;var msg="forge.setImmediate";var callbacks=[];util.setImmediate=function(callback){callbacks.push(callback);if(callbacks.length===1){window.postMessage(msg,"*")}};window.addEventListener("message",handler2,true)}if(typeof MutationObserver!=="undefined"){var now=Date.now();var attr=true;var div=document.createElement("div");var callbacks=[];new MutationObserver(function(){var copy=callbacks.slice();callbacks.length=0;copy.forEach(function(callback){callback()})}).observe(div,{attributes:true});var oldSetImmediate=util.setImmediate;util.setImmediate=function(callback){if(Date.now()-now>15){now=Date.now();oldSetImmediate(callback)}else{callbacks.push(callback);if(callbacks.length===1){div.setAttribute("a",attr=!attr)}}}}util.nextTick=util.setImmediate})();util.isNodejs=typeof process!=="undefined"&&process.versions&&process.versions.node;util.globalScope=(function(){if(util.isNodejs){return global}return typeof self==="undefined"?window:self})();util.isArray=Array.isArray||function(x){return Object.prototype.toString.call(x)==="[object Array]"};util.isArrayBuffer=function(x){return typeof ArrayBuffer!=="undefined"&&x instanceof ArrayBuffer};util.isArrayBufferView=function(x){return x&&util.isArrayBuffer(x.buffer)&&x.byteLength!==void 0};function _checkBitsParam(n){if(!(n===8||n===16||n===24||n===32)){throw new Error("Only 8, 16, 24, or 32 bits supported: "+n)}}util.ByteBuffer=ByteStringBuffer;function ByteStringBuffer(b2){this.data="";this.read=0;if(typeof b2==="string"){this.data=b2}else if(util.isArrayBuffer(b2)||util.isArrayBufferView(b2)){if(typeof Buffer!=="undefined"&&b2 instanceof Buffer){this.data=b2.toString("binary")}else{var arr=new Uint8Array(b2);try{this.data=String.fromCharCode.apply(null,arr)}catch(e){for(var i=0;i<arr.length;++i){this.putByte(arr[i])}}}}else if(b2 instanceof ByteStringBuffer||typeof b2==="object"&&typeof b2.data==="string"&&typeof b2.read==="number"){this.data=b2.data;this.read=b2.read}this._constructedStringLength=0}util.ByteStringBuffer=ByteStringBuffer;var _MAX_CONSTRUCTED_STRING_LENGTH=4096;util.ByteStringBuffer.prototype._optimizeConstructedString=function(x){this._constructedStringLength+=x;if(this._constructedStringLength>_MAX_CONSTRUCTED_STRING_LENGTH){this.data.substr(0,1);this._constructedStringLength=0}};util.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};util.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};util.ByteStringBuffer.prototype.putByte=function(b2){return this.putBytes(String.fromCharCode(b2))};util.ByteStringBuffer.prototype.fillWithByte=function(b2,n){b2=String.fromCharCode(b2);var d=this.data;while(n>0){if(n&1){d+=b2}n>>>=1;if(n>0){b2+=b2}}this.data=d;this._optimizeConstructedString(n);return this};util.ByteStringBuffer.prototype.putBytes=function(bytes){this.data+=bytes;this._optimizeConstructedString(bytes.length);return this};util.ByteStringBuffer.prototype.putString=function(str){return this.putBytes(util.encodeUtf8(str))};util.ByteStringBuffer.prototype.putInt16=function(i){return this.putBytes(String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.ByteStringBuffer.prototype.putInt24=function(i){return this.putBytes(String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255))};util.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(i&255))};util.ByteStringBuffer.prototype.putInt16Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255))};util.ByteStringBuffer.prototype.putInt24Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255))};util.ByteStringBuffer.prototype.putInt32Le=function(i){return this.putBytes(String.fromCharCode(i&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>24&255))};util.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.ByteStringBuffer.prototype.putSignedInt=function(i,n){if(i<0){i+=2<<n-1}return this.putInt(i,n)};util.ByteStringBuffer.prototype.putBuffer=function(buffer){return this.putBytes(buffer.getBytes())};util.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};util.ByteStringBuffer.prototype.getInt16=function(){var rval=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);this.read+=2;return rval};util.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);this.read+=3;return rval};util.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);this.read+=4;return rval};util.ByteStringBuffer.prototype.getInt16Le=function(){var rval=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;this.read+=2;return rval};util.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;this.read+=3;return rval};util.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;this.read+=4;return rval};util.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.ByteStringBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<<n-2;if(x>=max){x-=max<<1}return x};util.ByteStringBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.ByteStringBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.ByteStringBuffer.prototype.at=function(i){return this.data.charCodeAt(this.read+i)};util.ByteStringBuffer.prototype.setAt=function(i,b2){this.data=this.data.substr(0,this.read+i)+String.fromCharCode(b2)+this.data.substr(this.read+i+1);return this};util.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};util.ByteStringBuffer.prototype.copy=function(){var c=util.createBuffer(this.data);c.read=this.read;return c};util.ByteStringBuffer.prototype.compact=function(){if(this.read>0){this.data=this.data.slice(this.read);this.read=0}return this};util.ByteStringBuffer.prototype.clear=function(){this.data="";this.read=0;return this};util.ByteStringBuffer.prototype.truncate=function(count){var len=Math.max(0,this.length()-count);this.data=this.data.substr(this.read,len);this.read=0;return this};util.ByteStringBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i<this.data.length;++i){var b2=this.data.charCodeAt(i);if(b2<16){rval+="0"}rval+=b2.toString(16)}return rval};util.ByteStringBuffer.prototype.toString=function(){return util.decodeUtf8(this.bytes())};function DataBuffer(b2,options){options=options||{};this.read=options.readOffset||0;this.growSize=options.growSize||1024;var isArrayBuffer=util.isArrayBuffer(b2);var isArrayBufferView=util.isArrayBufferView(b2);if(isArrayBuffer||isArrayBufferView){if(isArrayBuffer){this.data=new DataView(b2)}else{this.data=new DataView(b2.buffer,b2.byteOffset,b2.byteLength)}this.write="writeOffset"in options?options.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0));this.write=0;if(b2!==null&&b2!==void 0){this.putBytes(b2)}if("writeOffset"in options){this.write=options.writeOffset}}util.DataBuffer=DataBuffer;util.DataBuffer.prototype.length=function(){return this.write-this.read};util.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};util.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);var dst=new Uint8Array(this.length()+growSize);dst.set(src);this.data=new DataView(dst.buffer);return this};util.DataBuffer.prototype.putByte=function(b2){this.accommodate(1);this.data.setUint8(this.write++,b2);return this};util.DataBuffer.prototype.fillWithByte=function(b2,n){this.accommodate(n);for(var i=0;i<n;++i){this.data.setUint8(b2)}return this};util.DataBuffer.prototype.putBytes=function(bytes,encoding){if(util.isArrayBufferView(bytes)){var src=new Uint8Array(bytes.buffer,bytes.byteOffset,bytes.byteLength);var len=src.byteLength-src.byteOffset;this.accommodate(len);var dst=new Uint8Array(this.data.buffer,this.write);dst.set(src);this.write+=len;return this}if(util.isArrayBuffer(bytes)){var src=new Uint8Array(bytes);this.accommodate(src.byteLength);var dst=new Uint8Array(this.data.buffer);dst.set(src,this.write);this.write+=src.byteLength;return this}if(bytes instanceof util.DataBuffer||typeof bytes==="object"&&typeof bytes.read==="number"&&typeof bytes.write==="number"&&util.isArrayBufferView(bytes.data)){var src=new Uint8Array(bytes.data.byteLength,bytes.read,bytes.length());this.accommodate(src.byteLength);var dst=new Uint8Array(bytes.data.byteLength,this.write);dst.set(src);this.write+=src.byteLength;return this}if(bytes instanceof util.ByteStringBuffer){bytes=bytes.data;encoding="binary"}encoding=encoding||"binary";if(typeof bytes==="string"){var view;if(encoding==="hex"){this.accommodate(Math.ceil(bytes.length/2));view=new Uint8Array(this.data.buffer,this.write);this.write+=util.binary.hex.decode(bytes,view,this.write);return this}if(encoding==="base64"){this.accommodate(Math.ceil(bytes.length/4)*3);view=new Uint8Array(this.data.buffer,this.write);this.write+=util.binary.base64.decode(bytes,view,this.write);return this}if(encoding==="utf8"){bytes=util.encodeUtf8(bytes);encoding="binary"}if(encoding==="binary"||encoding==="raw"){this.accommodate(bytes.length);view=new Uint8Array(this.data.buffer,this.write);this.write+=util.binary.raw.decode(view);return this}if(encoding==="utf16"){this.accommodate(bytes.length*2);view=new Uint16Array(this.data.buffer,this.write);this.write+=util.text.utf16.encode(view);return this}throw new Error("Invalid encoding: "+encoding)}throw Error("Invalid parameter: "+bytes)};util.DataBuffer.prototype.putBuffer=function(buffer){this.putBytes(buffer);buffer.clear();return this};util.DataBuffer.prototype.putString=function(str){return this.putBytes(str,"utf16")};util.DataBuffer.prototype.putInt16=function(i){this.accommodate(2);this.data.setInt16(this.write,i);this.write+=2;return this};util.DataBuffer.prototype.putInt24=function(i){this.accommodate(3);this.data.setInt16(this.write,i>>8&65535);this.data.setInt8(this.write,i>>16&255);this.write+=3;return this};util.DataBuffer.prototype.putInt32=function(i){this.accommodate(4);this.data.setInt32(this.write,i);this.write+=4;return this};util.DataBuffer.prototype.putInt16Le=function(i){this.accommodate(2);this.data.setInt16(this.write,i,true);this.write+=2;return this};util.DataBuffer.prototype.putInt24Le=function(i){this.accommodate(3);this.data.setInt8(this.write,i>>16&255);this.data.setInt16(this.write,i>>8&65535,true);this.write+=3;return this};util.DataBuffer.prototype.putInt32Le=function(i){this.accommodate(4);this.data.setInt32(this.write,i,true);this.write+=4;return this};util.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.DataBuffer.prototype.putSignedInt=function(i,n){_checkBitsParam(n);this.accommodate(n/8);if(i<0){i+=2<<n-1}return this.putInt(i,n)};util.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};util.DataBuffer.prototype.getInt16=function(){var rval=this.data.getInt16(this.read);this.read+=2;return rval};util.DataBuffer.prototype.getInt24=function(){var rval=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);this.read+=3;return rval};util.DataBuffer.prototype.getInt32=function(){var rval=this.data.getInt32(this.read);this.read+=4;return rval};util.DataBuffer.prototype.getInt16Le=function(){var rval=this.data.getInt16(this.read,true);this.read+=2;return rval};util.DataBuffer.prototype.getInt24Le=function(){var rval=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,true)<<8;this.read+=3;return rval};util.DataBuffer.prototype.getInt32Le=function(){var rval=this.data.getInt32(this.read,true);this.read+=4;return rval};util.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.DataBuffer.prototype.getSignedInt=function(n){var x=this.getInt(n);var max=2<<n-2;if(x>=max){x-=max<<1}return x};util.DataBuffer.prototype.getBytes=function(count){var rval;if(count){count=Math.min(this.length(),count);rval=this.data.slice(this.read,this.read+count);this.read+=count}else if(count===0){rval=""}else{rval=this.read===0?this.data:this.data.slice(this.read);this.clear()}return rval};util.DataBuffer.prototype.bytes=function(count){return typeof count==="undefined"?this.data.slice(this.read):this.data.slice(this.read,this.read+count)};util.DataBuffer.prototype.at=function(i){return this.data.getUint8(this.read+i)};util.DataBuffer.prototype.setAt=function(i,b2){this.data.setUint8(i,b2);return this};util.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};util.DataBuffer.prototype.copy=function(){return new util.DataBuffer(this)};util.DataBuffer.prototype.compact=function(){if(this.read>0){var src=new Uint8Array(this.data.buffer,this.read);var dst=new Uint8Array(src.byteLength);dst.set(src);this.data=new DataView(dst);this.write-=this.read;this.read=0}return this};util.DataBuffer.prototype.clear=function(){this.data=new DataView(new ArrayBuffer(0));this.read=this.write=0;return this};util.DataBuffer.prototype.truncate=function(count){this.write=Math.max(0,this.length()-count);this.read=Math.min(this.read,this.write);return this};util.DataBuffer.prototype.toHex=function(){var rval="";for(var i=this.read;i<this.data.byteLength;++i){var b2=this.data.getUint8(i);if(b2<16){rval+="0"}rval+=b2.toString(16)}return rval};util.DataBuffer.prototype.toString=function(encoding){var view=new Uint8Array(this.data,this.read,this.length());encoding=encoding||"utf8";if(encoding==="binary"||encoding==="raw"){return util.binary.raw.encode(view)}if(encoding==="hex"){return util.binary.hex.encode(view)}if(encoding==="base64"){return util.binary.base64.encode(view)}if(encoding==="utf8"){return util.text.utf8.decode(view)}if(encoding==="utf16"){return util.text.utf16.decode(view)}throw new Error("Invalid encoding: "+encoding)};util.createBuffer=function(input,encoding){encoding=encoding||"raw";if(input!==void 0&&encoding==="utf8"){input=util.encodeUtf8(input)}return new util.ByteBuffer(input)};util.fillString=function(c,n){var s3="";while(n>0){if(n&1){s3+=c}n>>>=1;if(n>0){c+=c}}return s3};util.xorBytes=function(s1,s22,n){var s3="";var b2="";var t="";var i=0;var c=0;for(;n>0;--n,++i){b2=s1.charCodeAt(i)^s22.charCodeAt(i);if(c>=10){s3+=t;t="";c=0}t+=String.fromCharCode(b2);++c}s3+=t;return s3};util.hexToBytes=function(hex){var rval="";var i=0;if(hex.length&true){i=1;rval+=String.fromCharCode(parseInt(hex[0],16))}for(;i<hex.length;i+=2){rval+=String.fromCharCode(parseInt(hex.substr(i,2),16))}return rval};util.bytesToHex=function(bytes){return util.createBuffer(bytes).toHex()};util.int32ToBytes=function(i){return String.fromCharCode(i>>24&255)+String.fromCharCode(i>>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(i&255)};var _base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var _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];var _base58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";util.encode64=function(input,maxline){var line="";var output="";var chr1,chr2,chr3;var i=0;while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);line+=_base64.charAt(chr1>>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.decode64=function(input){input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");var output="";var enc1,enc2,enc3,enc4;var i=0;while(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);if(enc3!==64){output+=String.fromCharCode((enc2&15)<<4|enc3>>2);if(enc4!==64){output+=String.fromCharCode((enc3&3)<<6|enc4)}}}return output};util.encodeUtf8=function(str){return unescape(encodeURIComponent(str))};util.decodeUtf8=function(str){return decodeURIComponent(escape(str))};util.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:baseN.encode,decode:baseN.decode}};util.binary.raw.encode=function(bytes){return String.fromCharCode.apply(null,bytes)};util.binary.raw.decode=function(str,output,offset){var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j2=offset;for(var i=0;i<str.length;++i){out[j2++]=str.charCodeAt(i)}return output?j2-offset:out};util.binary.hex.encode=util.bytesToHex;util.binary.hex.decode=function(hex,output,offset){var out=output;if(!out){out=new Uint8Array(Math.ceil(hex.length/2))}offset=offset||0;var i=0,j2=offset;if(hex.length&1){i=1;out[j2++]=parseInt(hex[0],16)}for(;i<hex.length;i+=2){out[j2++]=parseInt(hex.substr(i,2),16)}return output?j2-offset:out};util.binary.base64.encode=function(input,maxline){var line="";var output="";var chr1,chr2,chr3;var i=0;while(i<input.byteLength){chr1=input[i++];chr2=input[i++];chr3=input[i++];line+=_base64.charAt(chr1>>2);line+=_base64.charAt((chr1&3)<<4|chr2>>4);if(isNaN(chr2)){line+="=="}else{line+=_base64.charAt((chr2&15)<<2|chr3>>6);line+=isNaN(chr3)?"=":_base64.charAt(chr3&63)}if(maxline&&line.length>maxline){output+=line.substr(0,maxline)+"\r\n";line=line.substr(maxline)}}output+=line;return output};util.binary.base64.decode=function(input,output,offset){var out=output;if(!out){out=new Uint8Array(Math.ceil(input.length/4)*3)}input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");offset=offset||0;var enc1,enc2,enc3,enc4;var i=0,j2=offset;while(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[j2++]=enc1<<2|enc2>>4;if(enc3!==64){out[j2++]=(enc2&15)<<4|enc3>>2;if(enc4!==64){out[j2++]=(enc3&3)<<6|enc4}}}return output?j2-offset:out.subarray(0,j2)};util.binary.base58.encode=function(input,maxline){return util.binary.baseN.encode(input,_base58,maxline)};util.binary.base58.decode=function(input,maxline){return util.binary.baseN.decode(input,_base58,maxline)};util.text={utf8:{},utf16:{}};util.text.utf8.encode=function(str,output,offset){str=util.encodeUtf8(str);var out=output;if(!out){out=new Uint8Array(str.length)}offset=offset||0;var j2=offset;for(var i=0;i<str.length;++i){out[j2++]=str.charCodeAt(i)}return output?j2-offset:out};util.text.utf8.decode=function(bytes){return util.decodeUtf8(String.fromCharCode.apply(null,bytes))};util.text.utf16.encode=function(str,output,offset){var out=output;if(!out){out=new Uint8Array(str.length*2)}var view=new Uint16Array(out.buffer);offset=offset||0;var j2=offset;var k2=offset;for(var i=0;i<str.length;++i){view[k2++]=str.charCodeAt(i);j2+=2}return output?j2-offset:out};util.text.utf16.decode=function(bytes){return String.fromCharCode.apply(null,new Uint16Array(bytes.buffer))};util.deflate=function(api,bytes,raw){bytes=util.decode64(api.deflate(util.encode64(bytes)).rval);if(raw){var start=2;var flg=bytes.charCodeAt(1);if(flg&32){start=6}bytes=bytes.substring(start,bytes.length-4)}return bytes};util.inflate=function(api,bytes,raw){var rval=api.inflate(util.encode64(bytes)).rval;return rval===null?null:util.decode64(rval)};var _setStorageObject=function(api,id,obj){if(!api){throw new Error("WebStorage not available.")}var rval;if(obj===null){rval=api.removeItem(id)}else{obj=util.encode64(JSON.stringify(obj));rval=api.setItem(id,obj)}if(typeof rval!=="undefined"&&rval.rval!==true){var error=new Error(rval.error.message);error.id=rval.error.id;error.name=rval.error.name;throw error}};var _getStorageObject=function(api,id){if(!api){throw new Error("WebStorage not available.")}var rval=api.getItem(id);if(api.init){if(rval.rval===null){if(rval.error){var error=new Error(rval.error.message);error.id=rval.error.id;error.name=rval.error.name;throw error}rval=null}else{rval=rval.rval}}if(rval!==null){rval=JSON.parse(util.decode64(rval))}return rval};var _setItem=function(api,id,key,data){var obj=_getStorageObject(api,id);if(obj===null){obj={}}obj[key]=data;_setStorageObject(api,id,obj)};var _getItem=function(api,id,key){var rval=_getStorageObject(api,id);if(rval!==null){rval=key in rval?rval[key]:null}return rval};var _removeItem=function(api,id,key){var obj=_getStorageObject(api,id);if(obj!==null&&key in obj){delete obj[key];var empty=true;for(var prop in obj){empty=false;break}if(empty){obj=null}_setStorageObject(api,id,obj)}};var _clearItems=function(api,id){_setStorageObject(api,id,null)};var _callStorageFunction=function(func,args,location){var rval=null;if(typeof location==="undefined"){location=["web","flash"]}var type;var done=false;var exception=null;for(var idx in location){type=location[idx];try{if(type==="flash"||type==="both"){if(args[0]===null){throw new Error("Flash local storage not available.")}rval=func.apply(this,args);done=type==="flash"}if(type==="web"||type==="both"){args[0]=localStorage;rval=func.apply(this,args);done=true}}catch(ex){exception=ex}if(done){break}}if(!done){throw exception}return rval};util.setItem=function(api,id,key,data,location){_callStorageFunction(_setItem,arguments,location)};util.getItem=function(api,id,key,location){return _callStorageFunction(_getItem,arguments,location)};util.removeItem=function(api,id,key,location){_callStorageFunction(_removeItem,arguments,location)};util.clearItems=function(api,id,location){_callStorageFunction(_clearItems,arguments,location)};util.isEmpty=function(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){return false}}return true};util.format=function(format2){var re2=/%./g;var match;var part;var argi=0;var parts=[];var last=0;while(match=re2.exec(format2)){part=format2.substring(last,re2.lastIndex-2);if(part.length>0){parts.push(part)}last=re2.lastIndex;var code=match[0][1];switch(code){case"s":case"o":if(argi<arguments.length){parts.push(arguments[argi+++1])}else{parts.push("<?>")}break;case"%":parts.push("%");break;default:parts.push("<%"+code+"?>")}}parts.push(format2.substring(last));return parts.join("")};util.formatNumber=function(number,decimals,dec_point,thousands_sep){var n=number,c=isNaN(decimals=Math.abs(decimals))?2:decimals;var d=dec_point===void 0?",":dec_point;var t=thousands_sep===void 0?".":thousands_sep,s3=n<0?"-":"";var i=parseInt(n=Math.abs(+n||0).toFixed(c),10)+"";var j2=i.length>3?i.length%3:0;return s3+(j2?i.substr(0,j2)+t:"")+i.substr(j2).replace(/(\d{3})(?=\d)/g,"$1"+t)+(c?d+Math.abs(n-i).toFixed(c).slice(2):"")};util.formatSize=function(size){if(size>=1073741824){size=util.formatNumber(size/1073741824,2,".","")+" GiB"}else if(size>=1048576){size=util.formatNumber(size/1048576,2,".","")+" MiB"}else if(size>=1024){size=util.formatNumber(size/1024,0)+" KiB"}else{size=util.formatNumber(size,0)+" bytes"}return size};util.bytesFromIP=function(ip){if(ip.indexOf(".")!==-1){return util.bytesFromIPv4(ip)}if(ip.indexOf(":")!==-1){return util.bytesFromIPv6(ip)}return null};util.bytesFromIPv4=function(ip){ip=ip.split(".");if(ip.length!==4){return null}var b2=util.createBuffer();for(var i=0;i<ip.length;++i){var num=parseInt(ip[i],10);if(isNaN(num)){return null}b2.putByte(num)}return b2.getBytes()};util.bytesFromIPv6=function(ip){var blanks=0;ip=ip.split(":").filter(function(e){if(e.length===0)++blanks;return true});var zeros=(8-ip.length+blanks)*2;var b2=util.createBuffer();for(var i=0;i<8;++i){if(!ip[i]||ip[i].length===0){b2.fillWithByte(0,zeros);zeros=0;continue}var bytes=util.hexToBytes(ip[i]);if(bytes.length<2){b2.putByte(0)}b2.putBytes(bytes)}return b2.getBytes()};util.bytesToIP=function(bytes){if(bytes.length===4){return util.bytesToIPv4(bytes)}if(bytes.length===16){return util.bytesToIPv6(bytes)}return null};util.bytesToIPv4=function(bytes){if(bytes.length!==4){return null}var ip=[];for(var i=0;i<bytes.length;++i){ip.push(bytes.charCodeAt(i))}return ip.join(".")};util.bytesToIPv6=function(bytes){if(bytes.length!==16){return null}var ip=[];var zeroGroups=[];var zeroMaxGroup=0;for(var i=0;i<bytes.length;i+=2){var hex=util.bytesToHex(bytes[i]+bytes[i+1]);while(hex[0]==="0"&&hex!=="0"){hex=hex.substr(1)}if(hex==="0"){var last=zeroGroups[zeroGroups.length-1];var idx=ip.length;if(!last||idx!==last.end+1){zeroGroups.push({start:idx,end:idx})}else{last.end=idx;if(last.end-last.start>zeroGroups[zeroMaxGroup].end-zeroGroups[zeroMaxGroup].start){zeroMaxGroup=zeroGroups.length-1}}}ip.push(hex)}if(zeroGroups.length>0){var group=zeroGroups[zeroMaxGroup];if(group.end-group.start>0){ip.splice(group.start,group.end-group.start+1,"");if(group.start===0){ip.unshift("")}if(group.end===7){ip.push("")}}}return ip.join(":")};util.estimateCores=function(options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};if("cores"in util&&!options.update){return callback(null,util.cores)}if(typeof navigator!=="undefined"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0){util.cores=navigator.hardwareConcurrency;return callback(null,util.cores)}if(typeof Worker==="undefined"){util.cores=1;return callback(null,util.cores)}if(typeof Blob==="undefined"){util.cores=2;return callback(null,util.cores)}var blobUrl=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){var st2=Date.now();var et2=st2+4;while(Date.now()<et2);self.postMessage({st:st2,et:et2})})}.toString(),")()"],{type:"application/javascript"}));sample([],5,16);function sample(max,samples,numWorkers){if(samples===0){var avg=Math.floor(max.reduce(function(avg2,x){return avg2+x},0)/max.length);util.cores=Math.max(1,avg);URL.revokeObjectURL(blobUrl);return callback(null,util.cores)}map(numWorkers,function(err,results){max.push(reduce(numWorkers,results));sample(max,samples-1,numWorkers)})}function map(numWorkers,callback2){var workers=[];var results=[];for(var i=0;i<numWorkers;++i){var worker=new Worker(blobUrl);worker.addEventListener("message",function(e){results.push(e.data);if(results.length===numWorkers){for(var i2=0;i2<numWorkers;++i2){workers[i2].terminate()}callback2(null,results)}});workers.push(worker)}for(var i=0;i<numWorkers;++i){workers[i].postMessage(i)}}function reduce(numWorkers,results){var overlaps=[];for(var n=0;n<numWorkers;++n){var r1=results[n];var overlap=overlaps[n]=[];for(var i=0;i<numWorkers;++i){if(n===i){continue}var r2=results[i];if(r1.st>r2.st&&r1.st<r2.et||r2.st>r1.st&&r2.st<r1.et){overlap.push(i)}}}return overlaps.reduce(function(max,overlap2){return Math.max(max,overlap2.length)},0)}}}});var require_cipher=__commonJS({"node_modules/node-forge/lib/cipher.js"(exports,module){"use strict";var forge2=require_forge();require_util7();module.exports=forge2.cipher=forge2.cipher||{};forge2.cipher.algorithms=forge2.cipher.algorithms||{};forge2.cipher.createCipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge2.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge2.cipher.BlockCipher({algorithm:api,key,decrypt:false})};forge2.cipher.createDecipher=function(algorithm,key){var api=algorithm;if(typeof api==="string"){api=forge2.cipher.getAlgorithm(api);if(api){api=api()}}if(!api){throw new Error("Unsupported algorithm: "+algorithm)}return new forge2.cipher.BlockCipher({algorithm:api,key,decrypt:true})};forge2.cipher.registerAlgorithm=function(name,algorithm){name=name.toUpperCase();forge2.cipher.algorithms[name]=algorithm};forge2.cipher.getAlgorithm=function(name){name=name.toUpperCase();if(name in forge2.cipher.algorithms){return forge2.cipher.algorithms[name]}return null};var BlockCipher=forge2.cipher.BlockCipher=function(options){this.algorithm=options.algorithm;this.mode=this.algorithm.mode;this.blockSize=this.mode.blockSize;this._finish=false;this._input=null;this.output=null;this._op=options.decrypt?this.mode.decrypt:this.mode.encrypt;this._decrypt=options.decrypt;this.algorithm.initialize(options)};BlockCipher.prototype.start=function(options){options=options||{};var opts={};for(var key in options){opts[key]=options[key]}opts.decrypt=this._decrypt;this._finish=false;this._input=forge2.util.createBuffer();this.output=options.output||forge2.util.createBuffer();this.mode.start(opts)};BlockCipher.prototype.update=function(input){if(input){this._input.putBuffer(input)}while(!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish){}this._input.compact()};BlockCipher.prototype.finish=function(pad){if(pad&&(this.mode.name==="ECB"||this.mode.name==="CBC")){this.mode.pad=function(input){return pad(this.blockSize,input,false)};this.mode.unpad=function(output){return pad(this.blockSize,output,true)}}var options={};options.decrypt=this._decrypt;options.overflow=this._input.length()%this.blockSize;if(!this._decrypt&&this.mode.pad){if(!this.mode.pad(this._input,options)){return false}}this._finish=true;this.update();if(this._decrypt&&this.mode.unpad){if(!this.mode.unpad(this.output,options)){return false}}if(this.mode.afterFinish){if(!this.mode.afterFinish(this.output,options)){return false}}return true}}});var require_cipherModes=__commonJS({"node_modules/node-forge/lib/cipherModes.js"(exports,module){"use strict";var forge2=require_forge();require_util7();forge2.cipher=forge2.cipher||{};var modes=module.exports=forge2.cipher.modes=forge2.cipher.modes||{};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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()}this.cipher.encrypt(this._inBlock,this._outBlock);for(var 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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()}this.cipher.decrypt(this._inBlock,this._outBlock);for(var 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();input.fillWithByte(padding,padding);return true};modes.ecb.prototype.unpad=function(output,options){if(options.overflow>0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};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(options.iv===null){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.")}else{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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=this._prev[i]^input.getInt32()}this.cipher.encrypt(this._inBlock,this._outBlock);for(var 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 true}for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()}this.cipher.decrypt(this._inBlock,this._outBlock);for(var 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();input.fillWithByte(padding,padding);return true};modes.cbc.prototype.unpad=function(output,options){if(options.overflow>0){return false}var len=output.length();var count=output.at(len-1);if(count>this.blockSize<<2){return false}output.truncate(count);return true};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=forge2.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(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32()^this._outBlock[i];output.putInt32(this._inBlock[i])}return}var partialBytes=(this.blockSize-inputLength)%this.blockSize;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var 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(var i=0;i<this._ints;++i){this._inBlock[i]=this._partialBlock[i]}}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}output.putBytes(this._partialOutput.getBytes(inputLength-this._partialBytes));this._partialBytes=0};modes.cfb.prototype.decrypt=function(input,output,finish){var inputLength=input.length();if(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i<this._ints;++i){this._inBlock[i]=input.getInt32();output.putInt32(this._inBlock[i]^this._outBlock[i])}return}var partialBytes=(this.blockSize-inputLength)%this.blockSize;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var 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(var i=0;i<this._ints;++i){this._inBlock[i]=this._partialBlock[i]}}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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=forge2.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(input.length()===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&inputLength>=this.blockSize){for(var i=0;i<this._ints;++i){output.putInt32(input.getInt32()^this._outBlock[i]);this._inBlock[i]=this._outBlock[i]}return}var partialBytes=(this.blockSize-inputLength)%this.blockSize;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i<this._ints;++i){this._partialOutput.putInt32(input.getInt32()^this._outBlock[i])}if(partialBytes>0){input.read-=this.blockSize}else{for(var i=0;i<this._ints;++i){this._inBlock[i]=this._outBlock[i]}}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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=forge2.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(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&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;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var i=0;i<this._ints;++i){this._partialOutput.putInt32(input.getInt32()^this._outBlock[i])}if(partialBytes>0){input.read-=this.blockSize}if(this._partialBytes>0){this._partialOutput.getBytes(this._partialBytes)}if(partialBytes>0&&!finish){output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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=forge2.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 iv=forge2.util.createBuffer(options.iv);this._cipherLength=0;var additionalData;if("additionalData"in options){additionalData=forge2.util.createBuffer(options.additionalData)}else{additionalData=forge2.util.createBuffer()}if("tagLength"in options){this._tagLength=options.tagLength}else{this._tagLength=128}this._tag=null;if(options.decrypt){this._tag=forge2.util.createBuffer(options.tag).getBytes();if(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(ivLength===12){this._j0=[iv.getInt32(),iv.getInt32(),iv.getInt32(),1]}else{this._j0=[0,0,0,0];while(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(ivLength*8)))}this._inBlock=this._j0.slice(0);inc32(this._inBlock);this._partialBytes=0;additionalData=forge2.util.createBuffer(additionalData);this._aDataLength=from64To32(additionalData.length()*8);var overflow=additionalData.length()%this.blockSize;if(overflow){additionalData.fillWithByte(0,this.blockSize-overflow)}this._s=[0,0,0,0];while(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(inputLength===0){return true}this.cipher.encrypt(this._inBlock,this._outBlock);if(this._partialBytes===0&&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;if(partialBytes>0){partialBytes=this.blockSize-partialBytes}this._partialOutput.clear();for(var 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(var 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)}if(partialBytes>0&&!finish){input.read-=this.blockSize;output.putBytes(this._partialOutput.getBytes(partialBytes-this._partialBytes));this._partialBytes=partialBytes;return true}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 true}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])}if(inputLength<this.blockSize){this._cipherLength+=inputLength%this.blockSize}else{this._cipherLength+=this.blockSize}};modes.gcm.prototype.afterFinish=function(output,options){var rval=true;if(options.decrypt&&options.overflow){output.truncate(this.blockSize-options.overflow)}this.tag=forge2.util.createBuffer();var lengths=this._aDataLength.concat(from64To32(this._cipherLength*8));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])}this.tag.truncate(this.tag.length()%(this._tagLength/8));if(options.decrypt&&this.tag.bytes()!==this._tag){rval=false}return rval};modes.gcm.prototype.multiply=function(x,y){var z_i=[0,0,0,0];var v_i=y.slice(0);for(var i=0;i<128;++i){var x_i=x[i/32|0]&1<<31-i%32;if(x_i){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){var lsb=x[3]&1;for(var i=3;i>0;--i){out[i]=x[i]>>>1|(x[i-1]&1)<<31}out[0]=x[0]>>>1;if(lsb){out[0]^=this._R}};modes.gcm.prototype.tableMultiply=function(x){var z2=[0,0,0,0];for(var i=0;i<32;++i){var idx=i/8|0;var x_i=x[idx]>>>(7-i%8)*4&15;var ah=this._m[i][x_i];z2[0]^=ah[0];z2[1]^=ah[1];z2[2]^=ah[2];z2[3]^=ah[3]}return z2};modes.gcm.prototype.ghash=function(h,y,x){y[0]^=x[0];y[1]^=x[1];y[2]^=x[2];y[3]^=x[3];return this.tableMultiply(y)};modes.gcm.prototype.generateHashTable=function(h,bits){var multiplier=8/bits;var perInt=4*multiplier;var size=16*multiplier;var m2=new Array(size);for(var i=0;i<size;++i){var tmp=[0,0,0,0];var idx=i/perInt|0;var shft=(perInt-1-i%perInt)*bits;tmp[idx]=1<<bits-1<<shft;m2[i]=this.generateSubHashTable(this.multiply(tmp,h),bits)}return m2};modes.gcm.prototype.generateSubHashTable=function(mid,bits){var size=1<<bits;var half=size>>>1;var m2=new Array(size);m2[half]=mid.slice(0);var i=half>>>1;while(i>0){this.pow(m2[2*i],m2[i]=[]);i>>=1}i=2;while(i<half){for(var j2=1;j2<i;++j2){var m_i=m2[i];var m_j=m2[j2];m2[i+j2]=[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}m2[0]=[0,0,0,0];for(i=half+1;i<size;++i){var c=m2[i^half];m2[i]=[mid[0]^c[0],mid[1]^c[1],mid[2]^c[2],mid[3]^c[3]]}return m2};function transformIV(iv,blockSize){if(typeof iv==="string"){iv=forge2.util.createBuffer(iv)}if(forge2.util.isArray(iv)&&iv.length>4){var tmp=iv;iv=forge2.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(!forge2.util.isArray(iv)){var ints=[];var blocks=blockSize/4;for(var 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,num&4294967295]}}});var require_aes=__commonJS({"node_modules/node-forge/lib/aes.js"(exports,module){"use strict";var forge2=require_forge();require_cipher();require_cipherModes();require_util7();module.exports=forge2.aes=forge2.aes||{};forge2.aes.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:false,mode});cipher.start(iv);return cipher};forge2.aes.createEncryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:false,mode})};forge2.aes.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:true,mode});cipher.start(iv);return cipher};forge2.aes.createDecryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:true,mode})};forge2.aes.Algorithm=function(name,mode){if(!init){initialize()}var self2=this;self2.name=name;self2.mode=new mode({blockSize:16,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self2._w,inBlock,outBlock,false)},decrypt:function(inBlock,outBlock){return _updateBlock(self2._w,inBlock,outBlock,true)}}});self2._init=false};forge2.aes.Algorithm.prototype.initialize=function(options){if(this._init){return}var key=options.key;var tmp;if(typeof key==="string"&&(key.length===16||key.length===24||key.length===32)){key=forge2.util.createBuffer(key)}else if(forge2.util.isArray(key)&&(key.length===16||key.length===24||key.length===32)){tmp=key;key=forge2.util.createBuffer();for(var i=0;i<tmp.length;++i){key.putByte(tmp[i])}}if(!forge2.util.isArray(key)){tmp=key;key=[];var len=tmp.length();if(len===16||len===24||len===32){len=len>>>2;for(var i=0;i<len;++i){key.push(tmp.getInt32())}}}if(!forge2.util.isArray(key)||!(key.length===4||key.length===6||key.length===8)){throw new Error("Invalid key parameter.")}var mode=this.mode.name;var encryptOp=["CFB","OFB","CTR","GCM"].indexOf(mode)!==-1;this._w=_expandKey(key,options.decrypt&&!encryptOp);this._init=true};forge2.aes._expandKey=function(key,decrypt){if(!init){initialize()}return _expandKey(key,decrypt)};forge2.aes._updateBlock=_updateBlock;registerAlgorithm("AES-ECB",forge2.cipher.modes.ecb);registerAlgorithm("AES-CBC",forge2.cipher.modes.cbc);registerAlgorithm("AES-CFB",forge2.cipher.modes.cfb);registerAlgorithm("AES-OFB",forge2.cipher.modes.ofb);registerAlgorithm("AES-CTR",forge2.cipher.modes.ctr);registerAlgorithm("AES-GCM",forge2.cipher.modes.gcm);function registerAlgorithm(name,mode){var factory=function(){return new forge2.aes.Algorithm(name,mode)};forge2.cipher.registerAlgorithm(name,factory)}var init=false;var Nb=4;var sbox;var isbox;var rcon;var mix;var imix;function initialize(){init=true;rcon=[0,1,2,4,8,16,32,64,128,27,54];var xtime=new Array(256);for(var 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(var i=0;i<4;++i){mix[i]=new Array(256);imix[i]=new Array(256)}var e=0,ei2=0,e2,e4,e8,sx,sx2,me2,ime;for(var i=0;i<256;++i){sx=ei2^ei2<<1^ei2<<2^ei2<<3^ei2<<4;sx=sx>>8^sx&255^99;sbox[e]=sx;isbox[sx]=e;sx2=xtime[sx];e2=xtime[e];e4=xtime[e2];e8=xtime[e4];me2=sx2<<24^sx<<16^sx<<8^(sx^sx2);ime=(e2^e4^e8)<<24^(e^e8)<<16^(e^e4^e8)<<8^(e^e2^e8);for(var n=0;n<4;++n){mix[n][e]=me2;imix[n][sx]=ime;me2=me2<<24|me2>>>8;ime=ime<<24|ime>>>8}if(e===0){e=ei2=1}else{e=e2^xtime[xtime[xtime[e2^e8]]];ei2^=xtime[xtime[ei2]]}}}function _expandKey(key,decrypt){var w2=key.slice(0);var temp,iNk=1;var Nk=w2.length;var Nr1=Nk+6+1;var end=Nb*Nr1;for(var i=Nk;i<end;++i){temp=w2[i-1];if(i%Nk===0){temp=sbox[temp>>>16&255]<<24^sbox[temp>>>8&255]<<16^sbox[temp&255]<<8^sbox[temp>>>24]^rcon[iNk]<<24;iNk++}else if(Nk>6&&i%Nk===4){temp=sbox[temp>>>24]<<24^sbox[temp>>>16&255]<<16^sbox[temp>>>8&255]<<8^sbox[temp&255]}w2[i]=w2[i-Nk]^temp}if(decrypt){var tmp;var m0=imix[0];var m1=imix[1];var m2=imix[2];var m3=imix[3];var wnew=w2.slice(0);end=w2.length;for(var i=0,wi2=end-Nb;i<end;i+=Nb,wi2-=Nb){if(i===0||i===end-Nb){wnew[i]=w2[wi2];wnew[i+1]=w2[wi2+3];wnew[i+2]=w2[wi2+2];wnew[i+3]=w2[wi2+1]}else{for(var n=0;n<Nb;++n){tmp=w2[wi2+n];wnew[i+(3&-n)]=m0[sbox[tmp>>>24]]^m1[sbox[tmp>>>16&255]]^m2[sbox[tmp>>>8&255]]^m3[sbox[tmp&255]]}}}w2=wnew}return w2}function _updateBlock(w2,input,output,decrypt){var Nr2=w2.length/4-1;var m0,m1,m2,m3,sub;if(decrypt){m0=imix[0];m1=imix[1];m2=imix[2];m3=imix[3];sub=isbox}else{m0=mix[0];m1=mix[1];m2=mix[2];m3=mix[3];sub=sbox}var a,b2,c,d,a2,b22,c2;a=input[0]^w2[0];b2=input[decrypt?3:1]^w2[1];c=input[2]^w2[2];d=input[decrypt?1:3]^w2[3];var i=3;for(var round=1;round<Nr2;++round){a2=m0[a>>>24]^m1[b2>>>16&255]^m2[c>>>8&255]^m3[d&255]^w2[++i];b22=m0[b2>>>24]^m1[c>>>16&255]^m2[d>>>8&255]^m3[a&255]^w2[++i];c2=m0[c>>>24]^m1[d>>>16&255]^m2[a>>>8&255]^m3[b2&255]^w2[++i];d=m0[d>>>24]^m1[a>>>16&255]^m2[b2>>>8&255]^m3[c&255]^w2[++i];a=a2;b2=b22;c=c2}output[0]=sub[a>>>24]<<24^sub[b2>>>16&255]<<16^sub[c>>>8&255]<<8^sub[d&255]^w2[++i];output[decrypt?3:1]=sub[b2>>>24]<<24^sub[c>>>16&255]<<16^sub[d>>>8&255]<<8^sub[a&255]^w2[++i];output[2]=sub[c>>>24]<<24^sub[d>>>16&255]<<16^sub[a>>>8&255]<<8^sub[b2&255]^w2[++i];output[decrypt?1:3]=sub[d>>>24]<<24^sub[a>>>16&255]<<16^sub[b2>>>8&255]<<8^sub[c&255]^w2[++i]}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="AES-"+mode;var cipher;if(options.decrypt){cipher=forge2.cipher.createDecipher(algorithm,options.key)}else{cipher=forge2.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options2){var output=null;if(options2 instanceof forge2.util.ByteBuffer){output=options2;options2={}}options2=options2||{};options2.output=output;options2.iv=iv;start.call(cipher,options2)};return cipher}}});var require_oids=__commonJS({"node_modules/node-forge/lib/oids.js"(exports,module){"use strict";var forge2=require_forge();forge2.pki=forge2.pki||{};var oids=module.exports=forge2.pki.oids=forge2.oids=forge2.oids||{};function _IN(id,name){oids[id]=name;oids[name]=id}function _I_(id,name){oids[id]=name}_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("2.5.4.65","pseudonym");_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")}});var require_asn1=__commonJS({"node_modules/node-forge/lib/asn1.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_oids();var asn1=module.exports=forge2.asn1=forge2.asn1||{};asn1.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};asn1.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.maxDepth=256;asn1.create=function(tagClass,type,constructed,value,options){if(forge2.util.isArray(value)){var tmp=[];for(var i=0;i<value.length;++i){if(value[i]!==void 0){tmp.push(value[i])}}value=tmp}var obj={tagClass,type,constructed,composed:constructed||forge2.util.isArray(value),value};if(options&&"bitStringContents"in options){obj.bitStringContents=options.bitStringContents;obj.original=asn1.copy(obj)}return obj};asn1.copy=function(obj,options){var copy;if(forge2.util.isArray(obj)){copy=[];for(var i=0;i<obj.length;++i){copy.push(asn1.copy(obj[i],options))}return copy}if(typeof obj==="string"){return obj}copy={tagClass:obj.tagClass,type:obj.type,constructed:obj.constructed,composed:obj.composed,value:asn1.copy(obj.value,options)};if(options&&!options.excludeBitStringContents){copy.bitStringContents=obj.bitStringContents}return copy};asn1.equals=function(obj1,obj2,options){if(forge2.util.isArray(obj1)){if(!forge2.util.isArray(obj2)){return false}if(obj1.length!==obj2.length){return false}for(var i=0;i<obj1.length;++i){if(!asn1.equals(obj1[i],obj2[i])){return false}}return true}if(typeof obj1!==typeof obj2){return false}if(typeof obj1==="string"){return obj1===obj2}var equal=obj1.tagClass===obj2.tagClass&&obj1.type===obj2.type&&obj1.constructed===obj2.constructed&&obj1.composed===obj2.composed&&asn1.equals(obj1.value,obj2.value);if(options&&options.includeBitStringContents){equal=equal&&obj1.bitStringContents===obj2.bitStringContents}return equal};asn1.getBerValueLength=function(b2){var b22=b2.getByte();if(b22===128){return void 0}var length;var longForm=b22&128;if(!longForm){length=b22}else{length=b2.getInt((b22&127)<<3)}return length};function _checkBufferLength(bytes,remaining,n){if(n>remaining){var error=new Error("Too few bytes to parse DER.");error.available=bytes.length();error.remaining=remaining;error.requested=n;throw error}}var _getValueLength=function(bytes,remaining){var b2=bytes.getByte();remaining--;if(b2===128){return void 0}var length;var longForm=b2&128;if(!longForm){length=b2}else{var longFormBytes=b2&127;_checkBufferLength(bytes,remaining,longFormBytes);length=bytes.getInt(longFormBytes<<3)}if(length<0){throw new Error("Negative length: "+length)}return length};asn1.fromDer=function(bytes,options){if(options===void 0){options={strict:true,parseAllBytes:true,decodeBitStrings:true}}if(typeof options==="boolean"){options={strict:options,parseAllBytes:true,decodeBitStrings:true}}if(!("strict"in options)){options.strict=true}if(!("parseAllBytes"in options)){options.parseAllBytes=true}if(!("decodeBitStrings"in options)){options.decodeBitStrings=true}if(!("maxDepth"in options)){options.maxDepth=asn1.maxDepth}if(typeof bytes==="string"){bytes=forge2.util.createBuffer(bytes)}var byteCount=bytes.length();var value=_fromDer(bytes,bytes.length(),0,options);if(options.parseAllBytes&&bytes.length()!==0){var error=new Error("Unparsed DER bytes remain after ASN.1 parsing.");error.byteCount=byteCount;error.remaining=bytes.length();throw error}return value};function _fromDer(bytes,remaining,depth,options){if(depth>=options.maxDepth){throw new Error("ASN.1 parsing error: Max depth exceeded.")}var start;_checkBufferLength(bytes,remaining,2);var b1=bytes.getByte();remaining--;var tagClass=b1&192;var type=b1&31;start=bytes.length();var length=_getValueLength(bytes,remaining);remaining-=start-bytes.length();if(length!==void 0&&length>remaining){if(options.strict){var error=new Error("Too few bytes to read ASN.1 value.");error.available=bytes.length();error.remaining=remaining;error.requested=length;throw error}length=remaining}var value;var bitStringContents;var constructed=(b1&32)===32;if(constructed){value=[];if(length===void 0){for(;;){_checkBufferLength(bytes,remaining,2);if(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{while(length>0){start=bytes.length();value.push(_fromDer(bytes,length,depth+1,options));remaining-=start-bytes.length();length-=start-bytes.length()}}}if(value===void 0&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING){bitStringContents=bytes.bytes(length)}if(value===void 0&&options.decodeBitStrings&&tagClass===asn1.Class.UNIVERSAL&&type===asn1.Type.BITSTRING&&length>1){var savedRead=bytes.read;var savedRemaining=remaining;var unused=0;if(type===asn1.Type.BITSTRING){_checkBufferLength(bytes,remaining,1);unused=bytes.getByte();remaining--}if(unused===0){try{start=bytes.length();var subOptions={strict:true,decodeBitStrings:true};var composed=_fromDer(bytes,remaining,depth+1,subOptions);var used=start-bytes.length();remaining-=used;if(type==asn1.Type.BITSTRING){used++}var tc=composed.tagClass;if(used===length&&(tc===asn1.Class.UNIVERSAL||tc===asn1.Class.CONTEXT_SPECIFIC)){value=[composed]}}catch(ex){}}if(value===void 0){bytes.read=savedRead;remaining=savedRemaining}}if(value===void 0){if(length===void 0){if(options.strict){throw new Error("Non-constructed ASN.1 object of indefinite length.")}length=remaining}if(type===asn1.Type.BMPSTRING){value="";for(;length>0;length-=2){_checkBufferLength(bytes,remaining,2);value+=String.fromCharCode(bytes.getInt16());remaining-=2}}else{value=bytes.getBytes(length);remaining-=length}}var asn1Options=bitStringContents===void 0?null:{bitStringContents};return asn1.create(tagClass,type,constructed,value,asn1Options)}asn1.toDer=function(obj){var bytes=forge2.util.createBuffer();var b1=obj.tagClass|obj.type;var value=forge2.util.createBuffer();var useBitStringContents=false;if("bitStringContents"in obj){useBitStringContents=true;if(obj.original){useBitStringContents=asn1.equals(obj,obj.original)}}if(useBitStringContents){value.putBytes(obj.bitStringContents)}else if(obj.composed){if(obj.constructed){b1|=32}else{value.putByte(0)}for(var i=0;i<obj.value.length;++i){if(obj.value[i]!==void 0){value.putBuffer(asn1.toDer(obj.value[i]))}}}else{if(obj.type===asn1.Type.BMPSTRING){for(var i=0;i<obj.value.length;++i){value.putInt16(obj.value.charCodeAt(i))}}else{if(obj.type===asn1.Type.INTEGER&&obj.value.length>1&&(obj.value.charCodeAt(0)===0&&(obj.value.charCodeAt(1)&128)===0||obj.value.charCodeAt(0)===255&&(obj.value.charCodeAt(1)&128)===128)){value.putBytes(obj.value.substr(1))}else{value.putBytes(obj.value)}}}bytes.putByte(b1);if(value.length()<=127){bytes.putByte(value.length()&127)}else{var len=value.length();var lenBytes="";do{lenBytes+=String.fromCharCode(len&255);len=len>>>8}while(len>0);bytes.putByte(lenBytes.length|128);for(var i=lenBytes.length-1;i>=0;--i){bytes.putByte(lenBytes.charCodeAt(i))}}bytes.putBuffer(value);return bytes};asn1.oidToDer=function(oid){var values=oid.split(".");var bytes=forge2.util.createBuffer();bytes.putByte(40*parseInt(values[0],10)+parseInt(values[1],10));var last,valueBytes,value,b2;for(var i=2;i<values.length;++i){last=true;valueBytes=[];value=parseInt(values[i],10);if(value>4294967295){throw new Error("OID value too large; max is 32-bits.")}do{b2=value&127;value=value>>>7;if(!last){b2|=128}valueBytes.push(b2);last=false}while(value>0);for(var n=valueBytes.length-1;n>=0;--n){bytes.putByte(valueBytes[n])}}return bytes};asn1.derToOid=function(bytes){var oid;if(typeof bytes==="string"){bytes=forge2.util.createBuffer(bytes)}var b2=bytes.getByte();oid=Math.floor(b2/40)+"."+b2%40;var value=0;while(bytes.length()>0){if(value>70368744177663){throw new Error("OID value too large; max is 53-bits.")}b2=bytes.getByte();value=value*128;if(b2&128){value+=b2&127}else{oid+="."+(value+b2);value=0}}return oid};asn1.utcTimeToDate=function(utc){var date=new Date;var year=parseInt(utc.substr(0,2),10);year=year>=50?1900+year:2e3+year;var MM=parseInt(utc.substr(2,2),10)-1;var DD=parseInt(utc.substr(4,2),10);var hh=parseInt(utc.substr(6,2),10);var mm=parseInt(utc.substr(8,2),10);var ss2=0;if(utc.length>11){var c=utc.charAt(10);var end=10;if(c!=="+"&&c!=="-"){ss2=parseInt(utc.substr(10,2),10);end+=2}}date.setUTCFullYear(year,MM,DD);date.setUTCHours(hh,mm,ss2,0);if(end){c=utc.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(utc.substr(end+1,2),10);var mmoffset=parseInt(utc.substr(end+4,2),10);var offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){date.setTime(+date-offset)}else{date.setTime(+date+offset)}}}return date};asn1.generalizedTimeToDate=function(gentime){var date=new Date;var YYYY=parseInt(gentime.substr(0,4),10);var MM=parseInt(gentime.substr(4,2),10)-1;var DD=parseInt(gentime.substr(6,2),10);var hh=parseInt(gentime.substr(8,2),10);var mm=parseInt(gentime.substr(10,2),10);var ss2=parseInt(gentime.substr(12,2),10);var fff=0;var offset=0;var isUTC=false;if(gentime.charAt(gentime.length-1)==="Z"){isUTC=true}var end=gentime.length-5,c=gentime.charAt(end);if(c==="+"||c==="-"){var hhoffset=parseInt(gentime.substr(end+1,2),10);var mmoffset=parseInt(gentime.substr(end+4,2),10);offset=hhoffset*60+mmoffset;offset*=6e4;if(c==="+"){offset*=-1}isUTC=true}if(gentime.charAt(14)==="."){fff=parseFloat(gentime.substr(14),10)*1e3}if(isUTC){date.setUTCFullYear(YYYY,MM,DD);date.setUTCHours(hh,mm,ss2,fff);date.setTime(+date+offset)}else{date.setFullYear(YYYY,MM,DD);date.setHours(hh,mm,ss2,fff)}return date};asn1.dateToUtcTime=function(date){if(typeof date==="string"){return date}var rval="";var format2=[];format2.push((""+date.getUTCFullYear()).substr(2));format2.push(""+(date.getUTCMonth()+1));format2.push(""+date.getUTCDate());format2.push(""+date.getUTCHours());format2.push(""+date.getUTCMinutes());format2.push(""+date.getUTCSeconds());for(var i=0;i<format2.length;++i){if(format2[i].length<2){rval+="0"}rval+=format2[i]}rval+="Z";return rval};asn1.dateToGeneralizedTime=function(date){if(typeof date==="string"){return date}var rval="";var format2=[];format2.push(""+date.getUTCFullYear());format2.push(""+(date.getUTCMonth()+1));format2.push(""+date.getUTCDate());format2.push(""+date.getUTCHours());format2.push(""+date.getUTCMinutes());format2.push(""+date.getUTCSeconds());for(var i=0;i<format2.length;++i){if(format2[i].length<2){rval+="0"}rval+=format2[i]}rval+="Z";return rval};asn1.integerToDer=function(x){var rval=forge2.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.");error.integer=x;throw error};asn1.derToInteger=function(bytes){if(typeof bytes==="string"){bytes=forge2.util.createBuffer(bytes)}var n=bytes.length()*8;if(n>32){throw new Error("Integer too large; max is 32-bits.")}return bytes.getSignedInt(n)};asn1.validate=function(obj,v2,capture2,errors){var rval=false;if((obj.tagClass===v2.tagClass||typeof v2.tagClass==="undefined")&&(obj.type===v2.type||typeof v2.type==="undefined")){if(obj.constructed===v2.constructed||typeof v2.constructed==="undefined"){rval=true;if(v2.value&&forge2.util.isArray(v2.value)){var j2=0;for(var i=0;rval&&i<v2.value.length;++i){var schemaItem=v2.value[i];rval=!!schemaItem.optional;var objChild=obj.value[j2];if(!objChild){if(!schemaItem.optional){rval=false;if(errors){errors.push("["+v2.name+'] Missing required element. Expected tag class "'+schemaItem.tagClass+'", type "'+schemaItem.type+'"')}}continue}var schemaHasTag=typeof schemaItem.tagClass!=="undefined"&&typeof schemaItem.type!=="undefined";if(schemaHasTag&&(objChild.tagClass!==schemaItem.tagClass||objChild.type!==schemaItem.type)){if(schemaItem.optional){rval=true;continue}else{rval=false;if(errors){errors.push("["+v2.name+"] Tag mismatch. Expected ("+schemaItem.tagClass+","+schemaItem.type+"), got ("+objChild.tagClass+","+objChild.type+")")}break}}var childRval=asn1.validate(objChild,schemaItem,capture2,errors);if(childRval){++j2;rval=true}else if(schemaItem.optional){rval=true}else{rval=false;break}}}if(rval&&capture2){if(v2.capture){capture2[v2.capture]=obj.value}if(v2.captureAsn1){capture2[v2.captureAsn1]=obj}if(v2.captureBitStringContents&&"bitStringContents"in obj){capture2[v2.captureBitStringContents]=obj.bitStringContents}if(v2.captureBitStringValue&&"bitStringContents"in obj){var value;if(obj.bitStringContents.length<2){capture2[v2.captureBitStringValue]=""}else{var unused=obj.bitStringContents.charCodeAt(0);if(unused!==0){throw new Error("captureBitStringValue only supported for zero unused bits")}capture2[v2.captureBitStringValue]=obj.bitStringContents.slice(1)}}}}else if(errors){errors.push("["+v2.name+'] Expected constructed "'+v2.constructed+'", got "'+obj.constructed+'"')}}else if(errors){if(obj.tagClass!==v2.tagClass){errors.push("["+v2.name+'] Expected tag class "'+v2.tagClass+'", got "'+obj.tagClass+'"')}if(obj.type!==v2.type){errors.push("["+v2.name+'] Expected type "'+v2.type+'", got "'+obj.type+'"')}}return rval};var _nonLatinRegex=/[^\\u0000-\\u00ff]/;asn1.prettyPrint=function(obj,level,indentation){var rval="";level=level||0;indentation=indentation||2;if(level>0){rval+="\n"}var indent="";for(var i=0;i<level*indentation;++i){indent+=" "}rval+=indent+"Tag: ";switch(obj.tagClass){case asn1.Class.UNIVERSAL:rval+="Universal:";break;case asn1.Class.APPLICATION:rval+="Application:";break;case asn1.Class.CONTEXT_SPECIFIC:rval+="Context-Specific:";break;case asn1.Class.PRIVATE:rval+="Private:";break}if(obj.tagClass===asn1.Class.UNIVERSAL){rval+=obj.type;switch(obj.type){case asn1.Type.NONE:rval+=" (None)";break;case asn1.Type.BOOLEAN:rval+=" (Boolean)";break;case asn1.Type.INTEGER:rval+=" (Integer)";break;case asn1.Type.BITSTRING:rval+=" (Bit string)";break;case asn1.Type.OCTETSTRING:rval+=" (Octet string)";break;case asn1.Type.NULL:rval+=" (Null)";break;case asn1.Type.OID:rval+=" (Object Identifier)";break;case asn1.Type.ODESC:rval+=" (Object Descriptor)";break;case asn1.Type.EXTERNAL:rval+=" (External or Instance of)";break;case asn1.Type.REAL:rval+=" (Real)";break;case asn1.Type.ENUMERATED:rval+=" (Enumerated)";break;case asn1.Type.EMBEDDED:rval+=" (Embedded PDV)";break;case asn1.Type.UTF8:rval+=" (UTF8)";break;case asn1.Type.ROID:rval+=" (Relative Object Identifier)";break;case asn1.Type.SEQUENCE:rval+=" (Sequence)";break;case asn1.Type.SET:rval+=" (Set)";break;case asn1.Type.PRINTABLESTRING:rval+=" (Printable String)";break;case asn1.Type.IA5String:rval+=" (IA5String (ASCII))";break;case asn1.Type.UTCTIME:rval+=" (UTC time)";break;case asn1.Type.GENERALIZEDTIME:rval+=" (Generalized time)";break;case asn1.Type.BMPSTRING:rval+=" (BMP String)";break}}else{rval+=obj.type}rval+="\n";rval+=indent+"Constructed: "+obj.constructed+"\n";if(obj.composed){var subvalues=0;var sub="";for(var i=0;i<obj.value.length;++i){if(obj.value[i]!==void 0){subvalues+=1;sub+=asn1.prettyPrint(obj.value[i],level+1,indentation);if(i+1<obj.value.length){sub+=","}}}rval+=indent+"Sub values: "+subvalues+sub}else{rval+=indent+"Value: ";if(obj.type===asn1.Type.OID){var oid=asn1.derToOid(obj.value);rval+=oid;if(forge2.pki&&forge2.pki.oids){if(oid in forge2.pki.oids){rval+=" ("+forge2.pki.oids[oid]+") "}}}if(obj.type===asn1.Type.INTEGER){try{rval+=asn1.derToInteger(obj.value)}catch(ex){rval+="0x"+forge2.util.bytesToHex(obj.value)}}else if(obj.type===asn1.Type.BITSTRING){if(obj.value.length>1){rval+="0x"+forge2.util.bytesToHex(obj.value.slice(1))}else{rval+="(none)"}if(obj.value.length>0){var unused=obj.value.charCodeAt(0);if(unused==1){rval+=" (1 unused bit shown)"}else if(unused>1){rval+=" ("+unused+" unused bits shown)"}}}else if(obj.type===asn1.Type.OCTETSTRING){if(!_nonLatinRegex.test(obj.value)){rval+="("+obj.value+") "}rval+="0x"+forge2.util.bytesToHex(obj.value)}else if(obj.type===asn1.Type.UTF8){try{rval+=forge2.util.decodeUtf8(obj.value)}catch(e){if(e.message==="URI malformed"){rval+="0x"+forge2.util.bytesToHex(obj.value)+" (malformed UTF8)"}else{throw e}}}else if(obj.type===asn1.Type.PRINTABLESTRING||obj.type===asn1.Type.IA5String){rval+=obj.value}else if(_nonLatinRegex.test(obj.value)){rval+="0x"+forge2.util.bytesToHex(obj.value)}else if(obj.value.length===0){rval+="[null]"}else{rval+=obj.value}}return rval}}});var require_md=__commonJS({"node_modules/node-forge/lib/md.js"(exports,module){"use strict";var forge2=require_forge();module.exports=forge2.md=forge2.md||{};forge2.md.algorithms=forge2.md.algorithms||{}}});var require_hmac=__commonJS({"node_modules/node-forge/lib/hmac.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var hmac=module.exports=forge2.hmac=forge2.hmac||{};hmac.create=function(){var _key=null;var _md=null;var _ipadding=null;var _opadding=null;var ctx={};ctx.start=function(md,key){if(md!==null){if(typeof md==="string"){md=md.toLowerCase();if(md in forge2.md.algorithms){_md=forge2.md.algorithms[md].create()}else{throw new Error('Unknown hash algorithm "'+md+'"')}}else{_md=md}}if(key===null){key=_key}else{if(typeof key==="string"){key=forge2.util.createBuffer(key)}else if(forge2.util.isArray(key)){var tmp=key;key=forge2.util.createBuffer();for(var i=0;i<tmp.length;++i){key.putByte(tmp[i])}}var keylen=key.length();if(keylen>_md.blockLength){_md.start();_md.update(key.bytes());key=_md.digest()}_ipadding=forge2.util.createBuffer();_opadding=forge2.util.createBuffer();keylen=key.length();for(var i=0;i<keylen;++i){var tmp=key.at(i);_ipadding.putByte(54^tmp);_opadding.putByte(92^tmp)}if(keylen<_md.blockLength){var tmp=_md.blockLength-keylen;for(var i=0;i<tmp;++i){_ipadding.putByte(54);_opadding.putByte(92)}}_key=key;_ipadding=_ipadding.bytes();_opadding=_opadding.bytes()}_md.start();_md.update(_ipadding)};ctx.update=function(bytes){_md.update(bytes)};ctx.getMac=function(){var inner=_md.digest().bytes();_md.start();_md.update(_opadding);_md.update(inner);return _md.digest()};ctx.digest=ctx.getMac;return ctx}}});var require_md5=__commonJS({"node_modules/node-forge/lib/md5.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var md5=module.exports=forge2.md5=forge2.md5||{};forge2.md.md5=forge2.md.algorithms.md5=md5;md5.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge2.util.createBuffer();var _w=new Array(16);var md={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_state={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878};return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var bits,carry=0;for(var i=md.fullMessageLength.length-1;i>=0;--i){bits=md.fullMessageLength[i]*8+carry;carry=bits/4294967296>>>0;finalBlock.putInt32Le(bits>>>0)}var s22={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3};_update(s22,_w,finalBlock);var rval=forge2.util.createBuffer();rval.putInt32Le(s22.h0);rval.putInt32Le(s22.h1);rval.putInt32Le(s22.h2);rval.putInt32Le(s22.h3);return rval};return md};var _padding=null;var _g=null;var _r2=null;var _k=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.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];_r2=[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(Math.abs(Math.sin(i+1))*4294967296)}_initialized=true}function _update(s3,w2,bytes){var t,a,b2,c,d,f2,r,i;var len=bytes.length();while(len>=64){a=s3.h0;b2=s3.h1;c=s3.h2;d=s3.h3;for(i=0;i<16;++i){w2[i]=bytes.getInt32Le();f2=d^b2&(c^d);t=a+f2+_k[i]+w2[i];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}for(;i<32;++i){f2=c^d&(b2^c);t=a+f2+_k[i]+w2[_g[i]];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}for(;i<48;++i){f2=b2^c^d;t=a+f2+_k[i]+w2[_g[i]];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}for(;i<64;++i){f2=c^(b2|~d);t=a+f2+_k[i]+w2[_g[i]];r=_r2[i];a=d;d=c;c=b2;b2+=t<<r|t>>>32-r}s3.h0=s3.h0+a|0;s3.h1=s3.h1+b2|0;s3.h2=s3.h2+c|0;s3.h3=s3.h3+d|0;len-=64}}}});var require_pem=__commonJS({"node_modules/node-forge/lib/pem.js"(exports,module){"use strict";var forge2=require_forge();require_util7();var pem=module.exports=forge2.pem=forge2.pem||{};pem.encode=function(msg,options){options=options||{};var rval="-----BEGIN "+msg.type+"-----\r\n";var header;if(msg.procType){header={name:"Proc-Type",values:[String(msg.procType.version),msg.procType.type]};rval+=foldHeader(header)}if(msg.contentDomain){header={name:"Content-Domain",values:[msg.contentDomain]};rval+=foldHeader(header)}if(msg.dekInfo){header={name:"DEK-Info",values:[msg.dekInfo.algorithm]};if(msg.dekInfo.parameters){header.values.push(msg.dekInfo.parameters)}rval+=foldHeader(header)}if(msg.headers){for(var i=0;i<msg.headers.length;++i){rval+=foldHeader(msg.headers[i])}}if(msg.procType){rval+="\r\n"}rval+=forge2.util.encode64(msg.body,options.maxline||64)+"\r\n";rval+="-----END "+msg.type+"-----\r\n";return rval};pem.decode=function(str){var rval=[];var rMessage=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;var rHeader=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;var rCRLF=/\r?\n/;var match;while(true){match=rMessage.exec(str);if(!match){break}var type=match[1];if(type==="NEW CERTIFICATE REQUEST"){type="CERTIFICATE REQUEST"}var msg={type,procType:null,contentDomain:null,dekInfo:null,headers:[],body:forge2.util.decode64(match[3])};rval.push(msg);if(!match[2]){continue}var lines=match[2].split(rCRLF);var li2=0;while(match&&li2<lines.length){var line=lines[li2].replace(/\s+$/,"");for(var nl=li2+1;nl<lines.length;++nl){var next=lines[nl];if(!/\s/.test(next[0])){break}line+=next;li2=nl}match=line.match(rHeader);if(match){var header={name:match[1],values:[]};var values=match[2].split(",");for(var vi2=0;vi2<values.length;++vi2){header.values.push(ltrim(values[vi2]))}if(!msg.procType){if(header.name!=="Proc-Type"){throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".')}else if(header.values.length!==2){throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.')}msg.procType={version:values[0],type:values[1]}}else if(!msg.contentDomain&&header.name==="Content-Domain"){msg.contentDomain=values[0]||""}else if(!msg.dekInfo&&header.name==="DEK-Info"){if(header.values.length===0){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.headers.push(header)}}++li2}if(msg.procType==="ENCRYPTED"&&!msg.dekInfo){throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(rval.length===0){throw new Error("Invalid PEM formatted message.")}return rval};function foldHeader(header){var rval=header.name+": ";var values=[];var insertSpace=function(match,$1){return" "+$1};for(var 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;var candidate=-1;for(var i=0;i<rval.length;++i,++length){if(length>65&&candidate!==-1){var insert=rval[candidate];if(insert===","){++candidate;rval=rval.substr(0,candidate)+"\r\n "+rval.substr(candidate)}else{rval=rval.substr(0,candidate)+"\r\n"+insert+rval.substr(candidate+1)}length=i-candidate-1;candidate=-1;++i}else if(rval[i]===" "||rval[i]===" "||rval[i]===","){candidate=i}}return rval}function ltrim(str){return str.replace(/^\s+/,"")}}});var require_des=__commonJS({"node_modules/node-forge/lib/des.js"(exports,module){"use strict";var forge2=require_forge();require_cipher();require_cipherModes();require_util7();module.exports=forge2.des=forge2.des||{};forge2.des.startEncrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:false,mode:mode||(iv===null?"ECB":"CBC")});cipher.start(iv);return cipher};forge2.des.createEncryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:false,mode})};forge2.des.startDecrypting=function(key,iv,output,mode){var cipher=_createCipher({key,output,decrypt:true,mode:mode||(iv===null?"ECB":"CBC")});cipher.start(iv);return cipher};forge2.des.createDecryptionCipher=function(key,mode){return _createCipher({key,output:null,decrypt:true,mode})};forge2.des.Algorithm=function(name,mode){var self2=this;self2.name=name;self2.mode=new mode({blockSize:8,cipher:{encrypt:function(inBlock,outBlock){return _updateBlock(self2._keys,inBlock,outBlock,false)},decrypt:function(inBlock,outBlock){return _updateBlock(self2._keys,inBlock,outBlock,true)}}});self2._init=false};forge2.des.Algorithm.prototype.initialize=function(options){if(this._init){return}var key=forge2.util.createBuffer(options.key);if(this.name.indexOf("3DES")===0){if(key.length()!==24){throw new Error("Invalid Triple-DES key size: "+key.length()*8)}}this._keys=_createKeys(key);this._init=true};registerAlgorithm("DES-ECB",forge2.cipher.modes.ecb);registerAlgorithm("DES-CBC",forge2.cipher.modes.cbc);registerAlgorithm("DES-CFB",forge2.cipher.modes.cfb);registerAlgorithm("DES-OFB",forge2.cipher.modes.ofb);registerAlgorithm("DES-CTR",forge2.cipher.modes.ctr);registerAlgorithm("3DES-ECB",forge2.cipher.modes.ecb);registerAlgorithm("3DES-CBC",forge2.cipher.modes.cbc);registerAlgorithm("3DES-CFB",forge2.cipher.modes.cfb);registerAlgorithm("3DES-OFB",forge2.cipher.modes.ofb);registerAlgorithm("3DES-CTR",forge2.cipher.modes.ctr);function registerAlgorithm(name,mode){var factory=function(){return new forge2.des.Algorithm(name,mode)};forge2.cipher.registerAlgorithm(name,factory)}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];var 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];var 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];var 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];var 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];var 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];var 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];var 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 _createKeys(key){var 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];var iterations=key.length()>8?3:1;var keys=[];var shifts=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0];var n=0,tmp;for(var j2=0;j2<iterations;j2++){var left=key.getInt32();var right=key.getInt32();tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>2^right)&858993459;right^=tmp;left^=tmp<<2;tmp=(right>>>-16^left)&65535;left^=tmp;right^=tmp<<-16;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=left<<8|right>>>20&240;left=right<<24|right<<8&16711680|right>>>8&65280|right>>>24&240;right=tmp;for(var i=0;i<shifts.length;++i){if(shifts[i]){left=left<<2|left>>>26;right=right<<2|right>>>26}else{left=left<<1|left>>>27;right=right<<1|right>>>27}left&=-15;right&=-15;var lefttmp=pc2bytes0[left>>>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];var 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=(righttmp>>>16^lefttmp)&65535;keys[n++]=lefttmp^tmp;keys[n++]=righttmp^tmp<<16}}return keys}function _updateBlock(keys,input,output,decrypt){var iterations=keys.length===32?3:9;var looping;if(iterations===3){looping=decrypt?[30,-2,-2]:[0,32,2]}else{looping=decrypt?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2]}var tmp;var left=input[0];var right=input[1];tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;left=left<<1|left>>>31;right=right<<1|right>>>31;for(var j2=0;j2<iterations;j2+=3){var endloop=looping[j2+1];var loopinc=looping[j2+2];for(var i=looping[j2];i!=endloop;i+=loopinc){var right1=right^keys[i];var 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[right1&63]|spfunction1[right2>>>24&63]|spfunction3[right2>>>16&63]|spfunction5[right2>>>8&63]|spfunction7[right2&63])}tmp=left;left=right;right=tmp}left=left>>>1|left<<31;right=right>>>1|right<<31;tmp=(left>>>1^right)&1431655765;right^=tmp;left^=tmp<<1;tmp=(right>>>8^left)&16711935;left^=tmp;right^=tmp<<8;tmp=(right>>>2^left)&858993459;left^=tmp;right^=tmp<<2;tmp=(left>>>16^right)&65535;right^=tmp;left^=tmp<<16;tmp=(left>>>4^right)&252645135;right^=tmp;left^=tmp<<4;output[0]=left;output[1]=right}function _createCipher(options){options=options||{};var mode=(options.mode||"CBC").toUpperCase();var algorithm="DES-"+mode;var cipher;if(options.decrypt){cipher=forge2.cipher.createDecipher(algorithm,options.key)}else{cipher=forge2.cipher.createCipher(algorithm,options.key)}var start=cipher.start;cipher.start=function(iv,options2){var output=null;if(options2 instanceof forge2.util.ByteBuffer){output=options2;options2={}}options2=options2||{};options2.output=output;options2.iv=iv;start.call(cipher,options2)};return cipher}}});var require_pbkdf2=__commonJS({"node_modules/node-forge/lib/pbkdf2.js"(exports,module){"use strict";var forge2=require_forge();require_hmac();require_md();require_util7();var pkcs5=forge2.pkcs5=forge2.pkcs5||{};var crypto5;if(forge2.util.isNodejs&&!forge2.options.usePureJavaScript){crypto5=__require("crypto")}module.exports=forge2.pbkdf2=pkcs5.pbkdf2=function(p2,s3,c,dkLen,md,callback){if(typeof md==="function"){callback=md;md=null}if(forge2.util.isNodejs&&!forge2.options.usePureJavaScript&&crypto5.pbkdf2&&(md===null||typeof md!=="object")&&(crypto5.pbkdf2Sync.length>4||(!md||md==="sha1"))){if(typeof md!=="string"){md="sha1"}p2=Buffer.from(p2,"binary");s3=Buffer.from(s3,"binary");if(!callback){if(crypto5.pbkdf2Sync.length===4){return crypto5.pbkdf2Sync(p2,s3,c,dkLen).toString("binary")}return crypto5.pbkdf2Sync(p2,s3,c,dkLen,md).toString("binary")}if(crypto5.pbkdf2Sync.length===4){return crypto5.pbkdf2(p2,s3,c,dkLen,function(err2,key){if(err2){return callback(err2)}callback(null,key.toString("binary"))})}return crypto5.pbkdf2(p2,s3,c,dkLen,md,function(err2,key){if(err2){return callback(err2)}callback(null,key.toString("binary"))})}if(typeof md==="undefined"||md===null){md="sha1"}if(typeof md==="string"){if(!(md in forge2.md.algorithms)){throw new Error("Unknown hash algorithm: "+md)}md=forge2.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);var r=dkLen-(len-1)*hLen;var prf=forge2.hmac.create();prf.start(md,p2);var dk="";var xor,u_c,u_c1;if(!callback){for(var i=1;i<=len;++i){prf.start(null,null);prf.update(s3);prf.update(forge2.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();for(var j2=2;j2<=c;++j2){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge2.util.xorBytes(xor,u_c,hLen);u_c1=u_c}dk+=i<len?xor:xor.substr(0,r)}return dk}var i=1,j2;function outer(){if(i>len){return callback(null,dk)}prf.start(null,null);prf.update(s3);prf.update(forge2.util.int32ToBytes(i));xor=u_c1=prf.digest().getBytes();j2=2;inner()}function inner(){if(j2<=c){prf.start(null,null);prf.update(u_c1);u_c=prf.digest().getBytes();xor=forge2.util.xorBytes(xor,u_c,hLen);u_c1=u_c;++j2;return forge2.util.setImmediate(inner)}dk+=i<len?xor:xor.substr(0,r);++i;outer()}outer()}}});var require_sha256=__commonJS({"node_modules/node-forge/lib/sha256.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var sha2562=module.exports=forge2.sha256=forge2.sha256||{};forge2.md.sha256=forge2.md.algorithms.sha256=sha2562;sha2562.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge2.util.createBuffer();var _w=new Array(64);var md={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_state={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225};return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i<md.fullMessageLength.length-1;++i){next=md.fullMessageLength[i+1]*8;carry=next/4294967296>>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s22={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(s22,_w,finalBlock);var rval=forge2.util.createBuffer();rval.putInt32(s22.h0);rval.putInt32(s22.h1);rval.putInt32(s22.h2);rval.putInt32(s22.h3);rval.putInt32(s22.h4);rval.putInt32(s22.h5);rval.putInt32(s22.h6);rval.putInt32(s22.h7);return rval};return md};var _padding=null;var _initialized=false;var _k=null;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.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=true}function _update(s3,w2,bytes){var t1,t2,s0,s1,ch,maj,i,a,b2,c,d,e,f2,g2,h;var len=bytes.length();while(len>=64){for(i=0;i<16;++i){w2[i]=bytes.getInt32()}for(;i<64;++i){t1=w2[i-2];t1=(t1>>>17|t1<<15)^(t1>>>19|t1<<13)^t1>>>10;t2=w2[i-15];t2=(t2>>>7|t2<<25)^(t2>>>18|t2<<14)^t2>>>3;w2[i]=t1+w2[i-7]+t2+w2[i-16]|0}a=s3.h0;b2=s3.h1;c=s3.h2;d=s3.h3;e=s3.h4;f2=s3.h5;g2=s3.h6;h=s3.h7;for(i=0;i<64;++i){s1=(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7);ch=g2^e&(f2^g2);s0=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10);maj=a&b2|c&(a^b2);t1=h+s1+ch+_k[i]+w2[i];t2=s0+maj;h=g2;g2=f2;f2=e;e=d+t1>>>0;d=c;c=b2;b2=a;a=t1+t2>>>0}s3.h0=s3.h0+a|0;s3.h1=s3.h1+b2|0;s3.h2=s3.h2+c|0;s3.h3=s3.h3+d|0;s3.h4=s3.h4+e|0;s3.h5=s3.h5+f2|0;s3.h6=s3.h6+g2|0;s3.h7=s3.h7+h|0;len-=64}}}});var require_prng=__commonJS({"node_modules/node-forge/lib/prng.js"(exports,module){"use strict";var forge2=require_forge();require_util7();var _crypto=null;if(forge2.util.isNodejs&&!forge2.options.usePureJavaScript&&!process.versions["node-webkit"]){_crypto=__require("crypto")}var prng=module.exports=forge2.prng=forge2.prng||{};prng.create=function(plugin){var ctx={plugin,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""};var md=plugin.md;var pools=new Array(32);for(var i=0;i<32;++i){pools[i]=md.create()}ctx.pools=pools;ctx.pool=0;ctx.generate=function(count,callback){if(!callback){return ctx.generateSync(count)}var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;var b2=forge2.util.createBuffer();ctx.key=null;generate();function generate(err){if(err){return callback(err)}if(b2.length()>=count){return callback(null,b2.getBytes(count))}if(ctx.generated>1048575){ctx.key=null}if(ctx.key===null){return forge2.util.nextTick(function(){_reseed(generate)})}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b2.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed));forge2.util.setImmediate(generate)}};ctx.generateSync=function(count){var cipher=ctx.plugin.cipher;var increment=ctx.plugin.increment;var formatKey=ctx.plugin.formatKey;var formatSeed=ctx.plugin.formatSeed;ctx.key=null;var b2=forge2.util.createBuffer();while(b2.length()<count){if(ctx.generated>1048575){ctx.key=null}if(ctx.key===null){_reseedSync()}var bytes=cipher(ctx.key,ctx.seed);ctx.generated+=bytes.length;b2.putBytes(bytes);ctx.key=formatKey(cipher(ctx.key,increment(ctx.seed)));ctx.seed=formatSeed(cipher(ctx.key,ctx.seed))}return b2.getBytes(count)};function _reseed(callback){if(ctx.pools[0].messageLength>=32){_seed();return 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()})}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=ctx.reseeds===4294967295?0:ctx.reseeds+1;var md2=ctx.plugin.md.create();md2.update(ctx.keyBytes);var _2powK=1;for(var k2=0;k2<32;++k2){if(ctx.reseeds%_2powK===0){md2.update(ctx.pools[k2].digest().getBytes());ctx.pools[k2].start()}_2powK=_2powK<<1}ctx.keyBytes=md2.digest().getBytes();md2.start();md2.update(ctx.keyBytes);var seedBytes=md2.digest().getBytes();ctx.key=ctx.plugin.formatKey(ctx.keyBytes);ctx.seed=ctx.plugin.formatSeed(seedBytes);ctx.generated=0}function defaultSeedFile(needed){var getRandomValues=null;var globalScope=forge2.util.globalScope;var _crypto2=globalScope.crypto||globalScope.msCrypto;if(_crypto2&&_crypto2.getRandomValues){getRandomValues=function(arr){return _crypto2.getRandomValues(arr)}}var b2=forge2.util.createBuffer();if(getRandomValues){while(b2.length()<needed){var count=Math.max(1,Math.min(needed-b2.length(),65536)/4);var entropy=new Uint32Array(Math.floor(count));try{getRandomValues(entropy);for(var i2=0;i2<entropy.length;++i2){b2.putInt32(entropy[i2])}}catch(e){if(!(typeof QuotaExceededError!=="undefined"&&e instanceof QuotaExceededError)){throw e}}}}if(b2.length()<needed){var hi2,lo2,next;var seed=Math.floor(Math.random()*65536);while(b2.length()<needed){lo2=16807*(seed&65535);hi2=16807*(seed>>16);lo2+=(hi2&32767)<<16;lo2+=hi2>>15;lo2=(lo2&2147483647)+(lo2>>31);seed=lo2&4294967295;for(var i2=0;i2<3;++i2){next=seed>>>(i2<<3);next^=Math.floor(Math.random()*256);b2.putByte(next&255)}}}return b2.getBytes(needed)}if(_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()}}else{ctx.seedFile=function(needed,callback){try{callback(null,defaultSeedFile(needed))}catch(e){callback(e)}};ctx.seedFileSync=defaultSeedFile}ctx.collect=function(bytes){var count=bytes.length;for(var i2=0;i2<count;++i2){ctx.pools[ctx.pool].update(bytes.substr(i2,1));ctx.pool=ctx.pool===31?0:ctx.pool+1}};ctx.collectInt=function(i2,n){var bytes="";for(var x=0;x<n;x+=8){bytes+=String.fromCharCode(i2>>x&255)}ctx.collect(bytes)};ctx.registerWorker=function(worker){if(worker===self){ctx.seedFile=function(needed,callback){function listener2(e){var data=e.data;if(data.forge&&data.forge.prng){self.removeEventListener("message",listener2);callback(data.forge.prng.err,data.forge.prng.bytes)}}self.addEventListener("message",listener2);self.postMessage({forge:{prng:{needed}}})}}else{var listener=function(e){var data=e.data;if(data.forge&&data.forge.prng){ctx.seedFile(data.forge.prng.needed,function(err,bytes){worker.postMessage({forge:{prng:{err,bytes}}})})}};worker.addEventListener("message",listener)}};return ctx}}});var require_random=__commonJS({"node_modules/node-forge/lib/random.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_sha256();require_prng();require_util7();(function(){if(forge2.random&&forge2.random.getBytes){module.exports=forge2.random;return}(function(jQuery2){var prng_aes={};var _prng_aes_output=new Array(4);var _prng_aes_buffer=forge2.util.createBuffer();prng_aes.formatKey=function(key2){var tmp=forge2.util.createBuffer(key2);key2=new Array(4);key2[0]=tmp.getInt32();key2[1]=tmp.getInt32();key2[2]=tmp.getInt32();key2[3]=tmp.getInt32();return forge2.aes._expandKey(key2,false)};prng_aes.formatSeed=function(seed){var tmp=forge2.util.createBuffer(seed);seed=new Array(4);seed[0]=tmp.getInt32();seed[1]=tmp.getInt32();seed[2]=tmp.getInt32();seed[3]=tmp.getInt32();return seed};prng_aes.cipher=function(key2,seed){forge2.aes._updateBlock(key2,seed,_prng_aes_output,false);_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]);return _prng_aes_buffer.getBytes()};prng_aes.increment=function(seed){++seed[3];return seed};prng_aes.md=forge2.md.sha256;function spawnPrng(){var ctx=forge2.prng.create(prng_aes);ctx.getBytes=function(count,callback){return ctx.generate(count,callback)};ctx.getBytesSync=function(count){return ctx.generate(count)};return ctx}var _ctx=spawnPrng();var getRandomValues=null;var globalScope=forge2.util.globalScope;var _crypto=globalScope.crypto||globalScope.msCrypto;if(_crypto&&_crypto.getRandomValues){getRandomValues=function(arr){return _crypto.getRandomValues(arr)}}if(forge2.options.usePureJavaScript||!forge2.util.isNodejs&&!getRandomValues){if(typeof window==="undefined"||window.document===void 0){}_ctx.collectInt(+new Date,32);if(typeof navigator!=="undefined"){var _navBytes="";for(var key in navigator){try{if(typeof navigator[key]=="string"){_navBytes+=navigator[key]}}catch(e){}}_ctx.collect(_navBytes);_navBytes=null}if(jQuery2){jQuery2().mousemove(function(e){_ctx.collectInt(e.clientX,16);_ctx.collectInt(e.clientY,16)});jQuery2().keypress(function(e){_ctx.collectInt(e.charCode,8)})}}if(!forge2.random){forge2.random=_ctx}else{for(var key in _ctx){forge2.random[key]=_ctx[key]}}forge2.random.createInstance=spawnPrng;module.exports=forge2.random})(typeof jQuery!=="undefined"?jQuery:null)})()}});var require_rc2=__commonJS({"node_modules/node-forge/lib/rc2.js"(exports,module){"use strict";var forge2=require_forge();require_util7();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];var s3=[1,2,3,5];var rol=function(word,bits){return word<<bits&65535|(word&65535)>>16-bits};var ror=function(word,bits){return(word&65535)>>bits|word<<16-bits&65535};module.exports=forge2.rc2=forge2.rc2||{};forge2.rc2.expandKey=function(key,effKeyBits){if(typeof key==="string"){key=forge2.util.createBuffer(key)}effKeyBits=effKeyBits||128;var L2=key;var T=key.length();var T1=effKeyBits;var T8=Math.ceil(T1/8);var TM=255>>(T1&7);var i;for(i=T;i<128;i++){L2.putByte(piTable[L2.at(i-1)+L2.at(i-T)&255])}L2.setAt(128-T8,piTable[L2.at(128-T8)&TM]);for(i=127-T8;i>=0;i--){L2.setAt(i,piTable[L2.at(i+1)^L2.at(i+T8)])}return L2};var createCipher=function(key,bits,encrypt){var _finish=false,_input=null,_output=null,_iv=null;var mixRound,mashRound;var i,j2,K2=[];key=forge2.rc2.expandKey(key,bits);for(i=0;i<64;i++){K2.push(key.getInt16Le())}if(encrypt){mixRound=function(R2){for(i=0;i<4;i++){R2[i]+=K2[j2]+(R2[(i+3)%4]&R2[(i+2)%4])+(~R2[(i+3)%4]&R2[(i+1)%4]);R2[i]=rol(R2[i],s3[i]);j2++}};mashRound=function(R2){for(i=0;i<4;i++){R2[i]+=K2[R2[(i+3)%4]&63]}}}else{mixRound=function(R2){for(i=3;i>=0;i--){R2[i]=ror(R2[i],s3[i]);R2[i]-=K2[j2]+(R2[(i+3)%4]&R2[(i+2)%4])+(~R2[(i+3)%4]&R2[(i+1)%4]);j2--}};mashRound=function(R2){for(i=3;i>=0;i--){R2[i]-=K2[R2[(i+3)%4]&63]}}}var runPlan=function(plan2){var R2=[];for(i=0;i<4;i++){var val=_input.getInt16Le();if(_iv!==null){if(encrypt){val^=_iv.getInt16Le()}else{_iv.putInt16Le(val)}}R2.push(val&65535)}j2=encrypt?0:63;for(var ptr=0;ptr<plan2.length;ptr++){for(var ctr=0;ctr<plan2[ptr][0];ctr++){plan2[ptr][1](R2)}}for(i=0;i<4;i++){if(_iv!==null){if(encrypt){_iv.putInt16Le(R2[i])}else{R2[i]^=_iv.getInt16Le()}}_output.putInt16Le(R2[i])}};var cipher=null;cipher={start:function(iv,output){if(iv){if(typeof iv==="string"){iv=forge2.util.createBuffer(iv)}}_finish=false;_input=forge2.util.createBuffer();_output=output||new forge2.util.createBuffer;_iv=iv;cipher.output=_output},update:function(input){if(!_finish){_input.putBuffer(input)}while(_input.length()>=8){runPlan([[5,mixRound],[1,mashRound],[6,mixRound],[1,mashRound],[5,mixRound]])}},finish:function(pad){var rval=true;if(encrypt){if(pad){rval=pad(8,_input,!encrypt)}else{var padding=_input.length()===8?8:8-_input.length();_input.fillWithByte(padding,padding)}}if(rval){_finish=true;cipher.update()}if(!encrypt){rval=_input.length()===0;if(rval){if(pad){rval=pad(8,_output,!encrypt)}else{var len=_output.length();var count=_output.at(len-1);if(count>len){rval=false}else{_output.truncate(count)}}}}return rval}};return cipher};forge2.rc2.startEncrypting=function(key,iv,output){var cipher=forge2.rc2.createEncryptionCipher(key,128);cipher.start(iv,output);return cipher};forge2.rc2.createEncryptionCipher=function(key,bits){return createCipher(key,bits,true)};forge2.rc2.startDecrypting=function(key,iv,output){var cipher=forge2.rc2.createDecryptionCipher(key,128);cipher.start(iv,output);return cipher};forge2.rc2.createDecryptionCipher=function(key,bits){return createCipher(key,bits,false)}}});var require_jsbn=__commonJS({"node_modules/node-forge/lib/jsbn.js"(exports,module){"use strict";var forge2=require_forge();module.exports=forge2.jsbn=forge2.jsbn||{};var dbits;var canary=0xdeadbeefcafe;var j_lm=(canary&16777215)==15715070;function BigInteger(a,b2,c){this.data=[];if(a!=null)if("number"==typeof a)this.fromNumber(a,b2,c);else if(b2==null&&"string"!=typeof a)this.fromString(a,256);else this.fromString(a,b2)}forge2.jsbn.BigInteger=BigInteger;function nbi(){return new BigInteger(null)}function am1(i,x,w2,j2,c,n){while(--n>=0){var v2=x*this.data[i++]+w2.data[j2]+c;c=Math.floor(v2/67108864);w2.data[j2++]=v2&67108863}return c}function am2(i,x,w2,j2,c,n){var xl=x&32767,xh=x>>15;while(--n>=0){var l=this.data[i]&32767;var h=this.data[i++]>>15;var m2=xh*l+h*xl;l=xl*l+((m2&32767)<<15)+w2.data[j2]+(c&1073741823);c=(l>>>30)+(m2>>>15)+xh*h+(c>>>30);w2.data[j2++]=l&1073741823}return c}function am3(i,x,w2,j2,c,n){var xl=x&16383,xh=x>>14;while(--n>=0){var l=this.data[i]&16383;var h=this.data[i++]>>14;var m2=xh*l+h*xl;l=xl*l+((m2&16383)<<14)+w2.data[j2]+c;c=(l>>28)+(m2>>14)+xh*h;w2.data[j2++]=l&268435455}return c}if(typeof navigator==="undefined"){BigInteger.prototype.am=am3;dbits=28}else if(j_lm&&navigator.appName=="Microsoft Internet Explorer"){BigInteger.prototype.am=am2;dbits=30}else if(j_lm&&navigator.appName!="Netscape"){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<<dbits)-1;BigInteger.prototype.DV=1<<dbits;var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";var BI_RC=new Array;var rr2;var vv;rr2="0".charCodeAt(0);for(vv=0;vv<=9;++vv)BI_RC[rr2++]=vv;rr2="a".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr2++]=vv;rr2="A".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr2++]=vv;function int2char(n){return BI_RM.charAt(n)}function intAt(s3,i){var c=BI_RC[s3.charCodeAt(i)];return c==null?-1:c}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}function bnpFromInt(x){this.t=1;this.s=x<0?-1:0;if(x>0)this.data[0]=x;else if(x<-1)this.data[0]=x+this.DV;else this.t=0}function nbv(i){var r=nbi();r.fromInt(i);return r}function bnpFromString(s3,b2){var k2;if(b2==16)k2=4;else if(b2==8)k2=3;else if(b2==256)k2=8;else if(b2==2)k2=1;else if(b2==32)k2=5;else if(b2==4)k2=2;else{this.fromRadix(s3,b2);return}this.t=0;this.s=0;var i=s3.length,mi2=false,sh=0;while(--i>=0){var x=k2==8?s3[i]&255:intAt(s3,i);if(x<0){if(s3.charAt(i)=="-")mi2=true;continue}mi2=false;if(sh==0)this.data[this.t++]=x;else if(sh+k2>this.DB){this.data[this.t-1]|=(x&(1<<this.DB-sh)-1)<<sh;this.data[this.t++]=x>>this.DB-sh}else this.data[this.t-1]|=x<<sh;sh+=k2;if(sh>=this.DB)sh-=this.DB}if(k2==8&&(s3[0]&128)!=0){this.s=-1;if(sh>0)this.data[this.t-1]|=(1<<this.DB-sh)-1<<sh}this.clamp();if(mi2)BigInteger.ZERO.subTo(this,this)}function bnpClamp(){var c=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==c)--this.t}function bnToString(b2){if(this.s<0)return"-"+this.negate().toString(b2);var k2;if(b2==16)k2=4;else if(b2==8)k2=3;else if(b2==2)k2=1;else if(b2==32)k2=5;else if(b2==4)k2=2;else return this.toRadix(b2);var km=(1<<k2)-1,d,m2=false,r="",i=this.t;var p2=this.DB-i*this.DB%k2;if(i-- >0){if(p2<this.DB&&(d=this.data[i]>>p2)>0){m2=true;r=int2char(d)}while(i>=0){if(p2<k2){d=(this.data[i]&(1<<p2)-1)<<k2-p2;d|=this.data[--i]>>(p2+=this.DB-k2)}else{d=this.data[i]>>(p2-=k2)&km;if(p2<=0){p2+=this.DB;--i}}if(d>0)m2=true;if(m2)r+=int2char(d)}}return m2?r:"0"}function bnNegate(){var r=nbi();BigInteger.ZERO.subTo(this,r);return r}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(a){var r=this.s-a.s;if(r!=0)return r;var i=this.t;r=i-a.t;if(r!=0)return this.s<0?-r:r;while(--i>=0)if((r=this.data[i]-a.data[i])!=0)return r;return 0}function nbits(x){var r=1,t;if((t=x>>>16)!=0){x=t;r+=16}if((t=x>>8)!=0){x=t;r+=8}if((t=x>>4)!=0){x=t;r+=4}if((t=x>>2)!=0){x=t;r+=2}if((t=x>>1)!=0){x=t;r+=1}return r}function bnBitLength(){if(this.t<=0)return 0;return this.DB*(this.t-1)+nbits(this.data[this.t-1]^this.s&this.DM)}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}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}function bnpLShiftTo(n,r){var bs2=n%this.DB;var cbs=this.DB-bs2;var bm=(1<<cbs)-1;var ds2=Math.floor(n/this.DB),c=this.s<<bs2&this.DM,i;for(i=this.t-1;i>=0;--i){r.data[i+ds2+1]=this.data[i]>>cbs|c;c=(this.data[i]&bm)<<bs2}for(i=ds2-1;i>=0;--i)r.data[i]=0;r.data[ds2]=c;r.t=this.t+ds2+1;r.s=this.s;r.clamp()}function bnpRShiftTo(n,r){r.s=this.s;var ds2=Math.floor(n/this.DB);if(ds2>=this.t){r.t=0;return}var bs2=n%this.DB;var cbs=this.DB-bs2;var bm=(1<<bs2)-1;r.data[0]=this.data[ds2]>>bs2;for(var i=ds2+1;i<this.t;++i){r.data[i-ds2-1]|=(this.data[i]&bm)<<cbs;r.data[i-ds2]=this.data[i]>>bs2}if(bs2>0)r.data[this.t-ds2-1]|=(this.s&bm)<<cbs;r.t=this.t-ds2;r.clamp()}function bnpSubTo(a,r){var i=0,c=0,m2=Math.min(a.t,this.t);while(i<m2){c+=this.data[i]-a.data[i];r.data[i++]=c&this.DM;c>>=this.DB}if(a.t<this.t){c-=a.s;while(i<this.t){c+=this.data[i];r.data[i++]=c&this.DM;c>>=this.DB}c+=this.s}else{c+=this.s;while(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;if(c<-1)r.data[i++]=this.DV+c;else if(c>0)r.data[i++]=c;r.t=i;r.clamp()}function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs();var i=x.t;r.t=i+y.t;while(--i>=0)r.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();if(this.s!=a.s)BigInteger.ZERO.subTo(r,r)}function bnpSquareTo(r){var x=this.abs();var i=r.t=2*x.t;while(--i>=0)r.data[i]=0;for(i=0;i<x.t-1;++i){var c=x.am(i,x.data[i],r,2*i,0,1);if((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}}if(r.t>0)r.data[r.t-1]+=x.am(i,x.data[i],r,2*i,0,1);r.s=0;r.clamp()}function bnpDivRemTo(m2,q2,r){var pm=m2.abs();if(pm.t<=0)return;var pt2=this.abs();if(pt2.t<pm.t){if(q2!=null)q2.fromInt(0);if(r!=null)this.copyTo(r);return}if(r==null)r=nbi();var y=nbi(),ts2=this.s,ms2=m2.s;var nsh=this.DB-nbits(pm.data[pm.t-1]);if(nsh>0){pm.lShiftTo(nsh,y);pt2.lShiftTo(nsh,r)}else{pm.copyTo(y);pt2.copyTo(r)}var ys2=y.t;var y0=y.data[ys2-1];if(y0==0)return;var yt2=y0*(1<<this.F1)+(ys2>1?y.data[ys2-2]>>this.F2:0);var d1=this.FV/yt2,d2=(1<<this.F1)/yt2,e=1<<this.F2;var i=r.t,j2=i-ys2,t=q2==null?nbi():q2;y.dlShiftTo(j2,t);if(r.compareTo(t)>=0){r.data[r.t++]=1;r.subTo(t,r)}BigInteger.ONE.dlShiftTo(ys2,t);t.subTo(y,y);while(y.t<ys2)y.data[y.t++]=0;while(--j2>=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,j2,0,ys2))<qd){y.dlShiftTo(j2,t);r.subTo(t,r);while(r.data[i]<--qd)r.subTo(t,r)}}if(q2!=null){r.drShiftTo(ys2,q2);if(ts2!=ms2)BigInteger.ZERO.subTo(q2,q2)}r.t=ys2;r.clamp();if(nsh>0)r.rShiftTo(nsh,r);if(ts2<0)BigInteger.ZERO.subTo(r,r)}function bnMod(a){var r=nbi();this.abs().divRemTo(a,null,r);if(this.s<0&&r.compareTo(BigInteger.ZERO)>0)a.subTo(r,r);return r}function Classic(m2){this.m=m2}function cConvert(x){if(x.s<0||x.compareTo(this.m)>=0)return x.mod(this.m);else return x}function cRevert(x){return x}function cReduce(x){x.divRemTo(this.m,null,x)}function cMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}function cSqrTo(x,r){x.squareTo(r);this.reduce(r)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1)return 0;var x=this.data[0];if((x&1)==0)return 0;var y=x&3;y=y*(2-(x&15)*y)&15;y=y*(2-(x&255)*y)&255;y=y*(2-((x&65535)*y&65535))&65535;y=y*(2-x*y%this.DV)%this.DV;return y>0?this.DV-y:-y}function Montgomery(m2){this.m=m2;this.mp=m2.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<m2.DB-15)-1;this.mt2=2*m2.t}function montConvert(x){var r=nbi();x.abs().dlShiftTo(this.m.t,r);r.divRemTo(this.m,null,r);if(x.s<0&&r.compareTo(BigInteger.ZERO)>0)this.m.subTo(r,r);return r}function montRevert(x){var r=nbi();x.copyTo(r);this.reduce(r);return r}function montReduce(x){while(x.t<=this.mt2)x.data[x.t++]=0;for(var i=0;i<this.m.t;++i){var j2=x.data[i]&32767;var u0=j2*this.mpl+((j2*this.mph+(x.data[i]>>15)*this.mpl&this.um)<<15)&x.DM;j2=i+this.m.t;x.data[j2]+=this.m.am(0,u0,x,i,0,this.m.t);while(x.data[j2]>=x.DV){x.data[j2]-=x.DV;x.data[++j2]++}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function montSqrTo(x,r){x.squareTo(r);this.reduce(r)}function montMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return(this.t>0?this.data[0]&1:this.s)==0}function bnpExp(e,z2){if(e>4294967295||e<1)return BigInteger.ONE;var r=nbi(),r2=nbi(),g2=z2.convert(this),i=nbits(e)-1;g2.copyTo(r);while(--i>=0){z2.sqrTo(r,r2);if((e&1<<i)>0)z2.mulTo(r2,g2,r);else{var t=r;r=r2;r2=t}}return z2.revert(r)}function bnModPowInt(e,m2){var z2;if(e<256||m2.isEven())z2=new Classic(m2);else z2=new Montgomery(m2);return this.exp(e,z2)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var r=nbi();this.copyTo(r);return r}function bnIntValue(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function bnByteValue(){return this.t==0?this.s:this.data[0]<<24>>24}function bnShortValue(){return this.t==0?this.s:this.data[0]<<16>>16}function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function bnSigNum(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function bnpToRadix(b2){if(b2==null)b2=10;if(this.signum()==0||b2<2||b2>36)return"0";var cs2=this.chunkSize(b2);var a=Math.pow(b2,cs2);var d=nbv(a),y=nbi(),z2=nbi(),r="";this.divRemTo(d,y,z2);while(y.signum()>0){r=(a+z2.intValue()).toString(b2).substr(1)+r;y.divRemTo(d,y,z2)}return z2.intValue().toString(b2)+r}function bnpFromRadix(s3,b2){this.fromInt(0);if(b2==null)b2=10;var cs2=this.chunkSize(b2);var d=Math.pow(b2,cs2),mi2=false,j2=0,w2=0;for(var i=0;i<s3.length;++i){var x=intAt(s3,i);if(x<0){if(s3.charAt(i)=="-"&&this.signum()==0)mi2=true;continue}w2=b2*w2+x;if(++j2>=cs2){this.dMultiply(d);this.dAddOffset(w2,0);j2=0;w2=0}}if(j2>0){this.dMultiply(Math.pow(b2,j2));this.dAddOffset(w2,0)}if(mi2)BigInteger.ZERO.subTo(this,this)}function bnpFromNumber(a,b2,c){if("number"==typeof b2){if(a<2)this.fromInt(1);else{this.fromNumber(a,c);if(!this.testBit(a-1))this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(b2)){this.dAddOffset(2,0);if(this.bitLength()>a)this.subTo(BigInteger.ONE.shiftLeft(a-1),this)}}}else{var x=new Array,t=a&7;x.length=(a>>3)+1;b2.nextBytes(x);if(t>0)x[0]&=(1<<t)-1;else x[0]=0;this.fromString(x,256)}}function bnToByteArray(){var i=this.t,r=new Array;r[0]=this.s;var p2=this.DB-i*this.DB%8,d,k2=0;if(i-- >0){if(p2<this.DB&&(d=this.data[i]>>p2)!=(this.s&this.DM)>>p2)r[k2++]=d|this.s<<this.DB-p2;while(i>=0){if(p2<8){d=(this.data[i]&(1<<p2)-1)<<8-p2;d|=this.data[--i]>>(p2+=this.DB-8)}else{d=this.data[i]>>(p2-=8)&255;if(p2<=0){p2+=this.DB;--i}}if((d&128)!=0)d|=-256;if(k2==0&&(this.s&128)!=(d&128))++k2;if(k2>0||d!=this.s)r[k2++]=d}}return r}function bnEquals(a){return this.compareTo(a)==0}function bnMin(a){return this.compareTo(a)<0?this:a}function bnMax(a){return this.compareTo(a)>0?this:a}function bnpBitwiseTo(a,op,r){var i,f2,m2=Math.min(a.t,this.t);for(i=0;i<m2;++i)r.data[i]=op(this.data[i],a.data[i]);if(a.t<this.t){f2=a.s&this.DM;for(i=m2;i<this.t;++i)r.data[i]=op(this.data[i],f2);r.t=this.t}else{f2=this.s&this.DM;for(i=m2;i<a.t;++i)r.data[i]=op(f2,a.data[i]);r.t=a.t}r.s=op(this.s,a.s);r.clamp()}function op_and(x,y){return x&y}function bnAnd(a){var r=nbi();this.bitwiseTo(a,op_and,r);return r}function op_or(x,y){return x|y}function bnOr(a){var r=nbi();this.bitwiseTo(a,op_or,r);return r}function op_xor(x,y){return x^y}function bnXor(a){var r=nbi();this.bitwiseTo(a,op_xor,r);return r}function op_andnot(x,y){return x&~y}function bnAndNot(a){var r=nbi();this.bitwiseTo(a,op_andnot,r);return r}function bnNot(){var r=nbi();for(var i=0;i<this.t;++i)r.data[i]=this.DM&~this.data[i];r.t=this.t;r.s=~this.s;return r}function bnShiftLeft(n){var r=nbi();if(n<0)this.rShiftTo(-n,r);else this.lShiftTo(n,r);return r}function bnShiftRight(n){var r=nbi();if(n<0)this.lShiftTo(-n,r);else this.rShiftTo(n,r);return r}function lbit(x){if(x==0)return-1;var r=0;if((x&65535)==0){x>>=16;r+=16}if((x&255)==0){x>>=8;r+=8}if((x&15)==0){x>>=4;r+=4}if((x&3)==0){x>>=2;r+=2}if((x&1)==0)++r;return r}function bnGetLowestSetBit(){for(var i=0;i<this.t;++i)if(this.data[i]!=0)return i*this.DB+lbit(this.data[i]);if(this.s<0)return this.t*this.DB;return-1}function cbit(x){var r=0;while(x!=0){x&=x-1;++r}return r}function bnBitCount(){var r=0,x=this.s&this.DM;for(var i=0;i<this.t;++i)r+=cbit(this.data[i]^x);return r}function bnTestBit(n){var j2=Math.floor(n/this.DB);if(j2>=this.t)return this.s!=0;return(this.data[j2]&1<<n%this.DB)!=0}function bnpChangeBit(n,op){var r=BigInteger.ONE.shiftLeft(n);this.bitwiseTo(r,op,r);return r}function bnSetBit(n){return this.changeBit(n,op_or)}function bnClearBit(n){return this.changeBit(n,op_andnot)}function bnFlipBit(n){return this.changeBit(n,op_xor)}function bnpAddTo(a,r){var i=0,c=0,m2=Math.min(a.t,this.t);while(i<m2){c+=this.data[i]+a.data[i];r.data[i++]=c&this.DM;c>>=this.DB}if(a.t<this.t){c+=a.s;while(i<this.t){c+=this.data[i];r.data[i++]=c&this.DM;c>>=this.DB}c+=this.s}else{c+=this.s;while(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;if(c>0)r.data[i++]=c;else if(c<-1)r.data[i++]=this.DV+c;r.t=i;r.clamp()}function bnAdd(a){var r=nbi();this.addTo(a,r);return r}function bnSubtract(a){var r=nbi();this.subTo(a,r);return r}function bnMultiply(a){var r=nbi();this.multiplyTo(a,r);return r}function bnSquare(){var r=nbi();this.squareTo(r);return r}function bnDivide(a){var r=nbi();this.divRemTo(a,r,null);return r}function bnRemainder(a){var r=nbi();this.divRemTo(a,null,r);return r}function bnDivideAndRemainder(a){var q2=nbi(),r=nbi();this.divRemTo(a,q2,r);return new Array(q2,r)}function bnpDMultiply(n){this.data[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(n,w2){if(n==0)return;while(this.t<=w2)this.data[this.t++]=0;this.data[w2]+=n;while(this.data[w2]>=this.DV){this.data[w2]-=this.DV;if(++w2>=this.t)this.data[this.t++]=0;++this.data[w2]}}function NullExp(){}function nNop(x){return x}function nMulTo(x,y,r){x.multiplyTo(y,r)}function nSqrTo(x,r){x.squareTo(r)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);r.s=0;r.t=i;while(i>0)r.data[--i]=0;var j2;for(j2=r.t-this.t;i<j2;++i)r.data[i+this.t]=this.am(0,a.data[i],r,i,0,this.t);for(j2=Math.min(a.t,n);i<j2;++i)this.am(0,a.data[i],r,i,0,n-i);r.clamp()}function bnpMultiplyUpperTo(a,n,r){--n;var i=r.t=this.t+a.t-n;r.s=0;while(--i>=0)r.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)}function Barrett(m2){this.r2=nbi();this.q3=nbi();BigInteger.ONE.dlShiftTo(2*m2.t,this.r2);this.mu=this.r2.divide(m2);this.m=m2}function barrettConvert(x){if(x.s<0||x.t>2*this.m.t)return x.mod(this.m);else if(x.compareTo(this.m)<0)return x;else{var r=nbi();x.copyTo(r);this.reduce(r);return r}}function barrettRevert(x){return x}function barrettReduce(x){x.drShiftTo(this.m.t-1,this.r2);if(x.t>this.m.t+1){x.t=this.m.t+1;x.clamp()}this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(x.compareTo(this.r2)<0)x.dAddOffset(1,this.m.t+1);x.subTo(this.r2,x);while(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function barrettSqrTo(x,r){x.squareTo(r);this.reduce(r)}function barrettMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(e,m2){var i=e.bitLength(),k2,r=nbv(1),z2;if(i<=0)return r;else if(i<18)k2=1;else if(i<48)k2=3;else if(i<144)k2=4;else if(i<768)k2=5;else k2=6;if(i<8)z2=new Classic(m2);else if(m2.isEven())z2=new Barrett(m2);else z2=new Montgomery(m2);var g2=new Array,n=3,k1=k2-1,km=(1<<k2)-1;g2[1]=z2.convert(this);if(k2>1){var g22=nbi();z2.sqrTo(g2[1],g22);while(n<=km){g2[n]=nbi();z2.mulTo(g22,g2[n-2],g2[n]);n+=2}}var j2=e.t-1,w2,is1=true,r2=nbi(),t;i=nbits(e.data[j2])-1;while(j2>=0){if(i>=k1)w2=e.data[j2]>>i-k1&km;else{w2=(e.data[j2]&(1<<i+1)-1)<<k1-i;if(j2>0)w2|=e.data[j2-1]>>this.DB+i-k1}n=k2;while((w2&1)==0){w2>>=1;--n}if((i-=n)<0){i+=this.DB;--j2}if(is1){g2[w2].copyTo(r);is1=false}else{while(n>1){z2.sqrTo(r,r2);z2.sqrTo(r2,r);n-=2}if(n>0)z2.sqrTo(r,r2);else{t=r;r=r2;r2=t}z2.mulTo(r2,g2[w2],r)}while(j2>=0&&(e.data[j2]&1<<i)==0){z2.sqrTo(r,r2);t=r;r=r2;r2=t;if(--i<0){i=this.DB-1;--j2}}}return z2.revert(r)}function bnGCD(a){var x=this.s<0?this.negate():this.clone();var y=a.s<0?a.negate():a.clone();if(x.compareTo(y)<0){var t=x;x=y;y=t}var i=x.getLowestSetBit(),g2=y.getLowestSetBit();if(g2<0)return x;if(i<g2)g2=i;if(g2>0){x.rShiftTo(g2,x);y.rShiftTo(g2,y)}while(x.signum()>0){if((i=x.getLowestSetBit())>0)x.rShiftTo(i,x);if((i=y.getLowestSetBit())>0)y.rShiftTo(i,y);if(x.compareTo(y)>=0){x.subTo(y,x);x.rShiftTo(1,x)}else{y.subTo(x,y);y.rShiftTo(1,y)}}if(g2>0)y.lShiftTo(g2,y);return y}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(d==0)r=this.data[0]%n;else for(var i=this.t-1;i>=0;--i)r=(d*r+this.data[i])%n;return r}function bnModInverse(m2){if(this.signum()==0){return BigInteger.ZERO}var ac=m2.isEven();if(this.isEven()&&ac||m2.signum()==0)return BigInteger.ZERO;var u2=m2.clone(),v2=this.clone();var a=nbv(1),b2=nbv(0),c=nbv(0),d=nbv(1);while(u2.signum()!=0){while(u2.isEven()){u2.rShiftTo(1,u2);if(ac){if(!a.isEven()||!b2.isEven()){a.addTo(this,a);b2.subTo(m2,b2)}a.rShiftTo(1,a)}else if(!b2.isEven())b2.subTo(m2,b2);b2.rShiftTo(1,b2)}while(v2.isEven()){v2.rShiftTo(1,v2);if(ac){if(!c.isEven()||!d.isEven()){c.addTo(this,c);d.subTo(m2,d)}c.rShiftTo(1,c)}else if(!d.isEven())d.subTo(m2,d);d.rShiftTo(1,d)}if(u2.compareTo(v2)>=0){u2.subTo(v2,u2);if(ac)a.subTo(c,a);b2.subTo(d,b2)}else{v2.subTo(u2,v2);if(ac)c.subTo(a,c);d.subTo(b2,d)}}if(v2.compareTo(BigInteger.ONE)!=0)return BigInteger.ZERO;if(d.compareTo(m2)>=0)return d.subtract(m2);if(d.signum()<0)d.addTo(m2,d);else return d;if(d.signum()<0)return d.add(m2);else return d}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,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(t){var i,x=this.abs();if(x.t==1&&x.data[0]<=lowprimes[lowprimes.length-1]){for(i=0;i<lowprimes.length;++i)if(x.data[0]==lowprimes[i])return true;return false}if(x.isEven())return false;i=1;while(i<lowprimes.length){var m2=lowprimes[i],j2=i+1;while(j2<lowprimes.length&&m2<lplim)m2*=lowprimes[j2++];m2=x.modInt(m2);while(i<j2)if(m2%lowprimes[i++]==0)return false}return x.millerRabin(t)}function bnpMillerRabin(t){var n1=this.subtract(BigInteger.ONE);var k2=n1.getLowestSetBit();if(k2<=0)return false;var r=n1.shiftRight(k2);var prng=bnGetPrng();var a;for(var 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(y.compareTo(BigInteger.ONE)!=0&&y.compareTo(n1)!=0){var j2=1;while(j2++<k2&&y.compareTo(n1)!=0){y=y.modPowInt(2,this);if(y.compareTo(BigInteger.ONE)==0)return false}if(y.compareTo(n1)!=0)return false}}return true}function bnGetPrng(){return{nextBytes:function(x){for(var i=0;i<x.length;++i){x[i]=Math.floor(Math.random()*256)}}}}BigInteger.prototype.chunkSize=bnpChunkSize;BigInteger.prototype.toRadix=bnpToRadix;BigInteger.prototype.fromRadix=bnpFromRadix;BigInteger.prototype.fromNumber=bnpFromNumber;BigInteger.prototype.bitwiseTo=bnpBitwiseTo;BigInteger.prototype.changeBit=bnpChangeBit;BigInteger.prototype.addTo=bnpAddTo;BigInteger.prototype.dMultiply=bnpDMultiply;BigInteger.prototype.dAddOffset=bnpDAddOffset;BigInteger.prototype.multiplyLowerTo=bnpMultiplyLowerTo;BigInteger.prototype.multiplyUpperTo=bnpMultiplyUpperTo;BigInteger.prototype.modInt=bnpModInt;BigInteger.prototype.millerRabin=bnpMillerRabin;BigInteger.prototype.clone=bnClone;BigInteger.prototype.intValue=bnIntValue;BigInteger.prototype.byteValue=bnByteValue;BigInteger.prototype.shortValue=bnShortValue;BigInteger.prototype.signum=bnSigNum;BigInteger.prototype.toByteArray=bnToByteArray;BigInteger.prototype.equals=bnEquals;BigInteger.prototype.min=bnMin;BigInteger.prototype.max=bnMax;BigInteger.prototype.and=bnAnd;BigInteger.prototype.or=bnOr;BigInteger.prototype.xor=bnXor;BigInteger.prototype.andNot=bnAndNot;BigInteger.prototype.not=bnNot;BigInteger.prototype.shiftLeft=bnShiftLeft;BigInteger.prototype.shiftRight=bnShiftRight;BigInteger.prototype.getLowestSetBit=bnGetLowestSetBit;BigInteger.prototype.bitCount=bnBitCount;BigInteger.prototype.testBit=bnTestBit;BigInteger.prototype.setBit=bnSetBit;BigInteger.prototype.clearBit=bnClearBit;BigInteger.prototype.flipBit=bnFlipBit;BigInteger.prototype.add=bnAdd;BigInteger.prototype.subtract=bnSubtract;BigInteger.prototype.multiply=bnMultiply;BigInteger.prototype.divide=bnDivide;BigInteger.prototype.remainder=bnRemainder;BigInteger.prototype.divideAndRemainder=bnDivideAndRemainder;BigInteger.prototype.modPow=bnModPow;BigInteger.prototype.modInverse=bnModInverse;BigInteger.prototype.pow=bnPow;BigInteger.prototype.gcd=bnGCD;BigInteger.prototype.isProbablePrime=bnIsProbablePrime;BigInteger.prototype.square=bnSquare}});var require_sha1=__commonJS({"node_modules/node-forge/lib/sha1.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var sha1=module.exports=forge2.sha1=forge2.sha1||{};forge2.md.sha1=forge2.md.algorithms.sha1=sha1;sha1.create=function(){if(!_initialized){_init()}var _state=null;var _input=forge2.util.createBuffer();var _w=new Array(80);var md={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength64=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_state={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520};return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_state,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i<md.fullMessageLength.length-1;++i){next=md.fullMessageLength[i+1]*8;carry=next/4294967296>>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var s22={h0:_state.h0,h1:_state.h1,h2:_state.h2,h3:_state.h3,h4:_state.h4};_update(s22,_w,finalBlock);var rval=forge2.util.createBuffer();rval.putInt32(s22.h0);rval.putInt32(s22.h1);rval.putInt32(s22.h2);rval.putInt32(s22.h3);rval.putInt32(s22.h4);return rval};return md};var _padding=null;var _initialized=false;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.util.fillString(String.fromCharCode(0),64);_initialized=true}function _update(s3,w2,bytes){var t,a,b2,c,d,e,f2,i;var len=bytes.length();while(len>=64){a=s3.h0;b2=s3.h1;c=s3.h2;d=s3.h3;e=s3.h4;for(i=0;i<16;++i){t=bytes.getInt32();w2[i]=t;f2=d^b2&(c^d);t=(a<<5|a>>>27)+f2+e+1518500249+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<20;++i){t=w2[i-3]^w2[i-8]^w2[i-14]^w2[i-16];t=t<<1|t>>>31;w2[i]=t;f2=d^b2&(c^d);t=(a<<5|a>>>27)+f2+e+1518500249+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<32;++i){t=w2[i-3]^w2[i-8]^w2[i-14]^w2[i-16];t=t<<1|t>>>31;w2[i]=t;f2=b2^c^d;t=(a<<5|a>>>27)+f2+e+1859775393+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<40;++i){t=w2[i-6]^w2[i-16]^w2[i-28]^w2[i-32];t=t<<2|t>>>30;w2[i]=t;f2=b2^c^d;t=(a<<5|a>>>27)+f2+e+1859775393+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<60;++i){t=w2[i-6]^w2[i-16]^w2[i-28]^w2[i-32];t=t<<2|t>>>30;w2[i]=t;f2=b2&c|d&(b2^c);t=(a<<5|a>>>27)+f2+e+2400959708+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}for(;i<80;++i){t=w2[i-6]^w2[i-16]^w2[i-28]^w2[i-32];t=t<<2|t>>>30;w2[i]=t;f2=b2^c^d;t=(a<<5|a>>>27)+f2+e+3395469782+t;e=d;d=c;c=(b2<<30|b2>>>2)>>>0;b2=a;a=t}s3.h0=s3.h0+a|0;s3.h1=s3.h1+b2|0;s3.h2=s3.h2+c|0;s3.h3=s3.h3+d|0;s3.h4=s3.h4+e|0;len-=64}}}});var require_pkcs1=__commonJS({"node_modules/node-forge/lib/pkcs1.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_random();require_sha1();var pkcs1=module.exports=forge2.pkcs1=forge2.pkcs1||{};pkcs1.encode_rsa_oaep=function(key,message,options){var label;var seed;var md;var mgf1Md;if(typeof options==="string"){label=options;seed=arguments[3]||void 0;md=arguments[4]||void 0}else if(options){label=options.label||void 0;seed=options.seed||void 0;md=options.md||void 0;if(options.mgf1&&options.mgf1.md){mgf1Md=options.mgf1.md}}if(!md){md=forge2.md.sha1.create()}else{md.start()}if(!mgf1Md){mgf1Md=md}var keyLength=Math.ceil(key.n.bitLength()/8);var maxLength=keyLength-2*md.digestLength-2;if(message.length>maxLength){var error=new Error("RSAES-OAEP input message length is too long.");error.length=message.length;error.maxLength=maxLength;throw error}if(!label){label=""}md.update(label,"raw");var lHash=md.digest();var PS="";var PS_length=maxLength-message.length;for(var i=0;i<PS_length;i++){PS+="\0"}var DB=lHash.getBytes()+PS+""+message;if(!seed){seed=forge2.random.getBytes(md.digestLength)}else if(seed.length!==md.digestLength){var error=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");error.seedLength=seed.length;error.digestLength=md.digestLength;throw error}var dbMask=rsa_mgf1(seed,keyLength-md.digestLength-1,mgf1Md);var maskedDB=forge2.util.xorBytes(DB,dbMask,DB.length);var seedMask=rsa_mgf1(maskedDB,md.digestLength,mgf1Md);var maskedSeed=forge2.util.xorBytes(seed,seedMask,seed.length);return"\0"+maskedSeed+maskedDB};pkcs1.decode_rsa_oaep=function(key,em,options){var label;var md;var mgf1Md;if(typeof options==="string"){label=options;md=arguments[3]||void 0}else if(options){label=options.label||void 0;md=options.md||void 0;if(options.mgf1&&options.mgf1.md){mgf1Md=options.mgf1.md}}var keyLength=Math.ceil(key.n.bitLength()/8);if(em.length!==keyLength){var error=new Error("RSAES-OAEP encoded message length is invalid.");error.length=em.length;error.expectedLength=keyLength;throw error}if(md===void 0){md=forge2.md.sha1.create()}else{md.start()}if(!mgf1Md){mgf1Md=md}if(keyLength<2*md.digestLength+2){throw new Error("RSAES-OAEP key is too short for the hash function.")}if(!label){label=""}md.update(label,"raw");var lHash=md.digest().getBytes();var y=em.charAt(0);var maskedSeed=em.substring(1,md.digestLength+1);var maskedDB=em.substring(1+md.digestLength);var seedMask=rsa_mgf1(maskedDB,md.digestLength,mgf1Md);var seed=forge2.util.xorBytes(maskedSeed,seedMask,maskedSeed.length);var dbMask=rsa_mgf1(seed,keyLength-md.digestLength-1,mgf1Md);var db=forge2.util.xorBytes(maskedDB,dbMask,maskedDB.length);var lHashPrime=db.substring(0,md.digestLength);var error=y!=="\0";for(var i=0;i<md.digestLength;++i){error|=lHash.charAt(i)!==lHashPrime.charAt(i)}var in_ps=1;var index=md.digestLength;for(var j2=md.digestLength;j2<db.length;j2++){var code=db.charCodeAt(j2);var is_0=code&1^1;var error_mask=in_ps?65534:0;error|=code&error_mask;in_ps=in_ps&is_0;index+=in_ps}if(error||db.charCodeAt(index)!==1){throw new Error("Invalid RSAES-OAEP padding.")}return db.substring(index+1)};function rsa_mgf1(seed,maskLength,hash){if(!hash){hash=forge2.md.sha1.create()}var t="";var count=Math.ceil(maskLength/hash.digestLength);for(var i=0;i<count;++i){var c=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,i&255);hash.start();hash.update(seed+c);t+=hash.digest().getBytes()}return t.substring(0,maskLength)}}});var require_prime=__commonJS({"node_modules/node-forge/lib/prime.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_jsbn();require_random();(function(){if(forge2.prime){module.exports=forge2.prime;return}var prime=module.exports=forge2.prime=forge2.prime||{};var BigInteger=forge2.jsbn.BigInteger;var GCD_30_DELTA=[6,4,2,4,2,4,6,2];var THIRTY=new BigInteger(null);THIRTY.fromInt(30);var op_or=function(x,y){return x|y};prime.generateProbablePrime=function(bits,options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};var algorithm=options.algorithm||"PRIMEINC";if(typeof algorithm==="string"){algorithm={name:algorithm}}algorithm.options=algorithm.options||{};var prng=options.prng||forge2.random;var rng={nextBytes:function(x){var b2=prng.getBytesSync(x.length);for(var i=0;i<x.length;++i){x[i]=b2.charCodeAt(i)}}};if(algorithm.name==="PRIMEINC"){return primeincFindPrime(bits,rng,algorithm.options,callback)}throw new Error("Invalid prime generation algorithm: "+algorithm.name)};function primeincFindPrime(bits,rng,options,callback){if("workers"in options){return primeincFindPrimeWithWorkers(bits,rng,options,callback)}return primeincFindPrimeWithoutWorkers(bits,rng,options,callback)}function primeincFindPrimeWithoutWorkers(bits,rng,options,callback){var num=generateRandom(bits,rng);var deltaIdx=0;var mrTests=getMillerRabinTests(num.bitLength());if("millerRabinTests"in options){mrTests=options.millerRabinTests}var maxBlockTime=10;if("maxBlockTime"in options){maxBlockTime=options.maxBlockTime}_primeinc(num,bits,rng,deltaIdx,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)}if(num.isProbablePrime(mrTests)){return callback(null,num)}num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}while(maxBlockTime<0||+new Date-start<maxBlockTime);forge2.util.setImmediate(function(){_primeinc(num,bits,rng,deltaIdx,mrTests,maxBlockTime,callback)})}function primeincFindPrimeWithWorkers(bits,rng,options,callback){if(typeof Worker==="undefined"){return primeincFindPrimeWithoutWorkers(bits,rng,options,callback)}var num=generateRandom(bits,rng);var numWorkers=options.workers;var workLoad=options.workLoad||100;var range=workLoad*30/8;var workerScript=options.workerScript||"forge/prime.worker.js";if(numWorkers===-1){return forge2.util.estimateCores(function(err,cores){if(err){cores=2}numWorkers=cores-1;generate()})}generate();function generate(){numWorkers=Math.max(1,numWorkers);var workers=[];for(var i=0;i<numWorkers;++i){workers[i]=new Worker(workerScript)}var running=numWorkers;for(var i=0;i<numWorkers;++i){workers[i].addEventListener("message",workerMessage)}var found=false;function workerMessage(e){if(found){return}--running;var data=e.data;if(data.found){for(var i2=0;i2<workers.length;++i2){workers[i2].terminate()}found=true;return callback(null,new BigInteger(data.prime,16))}if(num.bitLength()>bits){num=generateRandom(bits,rng)}var hex=num.toString(16);e.target.postMessage({hex,workLoad});num.dAddOffset(range,0)}}}function generateRandom(bits,rng){var num=new BigInteger(bits,rng);var bits1=bits-1;if(!num.testBit(bits1)){num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,num)}num.dAddOffset(31-num.mod(THIRTY).byteValue(),0);return num}function getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}})()}});var require_rsa=__commonJS({"node_modules/node-forge/lib/rsa.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_jsbn();require_oids();require_pkcs1();require_prime();require_random();require_util7();if(typeof BigInteger==="undefined"){BigInteger=forge2.jsbn.BigInteger}var BigInteger;var _crypto=forge2.util.isNodejs?__require("crypto"):null;var asn1=forge2.asn1;var util=forge2.util;forge2.pki=forge2.pki||{};module.exports=forge2.pki.rsa=forge2.rsa=forge2.rsa||{};var pki=forge2.pki;var GCD_30_DELTA=[6,4,2,4,2,4,6,2];var privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"privateKey"}]};var rsaPrivateKeyValidator={name:"RSAPrivateKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPrivateKey.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyCoefficient"}]};var rsaPublicKeyValidator={name:"RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RSAPublicKey.modulus",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"publicKeyExponent"}]};var publicKeyValidator=forge2.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"rsaPublicKey"}]}]};var digestInfoValidator={name:"DigestInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.NULL,capture:"parameters",optional:true,constructed:false}]},{name:"DigestInfo.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"digest"}]};var emsaPkcs1v15encode=function(md){var oid;if(md.algorithm in pki.oids){oid=pki.oids[md.algorithm]}else{var error=new Error("Unknown message digest algorithm.");error.algorithm=md.algorithm;throw error}var oidBytes=asn1.oidToDer(oid).getBytes();var digestInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var digestAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,oidBytes));digestAlgorithm.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,""));var digest=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,md.digest().getBytes());digestInfo.value.push(digestAlgorithm);digestInfo.value.push(digest);return asn1.toDer(digestInfo).getBytes()};var _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)}if(!key.dP){key.dP=key.d.mod(key.p.subtract(BigInteger.ONE))}if(!key.dQ){key.dQ=key.d.mod(key.q.subtract(BigInteger.ONE))}if(!key.qInv){key.qInv=key.q.modInverse(key.p)}var r;do{r=new BigInteger(forge2.util.bytesToHex(forge2.random.getBytes(key.n.bitLength()/8)),16)}while(r.compareTo(key.n)>=0||!r.gcd(key.n).equals(BigInteger.ONE));x=x.multiply(r.modPow(key.e,key.n)).mod(key.n);var xp=x.mod(key.p).modPow(key.dP,key.p);var xq=x.mod(key.q).modPow(key.dQ,key.q);while(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);y=y.multiply(r.modInverse(key.n)).mod(key.n);return y};pki.rsa.encrypt=function(m2,key,bt2){var pub=bt2;var eb;var k2=Math.ceil(key.n.bitLength()/8);if(bt2!==false&&bt2!==true){pub=bt2===2;eb=_encodePkcs1_v1_5(m2,key,bt2)}else{eb=forge2.util.createBuffer();eb.putBytes(m2)}var x=new BigInteger(eb.toHex(),16);var y=_modPow(x,key,pub);var yhex=y.toString(16);var ed=forge2.util.createBuffer();var zeros=k2-Math.ceil(yhex.length/2);while(zeros>0){ed.putByte(0);--zeros}ed.putBytes(forge2.util.hexToBytes(yhex));return ed.getBytes()};pki.rsa.decrypt=function(ed,key,pub,ml){var k2=Math.ceil(key.n.bitLength()/8);if(ed.length!==k2){var error=new Error("Encrypted message length is invalid.");error.length=ed.length;error.expected=k2;throw error}var y=new BigInteger(forge2.util.createBuffer(ed).toHex(),16);if(y.compareTo(key.n)>=0){throw new Error("Encrypted message is invalid.")}var x=_modPow(y,key,pub);var xhex=x.toString(16);var eb=forge2.util.createBuffer();var zeros=k2-Math.ceil(xhex.length/2);while(zeros>0){eb.putByte(0);--zeros}eb.putBytes(forge2.util.hexToBytes(xhex));if(ml!==false){return _decodePkcs1_v1_5(eb.getBytes(),key,pub)}return eb.getBytes()};pki.rsa.createKeyPairGenerationState=function(bits,e,options){if(typeof bits==="string"){bits=parseInt(bits,10)}bits=bits||2048;options=options||{};var prng=options.prng||forge2.random;var rng={nextBytes:function(x){var b2=prng.getBytesSync(x.length);for(var i=0;i<x.length;++i){x[i]=b2.charCodeAt(i)}}};var algorithm=options.algorithm||"PRIMEINC";var rval;if(algorithm==="PRIMEINC"){rval={algorithm,state:0,bits,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};rval.e.fromInt(rval.eInt)}else{throw new Error("Invalid key generation algorithm: "+algorithm)}return rval};pki.rsa.stepKeyPairGenerationState=function(state3,n){if(!("algorithm"in state3)){state3.algorithm="PRIMEINC"}var THIRTY=new BigInteger(null);THIRTY.fromInt(30);var deltaIdx=0;var op_or=function(x,y){return x|y};var t1=+new Date;var t2;var total=0;while(state3.keys===null&&(n<=0||total<n)){if(state3.state===0){var bits=state3.p===null?state3.pBits:state3.qBits;var bits1=bits-1;if(state3.pqState===0){state3.num=new BigInteger(bits,state3.rng);if(!state3.num.testBit(bits1)){state3.num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1),op_or,state3.num)}state3.num.dAddOffset(31-state3.num.mod(THIRTY).byteValue(),0);deltaIdx=0;++state3.pqState}else if(state3.pqState===1){if(state3.num.bitLength()>bits){state3.pqState=0}else if(state3.num.isProbablePrime(_getMillerRabinTests(state3.num.bitLength()))){++state3.pqState}else{state3.num.dAddOffset(GCD_30_DELTA[deltaIdx++%8],0)}}else if(state3.pqState===2){state3.pqState=state3.num.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE)===0?3:0}else if(state3.pqState===3){state3.pqState=0;if(state3.p===null){state3.p=state3.num}else{state3.q=state3.num}if(state3.p!==null&&state3.q!==null){++state3.state}state3.num=null}}else if(state3.state===1){if(state3.p.compareTo(state3.q)<0){state3.num=state3.p;state3.p=state3.q;state3.q=state3.num}++state3.state}else if(state3.state===2){state3.p1=state3.p.subtract(BigInteger.ONE);state3.q1=state3.q.subtract(BigInteger.ONE);state3.phi=state3.p1.multiply(state3.q1);++state3.state}else if(state3.state===3){if(state3.phi.gcd(state3.e).compareTo(BigInteger.ONE)===0){++state3.state}else{state3.p=null;state3.q=null;state3.state=0}}else if(state3.state===4){state3.n=state3.p.multiply(state3.q);if(state3.n.bitLength()===state3.bits){++state3.state}else{state3.q=null;state3.state=0}}else if(state3.state===5){var d=state3.e.modInverse(state3.phi);state3.keys={privateKey:pki.rsa.setPrivateKey(state3.n,state3.e,d,state3.p,state3.q,d.mod(state3.p1),d.mod(state3.q1),state3.q.modInverse(state3.p)),publicKey:pki.rsa.setPublicKey(state3.n,state3.e)}}t2=+new Date;total+=t2-t1;t1=t2}return state3.keys!==null};pki.rsa.generateKeyPair=function(bits,e,options,callback){if(arguments.length===1){if(typeof bits==="object"){options=bits;bits=void 0}else if(typeof bits==="function"){callback=bits;bits=void 0}}else if(arguments.length===2){if(typeof bits==="number"){if(typeof e==="function"){callback=e;e=void 0}else if(typeof e!=="number"){options=e;e=void 0}}else{options=bits;callback=e;bits=void 0;e=void 0}}else if(arguments.length===3){if(typeof e==="number"){if(typeof options==="function"){callback=options;options=void 0}}else{callback=options;options=e;e=void 0}}options=options||{};if(bits===void 0){bits=options.bits||2048}if(e===void 0){e=options.e||65537}if(!forge2.options.usePureJavaScript&&!options.prng&&bits>=256&&bits<=16384&&(e===65537||e===3)){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"}},true,["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(forge2.util.createBuffer(pkcs8)));callback(null,{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"}},true,["sign","verify"]);genOp.oncomplete=function(e2){var pair=e2.target.result;var exportOp=util.globalScope.msCrypto.subtle.exportKey("pkcs8",pair.privateKey);exportOp.oncomplete=function(e3){var pkcs8=e3.target.result;var privateKey=pki.privateKeyFromAsn1(asn1.fromDer(forge2.util.createBuffer(pkcs8)));callback(null,{privateKey,publicKey:pki.setRsaPublicKey(privateKey.n,privateKey.e)})};exportOp.onerror=function(err){callback(err)}};genOp.onerror=function(err){callback(err)};return}}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 state3=pki.rsa.createKeyPairGenerationState(bits,e,options);if(!callback){pki.rsa.stepKeyPairGenerationState(state3,0);return state3.keys}_generateKeyPair(state3,options,callback)};pki.setRsaPublicKey=pki.rsa.setPublicKey=function(n,e){var key={n,e};key.encrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===void 0){scheme="RSAES-PKCS1-V1_5"}if(scheme==="RSAES-PKCS1-V1_5"){scheme={encode:function(m2,key2,pub){return _encodePkcs1_v1_5(m2,key2,2).getBytes()}}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={encode:function(m2,key2){return forge2.pkcs1.encode_rsa_oaep(key2,m2,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={encode:function(e3){return e3}}}else if(typeof scheme==="string"){throw new Error('Unsupported encryption scheme: "'+scheme+'".')}var e2=scheme.encode(data,key,true);return pki.rsa.encrypt(e2,key,true)};key.verify=function(digest,signature,scheme,options){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===void 0){scheme="RSASSA-PKCS1-V1_5"}if(options===void 0){options={_parseAllDigestBytes:true,_skipPaddingChecks:false}}if(!("_parseAllDigestBytes"in options)){options._parseAllDigestBytes=true}if(!("_skipPaddingChecks"in options)){options._skipPaddingChecks=false}if(scheme==="RSASSA-PKCS1-V1_5"){scheme={verify:function(digest2,d2){d2=_decodePkcs1_v1_5(d2,key,true,void 0,options);var obj=asn1.fromDer(d2,{parseAllBytes:options._parseAllDigestBytes});var capture2={};var errors=[];if(!asn1.validate(obj,digestInfoValidator,capture2,errors)||obj.value.length!==2){var error=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.algorithmIdentifier);if(!(oid===forge2.oids.md2||oid===forge2.oids.md5||oid===forge2.oids.sha1||oid===forge2.oids.sha224||oid===forge2.oids.sha256||oid===forge2.oids.sha384||oid===forge2.oids.sha512||oid===forge2.oids["sha512-224"]||oid===forge2.oids["sha512-256"])){var error=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");error.oid=oid;throw error}if(oid===forge2.oids.md2||oid===forge2.oids.md5){if(!("parameters"in capture2)){throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}}return digest2===capture2.digest}}}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={verify:function(digest2,d2){d2=_decodePkcs1_v1_5(d2,key,true,void 0,options);return digest2===d2}}}var d=pki.rsa.decrypt(signature,key,true,false);return scheme.verify(digest,d,key.n.bitLength())};return key};pki.setRsaPrivateKey=pki.rsa.setPrivateKey=function(n,e,d,p2,q2,dP,dQ,qInv){var key={n,e,d,p:p2,q:q2,dP,dQ,qInv};key.decrypt=function(data,scheme,schemeOptions){if(typeof scheme==="string"){scheme=scheme.toUpperCase()}else if(scheme===void 0){scheme="RSAES-PKCS1-V1_5"}var d2=pki.rsa.decrypt(data,key,false,false);if(scheme==="RSAES-PKCS1-V1_5"){scheme={decode:_decodePkcs1_v1_5}}else if(scheme==="RSA-OAEP"||scheme==="RSAES-OAEP"){scheme={decode:function(d3,key2){return forge2.pkcs1.decode_rsa_oaep(key2,d3,schemeOptions)}}}else if(["RAW","NONE","NULL",null].indexOf(scheme)!==-1){scheme={decode:function(d3){return d3}}}else{throw new Error('Unsupported encryption scheme: "'+scheme+'".')}return scheme.decode(d2,key,false)};key.sign=function(md,scheme){var bt2=false;if(typeof scheme==="string"){scheme=scheme.toUpperCase()}if(scheme===void 0||scheme==="RSASSA-PKCS1-V1_5"){scheme={encode:emsaPkcs1v15encode};bt2=1}else if(scheme==="NONE"||scheme==="NULL"||scheme===null){scheme={encode:function(){return md}};bt2=1}var d2=scheme.encode(md,key.n.bitLength());return pki.rsa.encrypt(d2,key,bt2)};return key};pki.wrapRsaPrivateKey=function(rsaKey){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(rsaKey).getBytes())])};pki.privateKeyFromAsn1=function(obj){var capture2={};var errors=[];if(asn1.validate(obj,privateKeyValidator,capture2,errors)){obj=asn1.fromDer(forge2.util.createBuffer(capture2.privateKey))}capture2={};errors=[];if(!asn1.validate(obj,rsaPrivateKeyValidator,capture2,errors)){var error=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");error.errors=errors;throw error}var n,e,d,p2,q2,dP,dQ,qInv;n=forge2.util.createBuffer(capture2.privateKeyModulus).toHex();e=forge2.util.createBuffer(capture2.privateKeyPublicExponent).toHex();d=forge2.util.createBuffer(capture2.privateKeyPrivateExponent).toHex();p2=forge2.util.createBuffer(capture2.privateKeyPrime1).toHex();q2=forge2.util.createBuffer(capture2.privateKeyPrime2).toHex();dP=forge2.util.createBuffer(capture2.privateKeyExponent1).toHex();dQ=forge2.util.createBuffer(capture2.privateKeyExponent2).toHex();qInv=forge2.util.createBuffer(capture2.privateKeyCoefficient).toHex();return pki.setRsaPrivateKey(new BigInteger(n,16),new BigInteger(e,16),new BigInteger(d,16),new BigInteger(p2,16),new BigInteger(q2,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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(0).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.d)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.p)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.q)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dP)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.dQ)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.qInv))])};pki.publicKeyFromAsn1=function(obj){var capture2={};var errors=[];if(asn1.validate(obj,publicKeyValidator,capture2,errors)){var oid=asn1.derToOid(capture2.publicKeyOid);if(oid!==pki.oids.rsaEncryption){var error=new Error("Cannot read public key. Unknown OID.");error.oid=oid;throw error}obj=capture2.rsaPublicKey}errors=[];if(!asn1.validate(obj,rsaPublicKeyValidator,capture2,errors)){var error=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");error.errors=errors;throw error}var n=forge2.util.createBuffer(capture2.publicKeyModulus).toHex();var e=forge2.util.createBuffer(capture2.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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.rsaEncryption).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,[pki.publicKeyToRSAPublicKey(key)])])};pki.publicKeyToRSAPublicKey=function(key){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.n)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,_bnToBytes(key.e))])};function _encodePkcs1_v1_5(m2,key,bt2){var eb=forge2.util.createBuffer();var k2=Math.ceil(key.n.bitLength()/8);if(m2.length>k2-11){var error=new Error("Message is too long for PKCS#1 v1.5 padding.");error.length=m2.length;error.max=k2-11;throw error}eb.putByte(0);eb.putByte(bt2);var padNum=k2-3-m2.length;var padByte;if(bt2===0||bt2===1){padByte=bt2===0?0:255;for(var i=0;i<padNum;++i){eb.putByte(padByte)}}else{while(padNum>0){var numZeros=0;var padBytes=forge2.random.getBytes(padNum);for(var i=0;i<padNum;++i){padByte=padBytes.charCodeAt(i);if(padByte===0){++numZeros}else{eb.putByte(padByte)}}padNum=numZeros}}eb.putByte(0);eb.putBytes(m2);return eb}function _decodePkcs1_v1_5(em,key,pub,ml,options){var k2=Math.ceil(key.n.bitLength()/8);var eb=forge2.util.createBuffer(em);var first=eb.getByte();var bt2=eb.getByte();if(first!==0||pub&&bt2!==0&&bt2!==1||!pub&&bt2!==2||pub&&bt2===0&&typeof ml==="undefined"){throw new Error("Encryption block is invalid.")}var padNum=0;if(bt2===0){padNum=k2-3-ml;for(var i=0;i<padNum;++i){if(eb.getByte()!==0){throw new Error("Encryption block is invalid.")}}}else if(bt2===1){padNum=0;while(eb.length()>1){if(eb.getByte()!==255){--eb.read;break}++padNum}if(padNum<8&&!(options?options._skipPaddingChecks:false)){throw new Error("Encryption block is invalid.")}}else if(bt2===2){padNum=0;while(eb.length()>1){if(eb.getByte()===0){--eb.read;break}++padNum}if(padNum<8&&!(options?options._skipPaddingChecks:false)){throw new Error("Encryption block is invalid.")}}var zero=eb.getByte();if(zero!==0||padNum!==k2-3-eb.length()){throw new Error("Encryption block is invalid.")}return eb.getBytes()}function _generateKeyPair(state3,options,callback){if(typeof options==="function"){callback=options;options={}}options=options||{};var opts={algorithm:{name:options.algorithm||"PRIMEINC",options:{workers:options.workers||2,workLoad:options.workLoad||100,workerScript:options.workerScript}}};if("prng"in options){opts.prng=options.prng}generate();function generate(){getPrime(state3.pBits,function(err,num){if(err){return callback(err)}state3.p=num;if(state3.q!==null){return finish(err,state3.q)}getPrime(state3.qBits,finish)})}function getPrime(bits,callback2){forge2.prime.generateProbablePrime(bits,opts,callback2)}function finish(err,num){if(err){return callback(err)}state3.q=num;if(state3.p.compareTo(state3.q)<0){var tmp=state3.p;state3.p=state3.q;state3.q=tmp}if(state3.p.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE)!==0){state3.p=null;generate();return}if(state3.q.subtract(BigInteger.ONE).gcd(state3.e).compareTo(BigInteger.ONE)!==0){state3.q=null;getPrime(state3.qBits,finish);return}state3.p1=state3.p.subtract(BigInteger.ONE);state3.q1=state3.q.subtract(BigInteger.ONE);state3.phi=state3.p1.multiply(state3.q1);if(state3.phi.gcd(state3.e).compareTo(BigInteger.ONE)!==0){state3.p=state3.q=null;generate();return}state3.n=state3.p.multiply(state3.q);if(state3.n.bitLength()!==state3.bits){state3.q=null;getPrime(state3.qBits,finish);return}var d=state3.e.modInverse(state3.phi);state3.keys={privateKey:pki.rsa.setPrivateKey(state3.n,state3.e,d,state3.p,state3.q,d.mod(state3.p1),d.mod(state3.q1),state3.q.modInverse(state3.p)),publicKey:pki.rsa.setPublicKey(state3.n,state3.e)};callback(null,state3.keys)}}function _bnToBytes(b2){var hex=b2.toString(16);if(hex[0]>="8"){hex="00"+hex}var bytes=forge2.util.hexToBytes(hex);if(bytes.length>1&&(bytes.charCodeAt(0)===0&&(bytes.charCodeAt(1)&128)===0||bytes.charCodeAt(0)===255&&(bytes.charCodeAt(1)&128)===128)){return bytes.substr(1)}return bytes}function _getMillerRabinTests(bits){if(bits<=100)return 27;if(bits<=150)return 18;if(bits<=200)return 15;if(bits<=250)return 12;if(bits<=300)return 9;if(bits<=350)return 8;if(bits<=400)return 7;if(bits<=500)return 6;if(bits<=600)return 5;if(bits<=800)return 4;if(bits<=1250)return 3;return 2}function _detectNodeCrypto(fn){return forge2.util.isNodejs&&typeof _crypto[fn]==="function"}function _detectSubtleCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.crypto==="object"&&typeof util.globalScope.crypto.subtle==="object"&&typeof util.globalScope.crypto.subtle[fn]==="function"}function _detectSubtleMsCrypto(fn){return typeof util.globalScope!=="undefined"&&typeof util.globalScope.msCrypto==="object"&&typeof util.globalScope.msCrypto.subtle==="object"&&typeof util.globalScope.msCrypto.subtle[fn]==="function"}function _intToUint8Array(x){var bytes=forge2.util.hexToBytes(x.toString(16));var buffer=new Uint8Array(bytes.length);for(var i=0;i<bytes.length;++i){buffer[i]=bytes.charCodeAt(i)}return buffer}}});var require_pbe=__commonJS({"node_modules/node-forge/lib/pbe.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_asn1();require_des();require_md();require_oids();require_pbkdf2();require_pem();require_random();require_rc2();require_rsa();require_util7();if(typeof BigInteger==="undefined"){BigInteger=forge2.jsbn.BigInteger}var BigInteger;var asn1=forge2.asn1;var pki=forge2.pki=forge2.pki||{};module.exports=pki.pbe=forge2.pbe=forge2.pbe||{};var oids=pki.oids;var encryptedPrivateKeyValidator={name:"EncryptedPrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"encryptedData"}]};var PBES2AlgorithmsValidator={name:"PBES2Algorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.params.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,optional:true,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"encIv"}]}]};var pkcs12PbeParamsValidator={name:"pkcs-12PbeParams",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"pkcs-12PbeParams.salt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"iterations"}]};pki.encryptPrivateKeyInfo=function(obj,password,options){options=options||{};options.saltSize=options.saltSize||8;options.count=options.count||2048;options.algorithm=options.algorithm||"aes128";options.prfAlgorithm=options.prfAlgorithm||"sha1";var salt=forge2.random.getBytesSync(options.saltSize);var count=options.count;var countBytes=asn1.integerToDer(count);var dkLen;var encryptionAlgorithm;var encryptedData;if(options.algorithm.indexOf("aes")===0||options.algorithm==="des"){var ivLen,encOid,cipherFn;switch(options.algorithm){case"aes128":dkLen=16;ivLen=16;encOid=oids["aes128-CBC"];cipherFn=forge2.aes.createEncryptionCipher;break;case"aes192":dkLen=24;ivLen=16;encOid=oids["aes192-CBC"];cipherFn=forge2.aes.createEncryptionCipher;break;case"aes256":dkLen=32;ivLen=16;encOid=oids["aes256-CBC"];cipherFn=forge2.aes.createEncryptionCipher;break;case"des":dkLen=8;ivLen=8;encOid=oids["desCBC"];cipherFn=forge2.des.createEncryptionCipher;break;default:var error=new Error("Cannot encrypt private key. Unknown encryption algorithm.");error.algorithm=options.algorithm;throw error}var prfAlgorithm="hmacWith"+options.prfAlgorithm.toUpperCase();var md=prfAlgorithmToMessageDigest(prfAlgorithm);var dk=forge2.pkcs5.pbkdf2(password,salt,count,dkLen,md);var iv=forge2.random.getBytesSync(ivLen);var cipher=cipherFn(dk);cipher.start(iv);cipher.update(asn1.toDer(obj));cipher.finish();encryptedData=cipher.output.getBytes();var params=createPbkdf2Params(salt,countBytes,dkLen,prfAlgorithm);encryptionAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids["pkcs5PBES2"]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes()),params]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(encOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,iv)])])])}else if(options.algorithm==="3des"){dkLen=24;var saltBytes=new forge2.util.ByteBuffer(salt);var dk=pki.pbe.generatePkcs12Key(password,saltBytes,1,count,dkLen);var iv=pki.pbe.generatePkcs12Key(password,saltBytes,2,count,dkLen);var cipher=forge2.des.createEncryptionCipher(dk);cipher.start(iv);cipher.update(asn1.toDer(obj));cipher.finish();encryptedData=cipher.output.getBytes();encryptionAlgorithm=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,salt),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,countBytes.getBytes())])])}else{var error=new Error("Cannot encrypt private key. Unknown encryption algorithm.");error.algorithm=options.algorithm;throw error}var rval=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[encryptionAlgorithm,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,encryptedData)]);return rval};pki.decryptPrivateKeyInfo=function(obj,password){var rval=null;var capture2={};var errors=[];if(!asn1.validate(obj,encryptedPrivateKeyValidator,capture2,errors)){var error=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.encryptionOid);var cipher=pki.pbe.getCipher(oid,capture2.encryptionParams,password);var encrypted=forge2.util.createBuffer(capture2.encryptedData);cipher.update(encrypted);if(cipher.finish()){rval=asn1.fromDer(cipher.output)}return rval};pki.encryptedPrivateKeyToPem=function(epki,maxline){var msg={type:"ENCRYPTED PRIVATE KEY",body:asn1.toDer(epki).getBytes()};return forge2.pem.encode(msg,{maxline})};pki.encryptedPrivateKeyFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="ENCRYPTED PRIVATE KEY"){var error=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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){options=options||{};if(!options.legacy){var rval=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey));rval=pki.encryptPrivateKeyInfo(rval,password,options);return pki.encryptedPrivateKeyToPem(rval)}var algorithm;var iv;var dkLen;var cipherFn;switch(options.algorithm){case"aes128":algorithm="AES-128-CBC";dkLen=16;iv=forge2.random.getBytesSync(16);cipherFn=forge2.aes.createEncryptionCipher;break;case"aes192":algorithm="AES-192-CBC";dkLen=24;iv=forge2.random.getBytesSync(16);cipherFn=forge2.aes.createEncryptionCipher;break;case"aes256":algorithm="AES-256-CBC";dkLen=32;iv=forge2.random.getBytesSync(16);cipherFn=forge2.aes.createEncryptionCipher;break;case"3des":algorithm="DES-EDE3-CBC";dkLen=24;iv=forge2.random.getBytesSync(8);cipherFn=forge2.des.createEncryptionCipher;break;case"des":algorithm="DES-CBC";dkLen=8;iv=forge2.random.getBytesSync(8);cipherFn=forge2.des.createEncryptionCipher;break;default:var error=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+options.algorithm+'".');error.algorithm=options.algorithm;throw error}var dk=forge2.pbe.opensslDeriveBytes(password,iv.substr(0,8),dkLen);var cipher=cipherFn(dk);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,parameters:forge2.util.bytesToHex(iv).toUpperCase()},body:cipher.output.getBytes()};return forge2.pem.encode(msg)};pki.decryptRsaPrivateKey=function(pem,password){var rval=null;var msg=forge2.pem.decode(pem)[0];if(msg.type!=="ENCRYPTED PRIVATE KEY"&&msg.type!=="PRIVATE KEY"&&msg.type!=="RSA PRIVATE KEY"){var error=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');error.headerType=error;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){var dkLen;var cipherFn;switch(msg.dekInfo.algorithm){case"DES-CBC":dkLen=8;cipherFn=forge2.des.createDecryptionCipher;break;case"DES-EDE3-CBC":dkLen=24;cipherFn=forge2.des.createDecryptionCipher;break;case"AES-128-CBC":dkLen=16;cipherFn=forge2.aes.createDecryptionCipher;break;case"AES-192-CBC":dkLen=24;cipherFn=forge2.aes.createDecryptionCipher;break;case"AES-256-CBC":dkLen=32;cipherFn=forge2.aes.createDecryptionCipher;break;case"RC2-40-CBC":dkLen=5;cipherFn=function(key){return forge2.rc2.createDecryptionCipher(key,40)};break;case"RC2-64-CBC":dkLen=8;cipherFn=function(key){return forge2.rc2.createDecryptionCipher(key,64)};break;case"RC2-128-CBC":dkLen=16;cipherFn=function(key){return forge2.rc2.createDecryptionCipher(key,128)};break;default:var error=new Error('Could not decrypt private key; unsupported encryption algorithm "'+msg.dekInfo.algorithm+'".');error.algorithm=msg.dekInfo.algorithm;throw error}var iv=forge2.util.hexToBytes(msg.dekInfo.parameters);var dk=forge2.pbe.opensslDeriveBytes(password,iv.substr(0,8),dkLen);var cipher=cipherFn(dk);cipher.start(iv);cipher.update(forge2.util.createBuffer(msg.body));if(cipher.finish()){rval=cipher.output.getBytes()}else{return rval}}else{rval=msg.body}if(msg.type==="ENCRYPTED PRIVATE KEY"){rval=pki.decryptPrivateKeyInfo(asn1.fromDer(rval),password)}else{rval=asn1.fromDer(rval)}if(rval!==null){rval=pki.privateKeyFromAsn1(rval)}return rval};pki.pbe.generatePkcs12Key=function(password,salt,id,iter,n,md){var j2,l;if(typeof md==="undefined"||md===null){if(!("sha1"in forge2.md)){throw new Error('"sha1" hash algorithm unavailable.')}md=forge2.md.sha1.create()}var u2=md.digestLength;var v2=md.blockLength;var result=new forge2.util.ByteBuffer;var passBuf=new forge2.util.ByteBuffer;if(password!==null&&password!==void 0){for(l=0;l<password.length;l++){passBuf.putInt16(password.charCodeAt(l))}passBuf.putInt16(0)}var p2=passBuf.length();var s3=salt.length();var D=new forge2.util.ByteBuffer;D.fillWithByte(id,v2);var Slen=v2*Math.ceil(s3/v2);var S2=new forge2.util.ByteBuffer;for(l=0;l<Slen;l++){S2.putByte(salt.at(l%s3))}var Plen=v2*Math.ceil(p2/v2);var P2=new forge2.util.ByteBuffer;for(l=0;l<Plen;l++){P2.putByte(passBuf.at(l%p2))}var I2=S2;I2.putBuffer(P2);var c=Math.ceil(n/u2);for(var i=1;i<=c;i++){var buf=new forge2.util.ByteBuffer;buf.putBytes(D.bytes());buf.putBytes(I2.bytes());for(var round=0;round<iter;round++){md.start();md.update(buf.getBytes());buf=md.digest()}var B2=new forge2.util.ByteBuffer;for(l=0;l<v2;l++){B2.putByte(buf.at(l%u2))}var k2=Math.ceil(s3/v2)+Math.ceil(p2/v2);var Inew=new forge2.util.ByteBuffer;for(j2=0;j2<k2;j2++){var chunk=new forge2.util.ByteBuffer(I2.getBytes(v2));var x=511;for(l=B2.length()-1;l>=0;l--){x=x>>8;x+=B2.at(l)+chunk.at(l);chunk.setAt(l,x&255)}Inew.putBuffer(chunk)}I2=Inew;result.putBuffer(buf)}result.truncate(result.length()-n);return 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.");error.oid=oid;error.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"];throw error}};pki.pbe.getCipherForPBES2=function(oid,params,password){var capture2={};var errors=[];if(!asn1.validate(params,PBES2AlgorithmsValidator,capture2,errors)){var error=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}oid=asn1.derToOid(capture2.kdfOid);if(oid!==pki.oids["pkcs5PBKDF2"]){var error=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");error.oid=oid;error.supportedOids=["pkcs5PBKDF2"];throw error}oid=asn1.derToOid(capture2.encOid);if(oid!==pki.oids["aes128-CBC"]&&oid!==pki.oids["aes192-CBC"]&&oid!==pki.oids["aes256-CBC"]&&oid!==pki.oids["des-EDE3-CBC"]&&oid!==pki.oids["desCBC"]){var error=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");error.oid=oid;error.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"];throw error}var salt=capture2.kdfSalt;var count=forge2.util.createBuffer(capture2.kdfIterationCount);count=count.getInt(count.length()<<3);var dkLen;var cipherFn;switch(pki.oids[oid]){case"aes128-CBC":dkLen=16;cipherFn=forge2.aes.createDecryptionCipher;break;case"aes192-CBC":dkLen=24;cipherFn=forge2.aes.createDecryptionCipher;break;case"aes256-CBC":dkLen=32;cipherFn=forge2.aes.createDecryptionCipher;break;case"des-EDE3-CBC":dkLen=24;cipherFn=forge2.des.createDecryptionCipher;break;case"desCBC":dkLen=8;cipherFn=forge2.des.createDecryptionCipher;break}var md=prfOidToMessageDigest(capture2.prfOid);var dk=forge2.pkcs5.pbkdf2(password,salt,count,dkLen,md);var iv=capture2.encIv;var cipher=cipherFn(dk);cipher.start(iv);return cipher};pki.pbe.getCipherForPKCS12PBE=function(oid,params,password){var capture2={};var errors=[];if(!asn1.validate(params,pkcs12PbeParamsValidator,capture2,errors)){var error=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");error.errors=errors;throw error}var salt=forge2.util.createBuffer(capture2.salt);var count=forge2.util.createBuffer(capture2.iterations);count=count.getInt(count.length()<<3);var dkLen,dIvLen,cipherFn;switch(oid){case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:dkLen=24;dIvLen=8;cipherFn=forge2.des.startDecrypting;break;case pki.oids["pbewithSHAAnd40BitRC2-CBC"]:dkLen=5;dIvLen=8;cipherFn=function(key2,iv2){var cipher=forge2.rc2.createDecryptionCipher(key2,40);cipher.start(iv2,null);return cipher};break;default:var error=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");error.oid=oid;throw error}var md=prfOidToMessageDigest(capture2.prfOid);var key=pki.pbe.generatePkcs12Key(password,salt,1,count,dkLen,md);md.start();var iv=pki.pbe.generatePkcs12Key(password,salt,2,count,dIvLen,md);return cipherFn(key,iv)};pki.pbe.opensslDeriveBytes=function(password,salt,dkLen,md){if(typeof md==="undefined"||md===null){if(!("md5"in forge2.md)){throw new Error('"md5" hash algorithm unavailable.')}md=forge2.md.md5.create()}if(salt===null){salt=""}var digests=[hash(md,password+salt)];for(var length=16,i=1;length<dkLen;++i,length+=16){digests.push(hash(md,digests[i-1]+password+salt))}return digests.join("").substr(0,dkLen)};function hash(md,bytes){return md.start().update(bytes).digest().getBytes()}function prfOidToMessageDigest(prfOid){var prfAlgorithm;if(!prfOid){prfAlgorithm="hmacWithSHA1"}else{prfAlgorithm=pki.oids[asn1.derToOid(prfOid)];if(!prfAlgorithm){var error=new Error("Unsupported PRF OID.");error.oid=prfOid;error.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"];throw error}}return prfAlgorithmToMessageDigest(prfAlgorithm)}function prfAlgorithmToMessageDigest(prfAlgorithm){var factory=forge2.md;switch(prfAlgorithm){case"hmacWithSHA224":factory=forge2.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":prfAlgorithm=prfAlgorithm.substr(8).toLowerCase();break;default:var error=new Error("Unsupported PRF algorithm.");error.algorithm=prfAlgorithm;error.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"];throw error}if(!factory||!(prfAlgorithm in factory)){throw new Error("Unknown hash algorithm: "+prfAlgorithm)}return factory[prfAlgorithm].create()}function createPbkdf2Params(salt,countBytes,dkLen,prfAlgorithm){var params=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,salt),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,countBytes.getBytes())]);if(prfAlgorithm!=="hmacWithSHA1"){params.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(dkLen.toString(16))),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]))}return params}}});var require_pkcs7asn1=__commonJS({"node_modules/node-forge/lib/pkcs7asn1.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_util7();var asn1=forge2.asn1;var p7v=module.exports=forge2.pkcs7asn1=forge2.pkcs7asn1||{};forge2.pkcs7=forge2.pkcs7||{};forge2.pkcs7.asn1=p7v;var contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"ContentInfo.ContentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,captureAsn1:"content"}]};p7v.contentInfoValidator=contentInfoValidator;var encryptedContentInfoValidator={name:"EncryptedContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,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:true,value:[{name:"EnvelopedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,captureAsn1:"recipientInfos"}].concat(encryptedContentInfoValidator)};p7v.encryptedDataValidator={name:"EncryptedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"EncryptedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"}].concat(encryptedContentInfoValidator)};var signerValidator={name:"SignerInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignerInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false},{name:"SignerInfo.issuerAndSerialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:asn1.Class.UNIVERSAL,constructed:false,captureAsn1:"digestParameter",optional:true}]},{name:"SignerInfo.authenticatedAttributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:true,optional:true,capture:"unauthenticatedAttributes"}]};p7v.signedDataValidator={name:"SignedData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SignedData.Version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,captureAsn1:"digestAlgorithms"},contentInfoValidator,{name:"SignedData.Certificates",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,optional:true,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,optional:true,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,capture:"signerInfos",optional:true,value:[signerValidator]}]};p7v.recipientInfoValidator={name:"RecipientInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RecipientInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:asn1.Class.UNIVERSAL,constructed:false,captureAsn1:"encParameter",optional:true}]},{name:"RecipientInfo.encryptedKey",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"encKey"}]}}});var require_mgf1=__commonJS({"node_modules/node-forge/lib/mgf1.js"(exports,module){"use strict";var forge2=require_forge();require_util7();forge2.mgf=forge2.mgf||{};var mgf1=module.exports=forge2.mgf.mgf1=forge2.mgf1=forge2.mgf1||{};mgf1.create=function(md){var mgf={generate:function(seed,maskLen){var t=new forge2.util.ByteBuffer;var len=Math.ceil(maskLen/md.digestLength);for(var i=0;i<len;i++){var c=new forge2.util.ByteBuffer;c.putInt32(i);md.start();md.update(seed+c.getBytes());t.putBuffer(md.digest())}t.truncate(t.length()-maskLen);return t.getBytes()}};return mgf}}});var require_mgf=__commonJS({"node_modules/node-forge/lib/mgf.js"(exports,module){"use strict";var forge2=require_forge();require_mgf1();module.exports=forge2.mgf=forge2.mgf||{};forge2.mgf.mgf1=forge2.mgf1}});var require_pss=__commonJS({"node_modules/node-forge/lib/pss.js"(exports,module){"use strict";var forge2=require_forge();require_random();require_util7();var pss=module.exports=forge2.pss=forge2.pss||{};pss.create=function(options){if(arguments.length===3){options={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]}}var hash=options.md;var mgf=options.mgf;var hLen=hash.digestLength;var salt_=options.salt||null;if(typeof salt_==="string"){salt_=forge2.util.createBuffer(salt_)}var sLen;if("saltLength"in options){sLen=options.saltLength}else if(salt_!==null){sLen=salt_.length()}else{throw new Error("Salt length not specified or specific salt not given.")}if(salt_!==null&&salt_.length()!==sLen){throw new Error("Given salt length does not match length of given salt.")}var prng=options.prng||forge2.random;var pssobj={};pssobj.encode=function(md,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);var mHash=md.digest().getBytes();if(emLen<hLen+sLen+2){throw new Error("Message is too long to encrypt.")}var salt;if(salt_===null){salt=prng.getBytesSync(sLen)}else{salt=salt_.bytes()}var m_=new forge2.util.ByteBuffer;m_.fillWithByte(0,8);m_.putBytes(mHash);m_.putBytes(salt);hash.start();hash.update(m_.getBytes());var h=hash.digest().getBytes();var ps2=new forge2.util.ByteBuffer;ps2.fillWithByte(0,emLen-sLen-hLen-2);ps2.putByte(1);ps2.putBytes(salt);var db=ps2.getBytes();var maskLen=emLen-hLen-1;var dbMask=mgf.generate(h,maskLen);var maskedDB="";for(i=0;i<maskLen;i++){maskedDB+=String.fromCharCode(db.charCodeAt(i)^dbMask.charCodeAt(i))}var mask=65280>>8*emLen-emBits&255;maskedDB=String.fromCharCode(maskedDB.charCodeAt(0)&~mask)+maskedDB.substr(1);return maskedDB+h+String.fromCharCode(188)};pssobj.verify=function(mHash,em,modBits){var i;var emBits=modBits-1;var emLen=Math.ceil(emBits/8);em=em.substr(-emLen);if(emLen<hLen+sLen+2){throw new Error("Inconsistent parameters to PSS signature verification.")}if(em.charCodeAt(emLen-1)!==188){throw new Error("Encoded message does not end in 0xBC.")}var maskLen=emLen-hLen-1;var maskedDB=em.substr(0,maskLen);var h=em.substr(maskLen,hLen);var mask=65280>>8*emLen-emBits&255;if((maskedDB.charCodeAt(0)&mask)!==0){throw new Error("Bits beyond keysize not zero as expected.")}var dbMask=mgf.generate(h,maskLen);var 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(db.charCodeAt(i)!==0){throw new Error("Leftmost octets not zero as expected")}}if(db.charCodeAt(checkLen)!==1){throw new Error("Inconsistent PSS signature, 0x01 marker not found")}var salt=db.substr(-sLen);var m_=new forge2.util.ByteBuffer;m_.fillWithByte(0,8);m_.putBytes(mHash);m_.putBytes(salt);hash.start();hash.update(m_.getBytes());var h_=hash.digest().getBytes();return h===h_};return pssobj}}});var require_x509=__commonJS({"node_modules/node-forge/lib/x509.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_asn1();require_des();require_md();require_mgf();require_oids();require_pem();require_pss();require_rsa();require_util7();var asn1=forge2.asn1;var pki=module.exports=forge2.pki=forge2.pki||{};var oids=pki.oids;var _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=forge2.pki.rsa.publicKeyValidator;var x509CertificateValidator={name:"Certificate",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.TBSCertificate",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:asn1.Class.UNIVERSAL,optional:true,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.UTCTIME,constructed:false,optional:true,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.GENERALIZEDTIME,constructed:false,optional:true,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.UTCTIME,constructed:false,optional:true,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.GENERALIZEDTIME,constructed:false,optional:true,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certSubject"},publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:true,optional:true,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:2,constructed:true,optional:true,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:3,constructed:true,captureAsn1:"certExtensions",optional:true}]},{name:"Certificate.signatureAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:asn1.Class.UNIVERSAL,optional:true,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"certSignature"}]};var rsassaPssParameterValidator={name:"rsapss",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"rsapss.hashAlgorithm",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.SEQUENCE,constructed:true,optional:true,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:1,constructed:true,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.SEQUENCE,constructed:true,optional:true,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:2,optional:true,value:[{name:"rsapss.saltLength.saltLength",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.INTEGER,constructed:false,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:3,optional:true,value:[{name:"rsapss.trailer.trailer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.INTEGER,constructed:false,capture:"trailer"}]}]};var certificationRequestInfoValidator={name:"CertificationRequestInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"certificationRequestInfoSubject"},publicKeyValidator,{name:"CertificationRequestInfo.attributes",tagClass:asn1.Class.CONTEXT_SPECIFIC,type:0,constructed:true,optional:true,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false},{name:"CertificationRequestInfo.attributes.value",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true}]}]}]};var certificationRequestValidator={name:"CertificationRequest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"csr",value:[certificationRequestInfoValidator,{name:"CertificationRequest.signatureAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:asn1.Class.UNIVERSAL,optional:true,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,captureBitStringValue:"csrSignature"}]};pki.RDNAttributesAsArray=function(rdn,md){var rval=[];var set,attr,obj;for(var si2=0;si2<rdn.value.length;++si2){set=rdn.value[si2];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;if(obj.type in oids){obj.name=oids[obj.type];if(obj.name in _shortNames){obj.shortName=_shortNames[obj.name]}}if(md){md.update(obj.type);md.update(obj.value)}rval.push(obj)}}return rval};pki.CRIAttributesAsArray=function(attributes){var rval=[];for(var si2=0;si2<attributes.length;++si2){var seq=attributes[si2];var type=asn1.derToOid(seq.value[0].value);var values=seq.value[1].value;for(var vi2=0;vi2<values.length;++vi2){var obj={};obj.type=type;obj.value=values[vi2].value;obj.valueTagClass=values[vi2].type;if(obj.type in oids){obj.name=oids[obj.type];if(obj.name in _shortNames){obj.shortName=_shortNames[obj.name]}}if(obj.type===oids.extensionRequest){obj.extensions=[];for(var ei2=0;ei2<obj.value.length;++ei2){obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei2]))}}rval.push(obj)}}return rval};function _getAttribute(obj,options){if(typeof options==="string"){options={shortName:options}}var rval=null;var attr;for(var i=0;rval===null&&i<obj.attributes.length;++i){attr=obj.attributes[i];if(options.type&&options.type===attr.type){rval=attr}else if(options.name&&options.name===attr.name){rval=attr}else if(options.shortName&&options.shortName===attr.shortName){rval=attr}}return rval}var _readSignatureParameters=function(oid,obj,fillDefaults){var params={};if(oid!==oids["RSASSA-PSS"]){return params}if(fillDefaults){params={hash:{algorithmOid:oids["sha1"]},mgf:{algorithmOid:oids["mgf1"],hash:{algorithmOid:oids["sha1"]}},saltLength:20}}var capture2={};var errors=[];if(!asn1.validate(obj,rsassaPssParameterValidator,capture2,errors)){var error=new Error("Cannot read RSASSA-PSS parameter block.");error.errors=errors;throw error}if(capture2.hashOid!==void 0){params.hash=params.hash||{};params.hash.algorithmOid=asn1.derToOid(capture2.hashOid)}if(capture2.maskGenOid!==void 0){params.mgf=params.mgf||{};params.mgf.algorithmOid=asn1.derToOid(capture2.maskGenOid);params.mgf.hash=params.mgf.hash||{};params.mgf.hash.algorithmOid=asn1.derToOid(capture2.maskGenHashOid)}if(capture2.saltLength!==void 0){params.saltLength=capture2.saltLength.charCodeAt(0)}return params};var _createSignatureDigest=function(options){switch(oids[options.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return forge2.md.sha1.create();case"md5WithRSAEncryption":return forge2.md.md5.create();case"sha256WithRSAEncryption":return forge2.md.sha256.create();case"sha384WithRSAEncryption":return forge2.md.sha384.create();case"sha512WithRSAEncryption":return forge2.md.sha512.create();case"RSASSA-PSS":return forge2.md.sha256.create();default:var error=new Error("Could not compute "+options.type+" digest. Unknown signature OID.");error.signatureOid=options.signatureOid;throw error}};var _verifySignature=function(options){var cert=options.certificate;var scheme;switch(cert.signatureOid){case oids.sha1WithRSAEncryption:case oids.sha1WithRSASignature:break;case oids["RSASSA-PSS"]:var hash,mgf;hash=oids[cert.signatureParameters.mgf.hash.algorithmOid];if(hash===void 0||forge2.md[hash]===void 0){var error=new Error("Unsupported MGF hash function.");error.oid=cert.signatureParameters.mgf.hash.algorithmOid;error.name=hash;throw error}mgf=oids[cert.signatureParameters.mgf.algorithmOid];if(mgf===void 0||forge2.mgf[mgf]===void 0){var error=new Error("Unsupported MGF function.");error.oid=cert.signatureParameters.mgf.algorithmOid;error.name=mgf;throw error}mgf=forge2.mgf[mgf].create(forge2.md[hash].create());hash=oids[cert.signatureParameters.hash.algorithmOid];if(hash===void 0||forge2.md[hash]===void 0){var error=new Error("Unsupported RSASSA-PSS hash function.");error.oid=cert.signatureParameters.hash.algorithmOid;error.name=hash;throw error}scheme=forge2.pss.create(forge2.md[hash].create(),mgf,cert.signatureParameters.saltLength);break}return cert.publicKey.verify(options.md.digest().getBytes(),options.signature,scheme)};pki.certificateFromPem=function(pem,computeHash,strict){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="CERTIFICATE"&&msg.type!=="X509 CERTIFICATE"&&msg.type!=="TRUSTED CERTIFICATE"){var error=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(msg,{maxline})};pki.publicKeyFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="PUBLIC KEY"&&msg.type!=="RSA PUBLIC KEY"){var error=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(msg,{maxline})};pki.publicKeyToRSAPublicKeyPem=function(key,maxline){var msg={type:"RSA PUBLIC KEY",body:asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()};return forge2.pem.encode(msg,{maxline})};pki.getPublicKeyFingerprint=function(key,options){options=options||{};var md=options.md||forge2.md.sha1.create();var type=options.type||"RSAPublicKey";var bytes;switch(type){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(options.encoding==="hex"){var hex=digest.toHex();if(options.delimiter){return hex.match(/.{2}/g).join(options.delimiter)}return hex}else if(options.encoding==="binary"){return digest.getBytes()}else if(options.encoding){throw new Error('Unknown encoding "'+options.encoding+'".')}return digest};pki.certificationRequestFromPem=function(pem,computeHash,strict){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="CERTIFICATE REQUEST"){var error=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(msg,{maxline})};pki.createCertificate=function(){var cert={};cert.version=2;cert.serialNumber="00";cert.signatureOid=null;cert.signature=null;cert.siginfo={};cert.siginfo.algorithmOid=null;cert.validity={};cert.validity.notBefore=new Date;cert.validity.notAfter=new Date;cert.issuer={};cert.issuer.getField=function(sn2){return _getAttribute(cert.issuer,sn2)};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(sn2){return _getAttribute(cert.subject,sn2)};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;if(uniqueId){cert.subject.uniqueId=uniqueId}cert.subject.hash=null};cert.setIssuer=function(attrs,uniqueId){_fillMissingFields(attrs);cert.issuer.attributes=attrs;delete cert.issuer.uniqueId;if(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.extensions=exts};cert.getExtension=function(options){if(typeof options==="string"){options={name:options}}var rval=null;var ext;for(var i=0;rval===null&&i<cert.extensions.length;++i){ext=cert.extensions[i];if(options.id&&ext.id===options.id){rval=ext}else if(options.name&&ext.name===options.name){rval=ext}}return rval};cert.sign=function(key,md){cert.md=md||forge2.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.");error.algorithm=cert.md.algorithm;throw 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=false;if(!cert.issued(child)){var issuer=child.issuer;var subject=cert.subject;var 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.");error.expectedIssuer=subject.attributes;error.actualIssuer=issuer.attributes;throw error}var md=child.md;if(md===null){md=_createSignatureDigest({signatureOid:child.signatureOid,type:"certificate"});var tbsCertificate=child.tbsCertificate||pki.getTBSCertificate(child);var bytes=asn1.toDer(tbsCertificate);md.update(bytes.getBytes())}if(md!==null){rval=_verifySignature({certificate:cert,md,signature:child.signature})}return rval};cert.isIssuer=function(parent){var rval=false;var i=cert.issuer;var s3=parent.subject;if(i.hash&&s3.hash){rval=i.hash===s3.hash}else if(i.attributes.length===s3.attributes.length){rval=true;var iattr,sattr;for(var n=0;rval&&n<i.attributes.length;++n){iattr=i.attributes[n];sattr=s3.attributes[n];if(iattr.type!==sattr.type||iattr.value!==sattr.value){rval=false}}}return rval};cert.issued=function(child){return child.isIssuer(cert)};cert.generateSubjectKeyIdentifier=function(){return pki.getPublicKeyFingerprint(cert.publicKey,{type:"RSAPublicKey"})};cert.verifySubjectKeyIdentifier=function(){var oid=oids["subjectKeyIdentifier"];for(var i=0;i<cert.extensions.length;++i){var ext=cert.extensions[i];if(ext.id===oid){var ski=cert.generateSubjectKeyIdentifier().getBytes();return forge2.util.hexToBytes(ext.subjectKeyIdentifier)===ski}}return false};return cert};pki.certificateFromAsn1=function(obj,computeHash){var capture2={};var errors=[];if(!asn1.validate(obj,x509CertificateValidator,capture2,errors)){var error=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.publicKeyOid);if(oid!==pki.oids.rsaEncryption){throw new Error("Cannot read public key. OID is not RSA.")}var cert=pki.createCertificate();cert.version=capture2.certVersion?capture2.certVersion.charCodeAt(0):0;var serial=forge2.util.createBuffer(capture2.certSerialNumber);cert.serialNumber=serial.toHex();cert.signatureOid=forge2.asn1.derToOid(capture2.certSignatureOid);cert.signatureParameters=_readSignatureParameters(cert.signatureOid,capture2.certSignatureParams,true);cert.siginfo.algorithmOid=forge2.asn1.derToOid(capture2.certinfoSignatureOid);cert.siginfo.parameters=_readSignatureParameters(cert.siginfo.algorithmOid,capture2.certinfoSignatureParams,false);cert.signature=capture2.certSignature;var validity=[];if(capture2.certValidity1UTCTime!==void 0){validity.push(asn1.utcTimeToDate(capture2.certValidity1UTCTime))}if(capture2.certValidity2GeneralizedTime!==void 0){validity.push(asn1.generalizedTimeToDate(capture2.certValidity2GeneralizedTime))}if(capture2.certValidity3UTCTime!==void 0){validity.push(asn1.utcTimeToDate(capture2.certValidity3UTCTime))}if(capture2.certValidity4GeneralizedTime!==void 0){validity.push(asn1.generalizedTimeToDate(capture2.certValidity4GeneralizedTime))}if(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.")}cert.validity.notBefore=validity[0];cert.validity.notAfter=validity[1];cert.tbsCertificate=capture2.tbsCertificate;if(computeHash){cert.md=_createSignatureDigest({signatureOid:cert.signatureOid,type:"certificate"});var bytes=asn1.toDer(cert.tbsCertificate);cert.md.update(bytes.getBytes())}var imd=forge2.md.sha1.create();var ibytes=asn1.toDer(capture2.certIssuer);imd.update(ibytes.getBytes());cert.issuer.getField=function(sn2){return _getAttribute(cert.issuer,sn2)};cert.issuer.addField=function(attr){_fillMissingFields([attr]);cert.issuer.attributes.push(attr)};cert.issuer.attributes=pki.RDNAttributesAsArray(capture2.certIssuer);if(capture2.certIssuerUniqueId){cert.issuer.uniqueId=capture2.certIssuerUniqueId}cert.issuer.hash=imd.digest().toHex();var smd=forge2.md.sha1.create();var sbytes=asn1.toDer(capture2.certSubject);smd.update(sbytes.getBytes());cert.subject.getField=function(sn2){return _getAttribute(cert.subject,sn2)};cert.subject.addField=function(attr){_fillMissingFields([attr]);cert.subject.attributes.push(attr)};cert.subject.attributes=pki.RDNAttributesAsArray(capture2.certSubject);if(capture2.certSubjectUniqueId){cert.subject.uniqueId=capture2.certSubjectUniqueId}cert.subject.hash=smd.digest().toHex();if(capture2.certExtensions){cert.extensions=pki.certificateExtensionsFromAsn1(capture2.certExtensions)}else{cert.extensions=[]}cert.publicKey=pki.publicKeyFromAsn1(capture2.subjectPublicKeyInfo);return cert};pki.certificateExtensionsFromAsn1=function(exts){var rval=[];for(var i=0;i<exts.value.length;++i){var extseq=exts.value[i];for(var ei2=0;ei2<extseq.value.length;++ei2){rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei2]))}}return rval};pki.certificateExtensionFromAsn1=function(ext){var e={};e.id=asn1.derToOid(ext.value[0].value);e.critical=false;if(ext.value[1].type===asn1.Type.BOOLEAN){e.critical=ext.value[1].value.charCodeAt(0)!==0;e.value=ext.value[2].value}else{e.value=ext.value[1].value}if(e.id in oids){e.name=oids[e.id];if(e.name==="keyUsage"){var ev=asn1.fromDer(e.value);var b2=0;var b3=0;if(ev.value.length>1){b2=ev.value.charCodeAt(1);b3=ev.value.length>2?ev.value.charCodeAt(2):0}e.digitalSignature=(b2&128)===128;e.nonRepudiation=(b2&64)===64;e.keyEncipherment=(b2&32)===32;e.dataEncipherment=(b2&16)===16;e.keyAgreement=(b2&8)===8;e.keyCertSign=(b2&4)===4;e.cRLSign=(b2&2)===2;e.encipherOnly=(b2&1)===1;e.decipherOnly=(b3&128)===128}else if(e.name==="basicConstraints"){var ev=asn1.fromDer(e.value);if(ev.value.length>0&&ev.value[0].type===asn1.Type.BOOLEAN){e.cA=ev.value[0].value.charCodeAt(0)!==0}else{e.cA=false}var value=null;if(ev.value.length>0&&ev.value[0].type===asn1.Type.INTEGER){value=ev.value[0].value}else if(ev.value.length>1){value=ev.value[1].value}if(value!==null){e.pathLenConstraint=asn1.derToInteger(value)}}else if(e.name==="extKeyUsage"){var ev=asn1.fromDer(e.value);for(var vi2=0;vi2<ev.value.length;++vi2){var oid=asn1.derToOid(ev.value[vi2].value);if(oid in oids){e[oids[oid]]=true}else{e[oid]=true}}}else if(e.name==="nsCertType"){var ev=asn1.fromDer(e.value);var b2=0;if(ev.value.length>1){b2=ev.value.charCodeAt(1)}e.client=(b2&128)===128;e.server=(b2&64)===64;e.email=(b2&32)===32;e.objsign=(b2&16)===16;e.reserved=(b2&8)===8;e.sslCA=(b2&4)===4;e.emailCA=(b2&2)===2;e.objCA=(b2&1)===1}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.altNames=[];var gn2;var ev=asn1.fromDer(e.value);for(var n=0;n<ev.value.length;++n){gn2=ev.value[n];var altName={type:gn2.type,value:gn2.value};e.altNames.push(altName);switch(gn2.type){case 1:case 2:case 6:break;case 7:altName.ip=forge2.util.bytesToIP(gn2.value);break;case 8:altName.oid=asn1.derToOid(gn2.value);break;default:}}}else if(e.name==="subjectKeyIdentifier"){var ev=asn1.fromDer(e.value);e.subjectKeyIdentifier=forge2.util.bytesToHex(ev.value)}}return e};pki.certificationRequestFromAsn1=function(obj,computeHash){var capture2={};var errors=[];if(!asn1.validate(obj,certificationRequestValidator,capture2,errors)){var error=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.publicKeyOid);if(oid!==pki.oids.rsaEncryption){throw new Error("Cannot read public key. OID is not RSA.")}var csr=pki.createCertificationRequest();csr.version=capture2.csrVersion?capture2.csrVersion.charCodeAt(0):0;csr.signatureOid=forge2.asn1.derToOid(capture2.csrSignatureOid);csr.signatureParameters=_readSignatureParameters(csr.signatureOid,capture2.csrSignatureParams,true);csr.siginfo.algorithmOid=forge2.asn1.derToOid(capture2.csrSignatureOid);csr.siginfo.parameters=_readSignatureParameters(csr.siginfo.algorithmOid,capture2.csrSignatureParams,false);csr.signature=capture2.csrSignature;csr.certificationRequestInfo=capture2.certificationRequestInfo;if(computeHash){csr.md=_createSignatureDigest({signatureOid:csr.signatureOid,type:"certification request"});var bytes=asn1.toDer(csr.certificationRequestInfo);csr.md.update(bytes.getBytes())}var smd=forge2.md.sha1.create();csr.subject.getField=function(sn2){return _getAttribute(csr.subject,sn2)};csr.subject.addField=function(attr){_fillMissingFields([attr]);csr.subject.attributes.push(attr)};csr.subject.attributes=pki.RDNAttributesAsArray(capture2.certificationRequestInfoSubject,smd);csr.subject.hash=smd.digest().toHex();csr.publicKey=pki.publicKeyFromAsn1(capture2.subjectPublicKeyInfo);csr.getAttribute=function(sn2){return _getAttribute(csr,sn2)};csr.addAttribute=function(attr){_fillMissingFields([attr]);csr.attributes.push(attr)};csr.attributes=pki.CRIAttributesAsArray(capture2.certificationRequestInfoAttributes||[]);return csr};pki.createCertificationRequest=function(){var csr={};csr.version=0;csr.signatureOid=null;csr.signature=null;csr.siginfo={};csr.siginfo.algorithmOid=null;csr.subject={};csr.subject.getField=function(sn2){return _getAttribute(csr.subject,sn2)};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(sn2){return _getAttribute(csr,sn2)};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||forge2.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.");error.algorithm=csr.md.algorithm;throw 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=false;var md=csr.md;if(md===null){md=_createSignatureDigest({signatureOid:csr.signatureOid,type:"certification request"});var cri=csr.certificationRequestInfo||pki.getCertificationRequestInfo(csr);var bytes=asn1.toDer(cri);md.update(bytes.getBytes())}if(md!==null){rval=_verifySignature({certificate:csr,md,signature:csr.signature})}return rval};return csr};function _dnToAsn1(obj){var rval=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var attr,set;var attrs=obj.attributes;for(var i=0;i<attrs.length;++i){attr=attrs[i];var value=attr.value;var valueTagClass=asn1.Type.PRINTABLESTRING;if("valueTagClass"in attr){valueTagClass=attr.valueTagClass;if(valueTagClass===asn1.Type.UTF8){value=forge2.util.encodeUtf8(value)}}set=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,valueTagClass,false,value)])]);rval.value.push(set)}return rval}function _fillMissingFields(attrs){var attr;for(var i=0;i<attrs.length;++i){attr=attrs[i];if(typeof attr.name==="undefined"){if(attr.type&&attr.type in pki.oids){attr.name=pki.oids[attr.type]}else if(attr.shortName&&attr.shortName in _shortNames){attr.name=pki.oids[_shortNames[attr.shortName]]}}if(typeof attr.type==="undefined"){if(attr.name&&attr.name in pki.oids){attr.type=pki.oids[attr.name]}else{var error=new Error("Attribute type not specified.");error.attribute=attr;throw error}}if(typeof attr.shortName==="undefined"){if(attr.name&&attr.name in _shortNames){attr.shortName=_shortNames[attr.name]}}if(attr.type===oids.extensionRequest){attr.valueConstructed=true;attr.valueTagClass=asn1.Type.SEQUENCE;if(!attr.value&&attr.extensions){attr.value=[];for(var ei2=0;ei2<attr.extensions.length;++ei2){attr.value.push(pki.certificateExtensionToAsn1(_fillMissingExtensionFields(attr.extensions[ei2])))}}}if(typeof attr.value==="undefined"){var error=new Error("Attribute value not specified.");error.attribute=attr;throw error}}}function _fillMissingExtensionFields(e,options){options=options||{};if(typeof e.name==="undefined"){if(e.id&&e.id in pki.oids){e.name=pki.oids[e.id]}}if(typeof e.id==="undefined"){if(e.name&&e.name in pki.oids){e.id=pki.oids[e.name]}else{var error=new Error("Extension ID not specified.");error.extension=e;throw error}}if(typeof e.value!=="undefined"){return e}if(e.name==="keyUsage"){var unused=0;var b2=0;var b3=0;if(e.digitalSignature){b2|=128;unused=7}if(e.nonRepudiation){b2|=64;unused=6}if(e.keyEncipherment){b2|=32;unused=5}if(e.dataEncipherment){b2|=16;unused=4}if(e.keyAgreement){b2|=8;unused=3}if(e.keyCertSign){b2|=4;unused=2}if(e.cRLSign){b2|=2;unused=1}if(e.encipherOnly){b2|=1;unused=0}if(e.decipherOnly){b3|=128;unused=7}var value=String.fromCharCode(unused);if(b3!==0){value+=String.fromCharCode(b2)+String.fromCharCode(b3)}else if(b2!==0){value+=String.fromCharCode(b2)}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,value)}else if(e.name==="basicConstraints"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);if(e.cA){e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BOOLEAN,false,String.fromCharCode(255)))}if("pathLenConstraint"in e){e.value.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(e.pathLenConstraint).getBytes()))}}else if(e.name==="extKeyUsage"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;for(var key in e){if(e[key]!==true){continue}if(key in oids){seq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oids[key]).getBytes()))}else if(key.indexOf(".")!==-1){seq.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(key).getBytes()))}}}else if(e.name==="nsCertType"){var unused=0;var b2=0;if(e.client){b2|=128;unused=7}if(e.server){b2|=64;unused=6}if(e.email){b2|=32;unused=5}if(e.objsign){b2|=16;unused=4}if(e.reserved){b2|=8;unused=3}if(e.sslCA){b2|=4;unused=2}if(e.emailCA){b2|=2;unused=1}if(e.objCA){b2|=1;unused=0}var value=String.fromCharCode(unused);if(b2!==0){value+=String.fromCharCode(b2)}e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,value)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var altName;for(var n=0;n<e.altNames.length;++n){altName=e.altNames[n];var value=altName.value;if(altName.type===7&&altName.ip){value=forge2.util.bytesFromIP(altName.ip);if(value===null){var error=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');error.extension=e;throw error}}else if(altName.type===8){if(altName.oid){value=asn1.oidToDer(asn1.oidToDer(altName.oid))}else{value=asn1.oidToDer(value)}}e.value.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,false,value))}}else if(e.name==="nsComment"&&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,false,e.comment)}else if(e.name==="subjectKeyIdentifier"&&options.cert){var ski=options.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=ski.toHex();e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ski.getBytes())}else if(e.name==="authorityKeyIdentifier"&&options.cert){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;if(e.keyIdentifier){var keyIdentifier=e.keyIdentifier===true?options.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,false,keyIdentifier))}if(e.authorityCertIssuer){var authorityCertIssuer=[asn1.create(asn1.Class.CONTEXT_SPECIFIC,4,true,[_dnToAsn1(e.authorityCertIssuer===true?options.cert.issuer:e.authorityCertIssuer)])];seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,authorityCertIssuer))}if(e.serialNumber){var serialNumber=forge2.util.hexToBytes(e.serialNumber===true?options.cert.serialNumber:e.serialNumber);seq.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,false,serialNumber))}}else if(e.name==="cRLDistributionPoints"){e.value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var seq=e.value.value;var subSeq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);var fullNameGeneralNames=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[]);var altName;for(var n=0;n<e.altNames.length;++n){altName=e.altNames[n];var value=altName.value;if(altName.type===7&&altName.ip){value=forge2.util.bytesFromIP(altName.ip);if(value===null){var error=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');error.extension=e;throw error}}else if(altName.type===8){if(altName.oid){value=asn1.oidToDer(asn1.oidToDer(altName.oid))}else{value=asn1.oidToDer(value)}}fullNameGeneralNames.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,altName.type,false,value))}subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[fullNameGeneralNames]));seq.push(subSeq)}if(typeof e.value==="undefined"){var error=new Error("Extension value not specified.");error.extension=e;throw error}return e}function _signatureParametersToAsn1(oid,params){switch(oid){case oids["RSASSA-PSS"]:var parts=[];if(params.hash.algorithmOid!==void 0){parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(params.hash.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")])]))}if(params.mgf.algorithmOid!==void 0){parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(params.mgf.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")])])]))}if(params.saltLength!==void 0){parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(params.saltLength).getBytes())]))}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,parts);default:return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")}}function _CRIAttributesToAsn1(csr){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[]);if(csr.attributes.length===0){return rval}var attrs=csr.attributes;for(var i=0;i<attrs.length;++i){var attr=attrs[i];var value=attr.value;var valueTagClass=asn1.Type.UTF8;if("valueTagClass"in attr){valueTagClass=attr.valueTagClass}if(valueTagClass===asn1.Type.UTF8){value=forge2.util.encodeUtf8(value)}var valueConstructed=false;if("valueConstructed"in attr){valueConstructed=attr.valueConstructed}var seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,valueTagClass,valueConstructed,value)])]);rval.value.push(seq)}return rval}var jan_1_1950=new Date("1950-01-01T00:00:00Z");var jan_1_2050=new Date("2050-01-01T00:00:00Z");function _dateToAsn1(date){if(date>=jan_1_1950&&date<jan_1_2050){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.UTCTIME,false,asn1.dateToUtcTime(date))}else{return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.GENERALIZEDTIME,false,asn1.dateToGeneralizedTime(date))}}pki.getTBSCertificate=function(cert){var notBefore=_dateToAsn1(cert.validity.notBefore);var notAfter=_dateToAsn1(cert.validity.notAfter);var tbs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(cert.version).getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(cert.serialNumber)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),_signatureParametersToAsn1(cert.siginfo.algorithmOid,cert.siginfo.parameters)]),_dnToAsn1(cert.issuer),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[notBefore,notAfter]),_dnToAsn1(cert.subject),pki.publicKeyToAsn1(cert.publicKey)]);if(cert.issuer.uniqueId){tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.issuer.uniqueId)]))}if(cert.subject.uniqueId){tbs.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,2,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.subject.uniqueId)]))}if(cert.extensions.length>0){tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions))}return tbs};pki.getCertificationRequestInfo=function(csr){var cri=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(csr.version).getBytes()),_dnToAsn1(csr.subject),pki.publicKeyToAsn1(csr.publicKey),_CRIAttributesToAsn1(csr)]);return cri};pki.distinguishedNameToAsn1=function(dn2){return _dnToAsn1(dn2)};pki.certificateToAsn1=function(cert){var tbsCertificate=cert.tbsCertificate||pki.getTBSCertificate(cert);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[tbsCertificate,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(cert.signatureOid).getBytes()),_signatureParametersToAsn1(cert.signatureOid,cert.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+cert.signature)])};pki.certificateExtensionsToAsn1=function(exts){var rval=asn1.create(asn1.Class.CONTEXT_SPECIFIC,3,true,[]);var seq=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[]);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,true,[]);extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(ext.id).getBytes()));if(ext.critical){extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BOOLEAN,false,String.fromCharCode(255)))}var value=ext.value;if(typeof ext.value!=="string"){value=asn1.toDer(value).getBytes()}extseq.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,value));return extseq};pki.certificationRequestToAsn1=function(csr){var cri=csr.certificationRequestInfo||pki.getCertificationRequestInfo(csr);return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[cri,asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(csr.signatureOid).getBytes()),_signatureParametersToAsn1(csr.signatureOid,csr.signatureParameters)]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BITSTRING,false,String.fromCharCode(0)+csr.signature)])};pki.createCaStore=function(certs){var caStore={certs:{}};caStore.getIssuer=function(cert2){var rval=getBySubject(cert2.issuer);return rval};caStore.addCertificate=function(cert2){if(typeof cert2==="string"){cert2=forge2.pki.certificateFromPem(cert2)}ensureSubjectHasHash(cert2.subject);if(!caStore.hasCertificate(cert2)){if(cert2.subject.hash in caStore.certs){var tmp=caStore.certs[cert2.subject.hash];if(!forge2.util.isArray(tmp)){tmp=[tmp]}tmp.push(cert2);caStore.certs[cert2.subject.hash]=tmp}else{caStore.certs[cert2.subject.hash]=cert2}}};caStore.hasCertificate=function(cert2){if(typeof cert2==="string"){cert2=forge2.pki.certificateFromPem(cert2)}var match=getBySubject(cert2.subject);if(!match){return false}if(!forge2.util.isArray(match)){match=[match]}var der1=asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();for(var i2=0;i2<match.length;++i2){var der2=asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes();if(der1===der2){return true}}return false};caStore.listAllCertificates=function(){var certList=[];for(var hash in caStore.certs){if(caStore.certs.hasOwnProperty(hash)){var value=caStore.certs[hash];if(!forge2.util.isArray(value)){certList.push(value)}else{for(var i2=0;i2<value.length;++i2){certList.push(value[i2])}}}}return certList};caStore.removeCertificate=function(cert2){var result;if(typeof cert2==="string"){cert2=forge2.pki.certificateFromPem(cert2)}ensureSubjectHasHash(cert2.subject);if(!caStore.hasCertificate(cert2)){return null}var match=getBySubject(cert2.subject);if(!forge2.util.isArray(match)){result=caStore.certs[cert2.subject.hash];delete caStore.certs[cert2.subject.hash];return result}var der1=asn1.toDer(pki.certificateToAsn1(cert2)).getBytes();for(var i2=0;i2<match.length;++i2){var der2=asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes();if(der1===der2){result=match[i2];match.splice(i2,1)}}if(match.length===0){delete caStore.certs[cert2.subject.hash]}return result};function getBySubject(subject){ensureSubjectHasHash(subject);return caStore.certs[subject.hash]||null}function ensureSubjectHasHash(subject){if(!subject.hash){var md=forge2.md.sha1.create();subject.attributes=pki.RDNAttributesAsArray(_dnToAsn1(subject),md);subject.hash=md.digest().toHex()}}if(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){if(typeof options==="function"){options={verify:options}}options=options||{};chain=chain.slice(0);var certs=chain.slice(0);var validityCheckDate=options.validityCheckDate;if(typeof validityCheckDate==="undefined"){validityCheckDate=new Date}var first=true;var error=null;var depth=0;do{var cert=chain.shift();var parent=null;var selfSigned=false;if(validityCheckDate){if(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}}}if(error===null){parent=chain[0]||caStore.getIssuer(cert);if(parent===null){if(cert.isIssuer(cert)){selfSigned=true;parent=cert}}if(parent){var parents=parent;if(!forge2.util.isArray(parents)){parents=[parents]}var verified=false;while(!verified&&parents.length>0){parent=parents.shift();try{verified=parent.verify(cert)}catch(ex){}}if(!verified){error={message:"Certificate signature is invalid.",error:pki.certificateError.bad_certificate}}}if(error===null&&(!parent||selfSigned)&&!caStore.hasCertificate(cert)){error={message:"Certificate is not trusted.",error:pki.certificateError.unknown_ca}}}if(error===null&&parent&&!cert.isIssuer(parent)){error={message:"Certificate issuer is invalid.",error:pki.certificateError.bad_certificate}}if(error===null){var se2={keyUsage:true,basicConstraints:true};for(var i=0;error===null&&i<cert.extensions.length;++i){var ext=cert.extensions[i];if(ext.critical&&!(ext.name in se2)){error={message:"Certificate has an unsupported critical extension.",error:pki.certificateError.unsupported_certificate}}}}if(error===null&&(!first||chain.length===0&&(!parent||selfSigned))){var bcExt=cert.getExtension("basicConstraints");var keyUsageExt=cert.getExtension("keyUsage");if(keyUsageExt!==null){if(!keyUsageExt.keyCertSign||bcExt===null){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}}}if(error===null&&bcExt===null){error={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:pki.certificateError.bad_certificate}}if(error===null&&bcExt!==null&&!bcExt.cA){error={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:pki.certificateError.bad_certificate}}if(error===null&&keyUsageExt!==null&&"pathLenConstraint"in bcExt){var pathLen=depth-1;if(pathLen>bcExt.pathLenConstraint){error={message:"Certificate basicConstraints pathLenConstraint violated.",error:pki.certificateError.bad_certificate}}}}var vfd=error===null?true:error.error;var ret=options.verify?options.verify(vfd,depth,certs):vfd;if(ret===true){error=null}else{if(vfd===true){error={message:"The application rejected the certificate.",error:pki.certificateError.bad_certificate}}if(ret||ret===0){if(typeof ret==="object"&&!forge2.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.error){error.error=ret.error}}else if(typeof ret==="string"){error.error=ret}}throw error}first=false;++depth}while(chain.length>0);return true}}});var require_pkcs12=__commonJS({"node_modules/node-forge/lib/pkcs12.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_hmac();require_oids();require_pkcs7asn1();require_pbe();require_random();require_rsa();require_sha1();require_util7();require_x509();var asn1=forge2.asn1;var pki=forge2.pki;var p12=module.exports=forge2.pkcs12=forge2.pkcs12||{};var contentInfoValidator={name:"ContentInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"ContentInfo.contentType",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"contentType"},{name:"ContentInfo.content",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"content"}]};var pfxValidator={name:"PFX",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"version"},contentInfoValidator,{name:"PFX.macData",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,optional:true,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:true,tagClass:asn1.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,optional:true,capture:"macIterations"}]}]};var safeBagValidator={name:"SafeBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"SafeBag.bagId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,optional:true,capture:"bagAttributes"}]};var attributeValidator={name:"Attribute",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"Attribute.attrId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"oid"},{name:"Attribute.attrValues",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SET,constructed:true,capture:"values"}]};var certBagValidator={name:"CertBag",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"CertBag.certId",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"certId"},{name:"CertBag.certValue",tagClass:asn1.Class.CONTEXT_SPECIFIC,constructed:true,value:[{name:"CertBag.certValue[0]",tagClass:asn1.Class.UNIVERSAL,type:asn1.Class.OCTETSTRING,constructed:false,capture:"cert"}]}]};function _getBagsByAttribute(safeContents,attrName,attrValue,bagType){var result=[];for(var i=0;i<safeContents.length;i++){for(var j2=0;j2<safeContents[i].safeBags.length;j2++){var bag=safeContents[i].safeBags[j2];if(bagType!==void 0&&bag.type!==bagType){continue}if(attrName===null){result.push(bag);continue}if(bag.attributes[attrName]!==void 0&&bag.attributes[attrName].indexOf(attrValue)>=0){result.push(bag)}}}return result}p12.pkcs12FromAsn1=function(obj,strict,password){if(typeof strict==="string"){password=strict;strict=true}else if(strict===void 0){strict=true}var capture2={};var errors=[];if(!asn1.validate(obj,pfxValidator,capture2,errors)){var error=new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");error.errors=error;throw error}var pfx={version:capture2.version.charCodeAt(0),safeContents:[],getBags:function(filter){var rval={};var localKeyId;if("localKeyId"in filter){localKeyId=filter.localKeyId}else if("localKeyIdHex"in filter){localKeyId=forge2.util.hexToBytes(filter.localKeyIdHex)}if(localKeyId===void 0&&!("friendlyName"in filter)&&"bagType"in filter){rval[filter.bagType]=_getBagsByAttribute(pfx.safeContents,null,null,filter.bagType)}if(localKeyId!==void 0){rval.localKeyId=_getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,filter.bagType)}if("friendlyName"in filter){rval.friendlyName=_getBagsByAttribute(pfx.safeContents,"friendlyName",filter.friendlyName,filter.bagType)}return rval},getBagsByFriendlyName:function(friendlyName,bagType){return _getBagsByAttribute(pfx.safeContents,"friendlyName",friendlyName,bagType)},getBagsByLocalKeyId:function(localKeyId,bagType){return _getBagsByAttribute(pfx.safeContents,"localKeyId",localKeyId,bagType)}};if(capture2.version.charCodeAt(0)!==3){var error=new Error("PKCS#12 PFX of version other than 3 not supported.");error.version=capture2.version.charCodeAt(0);throw error}if(asn1.derToOid(capture2.contentType)!==pki.oids.data){var error=new Error("Only PKCS#12 PFX in password integrity mode supported.");error.oid=asn1.derToOid(capture2.contentType);throw error}var data=capture2.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.")}data=_decodePkcs7Data(data);if(capture2.mac){var md=null;var macKeyBytes=0;var macAlgorithm=asn1.derToOid(capture2.macAlgorithm);switch(macAlgorithm){case pki.oids.sha1:md=forge2.md.sha1.create();macKeyBytes=20;break;case pki.oids.sha256:md=forge2.md.sha256.create();macKeyBytes=32;break;case pki.oids.sha384:md=forge2.md.sha384.create();macKeyBytes=48;break;case pki.oids.sha512:md=forge2.md.sha512.create();macKeyBytes=64;break;case pki.oids.md5:md=forge2.md.md5.create();macKeyBytes=16;break}if(md===null){throw new Error("PKCS#12 uses unsupported MAC algorithm: "+macAlgorithm)}var macSalt=new forge2.util.ByteBuffer(capture2.macSalt);var macIterations="macIterations"in capture2?parseInt(forge2.util.bytesToHex(capture2.macIterations),16):1;var macKey=p12.generateKey(password,macSalt,3,macIterations,macKeyBytes,md);var mac=forge2.hmac.create();mac.start(md,macKey);mac.update(data.value);var macValue=mac.getMac();if(macValue.getBytes()!==capture2.macDigest){throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}}else if(Array.isArray(obj.value)&&obj.value.length>2){throw new Error("Invalid PKCS#12. macData field present but MAC was not validated.")}_decodeAuthenticatedSafe(pfx,data.value,strict,password);return pfx};function _decodePkcs7Data(data){if(data.composed||data.constructed){var value=forge2.util.createBuffer();for(var i=0;i<data.value.length;++i){value.putBytes(data.value[i].value)}data.composed=data.constructed=false;data.value=value.getBytes()}return data}function _decodeAuthenticatedSafe(pfx,authSafe,strict,password){authSafe=asn1.fromDer(authSafe,strict);if(authSafe.tagClass!==asn1.Class.UNIVERSAL||authSafe.type!==asn1.Type.SEQUENCE||authSafe.constructed!==true){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];var capture2={};var errors=[];if(!asn1.validate(contentInfo,contentInfoValidator,capture2,errors)){var error=new Error("Cannot read ContentInfo.");error.errors=errors;throw error}var obj={encrypted:false};var safeContents=null;var data=capture2.content.value[0];switch(asn1.derToOid(capture2.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=true;break;default:var error=new Error("Unsupported PKCS#12 contentType.");error.contentType=asn1.derToOid(capture2.contentType);throw error}obj.safeBags=_decodeSafeContents(safeContents,strict,password);pfx.safeContents.push(obj)}}function _decryptSafeContents(data,password){var capture2={};var errors=[];if(!asn1.validate(data,forge2.pkcs7.asn1.encryptedDataValidator,capture2,errors)){var error=new Error("Cannot read EncryptedContentInfo.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.contentType);if(oid!==pki.oids.data){var error=new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");error.oid=oid;throw error}oid=asn1.derToOid(capture2.encAlgorithm);var cipher=pki.pbe.getCipher(oid,capture2.encParameter,password);var encryptedContentAsn1=_decodePkcs7Data(capture2.encryptedContentAsn1);var encrypted=forge2.util.createBuffer(encryptedContentAsn1.value);cipher.update(encrypted);if(!cipher.finish()){throw new Error("Failed to decrypt PKCS#12 SafeContents.")}return cipher.output.getBytes()}function _decodeSafeContents(safeContents,strict,password){if(!strict&&safeContents.length===0){return[]}safeContents=asn1.fromDer(safeContents,strict);if(safeContents.tagClass!==asn1.Class.UNIVERSAL||safeContents.type!==asn1.Type.SEQUENCE||safeContents.constructed!==true){throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.")}var res=[];for(var i=0;i<safeContents.value.length;i++){var safeBag=safeContents.value[i];var capture2={};var errors=[];if(!asn1.validate(safeBag,safeBagValidator,capture2,errors)){var error=new Error("Cannot read SafeBag.");error.errors=errors;throw error}var bag={type:asn1.derToOid(capture2.bagId),attributes:_decodeBagAttributes(capture2.bagAttributes)};res.push(bag);var validator,decoder;var bagAsn1=capture2.bagValue.value[0];switch(bag.type){case pki.oids.pkcs8ShroudedKeyBag:bagAsn1=pki.decryptPrivateKeyInfo(bagAsn1,password);if(bagAsn1===null){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(capture2.certId)!==pki.oids.x509Certificate){var error2=new Error("Unsupported certificate type, only X.509 supported.");error2.oid=asn1.derToOid(capture2.certId);throw error2}var certAsn1=asn1.fromDer(capture2.cert,strict);try{bag.cert=pki.certificateFromAsn1(certAsn1,true)}catch(e){bag.cert=null;bag.asn1=certAsn1}};break;default:var error=new Error("Unsupported PKCS#12 SafeBag type.");error.oid=bag.type;throw error}if(validator!==void 0&&!asn1.validate(bagAsn1,validator,capture2,errors)){var error=new Error("Cannot read PKCS#12 "+validator.name);error.errors=errors;throw error}decoder()}return res}function _decodeBagAttributes(attributes){var decodedAttrs={};if(attributes!==void 0){for(var i=0;i<attributes.length;++i){var capture2={};var errors=[];if(!asn1.validate(attributes[i],attributeValidator,capture2,errors)){var error=new Error("Cannot read PKCS#12 BagAttribute.");error.errors=errors;throw error}var oid=asn1.derToOid(capture2.oid);if(pki.oids[oid]===void 0){continue}decodedAttrs[pki.oids[oid]]=[];for(var j2=0;j2<capture2.values.length;++j2){decodedAttrs[pki.oids[oid]].push(capture2.values[j2].value)}}}return decodedAttrs}p12.toPkcs12Asn1=function(key,cert,password,options){options=options||{};options.saltSize=options.saltSize||8;options.count=options.count||2048;options.algorithm=options.algorithm||options.encAlgorithm||"aes128";if(!("useMac"in options)){options.useMac=true}if(!("localKeyId"in options)){options.localKeyId=null}if(!("generateLocalKeyId"in options)){options.generateLocalKeyId=true}var localKeyId=options.localKeyId;var bagAttrs;if(localKeyId!==null){localKeyId=forge2.util.hexToBytes(localKeyId)}else if(options.generateLocalKeyId){if(cert){var pairedCert=forge2.util.isArray(cert)?cert[0]:cert;if(typeof pairedCert==="string"){pairedCert=pki.certificateFromPem(pairedCert)}var sha1=forge2.md.sha1.create();sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes());localKeyId=sha1.digest().getBytes()}else{localKeyId=forge2.random.getBytes(20)}}var attrs=[];if(localKeyId!==null){attrs.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.localKeyId).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,localKeyId)])]))}if("friendlyName"in options){attrs.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.friendlyName).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.BMPSTRING,false,options.friendlyName)])]))}if(attrs.length>0){bagAttrs=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,attrs)}var contents=[];var chain=[];if(cert!==null){if(forge2.util.isArray(cert)){chain=cert}else{chain=[cert]}}var certSafeBags=[];for(var i=0;i<chain.length;++i){cert=chain[i];if(typeof cert==="string"){cert=pki.certificateFromPem(cert)}var certBagAttrs=i===0?bagAttrs:void 0;var certAsn1=pki.certificateToAsn1(cert);var certSafeBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.certBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.x509Certificate).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(certAsn1).getBytes())])])]),certBagAttrs]);certSafeBags.push(certSafeBag)}if(certSafeBags.length>0){var certSafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,certSafeBags);var certCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(certSafeContents).getBytes())])]);contents.push(certCI)}var keyBag=null;if(key!==null){var pkAsn1=pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key));if(password===null){keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.keyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pkAsn1]),bagAttrs])}else{keyBag=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[pki.encryptPrivateKeyInfo(pkAsn1,password,options)]),bagAttrs])}var keySafeContents=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[keyBag]);var keyCI=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(keySafeContents).getBytes())])]);contents.push(keyCI)}var safe=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,contents);var macData;if(options.useMac){var sha1=forge2.md.sha1.create();var macSalt=new forge2.util.ByteBuffer(forge2.random.getBytes(options.saltSize));var count=options.count;var key=p12.generateKey(password,macSalt,3,count,20);var mac=forge2.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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.sha1).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macValue.getBytes())]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,macSalt.getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(count).getBytes())])}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(3).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(pki.oids.data).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,asn1.toDer(safe).getBytes())])]),macData])};p12.generateKey=forge2.pbe.generatePkcs12Key}});var require_pki=__commonJS({"node_modules/node-forge/lib/pki.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_oids();require_pbe();require_pem();require_pbkdf2();require_pkcs12();require_pss();require_rsa();require_util7();require_x509();var asn1=forge2.asn1;var pki=module.exports=forge2.pki=forge2.pki||{};pki.pemToDer=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert PEM to DER; PEM is encrypted.")}return forge2.util.createBuffer(msg.body)};pki.privateKeyFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="PRIVATE KEY"&&msg.type!=="RSA PRIVATE KEY"){var error=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert private key from PEM; PEM is encrypted.")}var obj=asn1.fromDer(msg.body);return pki.privateKeyFromAsn1(obj)};pki.privateKeyToPem=function(key,maxline){var msg={type:"RSA PRIVATE KEY",body:asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()};return forge2.pem.encode(msg,{maxline})};pki.privateKeyInfoToPem=function(pki2,maxline){var msg={type:"PRIVATE KEY",body:asn1.toDer(pki2).getBytes()};return forge2.pem.encode(msg,{maxline})}}});var require_tls=__commonJS({"node_modules/node-forge/lib/tls.js"(exports,module){"use strict";var forge2=require_forge();require_asn1();require_hmac();require_md5();require_pem();require_pki();require_random();require_sha1();require_util7();var prf_TLS1=function(secret,label,seed,length){var rval=forge2.util.createBuffer();var idx=secret.length>>1;var slen=idx+(secret.length&1);var s1=secret.substr(0,slen);var s22=secret.substr(idx,slen);var ai2=forge2.util.createBuffer();var hmac=forge2.hmac.create();seed=label+seed;var md5itr=Math.ceil(length/16);var sha1itr=Math.ceil(length/20);hmac.start("MD5",s1);var md5bytes=forge2.util.createBuffer();ai2.putBytes(seed);for(var i=0;i<md5itr;++i){hmac.start(null,null);hmac.update(ai2.getBytes());ai2.putBuffer(hmac.digest());hmac.start(null,null);hmac.update(ai2.bytes()+seed);md5bytes.putBuffer(hmac.digest())}hmac.start("SHA1",s22);var sha1bytes=forge2.util.createBuffer();ai2.clear();ai2.putBytes(seed);for(var i=0;i<sha1itr;++i){hmac.start(null,null);hmac.update(ai2.getBytes());ai2.putBuffer(hmac.digest());hmac.start(null,null);hmac.update(ai2.bytes()+seed);sha1bytes.putBuffer(hmac.digest())}rval.putBytes(forge2.util.xorBytes(md5bytes.getBytes(),sha1bytes.getBytes(),length));return rval};var hmac_sha1=function(key2,seqNum,record){var hmac=forge2.hmac.create();hmac.start("SHA1",key2);var b2=forge2.util.createBuffer();b2.putInt32(seqNum[0]);b2.putInt32(seqNum[1]);b2.putByte(record.type);b2.putByte(record.version.major);b2.putByte(record.version.minor);b2.putInt16(record.length);b2.putBytes(record.fragment.bytes());hmac.update(b2.getBytes());return hmac.digest().getBytes()};var deflate=function(c,record,s3){var rval=false;try{var bytes=c.deflate(record.fragment.getBytes());record.fragment=forge2.util.createBuffer(bytes);record.length=bytes.length;rval=true}catch(ex){}return rval};var inflate=function(c,record,s3){var rval=false;try{var bytes=c.inflate(record.fragment.getBytes());record.fragment=forge2.util.createBuffer(bytes);record.length=bytes.length;rval=true}catch(ex){}return rval};var readVector=function(b2,lenBytes){var len=0;switch(lenBytes){case 1:len=b2.getByte();break;case 2:len=b2.getInt16();break;case 3:len=b2.getInt24();break;case 4:len=b2.getInt32();break}return forge2.util.createBuffer(b2.getBytes(len))};var writeVector=function(b2,lenBytes,v2){b2.putInt(v2.length(),lenBytes<<3);b2.putBuffer(v2)};var tls5={};tls5.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};tls5.SupportedVersions=[tls5.Versions.TLS_1_1,tls5.Versions.TLS_1_0];tls5.Version=tls5.SupportedVersions[0];tls5.MaxFragment=16384-1024;tls5.ConnectionEnd={server:0,client:1};tls5.PRFAlgorithm={tls_prf_sha256:0};tls5.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};tls5.CipherType={stream:0,block:1,aead:2};tls5.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};tls5.CompressionMethod={none:0,deflate:1};tls5.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};tls5.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};tls5.Alert={};tls5.Alert.Level={warning:1,fatal:2};tls5.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};tls5.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};tls5.CipherSuites={};tls5.getCipherSuite=function(twoBytes){var rval=null;for(var key2 in tls5.CipherSuites){var cs2=tls5.CipherSuites[key2];if(cs2.id[0]===twoBytes.charCodeAt(0)&&cs2.id[1]===twoBytes.charCodeAt(1)){rval=cs2;break}}return rval};tls5.handleUnexpected=function(c,record){var ignore=!c.open&&c.entity===tls5.ConnectionEnd.client;if(!ignore){c.error(c,{message:"Unexpected message. Received TLS record out of order.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unexpected_message}})}};tls5.handleHelloRequest=function(c,record,length){if(!c.handshaking&&c.handshakes>0){tls5.queue(c,tls5.createAlert(c,{level:tls5.Alert.Level.warning,description:tls5.Alert.Description.no_renegotiation}));tls5.flush(c)}c.process()};tls5.parseHelloMessage=function(c,record,length){var msg=null;var client=c.entity===tls5.ConnectionEnd.client;if(length<38){c.error(c,{message:client?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}else{var b2=record.fragment;var remaining=b2.length();msg={version:{major:b2.getByte(),minor:b2.getByte()},random:forge2.util.createBuffer(b2.getBytes(32)),session_id:readVector(b2,1),extensions:[]};if(client){msg.cipher_suite=b2.getBytes(2);msg.compression_method=b2.getByte()}else{msg.cipher_suites=readVector(b2,2);msg.compression_methods=readVector(b2,1)}remaining=length-(remaining-b2.length());if(remaining>0){var exts=readVector(b2,2);while(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(ext.type[0]===0&&ext.type[1]===0){var snl=readVector(ext.data,2);while(snl.length()>0){var snType=snl.getByte();if(snType!==0){break}c.session.extensions.server_name.serverNameList.push(readVector(snl,2).getBytes())}}}}}if(c.session.version){if(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:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.protocol_version}})}}if(client){c.session.cipherSuite=tls5.getCipherSuite(msg.cipher_suite)}else{var tmp=forge2.util.createBuffer(msg.cipher_suites.bytes());while(tmp.length()>0){c.session.cipherSuite=tls5.getCipherSuite(tmp.getBytes(2));if(c.session.cipherSuite!==null){break}}}if(c.session.cipherSuite===null){return c.error(c,{message:"No cipher suites in common.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.handshake_failure},cipherSuite:forge2.util.bytesToHex(msg.cipher_suite)})}if(client){c.session.compressionMethod=msg.compression_method}else{c.session.compressionMethod=tls5.CompressionMethod.none}}return msg};tls5.createSecurityParameters=function(c,msg){var client=c.entity===tls5.ConnectionEnd.client;var msgRandom=msg.random.bytes();var cRandom=client?c.session.sp.client_random:msgRandom;var sRandom=client?msgRandom:tls5.createRandom().getBytes();c.session.sp={entity:c.entity,prf_algorithm:tls5.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}};tls5.handleServerHello=function(c,record,length){var msg=tls5.parseHelloMessage(c,record,length);if(c.fail){return}if(msg.version.minor<=c.version.minor){c.version.minor=msg.version.minor}else{return c.error(c,{message:"Incompatible TLS version.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.protocol_version}})}c.session.version=c.version;var sessionId=msg.session_id.bytes();if(sessionId.length>0&&sessionId===c.session.id){c.expect=SCC;c.session.resuming=true;c.session.sp.server_random=msg.random.bytes()}else{c.expect=SCE;c.session.resuming=false;tls5.createSecurityParameters(c,msg)}c.session.id=sessionId;c.process()};tls5.handleClientHello=function(c,record,length){var msg=tls5.parseHelloMessage(c,record,length);if(c.fail){return}var sessionId=msg.session_id.bytes();var session=null;if(c.sessionCache){session=c.sessionCache.getSession(sessionId);if(session===null){sessionId=""}else if(session.version.major!==msg.version.major||session.version.minor>msg.version.minor){session=null;sessionId=""}}if(sessionId.length===0){sessionId=forge2.random.getBytes(32)}c.session.id=sessionId;c.session.clientHelloVersion=msg.version;c.session.sp={};if(session){c.version=c.session.version=session.version;c.session.sp=session.sp}else{var version;for(var i=1;i<tls5.SupportedVersions.length;++i){version=tls5.SupportedVersions[i];if(version.minor<=msg.version.minor){break}}c.version={major:version.major,minor:version.minor};c.session.version=c.version}if(session!==null){c.expect=CCC;c.session.resuming=true;c.session.sp.client_random=msg.random.bytes()}else{c.expect=c.verifyClient!==false?CCE:CKE;c.session.resuming=false;tls5.createSecurityParameters(c,msg)}c.open=true;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createServerHello(c)}));if(c.session.resuming){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.change_cipher_spec,data:tls5.createChangeCipherSpec()}));c.state.pending=tls5.createConnectionState(c);c.state.current.write=c.state.pending.write;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createFinished(c)}))}else{tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createCertificate(c)}));if(!c.fail){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createServerKeyExchange(c)}));if(c.verifyClient!==false){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createCertificateRequest(c)}))}tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createServerHelloDone(c)}))}}tls5.flush(c);c.process()};tls5.handleCertificate=function(c,record,length){if(length<3){return c.error(c,{message:"Invalid Certificate message. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var b2=record.fragment;var msg={certificate_list:readVector(b2,3)};var cert,asn1;var certs=[];try{while(msg.certificate_list.length()>0){cert=readVector(msg.certificate_list,3);asn1=forge2.asn1.fromDer(cert);cert=forge2.pki.certificateFromAsn1(asn1,true);certs.push(cert)}}catch(ex){return c.error(c,{message:"Could not parse certificate list.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_certificate}})}var client=c.entity===tls5.ConnectionEnd.client;if((client||c.verifyClient===true)&&certs.length===0){c.error(c,{message:client?"No server certificate provided.":"No client certificate provided.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}else if(certs.length===0){c.expect=client?SKE:CKE}else{if(client){c.session.serverCertificate=certs[0]}else{c.session.clientCertificate=certs[0]}if(tls5.verifyCertificateChain(c,certs)){c.expect=client?SKE:CKE}}c.process()};tls5.handleServerKeyExchange=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unsupported_certificate}})}c.expect=SCR;c.process()};tls5.handleClientKeyExchange=function(c,record,length){if(length<48){return c.error(c,{message:"Invalid key parameters. Only RSA is supported.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unsupported_certificate}})}var b2=record.fragment;var msg={enc_pre_master_secret:readVector(b2,2).getBytes()};var privateKey=null;if(c.getPrivateKey){try{privateKey=c.getPrivateKey(c,c.session.serverCertificate);privateKey=forge2.pki.privateKeyFromPem(privateKey)}catch(ex){c.error(c,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}}if(privateKey===null){return c.error(c,{message:"No private key set.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.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=forge2.random.getBytes(48)}c.expect=CCC;if(c.session.clientCertificate!==null){c.expect=CCV}c.process()};tls5.handleCertificateRequest=function(c,record,length){if(length<3){return c.error(c,{message:"Invalid CertificateRequest. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var b2=record.fragment;var msg={certificate_types:readVector(b2,1),certificate_authorities:readVector(b2,2)};c.session.certificateRequest=msg;c.expect=SHD;c.process()};tls5.handleCertificateVerify=function(c,record,length){if(length<2){return c.error(c,{message:"Invalid CertificateVerify. Message too short.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var b2=record.fragment;b2.read-=4;var msgBytes=b2.bytes();b2.read+=4;var msg={signature:readVector(b2,2).getBytes()};var verify=forge2.util.createBuffer();verify.putBuffer(c.session.md5.digest());verify.putBuffer(c.session.sha1.digest());verify=verify.getBytes();try{var cert=c.session.clientCertificate;if(!cert.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:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.handshake_failure}})}c.expect=CCC;c.process()};tls5.handleServerHelloDone=function(c,record,length){if(length>0){return c.error(c,{message:"Invalid ServerHelloDone message. Invalid length.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.record_overflow}})}if(c.serverCertificate===null){var error={message:"No server certificate provided. Not enough security.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.insufficient_security}};var depth=0;var ret=c.verify(c,error.alert.description,depth,[]);if(ret!==true){if(ret||ret===0){if(typeof ret==="object"&&!forge2.util.isArray(ret)){if(ret.message){error.message=ret.message}if(ret.alert){error.alert.description=ret.alert}}else if(typeof ret==="number"){error.alert.description=ret}}return c.error(c,error)}}if(c.session.certificateRequest!==null){record=tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createCertificate(c)});tls5.queue(c,record)}record=tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createClientKeyExchange(c)});tls5.queue(c,record);c.expect=SER;var callback=function(c2,signature){if(c2.session.certificateRequest!==null&&c2.session.clientCertificate!==null){tls5.queue(c2,tls5.createRecord(c2,{type:tls5.ContentType.handshake,data:tls5.createCertificateVerify(c2,signature)}))}tls5.queue(c2,tls5.createRecord(c2,{type:tls5.ContentType.change_cipher_spec,data:tls5.createChangeCipherSpec()}));c2.state.pending=tls5.createConnectionState(c2);c2.state.current.write=c2.state.pending.write;tls5.queue(c2,tls5.createRecord(c2,{type:tls5.ContentType.handshake,data:tls5.createFinished(c2)}));c2.expect=SCC;tls5.flush(c2);c2.process()};if(c.session.certificateRequest===null||c.session.clientCertificate===null){return callback(c,null)}tls5.getClientSignature(c,callback)};tls5.handleChangeCipherSpec=function(c,record){if(record.fragment.getByte()!==1){return c.error(c,{message:"Invalid ChangeCipherSpec message received.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.illegal_parameter}})}var client=c.entity===tls5.ConnectionEnd.client;if(c.session.resuming&&client||!c.session.resuming&&!client){c.state.pending=tls5.createConnectionState(c)}c.state.current.read=c.state.pending.read;if(!c.session.resuming&&client||c.session.resuming&&!client){c.state.pending=null}c.expect=client?SFI:CFI;c.process()};tls5.handleFinished=function(c,record,length){var b2=record.fragment;b2.read-=4;var msgBytes=b2.bytes();b2.read+=4;var vd=record.fragment.getBytes();b2=forge2.util.createBuffer();b2.putBuffer(c.session.md5.digest());b2.putBuffer(c.session.sha1.digest());var client=c.entity===tls5.ConnectionEnd.client;var label=client?"server finished":"client finished";var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;b2=prf(sp.master_secret,label,b2.getBytes(),vdl);if(b2.getBytes()!==vd){return c.error(c,{message:"Invalid verify_data in Finished message.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.decrypt_error}})}c.session.md5.update(msgBytes);c.session.sha1.update(msgBytes);if(c.session.resuming&&client||!c.session.resuming&&!client){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.change_cipher_spec,data:tls5.createChangeCipherSpec()}));c.state.current.write=c.state.pending.write;c.state.pending=null;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createFinished(c)}))}c.expect=client?SAD:CAD;c.handshaking=false;++c.handshakes;c.peerCertificate=client?c.session.serverCertificate:c.session.clientCertificate;tls5.flush(c);c.isConnected=true;c.connected(c);c.process()};tls5.handleAlert=function(c,record){var b2=record.fragment;var alert={level:b2.getByte(),description:b2.getByte()};var msg;switch(alert.description){case tls5.Alert.Description.close_notify:msg="Connection closed.";break;case tls5.Alert.Description.unexpected_message:msg="Unexpected message.";break;case tls5.Alert.Description.bad_record_mac:msg="Bad record MAC.";break;case tls5.Alert.Description.decryption_failed:msg="Decryption failed.";break;case tls5.Alert.Description.record_overflow:msg="Record overflow.";break;case tls5.Alert.Description.decompression_failure:msg="Decompression failed.";break;case tls5.Alert.Description.handshake_failure:msg="Handshake failure.";break;case tls5.Alert.Description.bad_certificate:msg="Bad certificate.";break;case tls5.Alert.Description.unsupported_certificate:msg="Unsupported certificate.";break;case tls5.Alert.Description.certificate_revoked:msg="Certificate revoked.";break;case tls5.Alert.Description.certificate_expired:msg="Certificate expired.";break;case tls5.Alert.Description.certificate_unknown:msg="Certificate unknown.";break;case tls5.Alert.Description.illegal_parameter:msg="Illegal parameter.";break;case tls5.Alert.Description.unknown_ca:msg="Unknown certificate authority.";break;case tls5.Alert.Description.access_denied:msg="Access denied.";break;case tls5.Alert.Description.decode_error:msg="Decode error.";break;case tls5.Alert.Description.decrypt_error:msg="Decrypt error.";break;case tls5.Alert.Description.export_restriction:msg="Export restriction.";break;case tls5.Alert.Description.protocol_version:msg="Unsupported protocol version.";break;case tls5.Alert.Description.insufficient_security:msg="Insufficient security.";break;case tls5.Alert.Description.internal_error:msg="Internal error.";break;case tls5.Alert.Description.user_canceled:msg="User canceled.";break;case tls5.Alert.Description.no_renegotiation:msg="Renegotiation not supported.";break;default:msg="Unknown error.";break}if(alert.description===tls5.Alert.Description.close_notify){return c.close()}c.error(c,{message:msg,send:false,origin:c.entity===tls5.ConnectionEnd.client?"server":"client",alert});c.process()};tls5.handleHandshake=function(c,record){var b2=record.fragment;var type=b2.getByte();var length=b2.getInt24();if(length>b2.length()){c.fragmented=record;record.fragment=forge2.util.createBuffer();b2.read-=4;return c.process()}c.fragmented=null;b2.read-=4;var bytes=b2.bytes(length+4);b2.read+=4;if(type in hsTable[c.entity][c.expect]){if(c.entity===tls5.ConnectionEnd.server&&!c.open&&!c.fail){c.handshaking=true;c.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:forge2.md.md5.create(),sha1:forge2.md.sha1.create()}}if(type!==tls5.HandshakeType.hello_request&&type!==tls5.HandshakeType.certificate_verify&&type!==tls5.HandshakeType.finished){c.session.md5.update(bytes);c.session.sha1.update(bytes)}hsTable[c.entity][c.expect][type](c,record,length)}else{tls5.handleUnexpected(c,record)}};tls5.handleApplicationData=function(c,record){c.data.putBuffer(record.fragment);c.dataReady(c);c.process()};tls5.handleHeartbeat=function(c,record){var b2=record.fragment;var type=b2.getByte();var length=b2.getInt16();var payload=b2.getBytes(length);if(type===tls5.HeartbeatMessageType.heartbeat_request){if(c.handshaking||length>payload.length){return c.process()}tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.heartbeat,data:tls5.createHeartbeat(tls5.HeartbeatMessageType.heartbeat_response,payload)}));tls5.flush(c)}else if(type===tls5.HeartbeatMessageType.heartbeat_response){if(payload!==c.expectedHeartbeatPayload){return c.process()}if(c.heartbeatReceived){c.heartbeatReceived(c,forge2.util.createBuffer(payload))}}c.process()};var SHE=0;var SCE=1;var SKE=2;var SCR=3;var SHD=4;var SCC=5;var SFI=6;var SAD=7;var SER=8;var CHE=0;var CCE=1;var CKE=2;var CCV=3;var CCC=4;var CFI=5;var CAD=6;var __=tls5.handleUnexpected;var R0=tls5.handleChangeCipherSpec;var R1=tls5.handleAlert;var R2=tls5.handleHandshake;var R3=tls5.handleApplicationData;var R4=tls5.handleHeartbeat;var ctTable=[];ctTable[tls5.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[tls5.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=tls5.handleHelloRequest;var H1=tls5.handleServerHello;var H2=tls5.handleCertificate;var H3=tls5.handleServerKeyExchange;var H4=tls5.handleCertificateRequest;var H5=tls5.handleServerHelloDone;var H6=tls5.handleFinished;var hsTable=[];hsTable[tls5.ConnectionEnd.client]=[[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];var H7=tls5.handleClientHello;var H8=tls5.handleClientKeyExchange;var H9=tls5.handleCertificateVerify;hsTable[tls5.ConnectionEnd.server]=[[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]];tls5.generateKeys=function(c,sp){var prf=prf_TLS1;var random=sp.client_random+sp.server_random;if(!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;var tls10=c.version.major===tls5.Versions.TLS_1_0.major&&c.version.minor===tls5.Versions.TLS_1_0.minor;if(tls10){length+=2*sp.fixed_iv_length}var km=prf(sp.master_secret,"key expansion",random,length);var 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)};if(tls10){rval.client_write_IV=km.getBytes(sp.fixed_iv_length);rval.server_write_IV=km.getBytes(sp.fixed_iv_length)}return rval};tls5.createConnectionState=function(c){var client=c.entity===tls5.ConnectionEnd.client;var createMode=function(){var mode={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(record){return true},compressionState:null,compressFunction:function(record){return true},updateSequenceNumber:function(){if(mode.sequenceNumber[1]===4294967295){mode.sequenceNumber[1]=0;++mode.sequenceNumber[0]}else{++mode.sequenceNumber[1]}}};return mode};var state3={read:createMode(),write:createMode()};state3.read.update=function(c2,record){if(!state3.read.cipherFunction(record,state3.read)){c2.error(c2,{message:"Could not decrypt record or bad MAC.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_record_mac}})}else if(!state3.read.compressFunction(c2,record,state3.read)){c2.error(c2,{message:"Could not decompress record.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.decompression_failure}})}return!c2.fail};state3.write.update=function(c2,record){if(!state3.write.compressFunction(c2,record,state3.write)){c2.error(c2,{message:"Could not compress record.",send:false,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}else if(!state3.write.cipherFunction(record,state3.write)){c2.error(c2,{message:"Could not encrypt record.",send:false,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}return!c2.fail};if(c.session){var sp=c.session.sp;c.session.cipherSuite.initSecurityParameters(sp);sp.keys=tls5.generateKeys(c,sp);state3.read.macKey=client?sp.keys.server_write_MAC_key:sp.keys.client_write_MAC_key;state3.write.macKey=client?sp.keys.client_write_MAC_key:sp.keys.server_write_MAC_key;c.session.cipherSuite.initConnectionState(state3,c,sp);switch(sp.compression_algorithm){case tls5.CompressionMethod.none:break;case tls5.CompressionMethod.deflate:state3.read.compressFunction=inflate;state3.write.compressFunction=deflate;break;default:throw new Error("Unsupported compression algorithm.")}}return state3};tls5.createRandom=function(){var d=new Date;var utc=+d+d.getTimezoneOffset()*6e4;var rval=forge2.util.createBuffer();rval.putInt32(utc);rval.putBytes(forge2.random.getBytes(28));return rval};tls5.createRecord=function(c,options){if(!options.data){return null}var record={type:options.type,version:{major:c.version.major,minor:c.version.minor},length:options.data.length(),fragment:options.data};return record};tls5.createAlert=function(c,alert){var b2=forge2.util.createBuffer();b2.putByte(alert.level);b2.putByte(alert.description);return tls5.createRecord(c,{type:tls5.ContentType.alert,data:b2})};tls5.createClientHello=function(c){c.session.clientHelloVersion={major:c.version.major,minor:c.version.minor};var cipherSuites=forge2.util.createBuffer();for(var i=0;i<c.cipherSuites.length;++i){var cs2=c.cipherSuites[i];cipherSuites.putByte(cs2.id[0]);cipherSuites.putByte(cs2.id[1])}var cSuites=cipherSuites.length();var compressionMethods=forge2.util.createBuffer();compressionMethods.putByte(tls5.CompressionMethod.none);var cMethods=compressionMethods.length();var extensions=forge2.util.createBuffer();if(c.virtualHost){var ext=forge2.util.createBuffer();ext.putByte(0);ext.putByte(0);var serverName=forge2.util.createBuffer();serverName.putByte(0);writeVector(serverName,2,forge2.util.createBuffer(c.virtualHost));var snList=forge2.util.createBuffer();writeVector(snList,2,serverName);writeVector(ext,2,snList);extensions.putBuffer(ext)}var extLength=extensions.length();if(extLength>0){extLength+=2}var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+cSuites+1+cMethods+extLength;var rval=forge2.util.createBuffer();rval.putByte(tls5.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,forge2.util.createBuffer(sessionId));writeVector(rval,2,cipherSuites);writeVector(rval,1,compressionMethods);if(extLength>0){writeVector(rval,2,extensions)}return rval};tls5.createServerHello=function(c){var sessionId=c.session.id;var length=sessionId.length+1+2+4+28+2+1;var rval=forge2.util.createBuffer();rval.putByte(tls5.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,forge2.util.createBuffer(sessionId));rval.putByte(c.session.cipherSuite.id[0]);rval.putByte(c.session.cipherSuite.id[1]);rval.putByte(c.session.compressionMethod);return rval};tls5.createCertificate=function(c){var client=c.entity===tls5.ConnectionEnd.client;var cert=null;if(c.getCertificate){var hint;if(client){hint=c.session.certificateRequest}else{hint=c.session.extensions.server_name.serverNameList}cert=c.getCertificate(c,hint)}var certList=forge2.util.createBuffer();if(cert!==null){try{if(!forge2.util.isArray(cert)){cert=[cert]}var asn1=null;for(var i=0;i<cert.length;++i){var msg=forge2.pem.decode(cert[i])[0];if(msg.type!=="CERTIFICATE"&&msg.type!=="X509 CERTIFICATE"&&msg.type!=="TRUSTED CERTIFICATE"){var error=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){throw new Error("Could not convert certificate from PEM; PEM is encrypted.")}var der=forge2.util.createBuffer(msg.body);if(asn1===null){asn1=forge2.asn1.fromDer(der.bytes(),false)}var certBuffer=forge2.util.createBuffer();writeVector(certBuffer,3,der);certList.putBuffer(certBuffer)}cert=forge2.pki.certificateFromAsn1(asn1);if(client){c.session.clientCertificate=cert}else{c.session.serverCertificate=cert}}catch(ex){return c.error(c,{message:"Could not send certificate list.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_certificate}})}}var length=3+certList.length();var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.certificate);rval.putInt24(length);writeVector(rval,3,certList);return rval};tls5.createClientKeyExchange=function(c){var b2=forge2.util.createBuffer();b2.putByte(c.session.clientHelloVersion.major);b2.putByte(c.session.clientHelloVersion.minor);b2.putBytes(forge2.random.getBytes(46));var sp=c.session.sp;sp.pre_master_secret=b2.getBytes();var key2=c.session.serverCertificate.publicKey;b2=key2.encrypt(sp.pre_master_secret);var length=b2.length+2;var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.client_key_exchange);rval.putInt24(length);rval.putInt16(b2.length);rval.putBytes(b2);return rval};tls5.createServerKeyExchange=function(c){var length=0;var rval=forge2.util.createBuffer();if(length>0){rval.putByte(tls5.HandshakeType.server_key_exchange);rval.putInt24(length)}return rval};tls5.getClientSignature=function(c,callback){var b2=forge2.util.createBuffer();b2.putBuffer(c.session.md5.digest());b2.putBuffer(c.session.sha1.digest());b2=b2.getBytes();c.getSignature=c.getSignature||function(c2,b3,callback2){var privateKey=null;if(c2.getPrivateKey){try{privateKey=c2.getPrivateKey(c2,c2.session.clientCertificate);privateKey=forge2.pki.privateKeyFromPem(privateKey)}catch(ex){c2.error(c2,{message:"Could not get private key.",cause:ex,send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}}if(privateKey===null){c2.error(c2,{message:"No private key set.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.internal_error}})}else{b3=privateKey.sign(b3,null)}callback2(c2,b3)};c.getSignature(c,b2,callback)};tls5.createCertificateVerify=function(c,signature){var length=signature.length+2;var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.certificate_verify);rval.putInt24(length);rval.putInt16(signature.length);rval.putBytes(signature);return rval};tls5.createCertificateRequest=function(c){var certTypes=forge2.util.createBuffer();certTypes.putByte(1);var cAs=forge2.util.createBuffer();for(var key2 in c.caStore.certs){var cert=c.caStore.certs[key2];var dn2=forge2.pki.distinguishedNameToAsn1(cert.subject);var byteBuffer=forge2.asn1.toDer(dn2);cAs.putInt16(byteBuffer.length());cAs.putBuffer(byteBuffer)}var length=1+certTypes.length()+2+cAs.length();var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.certificate_request);rval.putInt24(length);writeVector(rval,1,certTypes);writeVector(rval,2,cAs);return rval};tls5.createServerHelloDone=function(c){var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.server_hello_done);rval.putInt24(0);return rval};tls5.createChangeCipherSpec=function(){var rval=forge2.util.createBuffer();rval.putByte(1);return rval};tls5.createFinished=function(c){var b2=forge2.util.createBuffer();b2.putBuffer(c.session.md5.digest());b2.putBuffer(c.session.sha1.digest());var client=c.entity===tls5.ConnectionEnd.client;var sp=c.session.sp;var vdl=12;var prf=prf_TLS1;var label=client?"client finished":"server finished";b2=prf(sp.master_secret,label,b2.getBytes(),vdl);var rval=forge2.util.createBuffer();rval.putByte(tls5.HandshakeType.finished);rval.putInt24(b2.length());rval.putBuffer(b2);return rval};tls5.createHeartbeat=function(type,payload,payloadLength){if(typeof payloadLength==="undefined"){payloadLength=payload.length}var rval=forge2.util.createBuffer();rval.putByte(type);rval.putInt16(payloadLength);rval.putBytes(payload);var plaintextLength=rval.length();var paddingLength=Math.max(16,plaintextLength-payloadLength-3);rval.putBytes(forge2.random.getBytes(paddingLength));return rval};tls5.queue=function(c,record){if(!record){return}if(record.fragment.length()===0){if(record.type===tls5.ContentType.handshake||record.type===tls5.ContentType.alert||record.type===tls5.ContentType.change_cipher_spec){return}}if(record.type===tls5.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()<=tls5.MaxFragment){records=[record]}else{records=[];var data=record.fragment.bytes();while(data.length>tls5.MaxFragment){records.push(tls5.createRecord(c,{type:record.type,data:forge2.util.createBuffer(data.slice(0,tls5.MaxFragment))}));data=data.slice(tls5.MaxFragment)}if(data.length>0){records.push(tls5.createRecord(c,{type:record.type,data:forge2.util.createBuffer(data)}))}}for(var i=0;i<records.length&&!c.fail;++i){var rec=records[i];var s3=c.state.current.write;if(s3.update(c,rec)){c.records.push(rec)}}};tls5.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)}c.records=[];return c.tlsDataReady(c)};var _certErrorToAlertDesc=function(error){switch(error){case true:return true;case forge2.pki.certificateError.bad_certificate:return tls5.Alert.Description.bad_certificate;case forge2.pki.certificateError.unsupported_certificate:return tls5.Alert.Description.unsupported_certificate;case forge2.pki.certificateError.certificate_revoked:return tls5.Alert.Description.certificate_revoked;case forge2.pki.certificateError.certificate_expired:return tls5.Alert.Description.certificate_expired;case forge2.pki.certificateError.certificate_unknown:return tls5.Alert.Description.certificate_unknown;case forge2.pki.certificateError.unknown_ca:return tls5.Alert.Description.unknown_ca;default:return tls5.Alert.Description.bad_certificate}};var _alertDescToCertError=function(desc){switch(desc){case true:return true;case tls5.Alert.Description.bad_certificate:return forge2.pki.certificateError.bad_certificate;case tls5.Alert.Description.unsupported_certificate:return forge2.pki.certificateError.unsupported_certificate;case tls5.Alert.Description.certificate_revoked:return forge2.pki.certificateError.certificate_revoked;case tls5.Alert.Description.certificate_expired:return forge2.pki.certificateError.certificate_expired;case tls5.Alert.Description.certificate_unknown:return forge2.pki.certificateError.certificate_unknown;case tls5.Alert.Description.unknown_ca:return forge2.pki.certificateError.unknown_ca;default:return forge2.pki.certificateError.bad_certificate}};tls5.verifyCertificateChain=function(c,chain){try{var options={};for(var key2 in c.verifyOptions){options[key2]=c.verifyOptions[key2]}options.verify=function(vfd,depth,chain2){var desc=_certErrorToAlertDesc(vfd);var ret=c.verify(c,vfd,depth,chain2);if(ret!==true){if(typeof ret==="object"&&!forge2.util.isArray(ret)){var error=new Error("The application rejected the certificate.");error.send=true;error.alert={level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.bad_certificate};if(ret.message){error.message=ret.message}if(ret.alert){error.alert.description=ret.alert}throw error}if(ret!==vfd){ret=_alertDescToCertError(ret)}}return ret};forge2.pki.verifyCertificateChain(c.caStore,chain,options)}catch(ex){var err=ex;if(typeof err!=="object"||forge2.util.isArray(err)){err={send:true,alert:{level:tls5.Alert.Level.fatal,description:_certErrorToAlertDesc(ex)}}}if(!("send"in err)){err.send=true}if(!("alert"in err)){err.alert={level:tls5.Alert.Level.fatal,description:_certErrorToAlertDesc(err.error)}}c.error(c,err)}return!c.fail};tls5.createSessionCache=function(cache3,capacity){var rval=null;if(cache3&&cache3.getSession&&cache3.setSession&&cache3.order){rval=cache3}else{rval={};rval.cache=cache3||{};rval.capacity=Math.max(capacity||100,1);rval.order=[];for(var key2 in cache3){if(rval.order.length<=capacity){rval.order.push(key2)}else{delete cache3[key2]}}rval.getSession=function(sessionId){var session=null;var key3=null;if(sessionId){key3=forge2.util.bytesToHex(sessionId)}else if(rval.order.length>0){key3=rval.order[0]}if(key3!==null&&key3 in rval.cache){session=rval.cache[key3];delete rval.cache[key3];for(var i in rval.order){if(rval.order[i]===key3){rval.order.splice(i,1);break}}}return session};rval.setSession=function(sessionId,session){if(rval.order.length===rval.capacity){var key3=rval.order.shift();delete rval.cache[key3]}var key3=forge2.util.bytesToHex(sessionId);rval.order.push(key3);rval.cache[key3]=session}}return rval};tls5.createConnection=function(options){var caStore=null;if(options.caStore){if(forge2.util.isArray(options.caStore)){caStore=forge2.pki.createCaStore(options.caStore)}else{caStore=options.caStore}}else{caStore=forge2.pki.createCaStore()}var cipherSuites=options.cipherSuites||null;if(cipherSuites===null){cipherSuites=[];for(var key2 in tls5.CipherSuites){cipherSuites.push(tls5.CipherSuites[key2])}}var entity=options.server||false?tls5.ConnectionEnd.server:tls5.ConnectionEnd.client;var sessionCache=options.sessionCache?tls5.createSessionCache(options.sessionCache):null;var c={version:{major:tls5.Version.major,minor:tls5.Version.minor},entity,sessionId:options.sessionId,caStore,sessionCache,cipherSuites,connected:options.connected,virtualHost:options.virtualHost||null,verifyClient:options.verifyClient||false,verify:options.verify||function(cn2,vfd,dpth,cts){return vfd},verifyOptions:options.verifyOptions||{},getCertificate:options.getCertificate||null,getPrivateKey:options.getPrivateKey||null,getSignature:options.getSignature||null,input:forge2.util.createBuffer(),tlsData:forge2.util.createBuffer(),data:forge2.util.createBuffer(),tlsDataReady:options.tlsDataReady,dataReady:options.dataReady,heartbeatReceived:options.heartbeatReceived,closed:options.closed,error:function(c2,ex){ex.origin=ex.origin||(c2.entity===tls5.ConnectionEnd.client?"client":"server");if(ex.send){tls5.queue(c2,tls5.createAlert(c2,ex.alert));tls5.flush(c2)}var fatal=ex.fatal!==false;if(fatal){c2.fail=true}options.error(c2,ex);if(fatal){c2.close(false)}},deflate:options.deflate||null,inflate:options.inflate||null};c.reset=function(clearFail){c.version={major:tls5.Version.major,minor:tls5.Version.minor};c.record=null;c.session=null;c.peerCertificate=null;c.state={pending:null,current:null};c.expect=c.entity===tls5.ConnectionEnd.client?SHE:CHE;c.fragmented=null;c.records=[];c.open=false;c.handshakes=0;c.handshaking=false;c.isConnected=false;c.fail=!(clearFail||typeof clearFail==="undefined");c.input.clear();c.tlsData.clear();c.data.clear();c.state.current=tls5.createConnectionState(c)};c.reset();var _update=function(c2,record){var aligned=record.type-tls5.ContentType.change_cipher_spec;var handlers=ctTable[c2.entity][c2.expect];if(aligned in handlers){handlers[aligned](c2,record)}else{tls5.handleUnexpected(c2,record)}};var _readRecordHeader=function(c2){var rval=0;var b2=c2.input;var len=b2.length();if(len<5){rval=5-len}else{c2.record={type:b2.getByte(),version:{major:b2.getByte(),minor:b2.getByte()},length:b2.getInt16(),fragment:forge2.util.createBuffer(),ready:false};var compatibleVersion=c2.record.version.major===c2.version.major;if(compatibleVersion&&c2.session&&c2.session.version){compatibleVersion=c2.record.version.minor===c2.version.minor}if(!compatibleVersion){c2.error(c2,{message:"Incompatible TLS version.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.protocol_version}})}}return rval};var _readRecord=function(c2){var rval=0;var b2=c2.input;var len=b2.length();if(len<c2.record.length){rval=c2.record.length-len}else{c2.record.fragment.putBytes(b2.getBytes(c2.record.length));b2.compact();var s3=c2.state.current.read;if(s3.update(c2,c2.record)){if(c2.fragmented!==null){if(c2.fragmented.type===c2.record.type){c2.fragmented.fragment.putBuffer(c2.record.fragment);c2.record=c2.fragmented}else{c2.error(c2,{message:"Invalid fragmented record.",send:true,alert:{level:tls5.Alert.Level.fatal,description:tls5.Alert.Description.unexpected_message}})}}c2.record.ready=true}}return rval};c.handshake=function(sessionId){if(c.entity!==tls5.ConnectionEnd.client){c.error(c,{message:"Cannot initiate handshake as a server.",fatal:false})}else if(c.handshaking){c.error(c,{message:"Handshake already in progress.",fatal:false})}else{if(c.fail&&!c.open&&c.handshakes===0){c.fail=false}c.handshaking=true;sessionId=sessionId||"";var session=null;if(sessionId.length>0){if(c.sessionCache){session=c.sessionCache.getSession(sessionId)}if(session===null){sessionId=""}}if(sessionId.length===0&&c.sessionCache){session=c.sessionCache.getSession();if(session!==null){sessionId=session.id}}c.session={id:sessionId,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:forge2.md.md5.create(),sha1:forge2.md.sha1.create()};if(session){c.version=session.version;c.session.sp=session.sp}c.session.sp.client_random=tls5.createRandom().getBytes();c.open=true;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.handshake,data:tls5.createClientHello(c)}));tls5.flush(c)}};c.process=function(data){var rval=0;if(data){c.input.putBytes(data)}if(!c.fail){if(c.record!==null&&c.record.ready&&c.record.fragment.isEmpty()){c.record=null}if(c.record===null){rval=_readRecordHeader(c)}if(!c.fail&&c.record!==null&&!c.record.ready){rval=_readRecord(c)}if(!c.fail&&c.record!==null&&c.record.ready){_update(c,c.record)}}return rval};c.prepare=function(data){tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.application_data,data:forge2.util.createBuffer(data)}));return tls5.flush(c)};c.prepareHeartbeatRequest=function(payload,payloadLength){if(payload instanceof forge2.util.ByteBuffer){payload=payload.bytes()}if(typeof payloadLength==="undefined"){payloadLength=payload.length}c.expectedHeartbeatPayload=payload;tls5.queue(c,tls5.createRecord(c,{type:tls5.ContentType.heartbeat,data:tls5.createHeartbeat(tls5.HeartbeatMessageType.heartbeat_request,payload,payloadLength)}));return tls5.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)}if(c.open){c.open=false;c.input.clear();if(c.isConnected||c.handshaking){c.isConnected=c.handshaking=false;tls5.queue(c,tls5.createAlert(c,{level:tls5.Alert.Level.warning,description:tls5.Alert.Description.close_notify}));tls5.flush(c)}c.closed(c)}c.reset(clearFail)};return c};module.exports=forge2.tls=forge2.tls||{};for(key in tls5){if(typeof tls5[key]!=="function"){forge2.tls[key]=tls5[key]}}var key;forge2.tls.prf_tls1=prf_TLS1;forge2.tls.hmac_sha1=hmac_sha1;forge2.tls.createSessionCache=tls5.createSessionCache;forge2.tls.createConnection=tls5.createConnection}});var require_aesCipherSuites=__commonJS({"node_modules/node-forge/lib/aesCipherSuites.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_tls();var tls5=module.exports=forge2.tls;tls5.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=tls5.BulkCipherAlgorithm.aes;sp.cipher_type=tls5.CipherType.block;sp.enc_key_length=16;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls5.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState};tls5.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=tls5.BulkCipherAlgorithm.aes;sp.cipher_type=tls5.CipherType.block;sp.enc_key_length=32;sp.block_length=16;sp.fixed_iv_length=16;sp.record_iv_length=16;sp.mac_algorithm=tls5.MACAlgorithm.hmac_sha1;sp.mac_length=20;sp.mac_key_length=20},initConnectionState};function initConnectionState(state3,c,sp){var client=c.entity===forge2.tls.ConnectionEnd.client;state3.read.cipherState={init:false,cipher:forge2.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};state3.write.cipherState={init:false,cipher:forge2.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};state3.read.cipherFunction=decrypt_aes_cbc_sha1;state3.write.cipherFunction=encrypt_aes_cbc_sha1;state3.read.macLength=state3.write.macLength=sp.mac_length;state3.read.macFunction=state3.write.macFunction=tls5.hmac_sha1}function encrypt_aes_cbc_sha1(record,s3){var rval=false;var mac=s3.macFunction(s3.macKey,s3.sequenceNumber,record);record.fragment.putBytes(mac);s3.updateSequenceNumber();var iv;if(record.version.minor===tls5.Versions.TLS_1_0.minor){iv=s3.cipherState.init?null:s3.cipherState.iv}else{iv=forge2.random.getBytesSync(16)}s3.cipherState.init=true;var cipher=s3.cipherState.cipher;cipher.start({iv});if(record.version.minor>=tls5.Versions.TLS_1_1.minor){cipher.output.putBytes(iv)}cipher.update(record.fragment);if(cipher.finish(encrypt_aes_cbc_sha1_padding)){record.fragment=cipher.output;record.length=record.fragment.length();rval=true}return rval}function encrypt_aes_cbc_sha1_padding(blockSize,input,decrypt){if(!decrypt){var padding=blockSize-input.length()%blockSize;input.fillWithByte(padding-1,padding)}return true}function decrypt_aes_cbc_sha1_padding(blockSize,output,decrypt){var rval=true;if(decrypt){var len=output.length();var paddingLength=output.last();for(var i=len-1-paddingLength;i<len-1;++i){rval=rval&&output.at(i)==paddingLength}if(rval){output.truncate(paddingLength+1)}}return rval}function decrypt_aes_cbc_sha1(record,s3){var rval=false;var iv;if(record.version.minor===tls5.Versions.TLS_1_0.minor){iv=s3.cipherState.init?null:s3.cipherState.iv}else{iv=record.fragment.getBytes(16)}s3.cipherState.init=true;var cipher=s3.cipherState.cipher;cipher.start({iv});cipher.update(record.fragment);rval=cipher.finish(decrypt_aes_cbc_sha1_padding);var macLen=s3.macLength;var mac=forge2.random.getBytesSync(macLen);var len=cipher.output.length();if(len>=macLen){record.fragment=cipher.output.getBytes(len-macLen);mac=cipher.output.getBytes(macLen)}else{record.fragment=cipher.output.getBytes()}record.fragment=forge2.util.createBuffer(record.fragment);record.length=record.fragment.length();var mac2=s3.macFunction(s3.macKey,s3.sequenceNumber,record);s3.updateSequenceNumber();rval=compareMacs(s3.macKey,mac,mac2)&&rval;return rval}function compareMacs(key,mac1,mac2){var hmac=forge2.hmac.create();hmac.start("SHA1",key);hmac.update(mac1);mac1=hmac.digest().getBytes();hmac.start(null,null);hmac.update(mac2);mac2=hmac.digest().getBytes();return mac1===mac2}}});var require_sha512=__commonJS({"node_modules/node-forge/lib/sha512.js"(exports,module){"use strict";var forge2=require_forge();require_md();require_util7();var sha512=module.exports=forge2.sha512=forge2.sha512||{};forge2.md.sha512=forge2.md.algorithms.sha512=sha512;var sha384=forge2.sha384=forge2.sha512.sha384=forge2.sha512.sha384||{};sha384.create=function(){return sha512.create("SHA-384")};forge2.md.sha384=forge2.md.algorithms.sha384=sha384;forge2.sha512.sha256=forge2.sha512.sha256||{create:function(){return sha512.create("SHA-512/256")}};forge2.md["sha512/256"]=forge2.md.algorithms["sha512/256"]=forge2.sha512.sha256;forge2.sha512.sha224=forge2.sha512.sha224||{create:function(){return sha512.create("SHA-512/224")}};forge2.md["sha512/224"]=forge2.md.algorithms["sha512/224"]=forge2.sha512.sha224;sha512.create=function(algorithm){if(!_initialized){_init()}if(typeof algorithm==="undefined"){algorithm="SHA-512"}if(!(algorithm in _states)){throw new Error("Invalid SHA-512 algorithm: "+algorithm)}var _state=_states[algorithm];var _h=null;var _input=forge2.util.createBuffer();var _w=new Array(80);for(var wi2=0;wi2<80;++wi2){_w[wi2]=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;break}var md={algorithm:algorithm.replace("-","").toLowerCase(),blockLength:128,digestLength,messageLength:0,fullMessageLength:null,messageLengthSize:16};md.start=function(){md.messageLength=0;md.fullMessageLength=md.messageLength128=[];var int32s=md.messageLengthSize/4;for(var i=0;i<int32s;++i){md.fullMessageLength.push(0)}_input=forge2.util.createBuffer();_h=new Array(_state.length);for(var i=0;i<_state.length;++i){_h[i]=_state[i].slice(0)}return md};md.start();md.update=function(msg,encoding){if(encoding==="utf8"){msg=forge2.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}_input.putBytes(msg);_update(_h,_w,_input);if(_input.read>2048||_input.length()===0){_input.compact()}return md};md.digest=function(){var finalBlock=forge2.util.createBuffer();finalBlock.putBytes(_input.bytes());var remaining=md.fullMessageLength[md.fullMessageLength.length-1]+md.messageLengthSize;var overflow=remaining&md.blockLength-1;finalBlock.putBytes(_padding.substr(0,md.blockLength-overflow));var next,carry;var bits=md.fullMessageLength[0]*8;for(var i=0;i<md.fullMessageLength.length-1;++i){next=md.fullMessageLength[i+1]*8;carry=next/4294967296>>>0;bits+=carry;finalBlock.putInt32(bits>>>0);bits=next>>>0}finalBlock.putInt32(bits);var h=new Array(_h.length);for(var i=0;i<_h.length;++i){h[i]=_h[i].slice(0)}_update(h,_w,finalBlock);var rval=forge2.util.createBuffer();var hlen;if(algorithm==="SHA-512"){hlen=h.length}else if(algorithm==="SHA-384"){hlen=h.length-2}else{hlen=h.length-4}for(var i=0;i<hlen;++i){rval.putInt32(h[i][0]);if(i!==hlen-1||algorithm!=="SHA-512/224"){rval.putInt32(h[i][1])}}return rval};return md};var _padding=null;var _initialized=false;var _k=null;var _states=null;function _init(){_padding=String.fromCharCode(128);_padding+=forge2.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={};_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=true}function _update(s3,w2,bytes){var t1_hi,t1_lo;var t2_hi,t2_lo;var s0_hi,s0_lo;var s1_hi,s1_lo;var ch_hi,ch_lo;var maj_hi,maj_lo;var a_hi,a_lo;var b_hi,b_lo;var c_hi,c_lo;var d_hi,d_lo;var e_hi,e_lo;var f_hi,f_lo;var g_hi,g_lo;var h_hi,h_lo;var i,hi2,lo2,w22,w7,w15,w16;var len=bytes.length();while(len>=128){for(i=0;i<16;++i){w2[i][0]=bytes.getInt32()>>>0;w2[i][1]=bytes.getInt32()>>>0}for(;i<80;++i){w22=w2[i-2];hi2=w22[0];lo2=w22[1];t1_hi=((hi2>>>19|lo2<<13)^(lo2>>>29|hi2<<3)^hi2>>>6)>>>0;t1_lo=((hi2<<13|lo2>>>19)^(lo2<<3|hi2>>>29)^(hi2<<26|lo2>>>6))>>>0;w15=w2[i-15];hi2=w15[0];lo2=w15[1];t2_hi=((hi2>>>1|lo2<<31)^(hi2>>>8|lo2<<24)^hi2>>>7)>>>0;t2_lo=((hi2<<31|lo2>>>1)^(hi2<<24|lo2>>>8)^(hi2<<25|lo2>>>7))>>>0;w7=w2[i-7];w16=w2[i-16];lo2=t1_lo+w7[1]+t2_lo+w16[1];w2[i][0]=t1_hi+w7[0]+t2_hi+w16[0]+(lo2/4294967296>>>0)>>>0;w2[i][1]=lo2>>>0}a_hi=s3[0][0];a_lo=s3[0][1];b_hi=s3[1][0];b_lo=s3[1][1];c_hi=s3[2][0];c_lo=s3[2][1];d_hi=s3[3][0];d_lo=s3[3][1];e_hi=s3[4][0];e_lo=s3[4][1];f_hi=s3[5][0];f_lo=s3[5][1];g_hi=s3[6][0];g_lo=s3[6][1];h_hi=s3[7][0];h_lo=s3[7][1];for(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;s1_lo=((e_hi<<18|e_lo>>>14)^(e_hi<<14|e_lo>>>18)^(e_lo<<23|e_hi>>>9))>>>0;ch_hi=(g_hi^e_hi&(f_hi^g_hi))>>>0;ch_lo=(g_lo^e_lo&(f_lo^g_lo))>>>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;lo2=h_lo+s1_lo+ch_lo+_k[i][1]+w2[i][1];t1_hi=h_hi+s1_hi+ch_hi+_k[i][0]+w2[i][0]+(lo2/4294967296>>>0)>>>0;t1_lo=lo2>>>0;lo2=s0_lo+maj_lo;t2_hi=s0_hi+maj_hi+(lo2/4294967296>>>0)>>>0;t2_lo=lo2>>>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;lo2=d_lo+t1_lo;e_hi=d_hi+t1_hi+(lo2/4294967296>>>0)>>>0;e_lo=lo2>>>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;lo2=t1_lo+t2_lo;a_hi=t1_hi+t2_hi+(lo2/4294967296>>>0)>>>0;a_lo=lo2>>>0}lo2=s3[0][1]+a_lo;s3[0][0]=s3[0][0]+a_hi+(lo2/4294967296>>>0)>>>0;s3[0][1]=lo2>>>0;lo2=s3[1][1]+b_lo;s3[1][0]=s3[1][0]+b_hi+(lo2/4294967296>>>0)>>>0;s3[1][1]=lo2>>>0;lo2=s3[2][1]+c_lo;s3[2][0]=s3[2][0]+c_hi+(lo2/4294967296>>>0)>>>0;s3[2][1]=lo2>>>0;lo2=s3[3][1]+d_lo;s3[3][0]=s3[3][0]+d_hi+(lo2/4294967296>>>0)>>>0;s3[3][1]=lo2>>>0;lo2=s3[4][1]+e_lo;s3[4][0]=s3[4][0]+e_hi+(lo2/4294967296>>>0)>>>0;s3[4][1]=lo2>>>0;lo2=s3[5][1]+f_lo;s3[5][0]=s3[5][0]+f_hi+(lo2/4294967296>>>0)>>>0;s3[5][1]=lo2>>>0;lo2=s3[6][1]+g_lo;s3[6][0]=s3[6][0]+g_hi+(lo2/4294967296>>>0)>>>0;s3[6][1]=lo2>>>0;lo2=s3[7][1]+h_lo;s3[7][0]=s3[7][0]+h_hi+(lo2/4294967296>>>0)>>>0;s3[7][1]=lo2>>>0;len-=128}}}});var require_asn1_validator=__commonJS({"node_modules/node-forge/lib/asn1-validator.js"(exports){"use strict";var forge2=require_forge();require_asn1();var asn1=forge2.asn1;exports.privateKeyValidator={name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"PrivateKeyInfo.version",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.INTEGER,constructed:false,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OCTETSTRING,constructed:false,capture:"privateKey"}]};exports.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.SEQUENCE,constructed:true,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.OID,constructed:false,capture:"publicKeyOid"}]},{tagClass:asn1.Class.UNIVERSAL,type:asn1.Type.BITSTRING,constructed:false,composed:true,captureBitStringValue:"ed25519PublicKey"}]}}});var require_ed25519=__commonJS({"node_modules/node-forge/lib/ed25519.js"(exports,module){"use strict";var forge2=require_forge();require_jsbn();require_random();require_sha512();require_util7();var asn1Validator=require_asn1_validator();var publicKeyValidator=asn1Validator.publicKeyValidator;var privateKeyValidator=asn1Validator.privateKeyValidator;if(typeof BigInteger==="undefined"){BigInteger=forge2.jsbn.BigInteger}var BigInteger;var ByteBuffer=forge2.util.ByteBuffer;var NativeBuffer=typeof Buffer==="undefined"?Uint8Array:Buffer;forge2.pki=forge2.pki||{};module.exports=forge2.pki.ed25519=forge2.ed25519=forge2.ed25519||{};var ed25519=forge2.ed25519;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){options=options||{};var seed=options.seed;if(seed===void 0){seed=forge2.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH)}else if(typeof seed==="string"){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"});var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);var sk=new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i){sk[i]=seed[i]}crypto_sign_keypair(pk,sk);return{publicKey:pk,privateKey:sk}};ed25519.privateKeyFromAsn1=function(obj){var capture2={};var errors=[];var valid=forge2.asn1.validate(obj,privateKeyValidator,capture2,errors);if(!valid){var error=new Error("Invalid Key.");error.errors=errors;throw error}var oid=forge2.asn1.derToOid(capture2.privateKeyOid);var ed25519Oid=forge2.oids.EdDSA25519;if(oid!==ed25519Oid){throw new Error('Invalid OID "'+oid+'"; OID must be "'+ed25519Oid+'".')}var privateKey=capture2.privateKey;var privateKeyBytes=messageToNativeBuffer({message:forge2.asn1.fromDer(privateKey).value,encoding:"binary"});return{privateKeyBytes}};ed25519.publicKeyFromAsn1=function(obj){var capture2={};var errors=[];var valid=forge2.asn1.validate(obj,publicKeyValidator,capture2,errors);if(!valid){var error=new Error("Invalid Key.");error.errors=errors;throw error}var oid=forge2.asn1.derToOid(capture2.publicKeyOid);var ed25519Oid=forge2.oids.EdDSA25519;if(oid!==ed25519Oid){throw new Error('Invalid OID "'+oid+'"; OID must be "'+ed25519Oid+'".')}var publicKeyBytes=capture2.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){options=options||{};var privateKey=messageToNativeBuffer({message: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)}var pk=new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);for(var i=0;i<pk.length;++i){pk[i]=privateKey[32+i]}return pk};ed25519.sign=function(options){options=options||{};var msg=messageToNativeBuffer(options);var privateKey=messageToNativeBuffer({message:options.privateKey,encoding:"binary"});if(privateKey.length===ed25519.constants.SEED_BYTE_LENGTH){var keyPair=ed25519.generateKeyPair({seed:privateKey});privateKey=keyPair.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);crypto_sign(signedMsg,msg,msg.length,privateKey);var sig=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);for(var i=0;i<sig.length;++i){sig[i]=signedMsg[i]}return sig};ed25519.verify=function(options){options=options||{};var msg=messageToNativeBuffer(options);if(options.signature===void 0){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 sm=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH+msg.length);var m2=new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH+msg.length);var i;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 crypto_sign_open(m2,sm,sm.length,publicKey)>=0};function messageToNativeBuffer(options){var message=options.message;if(message instanceof Uint8Array||message instanceof NativeBuffer){return message}var encoding=options.encoding;if(message===void 0){if(options.md){message=options.md.digest().getBytes();encoding="binary"}else{throw new TypeError('"options.message" or "options.md" not specified.')}}if(typeof message==="string"&&!encoding){throw new TypeError('"options.encoding" must be "binary" or "utf8".')}if(typeof message==="string"){if(typeof Buffer!=="undefined"){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.')}var buffer=new NativeBuffer(message.length());for(var i=0;i<buffer.length;++i){buffer[i]=message.at(i)}return buffer}var gf0=gf();var gf1=gf([1]);var D=gf([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]);var D2=gf([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]);var X2=gf([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]);var Y2=gf([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]);var L2=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]);var I2=gf([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function sha512(msg,msgLen){var md=forge2.md.sha512.create();var buffer=new ByteBuffer(msg);md.update(buffer.getBytes(msgLen),"binary");var hash=md.digest().getBytes();if(typeof Buffer!=="undefined"){return Buffer.from(hash,"binary")}var out=new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);for(var i=0;i<64;++i){out[i]=hash.charCodeAt(i)}return out}function crypto_sign_keypair(pk,sk){var p2=[gf(),gf(),gf(),gf()];var i;var d=sha512(sk,32);d[0]&=248;d[31]&=127;d[31]|=64;scalarbase(p2,d);pack(pk,p2);for(i=0;i<32;++i){sk[i+32]=pk[i]}return 0}function crypto_sign(sm,m2,n,sk){var i,j2,x=new Float64Array(64);var p2=[gf(),gf(),gf(),gf()];var 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]=m2[i]}for(i=0;i<32;++i){sm[32+i]=d[32+i]}var r=sha512(sm.subarray(32),n+32);reduce(r);scalarbase(p2,r);pack(sm,p2);for(i=32;i<64;++i){sm[i]=sk[i]}var h=sha512(sm,n+64);reduce(h);for(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(j2=0;j2<32;j2++){x[i+j2]+=h[i]*d[j2]}}modL(sm.subarray(32),x);return smlen}function crypto_sign_open(m2,sm,n,pk){var i,mlen;var t=new NativeBuffer(32);var p2=[gf(),gf(),gf(),gf()],q2=[gf(),gf(),gf(),gf()];mlen=-1;if(n<64){return-1}if(unpackneg(q2,pk)){return-1}if(!_isCanonicalSignatureScalar(sm,32)){return-1}for(i=0;i<n;++i){m2[i]=sm[i]}for(i=0;i<32;++i){m2[i+32]=pk[i]}var h=sha512(m2,n);reduce(h);scalarmult(p2,q2,h);scalarbase(q2,sm.subarray(32));add(p2,q2);pack(t,p2);n-=64;if(crypto_verify_32(sm,0,t,0)){for(i=0;i<n;++i){m2[i]=0}return-1}for(i=0;i<n;++i){m2[i]=sm[i+64]}mlen=n;return mlen}function _isCanonicalSignatureScalar(bytes,offset){var i;for(i=31;i>=0;--i){if(bytes[offset+i]<L2[i]){return true}if(bytes[offset+i]>L2[i]){return false}}return false}function modL(r,x){var carry,i,j2,k2;for(i=63;i>=32;--i){carry=0;for(j2=i-32,k2=i-12;j2<k2;++j2){x[j2]+=carry-16*x[i]*L2[j2-(i-32)];carry=x[j2]+128>>8;x[j2]-=carry*256}x[j2]+=carry;x[i]=0}carry=0;for(j2=0;j2<32;++j2){x[j2]+=carry-(x[31]>>4)*L2[j2];carry=x[j2]>>8;x[j2]&=255}for(j2=0;j2<32;++j2){x[j2]-=carry*L2[j2]}for(i=0;i<32;++i){x[i+1]+=x[i]>>8;r[i]=x[i]&255}}function reduce(r){var x=new Float64Array(64);for(var i=0;i<64;++i){x[i]=r[i];r[i]=0}modL(r,x)}function add(p2,q2){var a=gf(),b2=gf(),c=gf(),d=gf(),e=gf(),f2=gf(),g2=gf(),h=gf(),t=gf();Z2(a,p2[1],p2[0]);Z2(t,q2[1],q2[0]);M2(a,a,t);A2(b2,p2[0],p2[1]);A2(t,q2[0],q2[1]);M2(b2,b2,t);M2(c,p2[3],q2[3]);M2(c,c,D2);M2(d,p2[2],q2[2]);A2(d,d,d);Z2(e,b2,a);Z2(f2,d,c);A2(g2,d,c);A2(h,b2,a);M2(p2[0],e,f2);M2(p2[1],h,g2);M2(p2[2],g2,f2);M2(p2[3],e,h)}function cswap(p2,q2,b2){for(var i=0;i<4;++i){sel25519(p2[i],q2[i],b2)}}function pack(r,p2){var tx=gf(),ty=gf(),zi2=gf();inv25519(zi2,p2[2]);M2(tx,p2[0],zi2);M2(ty,p2[1],zi2);pack25519(r,ty);r[31]^=par25519(tx)<<7}function pack25519(o,n){var i,j2,b2;var m2=gf(),t=gf();for(i=0;i<16;++i){t[i]=n[i]}car25519(t);car25519(t);car25519(t);for(j2=0;j2<2;++j2){m2[0]=t[0]-65517;for(i=1;i<15;++i){m2[i]=t[i]-65535-(m2[i-1]>>16&1);m2[i-1]&=65535}m2[15]=t[15]-32767-(m2[14]>>16&1);b2=m2[15]>>16&1;m2[14]&=65535;sel25519(t,m2,1-b2)}for(i=0;i<16;i++){o[2*i]=t[i]&255;o[2*i+1]=t[i]>>8}}function unpackneg(r,p2){var t=gf(),chk=gf(),num=gf(),den=gf(),den2=gf(),den4=gf(),den6=gf();set25519(r[2],gf1);unpack25519(r[1],p2);S2(num,r[1]);M2(den,num,D);Z2(num,num,r[2]);A2(den,r[2],den);S2(den2,den);S2(den4,den2);M2(den6,den4,den2);M2(t,den6,num);M2(t,t,den);pow2523(t,t);M2(t,t,num);M2(t,t,den);M2(t,t,den);M2(r[0],t,den);S2(chk,r[0]);M2(chk,chk,den);if(neq25519(chk,num)){M2(r[0],r[0],I2)}S2(chk,r[0]);M2(chk,chk,den);if(neq25519(chk,num)){return-1}if(par25519(r[0])===p2[31]>>7){Z2(r[0],gf0,r[0])}M2(r[3],r[0],r[1]);return 0}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}function pow2523(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=250;a>=0;--a){S2(c,c);if(a!==1){M2(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function neq25519(a,b2){var c=new NativeBuffer(32);var d=new NativeBuffer(32);pack25519(c,a);pack25519(d,b2);return crypto_verify_32(c,0,d,0)}function crypto_verify_32(x,xi2,y,yi2){return vn2(x,xi2,y,yi2,32)}function vn2(x,xi2,y,yi2,n){var i,d=0;for(i=0;i<n;++i){d|=x[xi2+i]^y[yi2+i]}return(1&d-1>>>8)-1}function par25519(a){var d=new NativeBuffer(32);pack25519(d,a);return d[0]&1}function scalarmult(p2,q2,s3){var b2,i;set25519(p2[0],gf0);set25519(p2[1],gf1);set25519(p2[2],gf1);set25519(p2[3],gf0);for(i=255;i>=0;--i){b2=s3[i/8|0]>>(i&7)&1;cswap(p2,q2,b2);add(q2,p2);add(p2,p2);cswap(p2,q2,b2)}}function scalarbase(p2,s3){var q2=[gf(),gf(),gf(),gf()];set25519(q2[0],X2);set25519(q2[1],Y2);set25519(q2[2],gf1);M2(q2[3],X2,Y2);scalarmult(p2,q2,s3)}function set25519(r,a){var i;for(i=0;i<16;i++){r[i]=a[i]|0}}function inv25519(o,i){var c=gf();var a;for(a=0;a<16;++a){c[a]=i[a]}for(a=253;a>=0;--a){S2(c,c);if(a!==2&&a!==4){M2(c,c,i)}}for(a=0;a<16;++a){o[a]=c[a]}}function car25519(o){var i,v2,c=1;for(i=0;i<16;++i){v2=o[i]+c+65535;c=Math.floor(v2/65536);o[i]=v2-c*65536}o[0]+=c-1+37*(c-1)}function sel25519(p2,q2,b2){var t,c=~(b2-1);for(var i=0;i<16;++i){t=c&(p2[i]^q2[i]);p2[i]^=t;q2[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 A2(o,a,b2){for(var i=0;i<16;++i){o[i]=a[i]+b2[i]}}function Z2(o,a,b2){for(var i=0;i<16;++i){o[i]=a[i]-b2[i]}}function S2(o,a){M2(o,a,a)}function M2(o,a,b2){var v2,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=b2[0],b1=b2[1],b22=b2[2],b3=b2[3],b4=b2[4],b5=b2[5],b6=b2[6],b7=b2[7],b8=b2[8],b9=b2[9],b10=b2[10],b11=b2[11],b12=b2[12],b13=b2[13],b14=b2[14],b15=b2[15];v2=a[0];t0+=v2*b0;t1+=v2*b1;t2+=v2*b22;t3+=v2*b3;t4+=v2*b4;t5+=v2*b5;t6+=v2*b6;t7+=v2*b7;t8+=v2*b8;t9+=v2*b9;t10+=v2*b10;t11+=v2*b11;t12+=v2*b12;t13+=v2*b13;t14+=v2*b14;t15+=v2*b15;v2=a[1];t1+=v2*b0;t2+=v2*b1;t3+=v2*b22;t4+=v2*b3;t5+=v2*b4;t6+=v2*b5;t7+=v2*b6;t8+=v2*b7;t9+=v2*b8;t10+=v2*b9;t11+=v2*b10;t12+=v2*b11;t13+=v2*b12;t14+=v2*b13;t15+=v2*b14;t16+=v2*b15;v2=a[2];t2+=v2*b0;t3+=v2*b1;t4+=v2*b22;t5+=v2*b3;t6+=v2*b4;t7+=v2*b5;t8+=v2*b6;t9+=v2*b7;t10+=v2*b8;t11+=v2*b9;t12+=v2*b10;t13+=v2*b11;t14+=v2*b12;t15+=v2*b13;t16+=v2*b14;t17+=v2*b15;v2=a[3];t3+=v2*b0;t4+=v2*b1;t5+=v2*b22;t6+=v2*b3;t7+=v2*b4;t8+=v2*b5;t9+=v2*b6;t10+=v2*b7;t11+=v2*b8;t12+=v2*b9;t13+=v2*b10;t14+=v2*b11;t15+=v2*b12;t16+=v2*b13;t17+=v2*b14;t18+=v2*b15;v2=a[4];t4+=v2*b0;t5+=v2*b1;t6+=v2*b22;t7+=v2*b3;t8+=v2*b4;t9+=v2*b5;t10+=v2*b6;t11+=v2*b7;t12+=v2*b8;t13+=v2*b9;t14+=v2*b10;t15+=v2*b11;t16+=v2*b12;t17+=v2*b13;t18+=v2*b14;t19+=v2*b15;v2=a[5];t5+=v2*b0;t6+=v2*b1;t7+=v2*b22;t8+=v2*b3;t9+=v2*b4;t10+=v2*b5;t11+=v2*b6;t12+=v2*b7;t13+=v2*b8;t14+=v2*b9;t15+=v2*b10;t16+=v2*b11;t17+=v2*b12;t18+=v2*b13;t19+=v2*b14;t20+=v2*b15;v2=a[6];t6+=v2*b0;t7+=v2*b1;t8+=v2*b22;t9+=v2*b3;t10+=v2*b4;t11+=v2*b5;t12+=v2*b6;t13+=v2*b7;t14+=v2*b8;t15+=v2*b9;t16+=v2*b10;t17+=v2*b11;t18+=v2*b12;t19+=v2*b13;t20+=v2*b14;t21+=v2*b15;v2=a[7];t7+=v2*b0;t8+=v2*b1;t9+=v2*b22;t10+=v2*b3;t11+=v2*b4;t12+=v2*b5;t13+=v2*b6;t14+=v2*b7;t15+=v2*b8;t16+=v2*b9;t17+=v2*b10;t18+=v2*b11;t19+=v2*b12;t20+=v2*b13;t21+=v2*b14;t22+=v2*b15;v2=a[8];t8+=v2*b0;t9+=v2*b1;t10+=v2*b22;t11+=v2*b3;t12+=v2*b4;t13+=v2*b5;t14+=v2*b6;t15+=v2*b7;t16+=v2*b8;t17+=v2*b9;t18+=v2*b10;t19+=v2*b11;t20+=v2*b12;t21+=v2*b13;t22+=v2*b14;t23+=v2*b15;v2=a[9];t9+=v2*b0;t10+=v2*b1;t11+=v2*b22;t12+=v2*b3;t13+=v2*b4;t14+=v2*b5;t15+=v2*b6;t16+=v2*b7;t17+=v2*b8;t18+=v2*b9;t19+=v2*b10;t20+=v2*b11;t21+=v2*b12;t22+=v2*b13;t23+=v2*b14;t24+=v2*b15;v2=a[10];t10+=v2*b0;t11+=v2*b1;t12+=v2*b22;t13+=v2*b3;t14+=v2*b4;t15+=v2*b5;t16+=v2*b6;t17+=v2*b7;t18+=v2*b8;t19+=v2*b9;t20+=v2*b10;t21+=v2*b11;t22+=v2*b12;t23+=v2*b13;t24+=v2*b14;t25+=v2*b15;v2=a[11];t11+=v2*b0;t12+=v2*b1;t13+=v2*b22;t14+=v2*b3;t15+=v2*b4;t16+=v2*b5;t17+=v2*b6;t18+=v2*b7;t19+=v2*b8;t20+=v2*b9;t21+=v2*b10;t22+=v2*b11;t23+=v2*b12;t24+=v2*b13;t25+=v2*b14;t26+=v2*b15;v2=a[12];t12+=v2*b0;t13+=v2*b1;t14+=v2*b22;t15+=v2*b3;t16+=v2*b4;t17+=v2*b5;t18+=v2*b6;t19+=v2*b7;t20+=v2*b8;t21+=v2*b9;t22+=v2*b10;t23+=v2*b11;t24+=v2*b12;t25+=v2*b13;t26+=v2*b14;t27+=v2*b15;v2=a[13];t13+=v2*b0;t14+=v2*b1;t15+=v2*b22;t16+=v2*b3;t17+=v2*b4;t18+=v2*b5;t19+=v2*b6;t20+=v2*b7;t21+=v2*b8;t22+=v2*b9;t23+=v2*b10;t24+=v2*b11;t25+=v2*b12;t26+=v2*b13;t27+=v2*b14;t28+=v2*b15;v2=a[14];t14+=v2*b0;t15+=v2*b1;t16+=v2*b22;t17+=v2*b3;t18+=v2*b4;t19+=v2*b5;t20+=v2*b6;t21+=v2*b7;t22+=v2*b8;t23+=v2*b9;t24+=v2*b10;t25+=v2*b11;t26+=v2*b12;t27+=v2*b13;t28+=v2*b14;t29+=v2*b15;v2=a[15];t15+=v2*b0;t16+=v2*b1;t17+=v2*b22;t18+=v2*b3;t19+=v2*b4;t20+=v2*b5;t21+=v2*b6;t22+=v2*b7;t23+=v2*b8;t24+=v2*b9;t25+=v2*b10;t26+=v2*b11;t27+=v2*b12;t28+=v2*b13;t29+=v2*b14;t30+=v2*b15;t0+=38*t16;t1+=38*t17;t2+=38*t18;t3+=38*t19;t4+=38*t20;t5+=38*t21;t6+=38*t22;t7+=38*t23;t8+=38*t24;t9+=38*t25;t10+=38*t26;t11+=38*t27;t12+=38*t28;t13+=38*t29;t14+=38*t30;c=1;v2=t0+c+65535;c=Math.floor(v2/65536);t0=v2-c*65536;v2=t1+c+65535;c=Math.floor(v2/65536);t1=v2-c*65536;v2=t2+c+65535;c=Math.floor(v2/65536);t2=v2-c*65536;v2=t3+c+65535;c=Math.floor(v2/65536);t3=v2-c*65536;v2=t4+c+65535;c=Math.floor(v2/65536);t4=v2-c*65536;v2=t5+c+65535;c=Math.floor(v2/65536);t5=v2-c*65536;v2=t6+c+65535;c=Math.floor(v2/65536);t6=v2-c*65536;v2=t7+c+65535;c=Math.floor(v2/65536);t7=v2-c*65536;v2=t8+c+65535;c=Math.floor(v2/65536);t8=v2-c*65536;v2=t9+c+65535;c=Math.floor(v2/65536);t9=v2-c*65536;v2=t10+c+65535;c=Math.floor(v2/65536);t10=v2-c*65536;v2=t11+c+65535;c=Math.floor(v2/65536);t11=v2-c*65536;v2=t12+c+65535;c=Math.floor(v2/65536);t12=v2-c*65536;v2=t13+c+65535;c=Math.floor(v2/65536);t13=v2-c*65536;v2=t14+c+65535;c=Math.floor(v2/65536);t14=v2-c*65536;v2=t15+c+65535;c=Math.floor(v2/65536);t15=v2-c*65536;t0+=c-1+37*(c-1);c=1;v2=t0+c+65535;c=Math.floor(v2/65536);t0=v2-c*65536;v2=t1+c+65535;c=Math.floor(v2/65536);t1=v2-c*65536;v2=t2+c+65535;c=Math.floor(v2/65536);t2=v2-c*65536;v2=t3+c+65535;c=Math.floor(v2/65536);t3=v2-c*65536;v2=t4+c+65535;c=Math.floor(v2/65536);t4=v2-c*65536;v2=t5+c+65535;c=Math.floor(v2/65536);t5=v2-c*65536;v2=t6+c+65535;c=Math.floor(v2/65536);t6=v2-c*65536;v2=t7+c+65535;c=Math.floor(v2/65536);t7=v2-c*65536;v2=t8+c+65535;c=Math.floor(v2/65536);t8=v2-c*65536;v2=t9+c+65535;c=Math.floor(v2/65536);t9=v2-c*65536;v2=t10+c+65535;c=Math.floor(v2/65536);t10=v2-c*65536;v2=t11+c+65535;c=Math.floor(v2/65536);t11=v2-c*65536;v2=t12+c+65535;c=Math.floor(v2/65536);t12=v2-c*65536;v2=t13+c+65535;c=Math.floor(v2/65536);t13=v2-c*65536;v2=t14+c+65535;c=Math.floor(v2/65536);t14=v2-c*65536;v2=t15+c+65535;c=Math.floor(v2/65536);t15=v2-c*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}}});var require_kem=__commonJS({"node_modules/node-forge/lib/kem.js"(exports,module){"use strict";var forge2=require_forge();require_util7();require_random();require_jsbn();module.exports=forge2.kem=forge2.kem||{};var BigInteger=forge2.jsbn.BigInteger;forge2.kem.rsa={};forge2.kem.rsa.create=function(kdf,options){options=options||{};var prng=options.prng||forge2.random;var kem={};kem.encrypt=function(publicKey,keyLength){var byteLength=Math.ceil(publicKey.n.bitLength()/8);var r;do{r=new BigInteger(forge2.util.bytesToHex(prng.getBytesSync(byteLength)),16).mod(publicKey.n)}while(r.compareTo(BigInteger.ONE)<=0);r=forge2.util.hexToBytes(r.toString(16));var zeros=byteLength-r.length;if(zeros>0){r=forge2.util.fillString(String.fromCharCode(0),zeros)+r}var encapsulation=publicKey.encrypt(r,"NONE");var key=kdf.generate(r,keyLength);return{encapsulation,key}};kem.decrypt=function(privateKey,encapsulation,keyLength){var r=privateKey.decrypt(encapsulation,"NONE");return kdf.generate(r,keyLength)};return kem};forge2.kem.kdf1=function(md,digestLength){_createKDF(this,md,0,digestLength||md.digestLength)};forge2.kem.kdf2=function(md,digestLength){_createKDF(this,md,1,digestLength||md.digestLength)};function _createKDF(kdf,md,counterStart,digestLength){kdf.generate=function(x,length){var key=new forge2.util.ByteBuffer;var k2=Math.ceil(length/digestLength)+counterStart;var c=new forge2.util.ByteBuffer;for(var i=counterStart;i<k2;++i){c.putInt32(i);md.start();md.update(x+c.getBytes());var hash=md.digest();key.putBytes(hash.getBytes(digestLength))}key.truncate(key.length()-length);return key.getBytes()}}}});var require_log=__commonJS({"node_modules/node-forge/lib/log.js"(exports,module){"use strict";var forge2=require_forge();require_util7();module.exports=forge2.log=forge2.log||{};forge2.log.levels=["none","error","warning","info","debug","verbose","max"];var sLevelInfo={};var sLoggers=[];var sConsoleLogger=null;forge2.log.LEVEL_LOCKED=1<<1;forge2.log.NO_LEVEL_CHECK=1<<2;forge2.log.INTERPOLATE=1<<3;for(i=0;i<forge2.log.levels.length;++i){level=forge2.log.levels[i];sLevelInfo[level]={index:i,name:level.toUpperCase()}}var level;var i;forge2.log.logMessage=function(message){var messageLevelIndex=sLevelInfo[message.level].index;for(var i2=0;i2<sLoggers.length;++i2){var logger2=sLoggers[i2];if(logger2.flags&forge2.log.NO_LEVEL_CHECK){logger2.f(message)}else{var loggerLevelIndex=sLevelInfo[logger2.level].index;if(messageLevelIndex<=loggerLevelIndex){logger2.f(logger2,message)}}}};forge2.log.prepareStandard=function(message){if(!("standard"in message)){message.standard=sLevelInfo[message.level].name+" ["+message.category+"] "+message.message}};forge2.log.prepareFull=function(message){if(!("full"in message)){var args=[message.message];args=args.concat([]);message.full=forge2.util.format.apply(this,args)}};forge2.log.prepareStandardFull=function(message){if(!("standardFull"in message)){forge2.log.prepareStandard(message);message.standardFull=message.standard}};if(true){levels=["error","warning","info","debug","verbose"];for(i=0;i<levels.length;++i){(function(level2){forge2.log[level2]=function(category,message){var args=Array.prototype.slice.call(arguments).slice(2);var msg={timestamp:new Date,level:level2,category,message,"arguments":args};forge2.log.logMessage(msg)}})(levels[i])}}var levels;var i;forge2.log.makeLogger=function(logFunction){var logger2={flags:0,f:logFunction};forge2.log.setLevel(logger2,"none");return logger2};forge2.log.setLevel=function(logger2,level2){var rval=false;if(logger2&&!(logger2.flags&forge2.log.LEVEL_LOCKED)){for(var i2=0;i2<forge2.log.levels.length;++i2){var aValidLevel=forge2.log.levels[i2];if(level2==aValidLevel){logger2.level=level2;rval=true;break}}}return rval};forge2.log.lock=function(logger2,lock2){if(typeof lock2==="undefined"||lock2){logger2.flags|=forge2.log.LEVEL_LOCKED}else{logger2.flags&=~forge2.log.LEVEL_LOCKED}};forge2.log.addLogger=function(logger2){sLoggers.push(logger2)};if(typeof console!=="undefined"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug){levelHandlers={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug};f2=function(logger2,message){forge2.log.prepareStandard(message);var handler=levelHandlers[message.level];var args=[message.standard];args=args.concat(message["arguments"].slice());handler.apply(console,args)};logger=forge2.log.makeLogger(f2)}else{f2=function(logger2,message){forge2.log.prepareStandardFull(message);console.log(message.standardFull)};logger=forge2.log.makeLogger(f2)}forge2.log.setLevel(logger,"debug");forge2.log.addLogger(logger);sConsoleLogger=logger}else{console={log:function(){}}}var logger;var levelHandlers;var f2;if(sConsoleLogger!==null&&typeof window!=="undefined"&&window.location){query=new URL(window.location.href).searchParams;if(query.has("console.level")){forge2.log.setLevel(sConsoleLogger,query.get("console.level").slice(-1)[0])}if(query.has("console.lock")){lock=query.get("console.lock").slice(-1)[0];if(lock=="true"){forge2.log.lock(sConsoleLogger)}}}var query;var lock;forge2.log.consoleLogger=sConsoleLogger}});var require_md_all=__commonJS({"node_modules/node-forge/lib/md.all.js"(exports,module){"use strict";module.exports=require_md();require_md5();require_sha1();require_sha256();require_sha512()}});var require_pkcs7=__commonJS({"node_modules/node-forge/lib/pkcs7.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_asn1();require_des();require_oids();require_pem();require_pkcs7asn1();require_random();require_util7();require_x509();var asn1=forge2.asn1;var p7=module.exports=forge2.pkcs7=forge2.pkcs7||{};p7.messageFromPem=function(pem){var msg=forge2.pem.decode(pem)[0];if(msg.type!=="PKCS7"){var error=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');error.headerType=msg.type;throw error}if(msg.procType&&msg.procType.type==="ENCRYPTED"){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 forge2.pem.encode(pemObj,{maxline})};p7.messageFromAsn1=function(obj){var capture2={};var errors=[];if(!asn1.validate(obj,p7.asn1.contentInfoValidator,capture2,errors)){var error=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");error.errors=errors;throw error}var contentType=asn1.derToOid(capture2.contentType);var msg;switch(contentType){case forge2.pki.oids.envelopedData:msg=p7.createEnvelopedData();break;case forge2.pki.oids.encryptedData:msg=p7.createEncryptedData();break;case forge2.pki.oids.signedData:msg=p7.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+contentType+" is not (yet) supported.")}msg.fromAsn1(capture2.content.value[0]);return msg};p7.createSignedData=function(){var msg=null;msg={type:forge2.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(obj){_fromAsn1(msg,obj,p7.asn1.signedDataValidator);msg.certificates=[];msg.crls=[];msg.digestAlgorithmIdentifiers=[];msg.contentInfo=null;msg.signerInfos=[];if(msg.rawCapture.certificates){var certs=msg.rawCapture.certificates.value;for(var i=0;i<certs.length;++i){msg.certificates.push(forge2.pki.certificateFromAsn1(certs[i]))}}},toAsn1:function(){if(!msg.contentInfo){msg.sign()}var certs=[];for(var i=0;i<msg.certificates.length;++i){certs.push(forge2.pki.certificateToAsn1(msg.certificates[i]))}var crls=[];var signedData=asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(msg.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,msg.digestAlgorithmIdentifiers),msg.contentInfo])]);if(certs.length>0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,certs))}if(crls.length>0){signedData.value[0].value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,crls))}signedData.value[0].value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,msg.signerInfos));return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(msg.type).getBytes()),signedData])},addSigner:function(signer){var issuer=signer.issuer;var serialNumber=signer.serialNumber;if(signer.certificate){var cert=signer.certificate;if(typeof cert==="string"){cert=forge2.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.")}if(typeof key==="string"){key=forge2.pki.privateKeyFromPem(key)}var digestAlgorithm=signer.digestAlgorithm||forge2.pki.oids.sha1;switch(digestAlgorithm){case forge2.pki.oids.sha1:case forge2.pki.oids.sha256:case forge2.pki.oids.sha384:case forge2.pki.oids.sha512:case forge2.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){var contentType=false;var messageDigest=false;for(var i=0;i<authenticatedAttributes.length;++i){var attr=authenticatedAttributes[i];if(!contentType&&attr.type===forge2.pki.oids.contentType){contentType=true;if(messageDigest){break}continue}if(!messageDigest&&attr.type===forge2.pki.oids.messageDigest){messageDigest=true;if(contentType){break}continue}}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,version:1,issuer,serialNumber,digestAlgorithm,signatureAlgorithm:forge2.pki.oids.rsaEncryption,signature:null,authenticatedAttributes,unauthenticatedAttributes:[]})},sign:function(options){options=options||{};if(typeof msg.content!=="object"||msg.contentInfo===null){msg.contentInfo=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(forge2.pki.oids.data).getBytes())]);if("content"in msg){var content;if(msg.content instanceof forge2.util.ByteBuffer){content=msg.content.bytes()}else if(typeof msg.content==="string"){content=forge2.util.encodeUtf8(msg.content)}if(options.detached){msg.detachedContent=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,content)}else{msg.contentInfo.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,content)]))}}}if(msg.signers.length===0){return}var mds=addDigestAlgorithmIds();addSignerInfos(mds)},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(cert){if(typeof cert==="string"){cert=forge2.pki.certificateFromPem(cert)}msg.certificates.push(cert)},addCertificateRevokationList:function(crl){throw new Error("PKCS#7 CRL support not yet implemented.")}};return msg;function addDigestAlgorithmIds(){var mds={};for(var i=0;i<msg.signers.length;++i){var signer=msg.signers[i];var oid=signer.digestAlgorithm;if(!(oid in mds)){mds[oid]=forge2.md[forge2.pki.oids[oid]].create()}if(signer.authenticatedAttributes.length===0){signer.md=mds[oid]}else{signer.md=forge2.md[forge2.pki.oids[oid]].create()}}msg.digestAlgorithmIdentifiers=[];for(var oid in mds){msg.digestAlgorithmIdentifiers.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(oid).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]))}return mds}function addSignerInfos(mds){var content;if(msg.detachedContent){content=msg.detachedContent}else{content=msg.contentInfo.value[1];content=content.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);var bytes=asn1.toDer(content);bytes.getByte();asn1.getBerValueLength(bytes);bytes=bytes.getBytes();for(var oid in mds){mds[oid].start().update(bytes)}var signingTime=new Date;for(var i=0;i<msg.signers.length;++i){var signer=msg.signers[i];if(signer.authenticatedAttributes.length===0){if(contentType!==forge2.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,true,[]);var attrsAsn1=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[]);for(var ai2=0;ai2<signer.authenticatedAttributes.length;++ai2){var attr=signer.authenticatedAttributes[ai2];if(attr.type===forge2.pki.oids.messageDigest){attr.value=mds[signer.digestAlgorithm].digest()}else if(attr.type===forge2.pki.oids.signingTime){if(!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=_signersToAsn1(msg.signers)}};p7.createEncryptedData=function(){var msg=null;msg={type:forge2.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:forge2.pki.oids["aes256-CBC"]},fromAsn1:function(obj){_fromAsn1(msg,obj,p7.asn1.encryptedDataValidator)},decrypt:function(key){if(key!==void 0){msg.encryptedContent.key=key}_decryptContent(msg)}};return msg};p7.createEnvelopedData=function(){var msg=null;msg={type:forge2.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:forge2.pki.oids["aes256-CBC"]},fromAsn1:function(obj){var capture2=_fromAsn1(msg,obj,p7.asn1.envelopedDataValidator);msg.recipients=_recipientsFromAsn1(capture2.recipientInfos.value)},toAsn1:function(){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(msg.type).getBytes()),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(msg.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,_recipientsToAsn1(msg.recipients)),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,_encryptedContentToAsn1(msg.encryptedContent))])])])},findRecipient:function(cert){var sAttr=cert.issuer.attributes;for(var i=0;i<msg.recipients.length;++i){var r=msg.recipients[i];var rAttr=r.issuer;if(r.serialNumber!==cert.serialNumber){continue}if(rAttr.length!==sAttr.length){continue}var match=true;for(var j2=0;j2<sAttr.length;++j2){if(rAttr[j2].type!==sAttr[j2].type||rAttr[j2].value!==sAttr[j2].value){match=false;break}}if(match){return r}}return null},decrypt:function(recipient,privKey){if(msg.encryptedContent.key===void 0&&recipient!==void 0&&privKey!==void 0){switch(recipient.encryptedContent.algorithm){case forge2.pki.oids.rsaEncryption:case forge2.pki.oids.desCBC:var key=privKey.decrypt(recipient.encryptedContent.content);msg.encryptedContent.key=forge2.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:forge2.pki.oids.rsaEncryption,key:cert.publicKey}})},encrypt:function(key,cipher){if(msg.encryptedContent.content===void 0){cipher=cipher||msg.encryptedContent.algorithm;key=key||msg.encryptedContent.key;var keyLen,ivLen,ciphFn;switch(cipher){case forge2.pki.oids["aes128-CBC"]:keyLen=16;ivLen=16;ciphFn=forge2.aes.createEncryptionCipher;break;case forge2.pki.oids["aes192-CBC"]:keyLen=24;ivLen=16;ciphFn=forge2.aes.createEncryptionCipher;break;case forge2.pki.oids["aes256-CBC"]:keyLen=32;ivLen=16;ciphFn=forge2.aes.createEncryptionCipher;break;case forge2.pki.oids["des-EDE3-CBC"]:keyLen=24;ivLen=8;ciphFn=forge2.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+cipher)}if(key===void 0){key=forge2.util.createBuffer(forge2.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=forge2.util.createBuffer(forge2.random.getBytes(ivLen));var ciph=ciphFn(key);ciph.start(msg.encryptedContent.parameter.copy());ciph.update(msg.content);if(!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(recipient.encryptedContent.content!==void 0){continue}switch(recipient.encryptedContent.algorithm){case forge2.pki.oids.rsaEncryption:recipient.encryptedContent.content=recipient.encryptedContent.key.encrypt(msg.encryptedContent.key.data);break;default:throw new Error("Unsupported asymmetric cipher, OID "+recipient.encryptedContent.algorithm)}}}};return msg};function _recipientFromAsn1(obj){var capture2={};var errors=[];if(!asn1.validate(obj,p7.asn1.recipientInfoValidator,capture2,errors)){var error=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");error.errors=errors;throw error}return{version:capture2.version.charCodeAt(0),issuer:forge2.pki.RDNAttributesAsArray(capture2.issuer),serialNumber:forge2.util.createBuffer(capture2.serial).toHex(),encryptedContent:{algorithm:asn1.derToOid(capture2.encAlgorithm),parameter:capture2.encParameter?capture2.encParameter.value:void 0,content:capture2.encKey}}}function _recipientToAsn1(obj){return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(obj.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[forge2.pki.distinguishedNameToAsn1({attributes:obj.issuer}),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(obj.serialNumber))]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,obj.encryptedContent.content)])}function _recipientsFromAsn1(infos){var ret=[];for(var i=0;i<infos.length;++i){ret.push(_recipientFromAsn1(infos[i]))}return ret}function _recipientsToAsn1(recipients){var ret=[];for(var 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,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,asn1.integerToDer(obj.version).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[forge2.pki.distinguishedNameToAsn1({attributes:obj.issuer}),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.INTEGER,false,forge2.util.hexToBytes(obj.serialNumber))]),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(obj.digestAlgorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")])]);if(obj.authenticatedAttributesAsn1){rval.value.push(obj.authenticatedAttributesAsn1)}rval.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(obj.signatureAlgorithm).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.NULL,false,"")]));rval.value.push(asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,obj.signature));if(obj.unauthenticatedAttributes.length>0){var attrsAsn1=asn1.create(asn1.Class.CONTEXT_SPECIFIC,1,true,[]);for(var i=0;i<obj.unauthenticatedAttributes.length;++i){var attr=obj.unauthenticatedAttributes[i];attrsAsn1.values.push(_attributeToAsn1(attr))}rval.value.push(attrsAsn1)}return rval}function _signersToAsn1(signers){var ret=[];for(var i=0;i<signers.length;++i){ret.push(_signerToAsn1(signers[i]))}return ret}function _attributeToAsn1(attr){var value;if(attr.type===forge2.pki.oids.contentType){value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.value).getBytes())}else if(attr.type===forge2.pki.oids.messageDigest){value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,attr.value.bytes())}else if(attr.type===forge2.pki.oids.signingTime){var jan_1_1950=new Date("1950-01-01T00:00:00Z");var jan_1_2050=new Date("2050-01-01T00:00:00Z");var date=attr.value;if(typeof date==="string"){var timestamp=Date.parse(date);if(!isNaN(timestamp)){date=new Date(timestamp)}else if(date.length===13){date=asn1.utcTimeToDate(date)}else{date=asn1.generalizedTimeToDate(date)}}if(date>=jan_1_1950&&date<jan_1_2050){value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.UTCTIME,false,asn1.dateToUtcTime(date))}else{value=asn1.create(asn1.Class.UNIVERSAL,asn1.Type.GENERALIZEDTIME,false,asn1.dateToGeneralizedTime(date))}}return asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(attr.type).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SET,true,[value])])}function _encryptedContentToAsn1(ec){return[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(forge2.pki.oids.data).getBytes()),asn1.create(asn1.Class.UNIVERSAL,asn1.Type.SEQUENCE,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OID,false,asn1.oidToDer(ec.algorithm).getBytes()),!ec.parameter?void 0:asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ec.parameter.getBytes())]),asn1.create(asn1.Class.CONTEXT_SPECIFIC,0,true,[asn1.create(asn1.Class.UNIVERSAL,asn1.Type.OCTETSTRING,false,ec.content.getBytes())])]}function _fromAsn1(msg,obj,validator){var capture2={};var errors=[];if(!asn1.validate(obj,validator,capture2,errors)){var error=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");error.errors=error;throw error}var contentType=asn1.derToOid(capture2.contentType);if(contentType!==forge2.pki.oids.data){throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.")}if(capture2.encryptedContent){var content="";if(forge2.util.isArray(capture2.encryptedContent)){for(var i=0;i<capture2.encryptedContent.length;++i){if(capture2.encryptedContent[i].type!==asn1.Type.OCTETSTRING){throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.")}content+=capture2.encryptedContent[i].value}}else{content=capture2.encryptedContent}msg.encryptedContent={algorithm:asn1.derToOid(capture2.encAlgorithm),parameter:forge2.util.createBuffer(capture2.encParameter.value),content:forge2.util.createBuffer(content)}}if(capture2.content){var content="";if(forge2.util.isArray(capture2.content)){for(var i=0;i<capture2.content.length;++i){if(capture2.content[i].type!==asn1.Type.OCTETSTRING){throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.")}content+=capture2.content[i].value}}else{content=capture2.content}msg.content=forge2.util.createBuffer(content)}msg.version=capture2.version.charCodeAt(0);msg.rawCapture=capture2;return capture2}function _decryptContent(msg){if(msg.encryptedContent.key===void 0){throw new Error("Symmetric key not available.")}if(msg.content===void 0){var ciph;switch(msg.encryptedContent.algorithm){case forge2.pki.oids["aes128-CBC"]:case forge2.pki.oids["aes192-CBC"]:case forge2.pki.oids["aes256-CBC"]:ciph=forge2.aes.createDecryptionCipher(msg.encryptedContent.key);break;case forge2.pki.oids["desCBC"]:case forge2.pki.oids["des-EDE3-CBC"]:ciph=forge2.des.createDecryptionCipher(msg.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+msg.encryptedContent.algorithm)}ciph.start(msg.encryptedContent.parameter);ciph.update(msg.encryptedContent.content);if(!ciph.finish()){throw new Error("Symmetric decryption failed.")}msg.content=ciph.output}}}});var require_ssh=__commonJS({"node_modules/node-forge/lib/ssh.js"(exports,module){"use strict";var forge2=require_forge();require_aes();require_hmac();require_md5();require_sha1();require_util7();var ssh=module.exports=forge2.ssh=forge2.ssh||{};ssh.privateKeyToPutty=function(privateKey,passphrase,comment){comment=comment||"";passphrase=passphrase||"";var algorithm="ssh-rsa";var encryptionAlgorithm=passphrase===""?"none":"aes256-cbc";var ppk="PuTTY-User-Key-File-2: "+algorithm+"\r\n";ppk+="Encryption: "+encryptionAlgorithm+"\r\n";ppk+="Comment: "+comment+"\r\n";var pubbuffer=forge2.util.createBuffer();_addStringToBuffer(pubbuffer,algorithm);_addBigIntegerToBuffer(pubbuffer,privateKey.e);_addBigIntegerToBuffer(pubbuffer,privateKey.n);var pub=forge2.util.encode64(pubbuffer.bytes(),64);var length=Math.floor(pub.length/66)+1;ppk+="Public-Lines: "+length+"\r\n";ppk+=pub;var privbuffer=forge2.util.createBuffer();_addBigIntegerToBuffer(privbuffer,privateKey.d);_addBigIntegerToBuffer(privbuffer,privateKey.p);_addBigIntegerToBuffer(privbuffer,privateKey.q);_addBigIntegerToBuffer(privbuffer,privateKey.qInv);var priv;if(!passphrase){priv=forge2.util.encode64(privbuffer.bytes(),64)}else{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=forge2.util.createBuffer();aeskey.putBuffer(_sha1("\0\0\0\0",passphrase));aeskey.putBuffer(_sha1("\0\0\0",passphrase));var cipher=forge2.aes.createEncryptionCipher(aeskey.truncate(8),"CBC");cipher.start(forge2.util.createBuffer().fillWithByte(0,16));cipher.update(privbuffer.copy());cipher.finish();var encrypted=cipher.output;encrypted.truncate(16);priv=forge2.util.encode64(encrypted.bytes(),64)}length=Math.floor(priv.length/66)+1;ppk+="\r\nPrivate-Lines: "+length+"\r\n";ppk+=priv;var mackey=_sha1("putty-private-key-file-mac-key",passphrase);var macbuffer=forge2.util.createBuffer();_addStringToBuffer(macbuffer,algorithm);_addStringToBuffer(macbuffer,encryptionAlgorithm);_addStringToBuffer(macbuffer,comment);macbuffer.putInt32(pubbuffer.length());macbuffer.putBuffer(pubbuffer);macbuffer.putInt32(privbuffer.length());macbuffer.putBuffer(privbuffer);var hmac=forge2.hmac.create();hmac.start("sha1",mackey);hmac.update(macbuffer.bytes());ppk+="\r\nPrivate-MAC: "+hmac.digest().toHex()+"\r\n";return ppk};ssh.publicKeyToOpenSSH=function(key,comment){var type="ssh-rsa";comment=comment||"";var buffer=forge2.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);return type+" "+forge2.util.encode64(buffer.bytes())+" "+comment};ssh.privateKeyToOpenSSH=function(privateKey,passphrase){if(!passphrase){return forge2.pki.privateKeyToPem(privateKey)}return forge2.pki.encryptRsaPrivateKey(privateKey,passphrase,{legacy:true,algorithm:"aes128"})};ssh.getPublicKeyFingerprint=function(key,options){options=options||{};var md=options.md||forge2.md.md5.create();var type="ssh-rsa";var buffer=forge2.util.createBuffer();_addStringToBuffer(buffer,type);_addBigIntegerToBuffer(buffer,key.e);_addBigIntegerToBuffer(buffer,key.n);md.start();md.update(buffer.getBytes());var digest=md.digest();if(options.encoding==="hex"){var hex=digest.toHex();if(options.delimiter){return hex.match(/.{2}/g).join(options.delimiter)}return hex}else if(options.encoding==="binary"){return digest.getBytes()}else if(options.encoding){throw new Error('Unknown encoding "'+options.encoding+'".')}return digest};function _addBigIntegerToBuffer(buffer,val){var hexVal=val.toString(16);if(hexVal[0]>="8"){hexVal="00"+hexVal}var bytes=forge2.util.hexToBytes(hexVal);buffer.putInt32(bytes.length);buffer.putBytes(bytes)}function _addStringToBuffer(buffer,val){buffer.putInt32(val.length);buffer.putString(val)}function _sha1(){var sha=forge2.md.sha1.create();var num=arguments.length;for(var i=0;i<num;++i){sha.update(arguments[i])}return sha.digest()}}});var require_lib=__commonJS({"node_modules/node-forge/lib/index.js"(exports,module){"use strict";module.exports=require_forge();require_aes();require_aesCipherSuites();require_asn1();require_cipher();require_des();require_ed25519();require_hmac();require_kem();require_log();require_md_all();require_mgf1();require_pbkdf2();require_pem();require_pkcs1();require_pkcs12();require_pkcs7();require_pki();require_prime();require_prng();require_pss();require_random();require_rc2();require_ssh();require_tls();require_util7()}});var init_vertex=__esm({"src/vertex.ts"(){"use strict"}});import fs2 from"fs";import os2 from"os";import path6 from"path";var TOML_KEY_PART_RE;var init_client_config=__esm({"src/client-config.ts"(){"use strict";init_main();init_vertex();TOML_KEY_PART_RE=new RegExp(String.raw`^(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*')(?:\.(?:[A-Za-z0-9_-]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\n])*'))*$`)}});import{createHash as createHash5,randomUUID}from"crypto";import fs4 from"fs";import os4 from"os";import path8 from"path";function isProxyInstanceFile(v2){return v2!==void 0&&"instanceId"in v2}function readProxyInstanceFile(file){let raw;try{raw=fs4.readFileSync(file??instanceFilePath(),"utf8").trim()}catch{return void 0}if(raw.startsWith("{")){try{const parsed=JSON.parse(raw);if(typeof parsed.origin==="string"&&/^https?:\/\/\S+$/.test(parsed.origin)){const windows={};if(parsed.modelWindows&&typeof parsed.modelWindows==="object"){for(const[k2,v2]of Object.entries(parsed.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(parsed.modelMaxOutputs&&typeof parsed.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(parsed.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{origin:parsed.origin,instanceId:typeof parsed.instanceId==="string"?parsed.instanceId:"",pid:typeof parsed.pid==="number"?parsed.pid:0,startedAt:typeof parsed.startedAt==="number"?parsed.startedAt:0,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,passthrough:Boolean(parsed.passthrough),mitmDomains:Array.isArray(parsed.mitmDomains)?parsed.mitmDomains.map(String):[],modelWindows:windows,modelMaxOutputs:Object.keys(maxOutputs).length>0?maxOutputs:void 0,launchToken:typeof parsed.launchToken==="string"?parsed.launchToken:void 0,lane:typeof parsed.lane==="string"&&parsed.lane!==""?parsed.lane:void 0,codeFingerprint:typeof parsed.codeFingerprint==="string"&&parsed.codeFingerprint!==""?parsed.codeFingerprint:void 0}}}catch{}}if(/^https?:\/\/\S+$/.test(raw))return{origin:raw};return void 0}function instanceFilePath(){return path8.join(stateDir(),"proxy-origin")}function portZoneFilePath(){return path8.join(stateDir(),"port-zone.json")}function readZonePort(lane,file=portZoneFilePath()){let raw;try{raw=fs4.readFileSync(file,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);const v2=parsed?.lanes?.[lane];if(typeof v2==="number"&&Number.isInteger(v2)&&v2>0&&v2<65536)return v2;return void 0}catch{return void 0}}function writeZonePort(lane,port,file=portZoneFilePath()){if(!Number.isInteger(port)||port<=0||port>=65536)return;let cur={};try{const parsed=JSON.parse(fs4.readFileSync(file,"utf8"));if(parsed!==null&&typeof parsed==="object"&&parsed.lanes!==null&&typeof parsed.lanes==="object")cur=parsed}catch{}atomicWriteJson({lanes:{...cur.lanes??{},[lane]:port}},file)}function lanePreferredPort(lane,env=process.env,file=portZoneFilePath()){return readZonePort(lane,file)??resolveZonePortBase(env)}function entryScriptFingerprint(scriptPath){if(!scriptPath)return void 0;const resolved=path8.resolve(scriptPath);const cached=scriptFingerprints.get(resolved);if(cached!==void 0)return cached;let digest;try{digest=createHash5("sha256").update(fs4.readFileSync(resolved)).digest("hex")}catch{return void 0}scriptFingerprints.set(resolved,digest);return digest}function atomicWriteJson(obj,filePath){fs4.mkdirSync(path8.dirname(filePath),{recursive:true});const tempPath=`${filePath}.${process.pid}.${randomUUID()}.tmp`;let descriptor;try{descriptor=fs4.openSync(tempPath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(obj)+"\n",null,"utf8");fs4.fsyncSync(descriptor);fs4.closeSync(descriptor);descriptor=void 0;fs4.renameSync(tempPath,filePath)}catch(error){if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}try{fs4.unlinkSync(tempPath)}catch{}throw error}}function startingMarkerPath(){return path8.join(stateDir(),"proxy-starting")}function readStartingMarker(file){let raw;try{raw=fs4.readFileSync(file??startingMarkerPath(),"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed.token!=="string"||parsed.token==="")return void 0;if(typeof parsed.pid!=="number"||!Number.isInteger(parsed.pid)||parsed.pid<=0)return void 0;if(typeof parsed.startedAt!=="number")return void 0;return{token:parsed.token,pid:parsed.pid,host:typeof parsed.host==="string"?parsed.host:"",port:typeof parsed.port==="number"?parsed.port:0,startedAt:parsed.startedAt,...typeof parsed.lane==="string"&&parsed.lane!==""?{lane:parsed.lane}:{}}}catch{return void 0}}function claimStartingMarker(marker,file){const filePath=file??startingMarkerPath();let descriptor;try{fs4.mkdirSync(path8.dirname(filePath),{recursive:true});descriptor=fs4.openSync(filePath,"wx",420);fs4.writeSync(descriptor,JSON.stringify(marker)+"\n",null,"utf8");fs4.fsyncSync(descriptor);descriptor=void 0;return true}catch{if(descriptor!==void 0){try{fs4.closeSync(descriptor)}catch{}}return false}}function clearStartingMarker(token,file){const filePath=file??startingMarkerPath();const current=readStartingMarker(filePath);if(current&&current.token===token){try{fs4.unlinkSync(filePath)}catch{}}}function removeStartingMarker(file){try{fs4.unlinkSync(file??startingMarkerPath())}catch{}}function isPidAlive(pid){if(!Number.isInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err){return err.code==="EPERM"}}function registryDirPath(){return path8.join(stateDir(),"instances")}function legacyRegistryFilePath(){return path8.join(stateDir(),"instances.json")}function safeReadJson(file){try{return JSON.parse(fs4.readFileSync(file,"utf8"))}catch{return void 0}}function coerceEntry(value){if(!value||typeof value!=="object")return void 0;const o=value;if(typeof o.instanceId!=="string"||o.instanceId==="")return void 0;const windows={};if(o.modelWindows&&typeof o.modelWindows==="object"){for(const[k2,v2]of Object.entries(o.modelWindows)){const n=Number(v2);if(Number.isFinite(n)&&n>0)windows[k2]=n}}const maxOutputs={};if(o.modelMaxOutputs&&typeof o.modelMaxOutputs==="object"){for(const[k2,v2]of Object.entries(o.modelMaxOutputs)){const n=Number(v2);if(Number.isFinite(n)&&n>0)maxOutputs[k2]=n}}return{instanceId:o.instanceId,pid:typeof o.pid==="number"?o.pid:0,port:typeof o.port==="number"?o.port:0,origin:typeof o.origin==="string"?o.origin:"",startedAt:typeof o.startedAt==="number"?o.startedAt:0,...typeof o.host==="string"&&o.host!==""?{host:o.host}:{},...typeof o.passthrough==="boolean"?{passthrough:o.passthrough}:{},...Array.isArray(o.mitmDomains)?{mitmDomains:o.mitmDomains.map(String)}:{},...Object.keys(windows).length>0?{modelWindows:windows}:{},...Object.keys(maxOutputs).length>0?{modelMaxOutputs:maxOutputs}:{},...typeof o.lane==="string"&&o.lane!==""?{lane:o.lane}:{},...typeof o.codeFingerprint==="string"&&o.codeFingerprint!==""?{codeFingerprint:o.codeFingerprint}:{}}}function readMarkerNames(){try{return fs4.readdirSync(registryDirPath())}catch{return[]}}function readAllRegistryEntries(){const seen=new Set;const out=[];for(const name of readMarkerNames()){if(!name.endsWith(".json"))continue;const entry=coerceEntry(safeReadJson(path8.join(registryDirPath(),name)));if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}const legacy=safeReadJson(legacyRegistryFilePath());if(legacy&&Array.isArray(legacy.instances)){for(const raw of legacy.instances){const entry=coerceEntry(raw);if(entry&&!seen.has(entry.instanceId)){seen.add(entry.instanceId);out.push(entry)}}}return out}function discoverLiveInstances(){const out=[];for(const e of readAllRegistryEntries()){if(!isPidAlive(e.pid))continue;out.push({origin:e.origin,instanceId:e.instanceId,pid:e.pid,startedAt:e.startedAt,host:e.host??"",port:e.port,passthrough:Boolean(e.passthrough),mitmDomains:e.mitmDomains??[],modelWindows:e.modelWindows??{},modelMaxOutputs:e.modelMaxOutputs,lane:e.lane,codeFingerprint:e.codeFingerprint})}return out}var scriptFingerprints;var init_instance=__esm({"src/instance.ts"(){"use strict";init_config();init_paths();scriptFingerprints=new Map}});var init_win_cmd=__esm({"src/win-cmd.ts"(){"use strict"}});import fs5 from"fs";import path9 from"path";import{execFile,spawnSync}from"child_process";import{promisify}from"util";var DSH_PACKAGE,DSH_EXEC_TIMEOUT_MS,pExecFile;var init_dsh_channel=__esm({"src/dsh-channel.ts"(){"use strict";init_client_config();init_win_cmd();DSH_PACKAGE="billion-context";DSH_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile=promisify(execFile)}});import fs6 from"fs";import path10 from"path";import{execFile as execFile2}from"child_process";import{promisify as promisify2}from"util";var PI_NPM_SPEC,PI_EXEC_TIMEOUT_MS,pExecFile2;var init_pi_channel=__esm({"src/pi-channel.ts"(){"use strict";init_client_config();init_dsh_channel();PI_NPM_SPEC="npm:billion-context";PI_EXEC_TIMEOUT_MS=5*60*1e3;pExecFile2=promisify2(execFile2)}});import Qr from"events";import I from"fs";import{EventEmitter as Di}from"events";import Cs from"stream";import{StringDecoder as Hr}from"string_decoder";import cr from"path";import Kt from"fs";import{dirname as Fn,parse as kn}from"path";import{EventEmitter as Dn}from"events";import zi from"assert";import{Buffer as Ot}from"buffer";import*as Ps from"zlib";import en from"zlib";import{posix as Zt}from"path";import{basename as _n}from"path";import mi from"fs";import X from"fs";import js from"path";import{win32 as Pn}from"path";import ar from"path";import Br from"fs";import co from"assert";import{randomBytes as Mr}from"crypto";import u from"fs";import R from"path";import pr from"fs";import wi from"fs";import we from"path";import k from"fs";import ro from"fs/promises";import Si from"path";import{join as xr}from"path";import v from"fs";import Pr from"path";function Zn(s3,t,e){let i=t,r=t?t.next:s3.head,n=new ue(e,i,r,s3);return n.next===void 0&&(s3.tail=n),n.prev===void 0&&(s3.head=n),s3.length++,n}function Yn(s3,t){s3.tail=new ue(t,s3.tail,void 0,s3),s3.head||(s3.head=s3.tail),s3.length++}function Kn(s3,t){s3.head=new ue(t,void 0,s3.head,s3),s3.tail||(s3.tail=s3.head),s3.length++}var zr,Ur,Ds,Wr,Gr,Zr,Q,J,nt,De,qt,Ne,Ns,Ae,As,z,Mt,g,Qt,Bt,b,N,_,bi,Ie,L,S,_i,Oi,Is,Ti,Z,xi,Ce,Jt,Rt,C,jt,Yr,Kr,Vr,$r,Fe,Li,Xr,qr,A,Jr,ht,H,te,m,Ni,tt,Ai,ki,vi,ie,ke,Ut,Ht,Ii,Pt,at,U,ot,Y,zt,Ci,j,ee,Fi,ve,gt,Me,bt,_t,Be,et,Wt,jr,Fs,ks,vs,Ms,Bs,tn,se,K,sn,M,rn,zs,nn,Bi,Tt,Gt,Pi,re,Pe,ze,Ue,He,We,Ge,Ze,Ye,Ke,Us,hn,an,Hs,ln,cn,Ws,Gs,Hi,ne,dn,Ui,oe,Ve,un,F,mn,xt,Wi,pn,lt,En,wn,Sn,ct,yn,Rn,gn,Gi,bn,Lt,ft,On,Tn,xn,Ln,f,$e,Dt,Nn,Xi,qi,An,B,Nt,it,Zi,Zs,V,he,dt,Ys,p,st,ut,Yi,At,w,Xe,qe,Ki,Ks,Vs,ae,Vi,Qe,Yt,$,Je,It,je,ti,$s,In,le,$i,Xs,Cn,rt,mt,vn,Qi,Mn,Bn,Ct,Ji,zn,qs,ce,ei,ji,Un,Hn,ts,Qs,rr,Wn,tr,er,ir,is,sr,fe,ii,ss,si,rs,ns,os5,hs,pt,ri,as,es,q,de,ni,oi,Gn,hi,ue,pi,nr,li,me,W,pe,Et,Ft,Ee,ai,G,ls,ci,or,ds,us,fi,di,hr,cs,ui,lr,fs7,wt,kt,Vn,$n,fr,dr,Xn,qn,Qn,Jn,Er,wr,ur,Sr,yr,Rr,jn,to,eo,mr,ms,ps,Ei,io,Es,so,ws,Se,St,no,gr,Ss,br,oo,_r,ys,Or,Vt,Tr,ho,ao,lo,yi,Lr,Dr,_s,Nr,Os,P,Ts,xs,gi,Ar,Ir,Re,Cr,Fr,Rs,yt,O,Ri,kr,$t,gs,bs,Ls,ge,be,_e,Oe,fo,Te,uo,mo,po,vr,Xt,ye,xe,Eo,wo,So,yo,Ro,go,bo,_o,vt,Oo,To;var init_index_min=__esm({"node_modules/tar/dist/esm/index.min.js"(){"use strict";zr=Object.defineProperty;Ur=(s3,t)=>{for(var e in t)zr(s3,e,{get:t[e],enumerable:true})};Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null};Wr=s3=>!!s3&&typeof s3=="object"&&(s3 instanceof A||s3 instanceof Cs||Gr(s3)||Zr(s3));Gr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.pipe=="function"&&s3.pipe!==Cs.Writable.prototype.pipe;Zr=s3=>!!s3&&typeof s3=="object"&&s3 instanceof Di&&typeof s3.write=="function"&&typeof s3.end=="function";Q=Symbol("EOF");J=Symbol("maybeEmitEnd");nt=Symbol("emittedEnd");De=Symbol("emittingEnd");qt=Symbol("emittedError");Ne=Symbol("closed");Ns=Symbol("read");Ae=Symbol("flush");As=Symbol("flushChunk");z=Symbol("encoding");Mt=Symbol("decoder");g=Symbol("flowing");Qt=Symbol("paused");Bt=Symbol("resume");b=Symbol("buffer");N=Symbol("pipes");_=Symbol("bufferLength");bi=Symbol("bufferPush");Ie=Symbol("bufferShift");L=Symbol("objectMode");S=Symbol("destroyed");_i=Symbol("error");Oi=Symbol("emitData");Is=Symbol("emitEnd");Ti=Symbol("emitEnd2");Z=Symbol("async");xi=Symbol("abort");Ce=Symbol("aborted");Jt=Symbol("signal");Rt=Symbol("dataListeners");C=Symbol("discarded");jt=s3=>Promise.resolve().then(s3);Yr=s3=>s3();Kr=s3=>s3==="end"||s3==="finish"||s3==="prefinish";Vr=s3=>s3 instanceof ArrayBuffer||!!s3&&typeof s3=="object"&&s3.constructor&&s3.constructor.name==="ArrayBuffer"&&s3.byteLength>=0;$r=s3=>!Buffer.isBuffer(s3)&&ArrayBuffer.isView(s3);Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}};Li=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}};Xr=s3=>!!s3.objectMode;qr=s3=>!s3.objectMode&&!!s3.encoding&&s3.encoding!=="buffer";A=class extends Di{[g]=false;[Qt]=false;[N]=[];[b]=[];[L];[z];[Z];[Mt];[Q]=false;[nt]=false;[De]=false;[Ne]=false;[qt]=null;[_]=0;[S]=false;[Jt];[Ce]=false;[Rt]=0;[C]=false;writable=true;readable=true;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Xr(e)?(this[L]=true,this[z]=null):qr(e)?(this[z]=e.encoding,this[L]=false):(this[L]=false,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Hr(this[z]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[N]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[xi](){this[Ce]=true,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ce]}set aborted(t){}write(t,e,i){if(this[Ce])return false;if(this[Q])throw new Error("write after end");if(this[S])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Yr;if(!this[L]&&!Buffer.isBuffer(t)){if($r(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[Ae](true),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[S])return null;if(this[C]=false,this[_]===0||t===0||t&&t>this[_])return this[J](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ns](t||null,this[b][0]);return this[J](),e}[Ns](t,e){if(this[L])this[Ie]();else{let i=e;t===i.length||t===null?this[Ie]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[Q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Q]=true,this.writable=false,(this[g]||!this[Qt])&&this[J](),this}[Bt](){this[S]||(!this[Rt]&&!this[N].length&&(this[C]=true),this[Qt]=false,this[g]=true,this.emit("resume"),this[b].length?this[Ae]():this[Q]?this[J]():this.emit("drain"))}resume(){return this[Bt]()}pause(){this[g]=false,this[Qt]=true,this[C]=false}get destroyed(){return this[S]}get flowing(){return this[g]}get paused(){return this[Qt]}[bi](t){this[L]?this[_]+=1:this[_]+=t.length,this[b].push(t)}[Ie](){return this[L]?this[_]-=1:this[_]-=this[b][0].length,this[b].shift()}[Ae](t=false){do;while(this[As](this[Ie]())&&this[b].length);!t&&!this[b].length&&!this[Q]&&this.emit("drain")}[As](t){return this.emit("data",t),this[g]}pipe(t,e){if(this[S])return t;this[C]=false;let i=this[nt];return e=e||{},t===Ds.stdout||t===Ds.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[N].push(e.proxyErrors?new Li(this,t,e):new Fe(this,t,e)),this[Z]?jt(()=>this[Bt]()):this[Bt]()),t}unpipe(t){let e=this[N].find(i=>i.dest===t);e&&(this[N].length===1?(this[g]&&this[Rt]===0&&(this[g]=false),this[N]=[]):this[N].splice(this[N].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[C]=false,this[Rt]++,!this[N].length&&!this[g]&&this[Bt]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(Kr(t)&&this[nt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[qt]){let r=e;this[Z]?jt(()=>r.call(this,this[qt])):r.call(this,this[qt])}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[Rt]=this.listeners("data").length,this[Rt]===0&&!this[C]&&!this[N].length&&(this[g]=false)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Rt]=0,!this[C]&&!this[N].length&&(this[g]=false)),e}get emittedEnd(){return this[nt]}[J](){!this[De]&&!this[nt]&&!this[S]&&this[b].length===0&&this[Q]&&(this[De]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ne]&&this.emit("close"),this[De]=false)}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==S&&this[S])return false;if(t==="data")return!this[L]&&!i?false:this[Z]?(jt(()=>this[Oi](i)),true):this[Oi](i);if(t==="end")return this[Is]();if(t==="close"){if(this[Ne]=true,!this[nt]&&!this[S])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[qt]=i,super.emit(_i,i);let n=!this[Jt]||this.listeners("error").length?super.emit("error",i):false;return this[J](),n}else if(t==="resume"){let n=super.emit("resume");return this[J](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[J](),r}[Oi](t){for(let i of this[N])i.dest.write(t)===false&&this.pause();let e=this[C]?false:super.emit("data",t);return this[J](),e}[Is](){return this[nt]?false:(this[nt]=true,this.readable=false,this[Z]?(jt(()=>this[Ti]()),true):this[Ti]())}[Ti](){if(this[Mt]){let e=this[Mt].end();if(e){for(let i of this[N])i.dest.write(e);this[C]||super.emit("data",e)}}for(let e of this[N])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[L]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[L]||(t.dataLength+=i.length)}),await e,t}async concat(){if(this[L])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[z]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(S,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[C]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:false,value:r});if(this[Q])return e();let n,o,h=d=>{this.off("data",a),this.off("end",l),this.off(S,c),e(),o(d)},a=d=>{this.off("error",h),this.off("end",l),this.off(S,c),this.pause(),n({value:d,done:!!this[Q]})},l=()=>{this.off("error",h),this.off("data",a),this.off(S,c),e(),n({done:true,value:void 0})},c=()=>h(new Error("stream destroyed"));return new Promise((d,y)=>{o=y,n=d,this.once(S,c),this.once("error",h),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[C]=false;let t=false,e=()=>(this.pause(),this.off(_i,e),this.off(S,e),this.off("end",e),t=true,{done:true,value:void 0}),i=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(_i,e),this.once(S,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[S])return t?this.emit("error",t):this.emit(S),this;this[S]=true,this[C]=true,this[b].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Ne]&&e.close(),t?this.emit("error",t):this.emit(S),this}static get isStream(){return Wr}};Jr=I.writev;ht=Symbol("_autoClose");H=Symbol("_close");te=Symbol("_ended");m=Symbol("_fd");Ni=Symbol("_finished");tt=Symbol("_flags");Ai=Symbol("_flush");ki=Symbol("_handleChunk");vi=Symbol("_makeBuf");ie=Symbol("_mode");ke=Symbol("_needDrain");Ut=Symbol("_onerror");Ht=Symbol("_onopen");Ii=Symbol("_onread");Pt=Symbol("_onwrite");at=Symbol("_open");U=Symbol("_path");ot=Symbol("_pos");Y=Symbol("_queue");zt=Symbol("_read");Ci=Symbol("_readSize");j=Symbol("_reading");ee=Symbol("_remain");Fi=Symbol("_size");ve=Symbol("_write");gt=Symbol("_writing");Me=Symbol("_defaultFlag");bt=Symbol("_errored");_t=class extends A{[bt]=false;[m];[U];[Ci];[j]=false;[Fi];[ee];[ht];constructor(t,e){if(e=e||{},super(e),this.readable=true,this.writable=false,typeof t!="string")throw new TypeError("path must be a string");this[bt]=false,this[m]=typeof e.fd=="number"?e.fd:void 0,this[U]=t,this[Ci]=e.readSize||16*1024*1024,this[j]=false,this[Fi]=typeof e.size=="number"?e.size:1/0,this[ee]=this[Fi],this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true,typeof this[m]=="number"?this[zt]():this[at]()}get fd(){return this[m]}get path(){return this[U]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[at](){I.open(this[U],"r",(t,e)=>this[Ht](t,e))}[Ht](t,e){t?this[Ut](t):(this[m]=e,this.emit("open",e),this[zt]())}[vi](){return Buffer.allocUnsafe(Math.min(this[Ci],this[ee]))}[zt](){if(!this[j]){this[j]=true;let t=this[vi]();if(t.length===0)return process.nextTick(()=>this[Ii](null,0,t));I.read(this[m],t,0,t.length,null,(e,i,r)=>this[Ii](e,i,r))}}[Ii](t,e,i){this[j]=false,t?this[Ut](t):this[ki](e,i)&&this[zt]()}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ut](t){this[j]=true,this[H](),this.emit("error",t)}[ki](t,e){let i=false;return this[ee]-=t,t>0&&(i=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[ee]<=0)&&(i=false,this[H](),super.end()),i}emit(t,...e){switch(t){case"prefinish":case"finish":return false;case"drain":return typeof this[m]=="number"&&this[zt](),false;case"error":return this[bt]?false:(this[bt]=true,super.emit(t,...e));default:return super.emit(t,...e)}}};Be=class extends _t{[at](){let t=true;try{this[Ht](null,I.openSync(this[U],"r")),t=false}finally{t&&this[H]()}}[zt](){let t=true;try{if(!this[j]){this[j]=true;do{let e=this[vi](),i=e.length===0?0:I.readSync(this[m],e,0,e.length,null);if(!this[ki](i,e))break}while(true);this[j]=false}t=false}finally{t&&this[H]()}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}};et=class extends Qr{readable=false;writable=true;[bt]=false;[gt]=false;[te]=false;[Y]=[];[ke]=false;[U];[ie];[ht];[m];[Me];[tt];[Ni]=false;[ot];constructor(t,e){e=e||{},super(e),this[U]=t,this[m]=typeof e.fd=="number"?e.fd:void 0,this[ie]=e.mode===void 0?438:e.mode,this[ot]=typeof e.start=="number"?e.start:void 0,this[ht]=typeof e.autoClose=="boolean"?e.autoClose:true;let i=this[ot]!==void 0?"r+":"w";this[Me]=e.flags===void 0,this[tt]=e.flags===void 0?i:e.flags,this[m]===void 0&&this[at]()}emit(t,...e){if(t==="error"){if(this[bt])return false;this[bt]=true}return super.emit(t,...e)}get fd(){return this[m]}get path(){return this[U]}[Ut](t){this[H](),this[gt]=true,this.emit("error",t)}[at](){I.open(this[U],this[tt],this[ie],(t,e)=>this[Ht](t,e))}[Ht](t,e){this[Me]&&this[tt]==="r+"&&t&&t.code==="ENOENT"?(this[tt]="w",this[at]()):t?this[Ut](t):(this[m]=e,this.emit("open",e),this[gt]||this[Ai]())}end(t,e){return t&&this.write(t,e),this[te]=true,!this[gt]&&!this[Y].length&&typeof this[m]=="number"&&this[Pt](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[te]?(this.emit("error",new Error("write() after end()")),false):this[m]===void 0||this[gt]||this[Y].length?(this[Y].push(t),this[ke]=true,false):(this[gt]=true,this[ve](t),true)}[ve](t){I.write(this[m],t,0,t.length,this[ot],(e,i)=>this[Pt](e,i))}[Pt](t,e){t?this[Ut](t):(this[ot]!==void 0&&typeof e=="number"&&(this[ot]+=e),this[Y].length?this[Ai]():(this[gt]=false,this[te]&&!this[Ni]?(this[Ni]=true,this[H](),this.emit("finish")):this[ke]&&(this[ke]=false,this.emit("drain"))))}[Ai](){if(this[Y].length===0)this[te]&&this[Pt](null,0);else if(this[Y].length===1)this[ve](this[Y].pop());else{let t=this[Y];this[Y]=[],Jr(this[m],t,this[ot],(e,i)=>this[Pt](e,i))}}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.close(t,e=>e?this.emit("error",e):this.emit("close"))}}};Wt=class extends et{[at](){let t;if(this[Me]&&this[tt]==="r+")try{t=I.openSync(this[U],this[tt],this[ie])}catch(e){if(e?.code==="ENOENT")return this[tt]="w",this[at]();throw e}else t=I.openSync(this[U],this[tt],this[ie]);this[Ht](null,t)}[H](){if(this[ht]&&typeof this[m]=="number"){let t=this[m];this[m]=void 0,I.closeSync(t),this.emit("close")}}[ve](t){let e=true;try{this[Pt](null,I.writeSync(this[m],t,0,t.length,this[ot])),e=false}finally{if(e)try{this[H]()}catch{}}}};jr=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]);Fs=s3=>!!s3.sync&&!!s3.file;ks=s3=>!s3.sync&&!!s3.file;vs=s3=>!!s3.sync&&!s3.file;Ms=s3=>!s3.sync&&!s3.file;Bs=s3=>!!s3.file;tn=s3=>{let t=jr.get(s3);return t||s3};se=(s3={})=>{if(!s3)return{};let t={};for(let[e,i]of Object.entries(s3)){let r=tn(e);t[r]=i}return t.chmod===void 0&&t.noChmod===false&&(t.chmod=true),delete t.noChmod,t};K=(s3,t,e,i,r)=>Object.assign((n=[],o,h)=>{Array.isArray(n)&&(o=n,n={}),typeof o=="function"&&(h=o,o=void 0),o=o?Array.from(o):[];let a=se(n);if(r?.(a,o),Fs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return s3(a,o)}else if(ks(a)){let l=t(a,o);return h?l.then(()=>h(),h):l}else if(vs(a)){if(typeof h=="function")throw new TypeError("callback not supported for sync tar functions");return e(a,o)}else if(Ms(a)){if(typeof h=="function")throw new TypeError("callback only supported with file option");return i(a,o)}throw new Error("impossible options??")},{syncFile:s3,asyncFile:t,syncNoFile:e,asyncNoFile:i,validate:r});sn=en.constants||{ZLIB_VERNUM:4736};M=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,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_VERSION_ERROR:-6,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,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},sn));rn=Ot.concat;zs=Object.getOwnPropertyDescriptor(Ot,"concat");nn=s3=>s3;Bi=zs?.writable===true||zs?.set!==void 0?s3=>{Ot.concat=s3?nn:rn}:s3=>{};Tt=Symbol("_superWrite");Gt=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}};Pi=Symbol("flushFlag");re=class extends A{#t=false;#i=false;#s;#n;#r;#e;#o;get sawError(){return this.#t}get handle(){return this.#e}get flushFlag(){return this.#s}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#s=t.flush??0,this.#n=t.finishFlush??0,this.#r=t.fullFlushFlag??0,typeof Ps[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#e=new Ps[e](t)}catch(i){throw new Gt(i,this.constructor)}this.#o=i=>{this.#t||(this.#t=true,this.close(),this.emit("error",i))},this.#e?.on("error",i=>this.#o(new Gt(i))),this.once("end",()=>this.close)}close(){this.#e&&(this.#e.close(),this.#e=void 0,this.emit("close"))}reset(){if(!this.#t)return zi(this.#e,"zlib binding closed"),this.#e.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#r),this.write(Object.assign(Ot.alloc(0),{[Pi]:t})))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#n),this.#i=true,super.end(i)}get ended(){return this.#i}[Tt](t){return super.write(t)}write(t,e,i){if(typeof e=="function"&&(i=e,e="utf8"),typeof t=="string"&&(t=Ot.from(t,e)),this.#t)return;zi(this.#e,"zlib binding closed");let r=this.#e._handle,n=r.close;r.close=()=>{};let o=this.#e.close;this.#e.close=()=>{},Bi(true);let h;try{let l=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l),Bi(false)}catch(l){Bi(false),this.#o(new Gt(l,this.write))}finally{this.#e&&(this.#e._handle=r,r.close=n,this.#e.close=o,this.#e.removeAllListeners("error"))}this.#e&&this.#e.on("error",l=>this.#o(new Gt(l,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l=h[0];a=this[Tt](Ot.from(l));for(let c=1;c<h.length;c++)a=this[Tt](h[c])}else a=this[Tt](Ot.from(h));return i&&i(),a}};Pe=class extends re{#t;#i;constructor(t,e){t=t||{},t.flush=t.flush||M.Z_NO_FLUSH,t.finishFlush=t.finishFlush||M.Z_FINISH,t.fullFlushFlag=M.Z_FULL_FLUSH,super(t,e),this.#t=t.level,this.#i=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#t!==t||this.#i!==e){this.flush(M.Z_SYNC_FLUSH),zi(this.handle,"zlib binding closed");let i=this.handle.flush;this.handle.flush=(r,n)=>{typeof r=="function"&&(n=r,r=this.flushFlag),this.flush(r),n?.()};try{this.handle.params(t,e)}finally{this.handle.flush=i}this.handle&&(this.#t=t,this.#i=e)}}}};ze=class extends Pe{#t;constructor(t){super(t,"Gzip"),this.#t=t&&!!t.portable}[Tt](t){return this.#t?(this.#t=false,t[9]=255,super[Tt](t)):super[Tt](t)}};Ue=class extends Pe{constructor(t){super(t,"Unzip")}};He=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||M.BROTLI_OPERATION_FINISH,t.fullFlushFlag=M.BROTLI_OPERATION_FLUSH,super(t,e)}};We=class extends He{constructor(t){super(t,"BrotliCompress")}};Ge=class extends He{constructor(t){super(t,"BrotliDecompress")}};Ze=class extends re{constructor(t,e){t=t||{},t.flush=t.flush||M.ZSTD_e_continue,t.finishFlush=t.finishFlush||M.ZSTD_e_end,t.fullFlushFlag=M.ZSTD_e_flush,super(t,e)}};Ye=class extends Ze{constructor(t){super(t,"ZstdCompress")}};Ke=class extends Ze{constructor(t){super(t,"ZstdDecompress")}};Us=(s3,t)=>{if(Number.isSafeInteger(s3))s3<0?an(s3,t):hn(s3,t);else throw Error("cannot encode number outside of javascript safe integer range");return t};hn=(s3,t)=>{t[0]=128;for(var e=t.length;e>1;e--)t[e-1]=s3&255,s3=Math.floor(s3/256)};an=(s3,t)=>{t[0]=255;var e=false;s3=s3*-1;for(var i=t.length;i>1;i--){var r=s3&255;s3=Math.floor(s3/256),e?t[i-1]=Ws(r):r===0?t[i-1]=0:(e=true,t[i-1]=Gs(r))}};Hs=s3=>{let t=s3[0],e=t===128?cn(s3.subarray(1,s3.length)):t===255?ln(s3):null;if(e===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(e))throw Error("parsed number outside of javascript safe integer range");return e};ln=s3=>{for(var t=s3.length,e=0,i=false,r=t-1;r>-1;r--){var n=Number(s3[r]),o;i?o=Ws(n):n===0?o=n:(i=true,o=Gs(n)),o!==0&&(e-=o*Math.pow(256,t-r-1))}return e};cn=s3=>{for(var t=s3.length,e=0,i=t-1;i>-1;i--){var r=Number(s3[i]);r!==0&&(e+=r*Math.pow(256,t-i-1))}return e};Ws=s3=>(255^s3)&255;Gs=s3=>(255^s3)+1&255;Hi={};Ur(Hi,{code:()=>Ve,isCode:()=>ne,isName:()=>dn,name:()=>oe,normalFsTypes:()=>Ui});ne=s3=>oe.has(s3);dn=s3=>Ve.has(s3);Ui=new Set(["0","","1","2","3","4","5","6","7","D"]);oe=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);Ve=new Map(Array.from(oe).map(s3=>[s3[1],s3[0]]));un=s3=>s3===void 0||s3<0?void 0:s3;F=class{cksumValid=false;needPax=false;nullBlock=false;block;path;mode;uid;gid;size;cksum;#t="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,i,r){Buffer.isBuffer(t)?this.decode(t,e||0,i,r):t&&this.#i(t)}decode(t,e,i,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=xt(t,e+156,1),o=Ui.has(n),h=o?i:void 0,a=o?r:void 0;if(this.path=h?.path??xt(t,e,100),this.mode=h?.mode??a?.mode??lt(t,e+100,8),this.uid=h?.uid??a?.uid??lt(t,e+108,8),this.gid=h?.gid??a?.gid??lt(t,e+116,8),this.size=un(h?.size??a?.size??lt(t,e+124,12)),this.mtime=h?.mtime??a?.mtime??Wi(t,e+136,12),this.cksum=lt(t,e+148,12),a&&this.#i(a,true),h&&this.#i(h),ne(n)&&(this.#t=n||"0"),this.#t==="0"&&this.path.slice(-1)==="/"&&(this.#t="5"),this.#t==="5"&&(this.size=0),this.linkpath=xt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=h?.uname??a?.uname??xt(t,e+265,32),this.gname=h?.gname??a?.gname??xt(t,e+297,32),this.devmaj=h?.devmaj??a?.devmaj??lt(t,e+329,8)??0,this.devmin=h?.devmin??a?.devmin??lt(t,e+337,8)??0,t[e+475]!==0){let c=xt(t,e+345,155);this.path=c+"/"+this.path}else{let c=xt(t,e+345,130);c&&(this.path=c+"/"+this.path),this.atime=i?.atime??r?.atime??Wi(t,e+476,12),this.ctime=i?.ctime??r?.ctime??Wi(t,e+488,12)}let l=256;for(let c=e;c<e+148;c++)l+=t[c];for(let c=e+156;c<e+512;c++)l+=t[c];this.cksumValid=l===this.cksum,this.cksum===void 0&&l===256&&(this.nullBlock=true)}#i(t,e=false){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="size"&&Number(r)<0||i==="path"&&e||i==="linkpath"&&e||i==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#t==="Unsupported"&&(this.#t="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let i=this.ctime||this.atime?130:155,r=mn(this.path||"",i),n=r[0],o=r[1];this.needPax=!!r[2],this.needPax=Lt(t,e,100,n)||this.needPax,this.needPax=ct(t,e+100,8,this.mode)||this.needPax,this.needPax=ct(t,e+108,8,this.uid)||this.needPax,this.needPax=ct(t,e+116,8,this.gid)||this.needPax,this.needPax=ct(t,e+124,12,this.size)||this.needPax,this.needPax=Gi(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#t.codePointAt(0)),this.needPax=Lt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Lt(t,e+265,32,this.uname)||this.needPax,this.needPax=Lt(t,e+297,32,this.gname)||this.needPax,this.needPax=ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Lt(t,e+345,i,o)||this.needPax,t[e+475]!==0?this.needPax=Lt(t,e+345,155,o)||this.needPax:(this.needPax=Lt(t,e+345,130,o)||this.needPax,this.needPax=Gi(t,e+476,12,this.atime)||this.needPax,this.needPax=Gi(t,e+488,12,this.ctime)||this.needPax);let h=256;for(let a=e;a<e+148;a++)h+=t[a];for(let a=e+156;a<e+512;a++)h+=t[a];return this.cksum=h,ct(t,e+148,8,this.cksum),this.cksumValid=true,this.needPax}get type(){return this.#t==="Unsupported"?this.#t:oe.get(this.#t)}get typeKey(){return this.#t}set type(t){let e=String(Ve.get(t));if(ne(e)||e==="Unsupported")this.#t=e;else if(ne(t))this.#t=t;else throw new TypeError("invalid entry type: "+t)}};mn=(s3,t)=>{let i=s3,r="",n,o=Zt.parse(s3).root||".";if(Buffer.byteLength(i)<100)n=[i,r,false];else{r=Zt.dirname(i),i=Zt.basename(i);do Buffer.byteLength(i)<=100&&Buffer.byteLength(r)<=t?n=[i,r,false]:Buffer.byteLength(i)>100&&Buffer.byteLength(r)<=t?n=[i.slice(0,99),r,true]:(i=Zt.join(Zt.basename(r),i),r=Zt.dirname(r));while(r!==o&&n===void 0);n||(n=[s3.slice(0,99),"",true])}return n};xt=(s3,t,e)=>s3.subarray(t,t+e).toString("utf8").replace(/\0.*/,"");Wi=(s3,t,e)=>pn(lt(s3,t,e));pn=s3=>s3===void 0?void 0:new Date(s3*1e3);lt=(s3,t,e)=>Number(s3[t])&128?Hs(s3.subarray(t,t+e)):wn(s3,t,e);En=s3=>isNaN(s3)?void 0:s3;wn=(s3,t,e)=>En(parseInt(s3.subarray(t,t+e).toString("utf8").replace(/\0.*$/,"").trim(),8));Sn={12:8589934591,8:2097151};ct=(s3,t,e,i)=>i===void 0?false:i>Sn[e]||i<0?(Us(i,s3.subarray(t,t+e)),true):(yn(s3,t,e,i),false);yn=(s3,t,e,i)=>s3.write(Rn(i,e),t,e,"ascii");Rn=(s3,t)=>gn(Math.floor(s3).toString(8),t);gn=(s3,t)=>(s3.length===t-1?s3:new Array(t-s3.length-1).join("0")+s3+" ")+"\0";Gi=(s3,t,e,i)=>i===void 0?false:ct(s3,t,e,i.getTime()/1e3);bn=new Array(156).join("\0");Lt=(s3,t,e,i)=>i===void 0?false:(s3.write(i+bn,t,e,"utf8"),i.length!==Buffer.byteLength(i)||i.length>e);ft=class s{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(t,e=false){this.atime=t.atime,this.charset=t.charset,this.comment=t.comment,this.ctime=t.ctime,this.dev=t.dev,this.gid=t.gid,this.global=e,this.gname=t.gname,this.ino=t.ino,this.linkpath=t.linkpath,this.mtime=t.mtime,this.nlink=t.nlink,this.path=t.path,this.size=t.size,this.uid=t.uid,this.uname=t.uname}encode(){let t=this.encodeBody();if(t==="")return Buffer.allocUnsafe(0);let e=Buffer.byteLength(t),i=512*Math.ceil(1+e/512),r=Buffer.allocUnsafe(i);for(let n=0;n<512;n++)r[n]=0;new F({path:("PaxHeader/"+_n(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:e,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(r),r.write(t,512,e,"utf8");for(let n=e+512;n<r.length;n++)r[n]=0;return r}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(t){if(this[t]===void 0)return"";let e=this[t],i=e instanceof Date?e.getTime()/1e3:e,r=" "+(t==="dev"||t==="ino"||t==="nlink"?"SCHILY.":"")+t+"="+i+`
310
310
  `,n=Buffer.byteLength(r),o=Math.floor(Math.log(n)/Math.log(10))+1;return n+o>=Math.pow(10,o)&&(o+=1),o+n+r}static parse(t,e,i=false){return new s(On(Tn(t),e),i)}};On=(s3,t)=>t?Object.assign({},t,s3):s3;Tn=s3=>s3.replace(/\n$/,"").split(`
311
311
  `).reduce(xn,Object.create(null));xn=(s3,t)=>{let e=parseInt(t,10);if(e!==Buffer.byteLength(t)+1)return s3;t=t.slice((e+" ").length);let i=t.split("="),r=i.shift();if(!r)return s3;let n=r.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=").replace(/\0.*/,"");switch(n){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":s3[n]=o;break;case"ctime":case"atime":case"mtime":s3[n]=new Date(Number(o)*1e3);break;case"size":let h=+o;h>=0&&(s3[n]=h);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":s3[n]=+o;break}return s3};Ln=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;f=Ln!=="win32"?s3=>String(s3):s3=>String(s3).replaceAll(/\\/g,"/");$e=class extends A{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=false;ignore=false;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=false;absolute;unsupported=false;constructor(t,e,i){switch(super({}),this.pause(),this.extended=e,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=true;break;default:this.ignore=true}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=f(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?f(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#t(e),i&&this.#t(i,true)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-e),this.blockRemain=Math.max(0,r-e),this.ignore?true:i>=e?super.write(t):super.write(t.subarray(0,i))}#t(t,e=false){t.path&&(t.path=f(t.path)),t.linkpath&&(t.linkpath=f(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="path"&&e))))}};Dt=(s3,t,e,i={})=>{s3.file&&(i.file=s3.file),s3.cwd&&(i.cwd=s3.cwd),i.code=e instanceof Error&&e.code||t,i.tarCode=t,!s3.strict&&i.recoverable!==false?(e instanceof Error&&(i=Object.assign(e,i),e=e.message),s3.emit("warn",t,e,i)):e instanceof Error?s3.emit("error",Object.assign(e,i)):s3.emit("error",Object.assign(new Error(`${t}: ${e}`),i))};Nn=1024*1024;Xi=Buffer.from([31,139]);qi=Buffer.from([40,181,47,253]);An=Math.max(Xi.length,qi.length);B=Symbol("state");Nt=Symbol("writeEntry");it=Symbol("readEntry");Zi=Symbol("nextEntry");Zs=Symbol("processEntry");V=Symbol("extendedHeader");he=Symbol("globalExtendedHeader");dt=Symbol("meta");Ys=Symbol("emitMeta");p=Symbol("buffer");st=Symbol("queue");ut=Symbol("ended");Yi=Symbol("emittedEnd");At=Symbol("emit");w=Symbol("unzip");Xe=Symbol("consumeChunk");qe=Symbol("consumeChunkSub");Ki=Symbol("consumeBody");Ks=Symbol("consumeMeta");Vs=Symbol("consumeHeader");ae=Symbol("consuming");Vi=Symbol("bufferConcat");Qe=Symbol("maybeEnd");Yt=Symbol("writing");$=Symbol("aborted");Je=Symbol("onDone");It=Symbol("sawValidEntry");je=Symbol("sawNullBlock");ti=Symbol("sawEOF");$s=Symbol("closeStream");In=1e3;le=Symbol("compressedBytesRead");$i=Symbol("decompressedBytesRead");Xs=Symbol("checkDecompressionRatio");Cn=()=>true;rt=class extends Dn{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=true;readable=false;[st]=[];[p];[it];[Nt];[B]="begin";[dt]="";[V];[he];[ut]=false;[w];[$]=false;[It];[je]=false;[ti]=false;[Yt]=false;[ae]=false;[Yi]=false;[le]=0;[$i]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Je,()=>{(this[B]==="begin"||this[It]===false)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Je,t.ondone):this.on(Je,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:In,this.maxMetaEntrySize=t.maxMetaEntrySize||Nn,this.filter=typeof t.filter=="function"?t.filter:Cn;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:false;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?true:void 0,this.on("end",()=>this[$s]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,i={}){Dt(this,t,e,i)}[Vs](t,e){this[It]===void 0&&(this[It]=false);let i;try{i=new F(t,e,this[V],this[he])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[je]?(this[ti]=true,this[B]==="begin"&&(this[B]="header"),this[At]("eof")):(this[je]=true,this[At]("nullBlock"));else if(this[je]=false,!i.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:i});else if(!i.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:i});else{let r=i.type;if(/^(Symbolic)?Link$/.test(r)&&!i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:i});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&i.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:i});else{let n=this[Nt]=new $e(i,this[V],this[he]);if(!this[It])if(n.remain){let o=()=>{n.invalid||(this[It]=true)};n.on("end",o)}else this[It]=true;n.meta?n.size>this.maxMetaEntrySize?(n.ignore=true,this[At]("ignoredEntry",n),this[B]="ignore",n.resume()):n.size>0&&(this[dt]="",n.on("data",o=>this[dt]+=o),this[B]="meta"):(this[V]=void 0,n.ignore=n.ignore||!this.filter(n.path,n),n.ignore?(this[At]("ignoredEntry",n),this[B]=n.remain?"ignore":"header",n.resume()):(n.remain?this[B]="body":(this[B]="header",n.end()),this[it]?this[st].push(n):(this[st].push(n),this[Zi]())))}}}[$s](){queueMicrotask(()=>this.emit("close"))}[Zs](t){let e=true;if(!t)this[it]=void 0,e=false;else if(Array.isArray(t)){let[i,...r]=t;this.emit(i,...r)}else this[it]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Zi]()),e=false);return e}[Zi](){do;while(this[Zs](this[st].shift()));if(this[st].length===0){let t=this[it];!t||t.flowing||t.size===t.remain?this[Yt]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ki](t,e){let i=this[Nt];if(!i)throw new Error("attempt to consume body without entry??");let r=i.blockRemain??0,n=r>=t.length&&e===0?t:t.subarray(e,e+r);return i.write(n),i.blockRemain||(this[B]="header",this[Nt]=void 0,i.end()),n.length}[Ks](t,e){let i=this[Nt],r=this[Ki](t,e);return!this[Nt]&&i&&this[Ys](i),r}[At](t,e,i){this[st].length===0&&!this[it]?this.emit(t,e,i):this[st].push([t,e,i])}[Ys](t){switch(this[At]("meta",this[dt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[V]=ft.parse(this[dt],this[V],false);break;case"GlobalExtendedHeader":this[he]=ft.parse(this[dt],this[he],true);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[V]??Object.create(null);this[V]=e,e.path=this[dt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[V]||Object.create(null);this[V]=e,e.linkpath=this[dt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){if(!this[$]){if(this[w]){let e=this[w];e.write=()=>true,e.end=()=>e,e.emit=()=>false,e.destroy?.()}this[$]=true,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:false})}}[Xs](t){this[$i]+=t.length;let e=this[$i]/this[le];return e>this.maxDecompressionRatio?(this.abort(new Error(`max decompression ratio exceeded: ${e.toFixed(2)} > ${this.maxDecompressionRatio}`)),false):true}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[$])return i?.(),false;if((this[w]===void 0||this.brotli===void 0&&this[w]===false)&&t){if(this[p]&&(t=Buffer.concat([this[p],t]),this[p]=void 0),t.length<An)return this[p]=t,i?.(),true;for(let a=0;this[w]===void 0&&a<Xi.length;a++)t[a]!==Xi[a]&&(this[w]=false);let o=false;if(this[w]===false&&this.zstd!==false){o=true;for(let a=0;a<qi.length;a++)if(t[a]!==qi[a]){o=false;break}}let h=this.brotli===void 0&&!o;if(this[w]===false&&h)if(t.length<512)if(this[ut])this.brotli=true;else return this[p]=t,i?.(),true;else try{new F(t.subarray(0,512)),this.brotli=false}catch{this.brotli=true}if(this[w]===void 0||this[w]===false&&(this.brotli||o)){let a=this[ut];this[ut]=false,this[w]=this[w]===void 0?new Ue({}):o?new Ke({}):new Ge({}),this[w].on("data",c=>{this[Xs](c)&&this[Xe](c)}),this[w].on("error",c=>{this[$]||this.abort(c)}),this[w].on("end",()=>{this[ut]=true,this[Xe]()}),this[Yt]=true,this[le]+=t.length;let l=!!this[w][a?"end":"write"](t);return this[Yt]=false,i?.(),l}}this[Yt]=true,this[w]?(this[le]+=t.length,this[w].write(t)):this[Xe](t),this[Yt]=false;let n=this[st].length>0?false:this[it]?this[it].flowing:true;return!n&&this[st].length===0&&this[it]?.once("drain",()=>this.emit("drain")),i?.(),n}[Vi](t){t&&!this[$]&&(this[p]=this[p]?Buffer.concat([this[p],t]):t)}[Qe](){if(this[ut]&&!this[Yi]&&!this[$]&&!this[ae]){this[Yi]=true;let t=this[Nt];if(t?.blockRemain){let e=this[p]?this[p].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[p]&&t.write(this[p]),t.end()}this[At](Je)}}[Xe](t){if(this[ae]&&t)this[Vi](t);else if(!t&&!this[p])this[Qe]();else if(t){if(this[ae]=true,this[p]){this[Vi](t);let e=this[p];this[p]=void 0,this[qe](e)}else this[qe](t);for(;this[p]&&this[p]?.length>=512&&!this[$]&&!this[ti];){let e=this[p];this[p]=void 0,this[qe](e)}this[ae]=false}(!this[p]||this[ut])&&this[Qe]()}[qe](t){let e=0,i=t.length;for(;e+512<=i&&!this[$]&&!this[ti];)switch(this[B]){case"begin":case"header":this[Vs](t,e),e+=512;break;case"ignore":case"body":e+=this[Ki](t,e);break;case"meta":e+=this[Ks](t,e);break;default:throw new Error("invalid state: "+this[B])}e<i&&(this[p]=this[p]?Buffer.concat([t.subarray(e),this[p]]):t.subarray(e))}end(t,e,i){return typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),i&&this.once("finish",i),this[$]||(this[w]?(t&&(this[le]+=t.length,this[w].write(t)),this[w].end()):(this[ut]=true,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Qe]())),this}};mt=s3=>{let t=s3.length-1,e=-1;for(;t>-1&&s3.charAt(t)==="/";)e=t,t--;return e===-1?s3:s3.slice(0,e)};vn=s3=>{let t=s3.onReadEntry;s3.onReadEntry=t?e=>{t(e),e.resume()}:e=>e.resume()};Qi=(s3,t)=>{let e=new Map(t.map(o=>[mt(o),true])),i=s3.filter,r=100,n=(o,h="",a=0)=>{if(a>=r)return e.set(o,false),false;let l=h||kn(o).root||".",c;if(o===l)c=false;else{let d=e.get(o);c=d!==void 0?d:n(Fn(o),l,a+1)}return e.set(o,c),c};s3.filter=i?(o,h)=>i(o,h)&&n(mt(o)):o=>n(mt(o))};Mn=s3=>{let t=new rt(s3),e=s3.file,i;try{i=Kt.openSync(e,"r");let r=Kt.fstatSync(i),n=s3.maxReadSize||16*1024*1024;if(r.size<n){let o=Buffer.allocUnsafe(r.size),h=Kt.readSync(i,o,0,r.size,0);t.end(h===o.byteLength?o:o.subarray(0,h))}else{let o=0,h=Buffer.allocUnsafe(n);for(;o<r.size;){let a=Kt.readSync(i,h,0,n,o);if(a===0)break;o+=a,t.write(h.subarray(0,a))}t.end()}}finally{if(typeof i=="number")try{Kt.closeSync(i)}catch{}}};Bn=(s3,t)=>{let e=new rt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("end",o),Kt.stat(r,(a,l)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l.size});c.on("error",h),c.pipe(e)}})})};Ct=K(Mn,Bn,s3=>new rt(s3),s3=>new rt(s3),(s3,t)=>{t?.length&&Qi(s3,t),s3.noResume||vn(s3)});Ji=(s3,t,e)=>(s3&=4095,e&&(s3=(s3|384)&-19),t&&(s3&256&&(s3|=64),s3&32&&(s3|=8),s3&4&&(s3|=1)),s3);({isAbsolute:zn,parse:qs}=Pn);ce=s3=>{let t="",e=qs(s3);for(;zn(s3)||e.root;){let i=s3.charAt(0)==="/"&&s3.slice(0,4)!=="//?/"?"/":e.root;s3=s3.slice(i.length),t+=i,e=qs(s3)}return[t,s3]};ei=["|","<",">","?",":"];ji=ei.map(s3=>String.fromCodePoint(61440+Number(s3.codePointAt(0))));Un=new Map(ei.map((s3,t)=>[s3,ji[t]]));Hn=new Map(ji.map((s3,t)=>[s3,ei[t]]));ts=s3=>ei.reduce((t,e)=>t.split(e).join(Un.get(e)),s3);Qs=s3=>ji.reduce((t,e)=>t.split(e).join(Hn.get(e)),s3);rr=(s3,t)=>t?(s3=f(s3).replace(/^\.(\/|$)/,""),mt(t)+"/"+s3):f(s3);Wn=16*1024*1024;tr=Symbol("process");er=Symbol("file");ir=Symbol("directory");is=Symbol("symlink");sr=Symbol("hardlink");fe=Symbol("header");ii=Symbol("read");ss=Symbol("lstat");si=Symbol("onlstat");rs=Symbol("onread");ns=Symbol("onreadlink");os5=Symbol("openfile");hs=Symbol("onopenfile");pt=Symbol("close");ri=Symbol("mode");as=Symbol("awaitDrain");es=Symbol("ondrain");q=Symbol("prefix");de=class extends A{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#t=false;constructor(t,e={}){let i=se(e);super(),this.path=f(t),this.portable=!!i.portable,this.maxReadSize=i.maxReadSize||Wn,this.linkCache=i.linkCache||new Map,this.statCache=i.statCache||new Map,this.preservePaths=!!i.preservePaths,this.cwd=f(i.cwd||process.cwd()),this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.mtime=i.mtime,this.prefix=i.prefix?f(i.prefix):void 0,this.onWriteEntry=i.onWriteEntry,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let r=false;if(!this.preservePaths){let[o,h]=ce(this.path);o&&typeof h=="string"&&(this.path=h,r=o)}this.win32=!!i.win32||process.platform==="win32",this.win32&&(this.path=Qs(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=f(i.absolute||js.resolve(this.cwd,t)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let n=this.statCache.get(this.absolute);n?this[si](n):this[ss]()}warn(t,e,i={}){return Dt(this,t,e,i)}emit(t,...e){return t==="error"&&(this.#t=true),super.emit(t,...e)}[ss](){X.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[si](e)})}[si](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Gn(t),this.emit("stat",t),this[tr]()}[tr](){switch(this.type){case"File":return this[er]();case"Directory":return this[ir]();case"SymbolicLink":return this[is]();default:return this.end()}}[ri](t){return Ji(t,this.type==="Directory",this.portable)}[q](t){return rr(t,this.prefix)}[fe](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=true),this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,mode:this[ri](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new ft({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[ir](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[fe](),this.end()}[is](){X.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ns](e)})}[ns](t){this.linkpath=f(t),this[fe](),this.end()}[sr](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=f(js.relative(this.cwd,t)),this.stat.size=0,this[fe](),this.end()}[er](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[sr](e);this.linkCache.set(t,this.absolute)}if(this[fe](),this.stat.size===0)return this.end();this[os5]()}[os5](){X.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[hs](e)})}[hs](t){if(this.fd=t,this.#t)return this[pt]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[ii]()}[ii](){let{fd:t,buf:e,offset:i,length:r,pos:n}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");X.read(t,e,i,r,n,(o,h)=>{if(o)return this[pt](()=>this.emit("error",o));this[rs](h)})}[pt](t=()=>{}){this.fd!==void 0&&X.close(this.fd,t)}[rs](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[pt](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[es]():this[as](()=>this[es]())}[as](t){this.once("drain",t)}write(t,e,i){if(typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let r=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",r)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,i)}[es](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[pt](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[ii]()}};ni=class extends de{sync=true;[ss](){this[si](X.lstatSync(this.absolute))}[is](){this[ns](X.readlinkSync(this.absolute))}[os5](){this[hs](X.openSync(this.absolute,"r"))}[ii](){let t=true;try{let{fd:e,buf:i,offset:r,length:n,pos:o}=this;if(e===void 0||i===void 0)throw new Error("fd and buf must be set in READ method");let h=X.readSync(e,i,r,n,o);this[rs](h),t=false}finally{if(t)try{this[pt](()=>{})}catch{}}}[as](t){t()}[pt](t=()=>{}){this.fd!==void 0&&X.closeSync(this.fd),t()}};oi=class extends A{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,i={}){return Dt(this,t,e,i)}constructor(t,e={}){let i=se(e);super(),this.preservePaths=!!i.preservePaths,this.portable=!!i.portable,this.strict=!!i.strict,this.noPax=!!i.noPax,this.noMtime=!!i.noMtime,this.onWriteEntry=i.onWriteEntry,this.readEntry=t;let{type:r}=t;if(r==="Unsupported")throw new Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=true),this.prefix=i.prefix,this.path=f(t.path),this.mode=t.mode!==void 0?this[ri](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:i.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?f(t.linkpath):void 0,typeof i.onwarn=="function"&&this.on("warn",i.onwarn);let n=false;if(!this.preservePaths){let[h,a]=ce(this.path);h&&typeof a=="string"&&(this.path=a,n=h)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new F({path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new ft({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[q](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[q](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let o=this.header?.block;if(!o)throw new Error("failed to encode header");super.write(o),t.pipe(this)}[q](t){return rr(t,this.prefix)}[ri](t){return Ji(t,this.type==="Directory",this.portable)}write(t,e,i){typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(t,i)}end(t,e,i){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(i=t,e=void 0,t=void 0),typeof e=="function"&&(i=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),i&&this.once("finish",i),t?super.end(t,i):super.end(i),this}};Gn=s3=>s3.isFile()?"File":s3.isDirectory()?"Directory":s3.isSymbolicLink()?"SymbolicLink":"Unsupported";hi=class s2{tail;head;length=0;static create(t=[]){return new s2(t)}constructor(t=[]){for(let e of t)this.push(e)}*[Symbol.iterator](){for(let t=this.head;t;t=t.next)yield t.value}removeNode(t){if(t.list!==this)throw new Error("removing node which does not belong to this list");let e=t.next,i=t.prev;return e&&(e.prev=i),i&&(i.next=e),t===this.head&&(this.head=e),t===this.tail&&(this.tail=i),this.length--,t.next=void 0,t.prev=void 0,t.list=void 0,e}unshiftNode(t){if(t===this.head)return;t.list&&t.list.removeNode(t);let e=this.head;t.list=this,t.next=e,e&&(e.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}pushNode(t){if(t===this.tail)return;t.list&&t.list.removeNode(t);let e=this.tail;t.list=this,t.prev=e,e&&(e.next=t),this.tail=t,this.head||(this.head=t),this.length++}push(...t){for(let e=0,i=t.length;e<i;e++)Yn(this,t[e]);return this.length}unshift(...t){for(var e=0,i=t.length;e<i;e++)Kn(this,t[e]);return this.length}pop(){if(!this.tail)return;let t=this.tail.value,e=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,e.list=void 0,this.length--,t}shift(){if(!this.head)return;let t=this.head.value,e=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,e.list=void 0,this.length--,t}forEach(t,e){e=e||this;for(let i=this.head,r=0;i;r++)t.call(e,i.value,r,this),i=i.next}forEachReverse(t,e){e=e||this;for(let i=this.tail,r=this.length-1;i;r--)t.call(e,i.value,r,this),i=i.prev}get(t){let e=0,i=this.head;for(;i&&e<t;e++)i=i.next;if(e===t&&i)return i.value}getReverse(t){let e=0,i=this.tail;for(;i&&e<t;e++)i=i.prev;if(e===t&&i)return i.value}map(t,e){e=e||this;let i=new s2;for(let r=this.head;r;)i.push(t.call(e,r.value,this)),r=r.next;return i}mapReverse(t,e){e=e||this;var i=new s2;for(let r=this.tail;r;)i.push(t.call(e,r.value,this)),r=r.prev;return i}reduce(t,e){let i,r=this.head;if(arguments.length>1)i=e;else if(this.head)r=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;r;n++)i=t(i,r.value,n),r=r.next;return i}reduceReverse(t,e){let i,r=this.tail;if(arguments.length>1)i=e;else if(this.tail)r=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let n=this.length-1;r;n--)i=t(i,r.value,n),r=r.prev;return i}toArray(){let t=new Array(this.length);for(let e=0,i=this.head;i;e++)t[e]=i.value,i=i.next;return t}toArrayReverse(){let t=new Array(this.length);for(let e=0,i=this.tail;i;e++)t[e]=i.value,i=i.prev;return t}slice(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.head,n=0;for(n=0;r&&n<t;n++)r=r.next;for(;r&&n<e;n++,r=r.next)i.push(r.value);return i}sliceReverse(t=0,e=this.length){e<0&&(e+=this.length),t<0&&(t+=this.length);let i=new s2;if(e<t||e<0)return i;t<0&&(t=0),e>this.length&&(e=this.length);let r=this.length,n=this.tail;for(;n&&r>e;r--)n=n.prev;for(;n&&r>t;r--,n=n.prev)i.push(n.value);return i}splice(t,e=0,...i){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);let r=this.head;for(let o=0;r&&o<t;o++)r=r.next;let n=[];for(let o=0;r&&o<e;o++)n.push(r.value),r=this.removeNode(r);r?r!==this.tail&&(r=r.prev):r=this.tail;for(let o of i)r=Zn(this,r,o);return n}reverse(){let t=this.head,e=this.tail;for(let i=t;i;i=i.prev){let r=i.prev;i.prev=i.next,i.next=r}return this.head=e,this.tail=t,this}};ue=class{list;next;prev;value;constructor(t,e,i,r){this.list=r,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,i?(i.prev=this,this.next=i):this.next=void 0}};pi=class{path;absolute;entry;stat;readdir;pending=false;pendingLink=false;ignore=false;piped=false;constructor(t,e){this.path=t||"./",this.absolute=e}};nr=Buffer.alloc(1024);li=Symbol("onStat");me=Symbol("ended");W=Symbol("queue");pe=Symbol("pendingLinks");Et=Symbol("current");Ft=Symbol("process");Ee=Symbol("processing");ai=Symbol("processJob");G=Symbol("jobs");ls=Symbol("jobDone");ci=Symbol("addFSEntry");or=Symbol("addTarEntry");ds=Symbol("stat");us=Symbol("readdir");fi=Symbol("onreaddir");di=Symbol("pipe");hr=Symbol("entry");cs=Symbol("entryOpt");ui=Symbol("writeEntryClass");lr=Symbol("write");fs7=Symbol("ondrain");wt=class extends A{sync=false;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ui];onWriteEntry;[W];[pe]=new Map;[G]=0;[Ee]=false;[me]=false;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=f(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[ui]=de,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=true),this.zip=new ze(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new We(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ye(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",i=>super.write(i)),e.on("end",()=>super.end()),e.on("drain",()=>this[fs7]()),this.on("resume",()=>e.resume())}else this.on("drain",this[fs7]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>true,this[W]=new hi,this[G]=0,this.jobs=Number(t.jobs)||4,this[Ee]=false,this[me]=false}[lr](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e=void 0),t&&this.add(t),this[me]=true,this[Ft](),i&&i(),this}write(t){if(this[me])throw new Error("write after end");return typeof t=="string"?this[ci](t):this[or](t),this.flowing}[or](t){let e=f(ar.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let i=new pi(t.path,e);i.entry=new oi(t,this[cs](i)),i.entry.on("end",()=>this[ls](i)),this[G]+=1,this[W].push(i)}this[Ft]()}[ci](t){let e=f(ar.resolve(this.cwd,t));this[W].push(new pi(t,e)),this[Ft]()}[ds](t){t.pending=true,this[G]+=1;let e=this.follow?"stat":"lstat";mi[e](t.absolute,(i,r)=>{t.pending=false,this[G]-=1,i?this.emit("error",i):this[li](t,r)})}[li](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=true;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Et])this[ai](t);else{let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);r?r.push(t):this[pe].set(i,[t]),t.pendingLink=true,t.pending=true}this[Ft]()}[us](t){t.pending=true,this[G]+=1,mi.readdir(t.absolute,(e,i)=>{if(t.pending=false,this[G]-=1,e)return this.emit("error",e);this[fi](t,i)})}[fi](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Ft]()}[Ft](){if(!this[Ee]){this[Ee]=true;for(let t=this[W].head;t&&this[G]<this.jobs;t=t.next)if(this[ai](t.value),t.value.ignore){let e=t.next;this[W].removeNode(t),t.next=e}this[Ee]=false,this[me]&&this[W].length===0&&this[G]===0&&(this.zip?this.zip.end(nr):(super.write(nr),super.end()))}}get[Et](){return this[W]&&this[W].head&&this[W].head.value}[ls](t){this[W].shift(),this[G]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let i=`${e.dev}:${e.ino}`,r=this[pe].get(i);if(r){this[pe].delete(i);for(let n of r)n.pending=false,this[ai](n)}}this[Ft]()}[ai](t){if(t.pending&&t.pendingLink&&t===this[Et]&&(t.pending=false,t.pendingLink=false),!t.pending){if(t.entry){t===this[Et]&&!t.piped&&this[di](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[li](t,e):this[ds](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[fi](t,e):this[us](t),!t.readdir)return}if(t.entry=this[hr](t),!t.entry){t.ignore=true;return}t===this[Et]&&!t.piped&&this[di](t)}}}[cs](t){return{onwarn:(e,i,r)=>this.warn(e,i,r),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[hr](t){this[G]+=1;try{return new this[ui](t.path,this[cs](t)).on("end",()=>this[ls](t)).on("error",i=>this.emit("error",i))}catch(e){this.emit("error",e)}}[fs7](){this[Et]&&this[Et].entry&&this[Et].entry.resume()}[di](t){t.piped=true,t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)});let e=t.entry,i=this.zip;if(!e)throw new Error("cannot pipe without source");i?e.on("data",r=>{i.write(r)||e.pause()}):e.on("data",r=>{super.write(r)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,i={}){Dt(this,t,e,i)}};kt=class extends wt{sync=true;constructor(t){super(t),this[ui]=ni}pause(){}resume(){}[ds](t){let e=this.follow?"statSync":"lstatSync";this[li](t,mi[e](t.absolute))}[us](t){this[fi](t,mi.readdirSync(t.absolute))}[di](t){let e=t.entry,i=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let n=t.path,o=n==="./"?"":n.replace(/\/*$/,"/");this[ci](o+r)}),!e)throw new Error("Cannot pipe without source");i?e.on("data",r=>{i.write(r)}):e.on("data",r=>{super[lr](r)})}};Vn=(s3,t)=>{let e=new kt(s3),i=new Wt(s3.file,{mode:s3.mode||438});e.pipe(i),fr(e,t)};$n=(s3,t)=>{let e=new wt(s3),i=new et(s3.file,{mode:s3.mode||438});e.pipe(i);let r=new Promise((n,o)=>{i.on("error",o),i.on("close",n),e.on("error",o)});return dr(e,t).catch(n=>e.emit("error",n)),r};fr=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:cr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};dr=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:cr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>{s3.add(i)}}):s3.add(e);s3.end()};Xn=(s3,t)=>{let e=new kt(s3);return fr(e,t),e};qn=(s3,t)=>{let e=new wt(s3);return dr(e,t).catch(i=>e.emit("error",i)),e};Qn=K(Vn,$n,Xn,qn,(s3,t)=>{if(!t?.length)throw new TypeError("no paths specified to add to archive")});Jn=process.env.__FAKE_PLATFORM__||process.platform;Er=Jn==="win32";({O_CREAT:wr,O_NOFOLLOW:ur,O_TRUNC:Sr,O_WRONLY:yr}=pr.constants);Rr=Number(process.env.__FAKE_FS_O_FILENAME__)||pr.constants.UV_FS_O_FILEMAP||0;jn=Er&&!!Rr;to=512*1024;eo=Rr|Sr|wr|yr;mr=!Er&&typeof ur=="number"?ur|Sr|wr|yr:null;ms=mr!==null?()=>mr:jn?s3=>s3<to?eo:"w":()=>"w";ps=(s3,t,e)=>{try{return wi.lchownSync(s3,t,e)}catch(i){if(i?.code!=="ENOENT")throw i}};Ei=(s3,t,e,i)=>{wi.lchown(s3,t,e,r=>{i(r&&r?.code!=="ENOENT"?r:null)})};io=(s3,t,e,i,r)=>{if(t.isDirectory())Es(we.resolve(s3,t.name),e,i,n=>{if(n)return r(n);let o=we.resolve(s3,t.name);Ei(o,e,i,r)});else{let n=we.resolve(s3,t.name);Ei(n,e,i,r)}};Es=(s3,t,e,i)=>{wi.readdir(s3,{withFileTypes:true},(r,n)=>{if(r){if(r.code==="ENOENT")return i();if(r.code!=="ENOTDIR"&&r.code!=="ENOTSUP")return i(r)}if(r||!n.length)return Ei(s3,t,e,i);let o=n.length,h=null,a=l=>{if(!h){if(l)return i(h=l);if(--o===0)return Ei(s3,t,e,i)}};for(let l of n)io(s3,l,t,e,a)})};so=(s3,t,e,i)=>{t.isDirectory()&&ws(we.resolve(s3,t.name),e,i),ps(we.resolve(s3,t.name),e,i)};ws=(s3,t,e)=>{let i;try{i=wi.readdirSync(s3,{withFileTypes:true})}catch(r){let n=r;if(n?.code==="ENOENT")return;if(n?.code==="ENOTDIR"||n?.code==="ENOTSUP")return ps(s3,t,e);throw n}for(let r of i)so(s3,r,t,e);return ps(s3,t,e)};Se=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}};St=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}};no=(s3,t)=>{k.stat(s3,(e,i)=>{(e||!i.isDirectory())&&(e=new Se(s3,e?.code||"ENOTDIR")),t(e)})};gr=(s3,t,e)=>{s3=f(s3);let i=t.umask??18,r=t.mode|448,n=(r&i)!==0,o=t.uid,h=t.gid,a=typeof o=="number"&&typeof h=="number"&&(o!==t.processUid||h!==t.processGid),l=t.preserve,c=t.unlink,d=f(t.cwd),y=(E,x)=>{E?e(E):x&&a?Es(x,o,h,Le=>y(Le)):n?k.chmod(s3,r,e):e()};if(s3===d)return no(s3,y);if(l)return ro.mkdir(s3,{mode:r,recursive:true}).then(E=>y(null,E??void 0),y);let D=f(Si.relative(d,s3)).split("/");Ss(d,D,r,c,d,void 0,y)};Ss=(s3,t,e,i,r,n,o)=>{if(t.length===0)return o(null,n);let h=t.shift(),a=f(Si.resolve(s3+"/"+h));k.mkdir(a,e,br(a,t,e,i,r,n,o))};br=(s3,t,e,i,r,n,o)=>h=>{h?k.lstat(s3,(a,l)=>{if(a)a.path=a.path&&f(a.path),o(a);else if(l.isDirectory())Ss(s3,t,e,i,r,n,o);else if(i)k.unlink(s3,c=>{if(c)return o(c);k.mkdir(s3,e,br(s3,t,e,i,r,n,o))});else{if(l.isSymbolicLink())return o(new St(s3,s3+"/"+t.join("/")));o(h)}}):(n=n||s3,Ss(s3,t,e,i,r,n,o))};oo=s3=>{let t=false,e;try{t=k.statSync(s3).isDirectory()}catch(i){e=i?.code}finally{if(!t)throw new Se(s3,e??"ENOTDIR")}};_r=(s3,t)=>{s3=f(s3);let e=t.umask??18,i=t.mode|448,r=(i&e)!==0,n=t.uid,o=t.gid,h=typeof n=="number"&&typeof o=="number"&&(n!==t.processUid||o!==t.processGid),a=t.preserve,l=t.unlink,c=f(t.cwd),d=E=>{E&&h&&ws(E,n,o),r&&k.chmodSync(s3,i)};if(s3===c)return oo(c),d();if(a)return d(k.mkdirSync(s3,{mode:i,recursive:true})??void 0);let T=f(Si.relative(c,s3)).split("/"),D;for(let E=T.shift(),x=c;E&&(x+="/"+E);E=T.shift()){x=f(Si.resolve(x));try{k.mkdirSync(x,i),D=D||x}catch{let Le=k.lstatSync(x);if(Le.isDirectory())continue;if(l){k.unlinkSync(x),k.mkdirSync(x,i),D=D||x;continue}else if(Le.isSymbolicLink())return new St(x,x+"/"+T.join("/"))}}return d(D)};ys=Object.create(null);Or=1e4;Vt=new Set;Tr=s3=>{Vt.has(s3)?Vt.delete(s3):ys[s3]=s3.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Vt.add(s3);let t=ys[s3],e=Vt.size-Or;if(e>Or/10){for(let i of Vt)if(Vt.delete(i),delete ys[i],--e<=0)break}return t};ho=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;ao=ho==="win32";lo=s3=>s3.split("/").slice(0,-1).reduce((e,i)=>{let r=e.at(-1);return r!==void 0&&(i=xr(r,i)),e.push(i||"/"),e},[]);yi=class{#t=new Map;#i=new Map;#s=new Set;reserve(t,e){t=ao?["win32 parallelization disabled"]:t.map(r=>mt(xr(Tr(r))));let i=new Set(t.map(r=>lo(r)).reduce((r,n)=>r.concat(n)));this.#i.set(e,{dirs:i,paths:t});for(let r of t){let n=this.#t.get(r);n?n.push(e):this.#t.set(r,[e])}for(let r of i){let n=this.#t.get(r);if(!n)this.#t.set(r,[new Set([e])]);else{let o=n.at(-1);o instanceof Set?o.add(e):n.push(new Set([e]))}}return this.#r(e)}#n(t){let e=this.#i.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(i=>this.#t.get(i)),dirs:[...e.dirs].map(i=>this.#t.get(i))}}check(t){let{paths:e,dirs:i}=this.#n(t);return e.every(r=>r&&r[0]===t)&&i.every(r=>r&&r[0]instanceof Set&&r[0].has(t))}#r(t){return this.#s.has(t)||!this.check(t)?false:(this.#s.add(t),t(()=>this.#e(t)),true)}#e(t){if(!this.#s.has(t))return false;let e=this.#i.get(t);if(!e)throw new Error("invalid reservation");let{paths:i,dirs:r}=e,n=new Set;for(let o of i){let h=this.#t.get(o);if(!h||h?.[0]!==t)continue;let a=h[1];if(!a){this.#t.delete(o);continue}if(h.shift(),typeof a=="function")n.add(a);else for(let l of a)n.add(l)}for(let o of r){let h=this.#t.get(o),a=h?.[0];if(!(!h||!(a instanceof Set)))if(a.size===1&&h.length===1){this.#t.delete(o);continue}else if(a.size===1){h.shift();let l=h[0];typeof l=="function"&&n.add(l)}else a.delete(t)}return this.#s.delete(t),n.forEach(o=>this.#r(o)),true}};Lr=()=>process.umask();Dr=Symbol("onEntry");_s=Symbol("checkFs");Nr=Symbol("checkFs2");Os=Symbol("isReusable");P=Symbol("makeFs");Ts=Symbol("file");xs=Symbol("directory");gi=Symbol("link");Ar=Symbol("symlink");Ir=Symbol("hardlink");Re=Symbol("ensureNoSymlink");Cr=Symbol("unsupported");Fr=Symbol("checkPath");Rs=Symbol("stripAbsolutePath");yt=Symbol("mkdir");O=Symbol("onError");Ri=Symbol("pending");kr=Symbol("pend");$t=Symbol("unpend");gs=Symbol("ended");bs=Symbol("maybeClose");Ls=Symbol("skip");ge=Symbol("doChown");be=Symbol("uid");_e=Symbol("gid");Oe=Symbol("checkedCwd");fo=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;Te=fo==="win32";uo=1024;mo=(s3,t)=>{if(!Te)return u.unlink(s3,t);let e=s3+".DELETE."+Mr(16).toString("hex");u.rename(s3,e,i=>{if(i)return t(i);u.unlink(e,t)})};po=s3=>{if(!Te)return u.unlinkSync(s3);let t=s3+".DELETE."+Mr(16).toString("hex");u.renameSync(s3,t),u.unlinkSync(t)};vr=(s3,t,e)=>s3!==void 0&&s3===s3>>>0?s3:t!==void 0&&t===t>>>0?t:e;Xt=class extends rt{[gs]=false;[Oe]=false;[Ri]=0;reservations=new yi;transform;writable=true;readable=false;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[gs]=true,this[bs]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=true}else this.uid=void 0,this.gid=void 0,this.setOwner=false;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?process.getuid?.()===0:!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:uo,this.forceChown=t.forceChown===true,this.win32=!!t.win32||Te,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=f(R.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Lr():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Dr](e))}warn(t,e,i={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(i.recoverable=false),super.warn(t,e,i)}[bs](){this[gs]&&this[Ri]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Rs](t,e){let i=t[e],{type:r}=t;if(!i||this.preservePaths)return true;let[n,o]=ce(i),h=o.replaceAll(/\\/g,"/").split("/");if(h.includes("..")||Te&&/^[a-z]:\.\.$/i.test(h[0]??"")){if(e==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:i}),false;let a=R.posix.dirname(t.path),l=R.posix.normalize(R.posix.join(a,h.join("/")));if(l.startsWith("../")||l==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:i}),false}return n&&(t[e]=String(o),this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute ${e}`,{entry:t,[e]:i})),true}[Fr](t){let e=f(t.path),i=e.split("/");if(this.strip){if(i.length<this.strip)return false;if(t.type==="Link"){let r=f(String(t.linkpath)).split("/");if(r.length>=this.strip)t.linkpath=r.slice(this.strip).join("/");else return false}i.splice(0,this.strip),t.path=i.join("/")}if(isFinite(this.maxDepth)&&i.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:i.length,maxDepth:this.maxDepth}),false;if(!this[Rs](t,"path")||!this[Rs](t,"linkpath"))return false;if(t.absolute=R.isAbsolute(t.path)?f(R.resolve(t.path)):f(R.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:f(t.path),resolvedPath:t.absolute,cwd:this.cwd}),false;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return false;if(this.win32){let{root:r}=R.win32.parse(String(t.absolute));t.absolute=r+ts(String(t.absolute).slice(r.length));let{root:n}=R.win32.parse(t.path);t.path=n+ts(t.path.slice(n.length))}return true}[Dr](t){if(!this[Fr](t))return t.resume();switch(co.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[_s](t);default:return this[Cr](t)}}[O](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[$t](),e.resume())}[yt](t,e,i){gr(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},i)}[ge](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[be](t){return vr(this.uid,t.uid,this.processUid)}[_e](t){return vr(this.gid,t.gid,this.processGid)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new et(String(t.absolute),{flags:ms(t.size),mode:i,autoClose:false});r.on("error",a=>{r.fd&&u.close(r.fd,()=>{}),r.write=()=>true,this[O](a,t),e()});let n=1,o=a=>{if(a){r.fd&&u.close(r.fd,()=>{}),this[O](a,t),e();return}--n===0&&r.fd!==void 0&&u.close(r.fd,l=>{l?this[O](l,t):this[$t](),e()})};r.on("finish",()=>{let a=String(t.absolute),l=r.fd;if(typeof l=="number"&&t.mtime&&!this.noMtime){n++;let c=t.atime||new Date,d=t.mtime;u.futimes(l,c,d,y=>y?u.utimes(a,c,d,T=>o(T&&y)):o())}if(typeof l=="number"&&this[ge](t)){n++;let c=this[be](t),d=this[_e](t);typeof c=="number"&&typeof d=="number"&&u.fchown(l,c,d,y=>y?u.chown(a,c,d,T=>o(T&&y)):o())}o()});let h=this.transform&&this.transform(t)||t;h!==t&&(h.on("error",a=>{this[O](a,t),e()}),t.pipe(h)),h.pipe(r)}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode;this[yt](String(t.absolute),i,r=>{if(r){this[O](r,t),e();return}let n=1,o=()=>{--n===0&&(e(),this[$t](),t.resume())};t.mtime&&!this.noMtime&&(n++,u.utimes(String(t.absolute),t.atime||new Date,t.mtime,o)),this[ge](t)&&(n++,u.chown(String(t.absolute),Number(this[be](t)),Number(this[_e](t)),o)),o()})}[Cr](t){t.unsupported=true,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Ar](t,e){let i=f(R.relative(this.cwd,R.resolve(R.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Re](t,this.cwd,i,()=>this[gi](t,String(t.linkpath),"symlink",e),r=>{this[O](r,t),e()})}[Ir](t,e){let i=f(R.resolve(this.cwd,String(t.linkpath))),r=f(String(t.linkpath)).split("/");this[Re](t,this.cwd,r,()=>this[gi](t,i,"link",e),n=>{this[O](n,t),e()})}[Re](t,e,i,r,n){let o=i.shift();if(this.preservePaths||o===void 0)return r();let h=R.resolve(e,o);u.lstat(h,(a,l)=>{if(a)return r();if(l?.isSymbolicLink())return n(new St(h,R.resolve(h,i.join("/"))));this[Re](t,h,i,r,n)})}[kr](){this[Ri]++}[$t](){this[Ri]--,this[bs]()}[Ls](t){this[$t](),t.resume()}[Os](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Te}[_s](t){this[kr]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,i=>this[Nr](t,i))}[Nr](t,e){let i=h=>{e(h)},r=()=>{this[yt](this.cwd,this.dmode,h=>{if(h){this[O](h,t),i();return}this[Oe]=true,n()})},n=()=>{if(t.absolute!==this.cwd){let h=f(R.dirname(String(t.absolute)));if(h!==this.cwd)return this[yt](h,this.dmode,a=>{if(a){this[O](a,t),i();return}o()})}o()},o=()=>{u.lstat(String(t.absolute),(h,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[Ls](t),i();return}if(h||this[Os](t,a))return this[P](null,t,i);if(a.isDirectory()){if(t.type==="Directory"){let l=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,c=d=>this[P](d??null,t,i);return l?u.chmod(String(t.absolute),Number(t.mode),c):c()}if(t.absolute!==this.cwd)return u.rmdir(String(t.absolute),l=>this[P](l??null,t,i))}if(t.absolute===this.cwd)return this[P](null,t,i);mo(String(t.absolute),l=>this[P](l??null,t,i))})};this[Oe]?n():r()}[P](t,e,i){if(t){this[O](t,e),i();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Ts](e,i);case"Link":return this[Ir](e,i);case"SymbolicLink":return this[Ar](e,i);case"Directory":case"GNUDumpDir":return this[xs](e,i)}}[gi](t,e,i,r){u[i](e,String(t.absolute),n=>{n?this[O](n,t):(this[$t](),t.resume()),r()})}};ye=s3=>{try{return[null,s3()]}catch(t){return[t,null]}};xe=class extends Xt{sync=true;[P](t,e){return super[P](t,e,()=>{})}[_s](t){if(!this[Oe]){let n=this[yt](this.cwd,this.dmode);if(n)return this[O](n,t);this[Oe]=true}if(t.absolute!==this.cwd){let n=f(R.dirname(String(t.absolute)));if(n!==this.cwd){let o=this[yt](n,this.dmode);if(o)return this[O](o,t)}}let[e,i]=ye(()=>u.lstatSync(String(t.absolute)));if(i&&(this.keep||this.newer&&i.mtime>(t.mtime??i.mtime)))return this[Ls](t);if(e||this[Os](t,i))return this[P](null,t);if(i.isDirectory()){if(t.type==="Directory"){let o=this.chmod&&t.mode&&(i.mode&4095)!==t.mode,[h]=o?ye(()=>{u.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[P](h,t)}let[n]=ye(()=>u.rmdirSync(String(t.absolute)));this[P](n,t)}let[r]=t.absolute===this.cwd?[]:ye(()=>po(String(t.absolute)));this[P](r,t)}[Ts](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.fmode,r=h=>{let a;try{u.closeSync(n)}catch(l){a=l}(h||a)&&this[O](h||a,t),e()},n;try{n=u.openSync(String(t.absolute),ms(t.size),i)}catch(h){return r(h)}let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",h=>this[O](h,t)),t.pipe(o)),o.on("data",h=>{try{u.writeSync(n,h,0,h.length)}catch(a){r(a)}}),o.on("end",()=>{let h=null;if(t.mtime&&!this.noMtime){let a=t.atime||new Date,l=t.mtime;try{u.futimesSync(n,a,l)}catch(c){try{u.utimesSync(String(t.absolute),a,l)}catch{h=c}}}if(this[ge](t)){let a=this[be](t),l=this[_e](t);try{u.fchownSync(n,Number(a),Number(l))}catch(c){try{u.chownSync(String(t.absolute),Number(a),Number(l))}catch{h=h||c}}}r(h)})}[xs](t,e){let i=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[yt](String(t.absolute),i);if(r){this[O](r,t),e();return}if(t.mtime&&!this.noMtime)try{u.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ge](t))try{u.chownSync(String(t.absolute),Number(this[be](t)),Number(this[_e](t)))}catch{}e(),t.resume()}[yt](t,e){try{return _r(f(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(i){return i}}[Re](t,e,i,r,n){if(this.preservePaths||i.length===0)return r();let o=e;for(let h of i){o=R.resolve(o,h);let[a,l]=ye(()=>u.lstatSync(o));if(a)return r();if(l.isSymbolicLink())return n(new St(o,R.resolve(e,i.join("/"))))}r()}[gi](t,e,i,r){let n=`${i}Sync`;try{u[n](e,String(t.absolute)),r(),t.resume()}catch(o){return this[O](o,t)}}};Eo=s3=>{let t=new xe(s3),e=s3.file,i=Br.statSync(e),r=s3.maxReadSize||16*1024*1024;new Be(e,{readSize:r,size:i.size}).pipe(t)};wo=(s3,t)=>{let e=new Xt(s3),i=s3.maxReadSize||16*1024*1024,r=s3.file;return new Promise((o,h)=>{e.on("error",h),e.on("close",o),Br.stat(r,(a,l)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l.size});c.on("error",h),c.pipe(e)}})})};So=K(Eo,wo,s3=>new xe(s3),s3=>new Xt(s3),(s3,t)=>{t?.length&&Qi(s3,t)});yo=(s3,t)=>{let e=new kt(s3),i=true,r,n;try{try{r=v.openSync(s3.file,"r+")}catch(a){if(a?.code==="ENOENT")r=v.openSync(s3.file,"w+");else throw a}let o=v.fstatSync(r),h=Buffer.alloc(512);t:for(n=0;n<o.size;n+=512){for(let c=0,d=0;c<512;c+=d){if(d=v.readSync(r,h,c,h.length-c,n+c),n===0&&h[0]===31&&h[1]===139)throw new Error("cannot append to compressed archives");if(!d)break t}let a=new F(h);if(!a.cksumValid)break;let l=512*Math.ceil((a.size||0)/512);if(n+l+512>o.size)break;n+=l,s3.mtimeCache&&a.mtime&&s3.mtimeCache.set(String(a.path),a.mtime)}i=false,Ro(s3,e,n,r,t)}finally{if(i)try{v.closeSync(r)}catch{}}};Ro=(s3,t,e,i,r)=>{let n=new Wt(s3.file,{fd:i,start:e});t.pipe(n),bo(t,r)};go=(s3,t)=>{t=Array.from(t);let e=new wt(s3),i=(n,o,h)=>{let a=(T,D)=>{T?v.close(n,E=>h(T)):h(null,D)},l=0;if(o===0)return a(null,0);let c=0,d=Buffer.alloc(512),y=(T,D)=>{if(T||D===void 0)return a(T);if(c+=D,c<512&&D)return v.read(n,d,c,d.length-c,l+c,y);if(l===0&&d[0]===31&&d[1]===139)return a(new Error("cannot append to compressed archives"));if(c<512)return a(null,l);let E=new F(d);if(!E.cksumValid)return a(null,l);let x=512*Math.ceil((E.size??0)/512);if(l+x+512>o||(l+=x+512,l>=o))return a(null,l);s3.mtimeCache&&E.mtime&&s3.mtimeCache.set(String(E.path),E.mtime),c=0,v.read(n,d,0,512,l,y)};v.read(n,d,0,512,l,y)};return new Promise((n,o)=>{e.on("error",o);let h="r+",a=(l,c)=>{if(l&&l.code==="ENOENT"&&h==="r+")return h="w+",v.open(s3.file,h,a);if(l||!c)return o(l);v.fstat(c,(d,y)=>{if(d)return v.close(c,()=>o(d));i(c,y.size,(T,D)=>{if(T)return o(T);let E=new et(s3.file,{fd:c,start:D});e.pipe(E),E.on("error",o),E.on("close",n),_o(e,t)})})};v.open(s3.file,h,a)})};bo=(s3,t)=>{t.forEach(e=>{e.charAt(0)==="@"?Ct({file:Pr.resolve(s3.cwd,e.slice(1)),sync:true,noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e)}),s3.end()};_o=async(s3,t)=>{for(let e of t)e.charAt(0)==="@"?await Ct({file:Pr.resolve(String(s3.cwd),e.slice(1)),noResume:true,onReadEntry:i=>s3.add(i)}):s3.add(e);s3.end()};vt=K(yo,go,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(s3,t)=>{if(!Bs(s3))throw new TypeError("file is required");if(s3.gzip||s3.brotli||s3.zstd||s3.file.endsWith(".br")||s3.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!t?.length)throw new TypeError("no paths specified to add/replace")});Oo=K(vt.syncFile,vt.asyncFile,vt.syncNoFile,vt.asyncNoFile,(s3,t=[])=>{vt.validate?.(s3,t),To(s3)});To=s3=>{let t=s3.filter;s3.mtimeCache||(s3.mtimeCache=new Map),s3.filter=t?(e,i)=>t(e,i)&&!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0)):(e,i)=>!((s3.mtimeCache?.get(e)??i.mtime??0)>(i.mtime??0))}}});var init_text_safe=__esm({"src/text-safe.ts"(){"use strict"}});import fs8 from"fs";import path11 from"path";var PKG_ESCAPED,PKG_ENTRY_RE;var init_dsh_ledger=__esm({"src/dsh-ledger.ts"(){"use strict";init_dsh_channel();PKG_ESCAPED=DSH_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");PKG_ENTRY_RE=new RegExp(`^([ \\t]+)${PKG_ESCAPED}:([ \\t]*(\\S+))?[ \\t]*$`)}});import{readFile,writeFile,mkdir,rename,unlink}from"fs/promises";import path12 from"path";var STAGGER_MIN_DELAY_DEFAULT_MS,STAGGER_MAX_DELAY_DEFAULT_MS,POLICY_STALE_CAP_MS,DELAY_SANITY_CAP_MS,PUBLISHED_VERSIONS_TTL_MS,STAGGER_PRUNE_MS;var init_update_policy=__esm({"src/update-policy.ts"(){"use strict";init_paths();init_logger();init_upstream_proxy();init_duration();STAGGER_MIN_DELAY_DEFAULT_MS=15*6e4;STAGGER_MAX_DELAY_DEFAULT_MS=48*36e5;POLICY_STALE_CAP_MS=30*864e5;DELAY_SANITY_CAP_MS=366*864e5;PUBLISHED_VERSIONS_TTL_MS=10*6e4;STAGGER_PRUNE_MS=7*864e5}});import{readFile as readFile2,writeFile as writeFile2,mkdir as mkdir2,access,constants,rm,cp,unlink as unlink2,lstat,stat,rename as rename2,mkdtemp,readdir}from"fs/promises";import{execFile as execFile3,spawn}from"child_process";import{realpathSync}from"fs";import crypto2 from"crypto";import path13 from"path";import os6 from"os";import{fileURLToPath as fileURLToPath2}from"url";function normalizeRegistryBase(raw){const v2=raw?.trim();if(!v2)return"https://registry.npmjs.org";return v2.replace(/\/+$/,"")}function isVersionNewer(latest,current){const next=parseSemVer(latest);const prev=parseSemVer(current);if(!next||!prev)return false;for(let i=0;i<3;i++){const a=next.parts[i]??0;const b2=prev.parts[i]??0;if(a!==b2)return a>b2}if(!next.pre.length&&prev.pre.length)return true;if(next.pre.length&&!prev.pre.length)return false;for(let i=0;i<Math.max(next.pre.length,prev.pre.length);i++){const a=next.pre[i];const b2=prev.pre[i];if(a===void 0)return false;if(b2===void 0)return true;if(a===b2)continue;const aNumber=/^\d+$/.test(a)?Number(a):void 0;const bNumber=/^\d+$/.test(b2)?Number(b2):void 0;if(aNumber!==void 0&&bNumber!==void 0)return aNumber>bNumber;if(aNumber!==void 0)return false;if(bNumber!==void 0)return true;return a>b2}return false}function parseSemVer(version){const match=version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.+)?$/);if(!match)return void 0;return{parts:[Number(match[1]),Number(match[2]),Number(match[3])],pre:match[4]?.split(".")??[]}}var REGISTRY_BASE,CHECK_INTERVAL_MS,THROTTLE_FILE,OWNER_THROTTLE_FILE,LOCK_FILE,OWNER_LANE_CHECK_BASE_MS,OWNER_LANE_CHECK_JITTER_MS,LOCK_MAX_AGE_MS,UPDATE_TMP_MAX_AGE_MS,BACKOFF_BASE_MS,BACKOFF_CAP_MS,BACKOFF_STATE_FILE,BACKOFF_PRUNE_MS,LAST_INSTALL_FILE,PI_LANE_HINT;var init_update=__esm({"src/update.ts"(){"use strict";init_index_min();init_text_safe();init_paths();init_logger();init_dsh_channel();init_dsh_ledger();init_pi_channel();init_client_config();init_upstream_proxy();init_knobs();init_update_policy();REGISTRY_BASE=normalizeRegistryBase(updateRegistryBase());CHECK_INTERVAL_MS=updateCheckIntervalMs();THROTTLE_FILE=path13.join(cacheDir(),".update-check");OWNER_THROTTLE_FILE=path13.join(cacheDir(),".owner-update-check");LOCK_FILE=path13.join(cacheDir(),".update-lock");OWNER_LANE_CHECK_BASE_MS=10*60*1e3;OWNER_LANE_CHECK_JITTER_MS=5*60*1e3;LOCK_MAX_AGE_MS=30*60*1e3;UPDATE_TMP_MAX_AGE_MS=60*60*1e3;BACKOFF_BASE_MS=5*60*1e3;BACKOFF_CAP_MS=6*60*60*1e3;BACKOFF_STATE_FILE=path13.join(cacheDir(),".install-backoff.json");BACKOFF_PRUNE_MS=7*24*60*60*1e3;LAST_INSTALL_FILE=path13.join(cacheDir(),".last-install.json");PI_LANE_HINT=`run \`pi update --extension ${PI_NPM_SPEC}\` from a shell where \`pi\` resolves (or point BILI_PI_BIN at pi's executable)`}});import path14 from"path";import{fileURLToPath as fileURLToPath3}from"url";function nativeProxyScriptPath(fromUrl=import.meta.url){return path14.resolve(path14.dirname(fileURLToPath3(fromUrl)),"..","index.js")}function nativeBootstrapGate(env,optOutKey){if(env.BILLION_CONTEXT_PLUGIN==="0")return false;if(env[optOutKey]==="0")return false;if(env.BILLION_CONTEXT_PROXY!==void 0&&env.BILLION_CONTEXT_PROXY.trim().length>0)return false;if(env.BILI_PROVIDER_REWRITES!==void 0)return false;return true}function proxyEnvOrigin(env){const raw=env.BILLION_CONTEXT_PROXY;if(raw===void 0)return void 0;const url=raw.trim();if(url.length===0||!/^https?:\/\//i.test(url))return void 0;try{new URL(url)}catch{return void 0}return url.replace(/\/+$/,"")}function nativeAttachOrigin(env){const raw=env.BILLION_CONTEXT_ATTACH;if(raw===void 0)return void 0;const url=raw.trim();if(url.length===0||!/^https?:\/\//i.test(url))return void 0;try{new URL(url)}catch{return void 0}return url.replace(/\/+$/,"")}function envMillis(env,name,fallback){const raw=env[name];if(raw===void 0)return fallback;const n=Number(raw);return Number.isFinite(n)&&n>0?Math.floor(n):fallback}function markNativeHost(env,host){if(env.BILLION_CONTEXT_NATIVE===void 0||env.BILLION_CONTEXT_NATIVE.length===0){env.BILLION_CONTEXT_NATIVE=host}}function singleFlight(fn){let inFlight;return()=>{if(inFlight===void 0){inFlight=fn().finally(()=>{inFlight=void 0})}return inFlight}}var init_native_bootstrap=__esm({"src/agent/native-bootstrap.ts"(){"use strict"}});function parseToolOutcome(value){return value==="applied"||value==="partial"||value==="refused"||value==="success"||value==="failure"?value:void 0}function parseBlocksCreated(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:void 0}function partialOutcomeNote(blocksCreated){const created=blocksCreated!==void 0?`${blocksCreated} block(s) created; `:"";return`[acp-result: PARTIAL \u2014 ${created}some requested range(s) were NOT folded. Retry ONLY the failed range(s) listed above; do not re-fold the ranges that were applied.]`}var init_proxy_tool_result=__esm({"src/proxy-tool-result.ts"(){"use strict"}});var shared_exports={};__export(shared_exports,{V2_SYNTHETIC_TEXT:()=>V2_SYNTHETIC_TEXT,armedIdleNotice:()=>armedIdleNotice,asciiHeaderValue:()=>asciiHeaderValue,destinationRoutedThroughProxy:()=>destinationRoutedThroughProxy,detectProxyBase:()=>detectProxyBase,effectiveToolTimeoutMs:()=>effectiveToolTimeoutMs,fetchManifest:()=>fetchManifest,fetchProxyVersion:()=>fetchProxyVersion,fetchStaleNotice:()=>fetchStaleNotice,fetchStatus:()=>fetchStatus,fetchStatusLatest:()=>fetchStatusLatest,fitNoticeDescription:()=>fitNoticeDescription,forwardTool:()=>forwardTool,noSessionWarning:()=>noSessionWarning,nonHttpProvidersFromEnv:()=>nonHttpProvidersFromEnv,postIdentityRegister:()=>postIdentityRegister,proxyBaseFromEnv:()=>proxyBaseFromEnv,proxyBaseFromUrl:()=>proxyBaseFromUrl,reportAttributionHealth:()=>reportAttributionHealth,reportCompactionBoundary:()=>reportCompactionBoundary,reportRuntimeInfo:()=>reportRuntimeInfo,reportRuntimeInfoOnChange:()=>reportRuntimeInfoOnChange,runSessionStartHook:()=>runSessionStartHook,waitForProxyVersion:()=>waitForProxyVersion});function asciiHeaderValue(value){return/^[\x21-\x7e]{1,256}$/.test(value)?value:void 0}function proxyBaseFromUrl(baseUrl){if(!baseUrl)return void 0;try{const url=new URL(baseUrl);if(url.protocol!=="http:"&&url.protocol!=="https:")return void 0;const segments=url.pathname.split("/").filter(s3=>s3.length>0);if(segments[0]!=="bili")return void 0;const rest=url.pathname.slice(url.pathname.indexOf("bili")+"bili".length);if(!/^\/(?:responses\/)?https?:\/\//.test(rest))return void 0;return`${url.protocol}//${url.host}`}catch{return void 0}}function proxyBaseFromEnv(){const raw=process.env.BILLION_CONTEXT_PROXY?.trim();if(!raw)return void 0;try{const url=new URL(raw);return url.protocol==="http:"||url.protocol==="https:"?`${url.protocol}//${url.host}`:void 0}catch{return void 0}}function detectProxyBase(baseUrl){if(process.env.BILLION_CONTEXT_PLUGIN==="0")return void 0;return proxyBaseFromUrl(baseUrl)??proxyBaseFromEnv()}function mitmHostsFromEnv(env=process.env){const out=new Set;for(const raw of env.BILI_MITM_HOSTS?.split(",")??[]){const host=raw.trim().toLowerCase();if(host.length>0)out.add(host)}return out}function nonHttpProvidersFromEnv(env=process.env){const out=new Set;for(const raw of env.BILI_NON_HTTP_PROVIDERS?.split(",")??[]){const id=raw.trim();if(id.length>0)out.add(id)}return out}function destinationRoutedThroughProxy(baseUrl){if(!baseUrl)return false;const viaBiliPath=proxyBaseFromUrl(baseUrl)!==void 0;if(viaBiliPath)return true;let origin;let host;try{const url=new URL(baseUrl);if(url.protocol!=="http:"&&url.protocol!=="https:")return false;origin=`${url.protocol}//${url.host}`;host=url.hostname.toLowerCase()}catch{return false}if(origin===proxyBaseFromEnv())return true;const mitmHosts=mitmHostsFromEnv();if(mitmHosts.size===0)return false;for(const d of mitmHosts){if(host===d||host.endsWith(`.${d}`))return true}return false}async function fetchJson(url,init,timeoutMs,externalSignal){const ac=new AbortController;if(externalSignal?.aborted)ac.abort();const timer=setTimeout(()=>ac.abort(),timeoutMs);const onExternalAbort=()=>ac.abort();externalSignal?.addEventListener("abort",onExternalAbort,{once:true});try{let res;try{res=await fetch(url,{...init,signal:ac.signal})}catch(err){if(ac.signal.aborted&&!externalSignal?.aborted)throw new Error(`timeout after ${timeoutMs}ms: ${url}`);throw err}const text=await res.text();let json=void 0;try{json=JSON.parse(text)}catch{json=void 0}return{ok:res.ok,status:res.status,json}}finally{clearTimeout(timer);externalSignal?.removeEventListener("abort",onExternalAbort)}}function recordManifestToolDuration(proxyBase,json){const caps=json?.capabilities?.externalSummary;const value=caps?.maxToolDurationMs;if(typeof value==="number"&&Number.isFinite(value)&&value>0)manifestToolDurations.set(proxyBase,value)}function effectiveToolTimeoutMs(proxyBase,tool){if(tool!=="compress")return TOOL_TIMEOUT_MS;const advertised=manifestToolDurations.get(proxyBase);if(advertised===void 0)return TOOL_TIMEOUT_MS;return Math.max(TOOL_TIMEOUT_MS,advertised+TOOL_TIMEOUT_OVERHEAD_MARGIN_MS)}async function fetchManifest(proxyBase,format2="anthropic"){const{ok,status,json}=await fetchJson(`${proxyBase}/__bili/plugin/manifest`,void 0,MANIFEST_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")throw new Error(`manifest fetch failed: ${status}`);recordManifestToolDuration(proxyBase,json);if(format2==="openai"){const data2=json;const tools2=[];for(const t of data2.tools?.openai??[]){const name=t.name??t.function?.name;if(typeof name!=="string"||name.length===0)continue;tools2.push({name,description:t.description??t.function?.description,inputSchema:t.parameters??t.function?.parameters??{type:"object",properties:{}}})}if(tools2.length===0)throw new Error("manifest served no openai tools");return tools2}const data=json;const tools=(data.tools?.anthropic??[]).filter(t=>typeof t.name==="string");if(tools.length===0)throw new Error("manifest served no anthropic tools");return tools.map(t=>({name:t.name,description:t.description,inputSchema:t.input_schema??{type:"object",properties:{}}}))}async function reportCompactionBoundary(proxyBase,conversationId){await fetchJson(`${proxyBase}/__bili/plugin/compact`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({conversationId})},COMPACT_TIMEOUT_MS)}async function postIdentityRegister(proxyBase,conversationId,agent,parentConversationId){const res=await fetch(`${proxyBase}/__bili/plugin/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({conversationId,agent,identity:true,...parentConversationId?{parentConversationId}:{}}),signal:AbortSignal.timeout(COMPACT_TIMEOUT_MS)});if(!res.ok)throw new Error(`register HTTP ${res.status}`)}function runSessionStartHook(main,deps={}){const exit=deps.exit??(code=>process.exit(code));const input=deps.input??process.stdin;void main().finally(()=>{try{input.destroy?.()}catch{}process.exitCode=0;const backstop=setTimeout(()=>exit(0),deps.backstopMs??HOOK_EXIT_BACKSTOP_MS);backstop.unref?.()})}async function reportRuntimeInfo(proxyBase,info){const{ok,status}=await fetchJson(`${proxyBase}/__bili/plugin/runtime-info`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(info)},STATUS_TIMEOUT_MS);if(!ok)throw new Error(`runtime-info report failed (${status})`)}function runtimeReportFingerprint(proxyBase,info){return[proxyBase,info.agent,info.conversationId??"",info.model,String(info.contextWindow??""),String(info.maxOutput??""),info.baseURL??""].join("\0")}async function reportRuntimeInfoOnChange(proxyBase,info){if(proxyBase===void 0||proxyBase.length===0)return;const key=`${info.agent}\0${info.conversationId??""}`;const fingerprint=runtimeReportFingerprint(proxyBase,info);if(lastRuntimeReport.get(key)===fingerprint)return;lastRuntimeReport.set(key,fingerprint);try{await reportRuntimeInfo(proxyBase,info)}catch{lastRuntimeReport.delete(key)}}async function reportAttributionHealth(proxyBase,health){const{ok,status}=await fetchJson(`${proxyBase}/__bili/plugin/attribution`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(health)},STATUS_TIMEOUT_MS);if(!ok)throw new Error(`attribution report failed (${status})`)}async function forwardTool(proxyBase,conversationId,tool,args,signal,nativeCaller=false){const body={conversationId,tool,args:args??{}};if(nativeCaller&&conversationId)body.nativeCaller=true;const{ok,status,json}=await fetchJson(`${proxyBase}/__bili/plugin/tool`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)},effectiveToolTimeoutMs(proxyBase,tool),signal);const data=json;if(!ok||!data?.ok){throw new Error(`bili proxy tool ${tool} failed (${status}): ${data?.error??"unknown error"}`)}const outcome=parseToolOutcome(data.outcome);const blocksCreated=parseBlocksCreated(data.blocksCreated);let text=data.result??"";if(outcome==="partial")text+=`
312
312
  ${partialOutcomeNote(blocksCreated)}`;const out={text,failed:outcome==="failure"||outcome==="refused"};if(outcome!==void 0)out.outcome=outcome;if(blocksCreated!==void 0)out.blocksCreated=blocksCreated;return out}async function fetchStatus(proxyBase,conversationId){const{ok,json}=await fetchJson(`${proxyBase}/__bili/plugin/status?conversationId=${encodeURIComponent(conversationId)}`,void 0,STATUS_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")return void 0;return json}async function fetchStatusLatest(proxyBase){const{ok,json}=await fetchJson(`${proxyBase}/__bili/plugin/status?conversationId=dsh&fallback=latest`,void 0,STATUS_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")return void 0;return json}async function fetchProxyVersion(proxyBase){const{ok,json}=await fetchJson(`${proxyBase}/__bili/plugin/manifest`,void 0,STATUS_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")return void 0;const m2=json;const version=m2.version;if(typeof version!=="string"||version.length===0)return void 0;const commit=m2.commit;if(typeof commit==="string"&&commit.length>0)return`${version} (${commit})`;return version}async function fetchStaleNotice(proxyBase){const{ok,json}=await fetchJson(`${proxyBase}/__bili/status`,void 0,STATUS_TIMEOUT_MS);if(!ok||!json||typeof json!=="object")return void 0;const s3=json;if(s3.stale!==true)return void 0;const running=typeof s3.version==="string"?s3.version:"?";const installed=typeof s3.diskVersion==="string"?s3.diskVersion:"?";const runningCommit=typeof s3.commit==="string"&&s3.commit.length>0?s3.commit:void 0;const tail=s3.autoRestartOnUpdate===true?" \u2014 auto-restart is enabled but did not fire this cycle; check the bili log":" \u2014 restart the host to activate (or enable --auto-restart-on-update)";return`\u26A0\uFE0F billion-context is stale: running v${running}${runningCommit?` (${runningCommit})`:""} but v${installed} is installed${tail}.`}async function waitForProxyVersion(proxyBase){const limit=envMillis(process.env,"BILI_ATTACH_HEALTH_DEADLINE_MS",ATTACH_HEALTH_DEADLINE_MS);const startedAt=Date.now();for(;;){const version=await fetchProxyVersion(proxyBase).catch(()=>void 0);if(version!==void 0)return proxyBase;const elapsed=Date.now()-startedAt;if(elapsed>=limit)return void 0;await new Promise(r=>setTimeout(r,Math.min(ATTACH_HEALTH_POLL_MS,limit-elapsed)))}}function armedIdleNotice(version){return`billion-context@${version} \u2014 proxy connected, compression armed. No model request yet; send one, then run /acp again.`}function noSessionWarning(){return"bili: no ACP session yet (send a model request first, then run /acp)"}function fitNoticeDescription(text,max,kind,webUrl){if(text.length<=max)return text;const lines=text.split("\n");if(webUrl!==void 0&&webUrl.length>0){const body=lines.filter(l=>!/^Web UI: \S/.test(l));lines.length=0;lines.push(`Web UI: ${webUrl}`,...body)}if(lines.length===1){const marker=`