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.
package/dist/agent/pi.js CHANGED
@@ -122,7 +122,7 @@ ${pendingInterceptorsFormatter.format(pending)}`.trim())}};module.exports=MockAg
122
122
  )
123
123
  `)}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 j3=potentialValue.length;while(j3>i&&isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j3-1)))--j3;while(j3>i&&isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i)))++i;return i===0&&j3===potentialValue.length?potentialValue:potentialValue.substring(i,j3)}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 j3=0;j3<cookies.length;++j3){headers.push([name,cookies[j3]])}}else{headers.push([name,value])}}return headersList.sortedMap=headers}function compareHeaderName(a,b3){return a[0]<b3[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,j3=0,right=0,left=0,pivot=0,x2,value;i<size;++i){value=iterator.next().value;x2=array[i]=[value[0],value[1].value];assert(x2[1]!==null);left=0;right=i;while(left<right){pivot=left+(right-left>>1);if(array[pivot][0]<=x2[0]){left=pivot+1}else{right=pivot}}if(i!==pivot){j3=i;while(j3>left){array[j3]=array[--j3]}array[left]=x2}}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(V3,prefix,argument){if(webidl.util.Type(V3)===webidl.util.Types.OBJECT){const iterator=Reflect.get(V3,Symbol.iterator);if(!util.types.isProxy(V3)&&iterator===Headers2.prototype.entries){try{return getHeadersList(V3).entriesList}catch{}}if(typeof iterator==="function"){return webidl.converters["sequence<sequence<ByteString>>"](V3,prefix,argument,iterator.bind(V3))}return webidl.converters["record<ByteString, ByteString>"](V3,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,state2){state2={internalResponse:response,...state2};return new Proxy(response,{get(target,p2){return p2 in state2?state2[p2]:target[p2]},set(target,p2,value){assert(!(p2 in state2));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(V3,prefix,name){if(typeof V3==="string"){return webidl.converters.USVString(V3,prefix,name)}if(webidl.is.Blob(V3)){return V3}if(webidl.is.BufferSource(V3)){return V3}if(webidl.is.FormData(V3)){return V3}if(webidl.is.URLSearchParams(V3)){return V3}return webidl.converters.DOMString(V3,prefix,name)};webidl.converters.BodyInit=function(V3,prefix,argument){if(webidl.is.ReadableStream(V3)){return V3}if(V3?.[Symbol.asyncIterator]){return V3}return webidl.converters.XMLHttpRequestBodyInit(V3,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 window="client";if(request.window?.constructor?.name==="EnvironmentSettingsObject"&&sameOrigin(request.window,origin)){window=request.window}if(init.window!=null){throw new TypeError(`'window' option '${window}' must be null`)}if("window"in init){window="no-window"}request=makeRequest({method:request.method,headersList:request.headersList,unsafeRequest:request.unsafeRequest,client:environmentSettingsObject.settingsObject,window,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(V3){if(typeof V3==="string"){return webidl.converters.USVString(V3)}if(webidl.is.Request(V3)){return V3}return webidl.converters.USVString(V3)};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 crypto2;if(runtimeFeatures.has("crypto")){crypto2=__require("crypto");const cryptoHashes=crypto2.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 crypto2.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 path24=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?`${path24}?`:path24,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(A3,B3,excludeFragment=false){const serializedA=URLSerializer(A3,excludeFragment);const serializedB=URLSerializer(B3,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 cache=this.#relevantRequestResponseList;const backupCache=[...cache];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=cache.indexOf(requestResponse);assert(idx!==-1);cache.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=cache.indexOf(requestResponse);assert(idx!==-1);cache.splice(idx,1)}cache.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 cache=new Cache(kConstruct,cacheList);return await cache.match(request,options)}}else{for(const cacheList of this.#caches.values()){const cache=new Cache(kConstruct,cacheList);const response=await cache.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 cache2=this.#caches.get(cacheName);return new Cache(kConstruct,cache2)}const cache=[];this.#caches.set(cacheName,cache);return new Cache(kConstruct,cache)}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(path24){for(let i=0;i<path24.length;++i){const code=path24.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((_3,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 crypto2=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=crypto2.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=crypto2.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,validate2=false){code??=null;reason??="";if(validate2)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 frame2=new WebsocketFrameSend;if(reason.length!==0&&code===null){code=1e3}assert(code===null||Number.isInteger(code));if(code===null&&reason.length===0){frame2.frameData=emptyBuffer}else if(code!==null&&reason===null){frame2.frameData=Buffer.allocUnsafe(2);frame2.frameData.writeUInt16BE(code,0)}else if(code!==null&&reason!==null){frame2.frameData=Buffer.allocUnsafe(2+Buffer.byteLength(reason));frame2.frameData.writeUInt16BE(code,0);frame2.frameData.write(reason,2,"utf-8")}else{frame2.frameData=emptyBuffer}object.socket.write(frame2.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,_3,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 frame2=new WebsocketFrameSend(body);this.#handler.socket.write(frame2.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 frame2=new WebsocketFrameSend(buffer);ws2.#handler.socket.write(frame2.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(V3,prefix,argument){if(webidl.util.Type(V3)===webidl.util.Types.OBJECT&&Symbol.iterator in V3){return webidl.converters["sequence<DOMString>"](V3)}return webidl.converters.DOMString(V3,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(V3){if(webidl.util.Type(V3)===webidl.util.Types.OBJECT&&!(Symbol.iterator in V3)){return webidl.converters.WebSocketInit(V3)}return{protocols:webidl.converters["DOMString or sequence<DOMString>"](V3)}};webidl.converters.WebSocketSendData=function(V3){if(webidl.util.Type(V3)===webidl.util.Types.OBJECT){if(webidl.is.Blob(V3)){return V3}if(webidl.is.BufferSource(V3)){return V3}}return webidl.converters.USVString(V3)};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 frame2=new WebsocketFrameSend(data);this.#handler.socket.write(frame2.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:V3=>webidl.converters["unsigned short"](V3,webidl.attributes.EnforceRange)},{key:"reason",converter:webidl.converters.USVString,defaultValue:()=>""}]);webidl.converters.WebSocketStreamWrite=function(V3){if(typeof V3==="string"){return webidl.converters.USVString(V3)}return webidl.converters.BufferSource(V3)};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]+=`
124
124
  ${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 ANONYMOUS2="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 settings2=environmentSettingsObject;let urlRecord;try{urlRecord=new URL(url,settings2.settingsObject.baseUrl);this.#state.origin=urlRecord.origin}catch(e){throw new DOMException(e,"SyntaxError")}this.#url=urlRecord.href;let corsAttributeState=ANONYMOUS2;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 path24=opts.path;if(!opts.path.startsWith("/")){path24=`/${path24}`}url=new URL(util.parseOrigin(url).origin+path24)}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}
125
- ${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{readFileSync as readFileSync2,statSync as statSync2}from"fs";import*as tls 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_undici,UPSTREAM_TIMEOUT_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici=__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}});import{execFileSync as execFileSync2}from"child_process";import net from"net";import tls2 from"tls";var import_undici2;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs()}});import{createHash as createHash4}from"crypto";function hashId2(s3){return createHash4("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var init_util=__esm({"src/util.ts"(){"use strict"}});var init_mitm_domains=__esm({"src/mitm-domains.ts"(){"use strict"}});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()}});function isPrivateIPv4(host){const a=Number.parseInt(host.split(".")[0]??"",10);const b3=Number.parseInt(host.split(".")[1]??"",10);if(a===127||a===10||a===0)return true;if(a===172&&b3>=16&&b3<=31)return true;if(a===192&&b3===168)return true;if(a===169&&b3===254)return true;return false}function isPrivateHostname(hostname){let host=hostname.toLowerCase();if(host==="localhost"||host.endsWith(".local")||host.endsWith(".lan")||host.endsWith(".internal"))return true;if(host.startsWith("["))host=host.slice(1,-1);if(host.includes(":")){if(host==="::1"||host==="::")return true;const first=host.split(":")[0]??"";if(/^f[cd]/.test(first))return true;if(/^fe[89ab]/.test(first))return true;const dotted=/::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(host);if(dotted&&isPrivateIPv4(dotted[1]))return true;const hex=/::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);if(hex){const w1=Number.parseInt(hex[1],16);const w22=Number.parseInt(hex[2],16);if(isPrivateIPv4(`${w1>>8}.${w1&255}.${w22>>8}.${w22&255}`))return true}return false}if(/^\d+\.\d+\.\d+\.\d+$/.test(host))return isPrivateIPv4(host);return false}function plainHttpTrusted(url,allowPrivate){if(LOOPBACK_HOSTNAMES.includes(url.hostname))return true;return allowPrivate&&isPrivateHostname(url.hostname)}var LOOPBACK_HOSTNAMES;var init_private_host=__esm({"src/private-host.ts"(){"use strict";LOOPBACK_HOSTNAMES=["localhost","127.0.0.1","[::1]"]}});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 readFileSync3,existsSync,mkdirSync as mkdirSync2,writeFileSync}from"fs";import{createHash as createHash5}from"crypto";import{dirname}from"path";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 path24=configFile();let raw;let value;try{raw=readFileSync3(path24,"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 ${path24}: ${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 d2=obj.dsh;if(d2!==null&&typeof d2==="object"&&!Array.isArray(d2)){const live=new Set(["authoredCompaction","contextTab","contextTabLabel"]);for(const key of Object.keys(d2))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 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).`)}var KNOWN_TOP_LEVEL_KEYS,COMPRESS_SETTING_FIELDS,seenUnknownTopLevelKeySignatures,configFileCache,removedDshAllowKeySignature,RESIGN_BUILTIN_SCHEME,inertResignPassthroughSignature,seenInertStripImagesSignature,INERT_REMOVED_COMPRESS_KEYS,seenInertRemovedCompressKeysSignature;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=""}});var init_duration=__esm({"src/duration.ts"(){"use strict"}});import{createHash as createHash6}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 fileNetwork(){return loadConfigFile().network??{}}function allowPrivateHttpProviders(){const envRaw=process.env.BILI_ALLOW_PRIVATE_HTTP_PROVIDERS;if(envRaw!==void 0)return envRaw==="1"||envRaw==="true";return fileNetwork().allowPrivateHttpProviders===true}function guardrailBashTimeout(){const n=tNumLoose("BILI_GUARDRAIL_BASH_TIMEOUT",loadConfigFile().guardrails?.bashTimeout);if(!Number.isFinite(n))return 60;return n>0?Math.floor(n):void 0}function guardrailMaxOutputBytes(){const n=tNumLoose("BILI_GUARDRAIL_MAX_OUTPUT_BYTES",loadConfigFile().guardrails?.maxOutputBytes);if(!Number.isFinite(n))return 5e4;return n>0?Math.floor(n):void 0}function guardrailRepetition(){const envRaw=process.env.BILI_GUARDRAIL_REPETITION;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().guardrails?.repetition!==false}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v3=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,v3||256)}function sessionResidentMaxBytes(){const v3=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):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 v3=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v3)&&v3>0?Math.floor(v3):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{createRequire}from"module";var require2;var init_driver=__esm({"src/storage/driver.ts"(){"use strict";require2=createRequire(import.meta.url)}});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,os,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,fs,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=d2=>{this.off("data",a),this.off("end",l3),this.off(S,c),e(),o(d2)},a=d2=>{this.off("error",h),this.off("end",l3),this.off(S,c),this.pause(),n({value:d2,done:!!this[Q]})},l3=()=>{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((d2,y2)=>{o=y2,n=d2,this.once(S,c),this.once("error",h),this.once("end",l3),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 l3=t(a,o);return h?l3.then(()=>h(),h):l3}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 l3=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l3),Bi(false)}catch(l3){Bi(false),this.#o(new Gt(l3,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",l3=>this.#o(new Gt(l3,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l3=h[0];a=this[Tt](Ot.from(l3));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 l3=256;for(let c=e;c<e+148;c++)l3+=t[c];for(let c=e+156;c<e+512;c++)l3+=t[c];this.cksumValid=l3===this.cksum,this.cksum===void 0&&l3===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+`
125
+ ${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{readFileSync as readFileSync2,statSync as statSync2}from"fs";import*as tls 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_undici,UPSTREAM_TIMEOUT_MS;var init_fetch_util=__esm({"src/fetch-util.ts"(){"use strict";import_undici=__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}});import{execFileSync as execFileSync2}from"child_process";import net from"net";import tls2 from"tls";var import_undici2;var init_upstream_proxy=__esm({"src/upstream-proxy.ts"(){"use strict";import_undici2=__toESM(require_undici(),1);init_logger();init_log_mask();init_fetch_util();init_upstream_fail();init_upstream_ca();init_knobs()}});import{createHash as createHash4}from"crypto";function hashId2(s3){return createHash4("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var init_util=__esm({"src/util.ts"(){"use strict"}});var init_mitm_domains=__esm({"src/mitm-domains.ts"(){"use strict"}});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()}});function isPrivateIPv4(host){const a=Number.parseInt(host.split(".")[0]??"",10);const b3=Number.parseInt(host.split(".")[1]??"",10);if(a===127||a===10||a===0)return true;if(a===172&&b3>=16&&b3<=31)return true;if(a===192&&b3===168)return true;if(a===169&&b3===254)return true;return false}function isPrivateHostname(hostname){let host=hostname.toLowerCase();if(host==="localhost"||host.endsWith(".local")||host.endsWith(".lan")||host.endsWith(".internal"))return true;if(host.startsWith("["))host=host.slice(1,-1);if(host.includes(":")){if(host==="::1"||host==="::")return true;const first=host.split(":")[0]??"";if(/^f[cd]/.test(first))return true;if(/^fe[89ab]/.test(first))return true;const dotted=/::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(host);if(dotted&&isPrivateIPv4(dotted[1]))return true;const hex=/::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);if(hex){const w1=Number.parseInt(hex[1],16);const w22=Number.parseInt(hex[2],16);if(isPrivateIPv4(`${w1>>8}.${w1&255}.${w22>>8}.${w22&255}`))return true}return false}if(/^\d+\.\d+\.\d+\.\d+$/.test(host))return isPrivateIPv4(host);return false}function plainHttpTrusted(url,allowPrivate){if(LOOPBACK_HOSTNAMES.includes(url.hostname))return true;return allowPrivate&&isPrivateHostname(url.hostname)}var LOOPBACK_HOSTNAMES;var init_private_host=__esm({"src/private-host.ts"(){"use strict";LOOPBACK_HOSTNAMES=["localhost","127.0.0.1","[::1]"]}});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 readFileSync3,existsSync,mkdirSync as mkdirSync2,writeFileSync}from"fs";import{createHash as createHash5}from"crypto";import{dirname}from"path";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 path24=configFile();let raw;let value;try{raw=readFileSync3(path24,"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 ${path24}: ${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 d2=obj.dsh;if(d2!==null&&typeof d2==="object"&&!Array.isArray(d2)){const live=new Set(["authoredCompaction","contextTab","contextTabLabel"]);for(const key of Object.keys(d2))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 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).`)}var KNOWN_TOP_LEVEL_KEYS,COMPRESS_SETTING_FIELDS,seenUnknownTopLevelKeySignatures,configFileCache,removedDshAllowKeySignature,RESIGN_BUILTIN_SCHEME,inertResignPassthroughSignature,seenInertStripImagesSignature,INERT_REMOVED_COMPRESS_KEYS,seenInertRemovedCompressKeysSignature;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=""}});var init_duration=__esm({"src/duration.ts"(){"use strict"}});import{createHash as createHash6}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 fileNetwork(){return loadConfigFile().network??{}}function allowPrivateHttpProviders(){const envRaw=process.env.BILI_ALLOW_PRIVATE_HTTP_PROVIDERS;if(envRaw!==void 0)return envRaw==="1"||envRaw==="true";return fileNetwork().allowPrivateHttpProviders===true}function guardrailBashTimeout(){const n=tNumLoose("BILI_GUARDRAIL_BASH_TIMEOUT",loadConfigFile().guardrails?.bashTimeout);if(!Number.isFinite(n))return 60;return n>0?Math.floor(n):void 0}function guardrailMaxOutputBytes(){const n=tNumLoose("BILI_GUARDRAIL_MAX_OUTPUT_BYTES",loadConfigFile().guardrails?.maxOutputBytes);if(!Number.isFinite(n))return 5e4;return n>0?Math.floor(n):void 0}function guardrailRepetition(){const envRaw=process.env.BILI_GUARDRAIL_REPETITION;if(envRaw!==void 0)return!(envRaw==="0"||envRaw==="false");return loadConfigFile().guardrails?.repetition!==false}function maxSessions(){const envRaw=process.env.BILI_MAX_SESSIONS;const v3=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,v3||256)}function sessionResidentMaxBytes(){const v3=tInt("BILI_SESSION_RESIDENT_MAX_BYTES",loadConfigFile().sessions?.residentMaxBytes);return Number.isFinite(v3)&&v3>=0?Math.floor(v3):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 v3=tNumLoose("BILI_UPDATE_CHECK_INTERVAL_MS",loadConfigFile().update?.checkIntervalMs);return Number.isFinite(v3)&&v3>0?Math.floor(v3):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{createRequire}from"module";var require2;var init_driver=__esm({"src/storage/driver.ts"(){"use strict";require2=createRequire(import.meta.url)}});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,os,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,fs,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=d2=>{this.off("data",a),this.off("end",l3),this.off(S,c),e(),o(d2)},a=d2=>{this.off("error",h),this.off("end",l3),this.off(S,c),this.pause(),n({value:d2,done:!!this[Q]})},l3=()=>{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((d2,y2)=>{o=y2,n=d2,this.once(S,c),this.once("error",h),this.once("end",l3),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 l3=t(a,o);return h?l3.then(()=>h(),h):l3}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 l3=typeof t[Pi]=="number"?t[Pi]:this.#s;h=this.#e._processChunk(t,l3),Bi(false)}catch(l3){Bi(false),this.#o(new Gt(l3,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",l3=>this.#o(new Gt(l3,this.write)));let a;if(h)if(Array.isArray(h)&&h.length>0){let l3=h[0];a=this[Tt](Ot.from(l3));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 l3=256;for(let c=e;c<e+148;c++)l3+=t[c];for(let c=e+156;c<e+512;c++)l3+=t[c];this.cksumValid=l3===this.cksum,this.cksum===void 0&&l3===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+`
126
126
  `,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(`
127
127
  `).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 l3=!!this[w][a?"end":"write"](t);return this[Yt]=false,i?.(),l3}}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 l3=h||kn(o).root||".",c;if(o===l3)c=false;else{let d2=e.get(o);c=d2!==void 0?d2:n(Fn(o),l3,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,l3)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l3.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");os=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[os]()}[os](){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))}[os](){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");fs=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[fs]()),this.on("resume",()=>e.resume())}else this.on("drain",this[fs]);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)}}[fs](){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=l3=>{if(!h){if(l3)return i(h=l3);if(--o===0)return Ei(s3,t,e,i)}};for(let l3 of n)io(s3,l3,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),l3=t.preserve,c=t.unlink,d2=f(t.cwd),y2=(E2,x2)=>{E2?e(E2):x2&&a?Es(x2,o,h,Le2=>y2(Le2)):n?k.chmod(s3,r,e):e()};if(s3===d2)return no(s3,y2);if(l3)return ro.mkdir(s3,{mode:r,recursive:true}).then(E2=>y2(null,E2??void 0),y2);let D2=f(Si.relative(d2,s3)).split("/");Ss(d2,D2,r,c,d2,void 0,y2)};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,l3)=>{if(a)a.path=a.path&&f(a.path),o(a);else if(l3.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(l3.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,l3=t.unlink,c=f(t.cwd),d2=E2=>{E2&&h&&ws(E2,n,o),r&&k.chmodSync(s3,i)};if(s3===c)return oo(c),d2();if(a)return d2(k.mkdirSync(s3,{mode:i,recursive:true})??void 0);let T2=f(Si.relative(c,s3)).split("/"),D2;for(let E2=T2.shift(),x2=c;E2&&(x2+="/"+E2);E2=T2.shift()){x2=f(Si.resolve(x2));try{k.mkdirSync(x2,i),D2=D2||x2}catch{let Le2=k.lstatSync(x2);if(Le2.isDirectory())continue;if(l3){k.unlinkSync(x2),k.mkdirSync(x2,i),D2=D2||x2;continue}else if(Le2.isSymbolicLink())return new St(x2,x2+"/"+T2.join("/"))}}return d2(D2)};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 l3 of a)n.add(l3)}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 l3=h[0];typeof l3=="function"&&n.add(l3)}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),l3=R.posix.normalize(R.posix.join(a,h.join("/")));if(l3.startsWith("../")||l3==="..")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,l3=>{l3?this[O](l3,t):this[$t](),e()})};r.on("finish",()=>{let a=String(t.absolute),l3=r.fd;if(typeof l3=="number"&&t.mtime&&!this.noMtime){n++;let c=t.atime||new Date,d2=t.mtime;u.futimes(l3,c,d2,y2=>y2?u.utimes(a,c,d2,T2=>o(T2&&y2)):o())}if(typeof l3=="number"&&this[ge](t)){n++;let c=this[be](t),d2=this[_e](t);typeof c=="number"&&typeof d2=="number"&&u.fchown(l3,c,d2,y2=>y2?u.chown(a,c,d2,T2=>o(T2&&y2)):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,l3)=>{if(a)return r();if(l3?.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 l3=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,c=d2=>this[P](d2??null,t,i);return l3?u.chmod(String(t.absolute),Number(t.mode),c):c()}if(t.absolute!==this.cwd)return u.rmdir(String(t.absolute),l3=>this[P](l3??null,t,i))}if(t.absolute===this.cwd)return this[P](null,t,i);mo(String(t.absolute),l3=>this[P](l3??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(l3){a=l3}(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,l3=t.mtime;try{u.futimesSync(n,a,l3)}catch(c){try{u.utimesSync(String(t.absolute),a,l3)}catch{h=c}}}if(this[ge](t)){let a=this[be](t),l3=this[_e](t);try{u.fchownSync(n,Number(a),Number(l3))}catch(c){try{u.chownSync(String(t.absolute),Number(a),Number(l3))}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,l3]=ye(()=>u.lstatSync(o));if(a)return r();if(l3.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,l3)=>{if(a)h(a);else{let c=new _t(r,{readSize:i,size:l3.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,d2=0;c<512;c+=d2){if(d2=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(!d2)break t}let a=new F(h);if(!a.cksumValid)break;let l3=512*Math.ceil((a.size||0)/512);if(n+l3+512>o.size)break;n+=l3,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=(T2,D2)=>{T2?v.close(n,E2=>h(T2)):h(null,D2)},l3=0;if(o===0)return a(null,0);let c=0,d2=Buffer.alloc(512),y2=(T2,D2)=>{if(T2||D2===void 0)return a(T2);if(c+=D2,c<512&&D2)return v.read(n,d2,c,d2.length-c,l3+c,y2);if(l3===0&&d2[0]===31&&d2[1]===139)return a(new Error("cannot append to compressed archives"));if(c<512)return a(null,l3);let E2=new F(d2);if(!E2.cksumValid)return a(null,l3);let x2=512*Math.ceil((E2.size??0)/512);if(l3+x2+512>o||(l3+=x2+512,l3>=o))return a(null,l3);s3.mtimeCache&&E2.mtime&&s3.mtimeCache.set(String(E2.path),E2.mtime),c=0,v.read(n,d2,0,512,l3,y2)};v.read(n,d2,0,512,l3,y2)};return new Promise((n,o)=>{e.on("error",o);let h="r+",a=(l3,c)=>{if(l3&&l3.code==="ENOENT"&&h==="r+")return h="w+",v.open(s3.file,h,a);if(l3||!c)return o(l3);v.fstat(c,(d2,y2)=>{if(d2)return v.close(c,()=>o(d2));i(c,y2.size,(T2,D2)=>{if(T2)return o(T2);let E2=new et(s3.file,{fd:c,start:D2});e.pipe(E2),E2.on("error",o),E2.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"}});var init_vertex=__esm({"src/vertex.ts"(){"use strict"}});import fs2 from"fs";import os2 from"os";import path5 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])*'))*$`)}});var init_win_cmd=__esm({"src/win-cmd.ts"(){"use strict"}});import fs3 from"fs";import path6 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 fs4 from"fs";import path7 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 fs5 from"fs";import path8 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{readFile,writeFile,mkdir,rename,unlink}from"fs/promises";import path9 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 crypto from"crypto";import path10 from"path";import os3 from"os";import{fileURLToPath as fileURLToPath2}from"url";function normalizeRegistryBase(raw){const v3=raw?.trim();if(!v3)return"https://registry.npmjs.org";return v3.replace(/\/+$/,"")}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=path10.join(cacheDir(),".update-check");OWNER_THROTTLE_FILE=path10.join(cacheDir(),".owner-update-check");LOCK_FILE=path10.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=path10.join(cacheDir(),".install-backoff.json");BACKOFF_PRUNE_MS=7*24*60*60*1e3;LAST_INSTALL_FILE=path10.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{createHash as createHash7,randomBytes}from"crypto";import{existsSync as existsSync2,readFileSync as readFileSync4}from"fs";import{promises as fsp}from"fs";import{createRequire as createRequire2}from"module";import path11 from"path";import{gunzipSync}from"zlib";var ENGINE_SPECS,COOLDOWN_MS,PINNED_DIR_PREFIXES;var init_engine_bootstrap=__esm({"src/storage/engine-bootstrap.ts"(){"use strict";init_logger();init_paths();init_driver();init_knobs();init_update();init_upstream_proxy();ENGINE_SPECS=Object.freeze([{version:"13.0.3",sha512Base64:"RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdVVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==",minNodeMajor:22,minNapiVersion:10},{version:"12.9.0",sha512Base64:"wqUv4Gm3toFpHDQmaKD4QhZm3g1DjUBI0yzS4UBl6lElUmXFYdTQmmEDpAFa5o8FiFiymURypEnfVHzILKaxqQ==",minNodeMajor:20,prebuild:{sha512Base64ByAbi:Object.freeze({"115":Object.freeze({"linux-x64":"fNMKurhPKb0ki9mnZJK9PVazCiRugcdmauo5qGjqQjUGIrdaVWrb4nlLwU7IiyppcfLu8n/qUsQ5CEZ36uoGaw==","linux-arm64":"7q7wZe0+5LLQt2YUkocGb41B9TvEMLKIaNI+CiQUQQ2DFBO1RPr3ixj/Gtb+0noMYHjJrqtqKUMO1xMQXnE0iw==","linuxmusl-x64":"GCriICDKw7K5dNjAVo8xFpSJXcYXXBAK9RDoeuSUv6rB5IVRP96IwxeynTy4Xc21l1507Efz+I2yy6FW5gKQ/w==","linuxmusl-arm64":"2OWfVP1nklnuR8ZfCwozJcLB0ZpOTRHqAkDpsLonEF5uHZMBnOAzGtd5d+nuPU+KaS5czciU0tXZFhsCUw7dbg==","darwin-x64":"tW2Vb19+Bh+PLfcGVnrERhc9Mk50Vi8HciIc0nwIJXlPm21xzKL6uEQHMoyKIAxF+vNXxDsUoJyNRg/TgCXjkA==","darwin-arm64":"H6jehr7s1D/RSTRplCL++hneLTgpqVzgzjrX/NJCsf0OMBSKNGCd9kMYAZJjMlp0IetS39sG5PTG7AcLCTQKeg==","win32-x64":"r+BAeN980mQEdIwDcrNU3iJqzAryuOyfeICFfYHuHVclonTr2L0IlzsaGp2D50KNWUeLQrIhBCFuNoT2+iBDTw==","win32-arm64":"jMSa36VrAiLsWFtnwWX+FEs4JWIjHeduVITY44ZcHsqn7BzPcMljL8LdJ0tVVGssV8x9PuqgIqMD5gFmzcYh9w=="}),"127":Object.freeze({"linux-x64":"jpVKlRCjwmKDIfohRK4Zf/potrKjl2CuvKiWm2SOL1eY7pTRQrGBc1DSEr4OBulYHE6PTl59w7hoAlzNOefG3g==","linux-arm64":"ei++r3DQbhwXsP97PHYENHnNd3jrai5dy11SCDZqzmqEm6mjloT1qwrpglVJmW4TLliYBJ8U9bMG/6Y8nbDBCQ==","linuxmusl-x64":"eFglLYVSmdQo7ehLh30dOF4H9csX92XIn1oKB3TdtTZ+7TTh7cfViO7TQIC4NPt6Ufbl3cos9y6/pU8FNL1dQg==","linuxmusl-arm64":"e72bURjJ4SYseIMY7uW1IkubTqzuKzD6NIVP0InsD8+DJBnRwi8+yIEEcODIK4xsFKSO6tE8TLuvPmetXEk8aA==","darwin-x64":"GxXg+WENfyP9DGnvOSMnPge+kDkEZmU8cF7EFOoFSzAFhEwYOBvFB4VTTqhZ6G4y54I7ufkjgkOxZmafdSOXOw==","darwin-arm64":"V1mPpKKnv3AvfZb/++CSOx49tmUi4fba4vORsD8GTaJVwvKmveJ/uPqXaEVhYQgDkao5VLiWL6gN2wk9rQXfPw==","win32-x64":"7chlb4LP9ETESK6djkGxDq4aDTTByiG1VoUwadJk7JZFhfn2u7vblPCulZaM2C3Ju3jHowc8LBKKQZiH52Uc5g==","win32-arm64":"0mD1nLGHG066cUFdIgMTEJfhbIeOgD52+dE0r8LAALarhU5JD0uyKPvpQH/V3rBjvwTOtaQtYqeEFgRj5NUL/g=="})})}}]);COOLDOWN_MS=6*60*60*1e3;PINNED_DIR_PREFIXES=ENGINE_SPECS.map(s3=>`better-sqlite3-${s3.version}`)}});import{createHash as createHash8,randomUUID}from"crypto";import fs6 from"fs";import os4 from"os";import path12 from"path";var init_instance=__esm({"src/instance.ts"(){"use strict";init_config();init_paths()}});import{createHash as createHash9}from"crypto";import{mkdirSync as mkdirSync3,writeFileSync as writeFileSync2,appendFileSync,readFileSync as readFileSync5,existsSync as existsSync3,unlinkSync as unlinkSync2,statSync as statSync3}from"fs";import{dirname as dirname2,join}from"path";var EXT_VALUE_MAX_BYTES;var init_store=__esm({"src/storage/store.ts"(){"use strict";init_logger();init_driver();init_schema();init_identity();init_runtime_status();init_instance();EXT_VALUE_MAX_BYTES=4*1024*1024}});function createInitialState(){return{blocks:[],messageRefs:{byRaw:{},byRef:{}},tokenSnapshot:{},nudge:{lastPerMessageNudgeTokens:0,lastNudgeShownTokens:0,baselineTokens:0,anchors:{},lastShownByTier:{}},stats:{tokensCompressed:0,compressionCount:0,absorbedTokens:0,storedCount:0,retrievalCount:0},absorbed:[],rules:[],nextRuleId:1,nextBlockId:1,nextRunId:1}}var init_state=__esm({"kernel/src/state.ts"(){"use strict"}});function isResponsesTurnSeparatorId(id){return id.startsWith(RESPONSES_TURN_SEPARATOR_ID_PREFIX)}function scrubTurnSeparatorIds(blocks){let removed=0;for(const block of blocks){for(const key of["directMessageIds","effectiveMessageIds"]){const ids=block[key];if(!ids)continue;const kept=ids.filter(id=>!isResponsesTurnSeparatorId(id));if(kept.length!==ids.length){removed+=ids.length-kept.length;block[key]=kept}}}return removed}var RESPONSES_TURN_SEPARATOR_ID_PREFIX;var init_turn_separator=__esm({"src/turn-separator.ts"(){"use strict";RESPONSES_TURN_SEPARATOR_ID_PREFIX="acp_turn_sep_"}});function mergeState(parsed){const fresh=createInitialState();return{blocks:(()=>{const blocks=parsed.blocks??fresh.blocks;scrubTurnSeparatorIds(blocks);return blocks})(),messageRefs:parsed.messageRefs??fresh.messageRefs,nudge:{...fresh.nudge,...parsed.nudge??{}},stats:{...fresh.stats,...parsed.stats??{}},nextBlockId:parsed.nextBlockId??fresh.nextBlockId,nextRunId:parsed.nextRunId??fresh.nextRunId,tokenSnapshot:parsed.tokenSnapshot??fresh.tokenSnapshot,lastPassIds:parsed.lastPassIds??fresh.lastPassIds,hiddenOrphanRefs:parsed.hiddenOrphanRefs??fresh.hiddenOrphanRefs,deadRefs:parsed.deadRefs??fresh.deadRefs,terminalStreak:parsed.terminalStreak??fresh.terminalStreak,nextRuleId:parsed.nextRuleId??fresh.nextRuleId,absorbed:parsed.absorbed??fresh.absorbed,rules:parsed.rules??fresh.rules,sweptOrphanCallIds:parsed.sweptOrphanCallIds??fresh.sweptOrphanCallIds,pendingOrphanSweepMinRef:parsed.pendingOrphanSweepMinRef??fresh.pendingOrphanSweepMinRef,emergencyTruncateLatch:parsed.emergencyTruncateLatch??fresh.emergencyTruncateLatch,renderDeferredRefs:parsed.renderDeferredRefs??fresh.renderDeferredRefs,viewLatches:parsed.viewLatches??fresh.viewLatches,viewLatchConfigDigest:parsed.viewLatchConfigDigest??fresh.viewLatchConfigDigest}}var COMPRESSION_STATE_FIELDS;var init_state_hydration=__esm({"src/state-hydration.ts"(){"use strict";init_state();init_turn_separator();COMPRESSION_STATE_FIELDS=Object.keys(mergeState(createInitialState()))}});var init_ingest=__esm({"src/storage/ingest.ts"(){"use strict";init_store();init_identity();init_state_hydration()}});var init_backend=__esm({"src/storage/backend.ts"(){"use strict";init_store()}});import{createHash as createHash10}from"crypto";var init_canonical=__esm({"src/storage/canonical.ts"(){"use strict"}});import{renameSync as renameSync2}from"fs";import path13 from"path";var init_shadow=__esm({"src/storage/shadow.ts"(){"use strict";init_logger();init_ingest();init_knobs();init_store();init_backend();init_canonical();init_runtime_status();init_knobs()}});function freshState(){return{requested:null,encryptionBlocked:false,persistDisabled:false,sidecar:null,sidecarOpenError:null,bootstrap:null,integrity:null,secondProcess:null,splitBrain:null,splitBrainAcks:new Map,backup:null}}var state;var init_runtime_status=__esm({"src/storage/runtime-status.ts"(){"use strict";init_engine_bootstrap();init_knobs();init_logger();init_shadow();state=freshState()}});import fs10 from"fs";import path23 from"path";import{fileURLToPath as fileURLToPath4}from"url";import{createHash as createHash2}from"crypto";import{createHash}from"crypto";function hashId(s3){return createHash("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var CANONICAL_IMAGE_TEXT="[image]";var CANONICAL_REDACTED_THINKING_TEXT="[redacted_thinking]";function canonicalToolArgs(argsText){const trimmed=argsText.trim();if(!trimmed.startsWith("{")&&!trimmed.startsWith("["))return argsText;try{return JSON.stringify(canonicalize(JSON.parse(trimmed)))}catch{return argsText}}function canonicalize(v3){if(Array.isArray(v3))return v3.map(canonicalize);if(v3!==null&&typeof v3==="object"){const src=v3;const out={};for(const k2 of Object.keys(src).sort())out[k2]=canonicalize(src[k2]);return out}return v3}var idSalt=null;function deriveCanonicalMessageId(role,contentType,text,options={}){const seed=`${idSalt?idSalt+"|":""}${role}|${contentType}||${options.toolName??""}|${text}`+(options.mediaFingerprint!==void 0?`|${options.mediaFingerprint}`:"");return"h_"+hashId(seed)}function imageMediaFingerprint(base64OrUrl){return hashId(base64OrUrl)}function canonicalOpaqueSeed(item){if(item===null||typeof item!=="object")return hashId(String(item));const src=item;const out={};for(const k2 of Object.keys(src)){if(k2==="id"||k2==="status")continue;out[k2]=src[k2]}return hashId(JSON.stringify(out))}var ClusterCounter=class{counts=new Map;next(baseId){const n=this.counts.get(baseId)??0;this.counts.set(baseId,n+1);return n===0?baseId:`${baseId}_${n}`}};function anthropicToCore(body){const msgs=[];const cacheControls=new Map;const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m3]of body.messages.entries()){const before=msgs.length;if(m3.role==="system"){const core=systemMessageCore(m3,clusters);core.wireIndex=wireIndex;msgs.push(core);const mark=systemMessageMark(m3);if(mark)cacheControls.set(core.id,mark);continue}const blocks=typeof m3.content==="string"?[{type:"text",text:m3.content}]:m3.content;for(const b3 of blocks){switch(b3.type){case"text":{const base=deriveCanonicalMessageId(m3.role,"text",b3.text);const id=clusters.next(base);msgs.push({id,role:m3.role,contentType:"text",text:b3.text});if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"tool_use":{const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(safeStringify(b3.input)),{toolName:b3.name});const id=clusters.next(base);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:b3.name,toolCallId:b3.id,text:safeStringify(b3.input)});toolNames.set(b3.id,b3.name);if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"tool_result":{const hasNonText=Array.isArray(b3.content)&&b3.content.some(c=>c.type!=="text");const text=typeof b3.content==="string"?b3.content:b3.content.map(c=>c.type==="text"?c.text:"").join("\n");const name=toolNames.get(b3.tool_use_id);const base=deriveCanonicalMessageId("tool","tool-result",text,{toolName:name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolCallId:b3.tool_use_id,text,...name?{toolName:name}:{},...b3.is_error===true?{toolIsError:true}:{},...hasNonText?{rawAnthropicBlock:b3}:{}});if(b3.cache_control)cacheControls.set(id,b3.cache_control);break}case"thinking":{const base=deriveCanonicalMessageId("assistant","reasoning",b3.thinking);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:b3.thinking,...b3.signature?{thinkingSignature:b3.signature}:{}});break}case"image":{const source=b3.source&&typeof b3.source==="object"&&!Array.isArray(b3.source)?b3.source:void 0;const mediaSidecar=source?.type==="base64"&&typeof source.media_type==="string"&&typeof source.data==="string"?{imageMediaType:source.media_type,imageBase64:source.data}:{};const base=deriveCanonicalMessageId(m3.role,"text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:source?.type==="base64"&&typeof source.data==="string"?imageMediaFingerprint(source.data):typeof source?.url==="string"?imageMediaFingerprint(source.url):void 0});msgs.push({id:clusters.next(base),role:m3.role,contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawAnthropicBlock:b3,...mediaSidecar});break}case"redacted_thinking":{const base=deriveCanonicalMessageId(m3.role,"text",CANONICAL_REDACTED_THINKING_TEXT);msgs.push({id:clusters.next(base),role:m3.role,contentType:"text",text:"[redacted_thinking]",rawAnthropicBlock:b3});break}default:{const unknownType=b3.type;const label=typeof unknownType==="string"?`[${unknownType}]`:"[unknown]";const base=deriveCanonicalMessageId(m3.role,"text",label);msgs.push({id:clusters.next(base),role:m3.role,contentType:"text",text:label,rawAnthropicBlock:b3});break}}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,cacheControls}}function systemMessageCore(m3,clusters){const label=systemMessageText(m3);const base=deriveCanonicalMessageId("system","text",label);return{id:clusters.next(base),role:"system",contentType:"text",text:label,rawAnthropicMessage:m3}}function systemMessageText(m3){const text=typeof m3.content==="string"?m3.content:m3.content.map(b3=>b3.type==="text"?b3.text:`[${b3.type}]`).join("\n");return text.length>0?text:"[system]"}function systemMessageMark(m3){if(typeof m3.content==="string")return void 0;let mark;for(const b3 of m3.content)if(b3.cache_control)mark=b3.cache_control;return mark}function safeStringify(v3){try{return JSON.stringify(v3??{})}catch{return"{}"}}var FORMS=[{open:"<think>\n",close:"\n</think>"},{open:"<thinking>\n",close:"\n</thinking>"},{open:"```thinking\n",close:"\n```"}];function splitDemotedThinking(content){let rest=content;const parts=[];for(;;){let matched=false;for(const form of FORMS){if(!rest.startsWith(form.open))continue;const end=rest.indexOf(form.close,form.open.length);if(end<0)continue;const inner=rest.slice(form.open.length,end);if(inner.length===0)continue;parts.push(inner);rest=rest.slice(end+form.close.length);if(rest.startsWith("\n"))rest=rest.slice(1);matched=true;break}if(!matched)break}if(parts.length===0)return null;return{reasoning:parts.join("\n"),text:rest}}function parseDataUrl(url){const m3=/^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);if(!m3)return void 0;return{mediaType:m3[1],base64:m3[2]}}function imageFingerprintsOfParts(parts){const out=[];for(const part of parts){if(!part||typeof part!=="object")continue;const p2=part;if(p2.type!=="image_url")continue;const url=typeof p2.image_url?.url==="string"?p2.image_url.url:void 0;if(!url)continue;const parsed=parseDataUrl(url);out.push(imageMediaFingerprint(parsed?parsed.base64:url))}return out}function openaiToCore(body){const msgs=[];const systemParts=[];const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m3]of body.messages.entries()){const before=msgs.length;switch(m3.role){case"system":case"developer":{if(msgs.length===0){systemParts.push(stringContent(m3.content));break}const base=deriveCanonicalMessageId(m3.role,"text",stringContent(m3.content));msgs.push({id:clusters.next(base),role:"system",contentType:"text",text:stringContent(m3.content),originalRole:m3.role,rawOpenaiMessage:m3});break}case"user":{if(typeof m3.content==="string"||m3.content==null||!Array.isArray(m3.content)){const base=deriveCanonicalMessageId("user","text",typeof m3.content==="string"?m3.content:"");msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:typeof m3.content==="string"?m3.content:""});break}let lastTextCore=null;let leadingOpaque=[];let sawText=false;for(const part of m3.content){if(typeof part==="string"){const base=deriveCanonicalMessageId("user","text",part);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="text"&&typeof part.text==="string"){const base=deriveCanonicalMessageId("user","text",part.text);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part.text};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="image_url"){const url=part.image_url?.url;const parsed=typeof url==="string"?parseDataUrl(url):void 0;const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(parsed?parsed.base64:typeof url==="string"?url:"")});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawOpenaiContent:part,...parsed?{imageMediaType:parsed.mediaType,imageBase64:parsed.base64}:{}});continue}if(lastTextCore){lastTextCore.rawOpenaiContentParts=[...lastTextCore.rawOpenaiContentParts??[],part]}else{leadingOpaque=[...leadingOpaque,part]}}if(leadingOpaque.length>0){if(sawText&&msgs.length>0){const firstTextCore=msgs.find((c,i)=>i>=before&&c.role==="user"&&c.contentType==="text"&&!c.rawOpenaiContent);const host=firstTextCore??msgs[msgs.length-1];host.rawOpenaiContentParts=[...leadingOpaque,...host.rawOpenaiContentParts??[]]}else{const base=deriveCanonicalMessageId("user","text","",{mediaFingerprint:imageFingerprintsOfParts(leadingOpaque).join(",")||void 0});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:"",rawOpenaiContentParts:leadingOpaque})}}break}case"assistant":{const rawReasoning=m3.reasoning_content;const fieldPresent=typeof rawReasoning==="string";const fieldReasoning=fieldPresent?rawReasoning:"";let reasoning=fieldReasoning;let text=stringContent(m3.content);if(!reasoning){const split=splitDemotedThinking(text);if(split){reasoning=split.reasoning;text=split.text}}const blankEcho=fieldPresent&&reasoning.length===0;if(reasoning){const base=deriveCanonicalMessageId("assistant","reasoning",reasoning);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:reasoning,reasoningContent:reasoning})}if(text){const base=deriveCanonicalMessageId("assistant","text",text);msgs.push({id:clusters.next(base),role:"assistant",contentType:"text",text,...blankEcho?{reasoningPresent:true}:{}})}if(Array.isArray(m3.tool_calls)){for(const tc of m3.tool_calls){const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(tc.function.arguments??""),{toolName:tc.function.name});msgs.push({id:clusters.next(base),role:"assistant",contentType:"tool-call",toolName:tc.function.name,toolCallId:tc.id,text:tc.function.arguments??"",...blankEcho?{reasoningPresent:true}:{}});toolNames.set(tc.id,tc.function.name)}}break}case"tool":{const base=deriveCanonicalMessageId("tool","tool-result",stringContent(m3.content),{toolName:m3.name||toolNames.get(m3.tool_call_id??"")});const name=m3.name||toolNames.get(m3.tool_call_id??"");msgs.push({id:clusters.next(base),role:"tool",contentType:"tool-result",toolCallId:m3.tool_call_id??"",text:stringContent(m3.content),...name?{toolName:name}:{}});break}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,systemText:systemParts.join("\n\n")}}function stringContent(content){if(content==null)return"";if(typeof content==="string")return content;if(Array.isArray(content)){return content.map(p2=>typeof p2==="string"?p2:p2.type==="text"?p2.text??"":"").join("\n")}return""}var OPAQUE_ITEM_TYPES=new Set(["additional_tools","mcp_list_tools"]);function isOpaqueItem(item){return OPAQUE_ITEM_TYPES.has(item.type)}var EASY_INPUT_ROLES=new Set(["user","assistant","system","developer"]);function normalizeEasyInputItem(item){if(typeof item.type==="string")return item;if(EASY_INPUT_ROLES.has(String(item.role))){return{...item,type:"message"}}return item}function shouldDropAllReasoning(){return(process.env.ACP_REASONING_KEEP??"").trim().toLowerCase()==="none"}function partText(part){if(part.type==="input_text"||part.type==="output_text"){return typeof part.text==="string"?part.text:""}return""}function messageContent(content){return typeof content==="string"?content:content.map(partText).join("\n")}function userDisplayText(content,text){if(typeof content==="string")return text;const hasImage=content.some(part=>part.type==="input_image");const hasTextPart=content.some(part=>part.type==="input_text"||part.type==="output_text");return!text||hasImage&&!hasTextPart?"[image]":text}function reasoningText(item){const fromParts=(parts,type)=>{if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(part&&typeof part==="object"&&"type"in part&&"text"in part){const rec=part;if(rec.type===type&&typeof rec.text==="string")texts.push(rec.text)}}return texts.join("\n")};const content="content"in item?item.content:void 0;const summary="summary"in item?item.summary:void 0;return fromParts(content,"reasoning_text")||fromParts(summary,"summary_text")}function responsesToCore(body){const msgs=[];const systemParts=[];const preamble=[];const customToolCallIds=new Set;const layout=[];let droppedReasoning=0;const clusters=new ClusterCounter;const toolNames=new Map;let idx=0;if(typeof body.instructions==="string"&&body.instructions.trim())systemParts.push(body.instructions);if(typeof body.input==="string"){const id=clusters.next(deriveCanonicalMessageId("user","text",body.input));msgs.push({id,role:"user",contentType:"text",text:body.input});return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,stringInput:{original:body.input,coreId:id}}}let sysDevHead=true;for(const[wireIndex,raw]of body.input.entries()){const item=normalizeEasyInputItem(raw);let coreId;const before=msgs.length;if(isOpaqueItem(item))preamble.push(item);switch(item.type){case"reasoning":{if(shouldDropAllReasoning()){droppedReasoning++;continue}const text=reasoningText(item);const rid=text.length>0?text:canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","reasoning",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"message":{const message=item;const text=messageContent(message.content);if(message.role==="system"||message.role==="developer"){if(sysDevHead){systemParts.push(text);idx++;continue}const midBase=deriveCanonicalMessageId(message.role,"text",text);msgs.push({id:clusters.next(midBase),role:"system",contentType:"text",text,originalRole:message.role,rawResponsesItem:item});break}else if(message.role==="user"||message.role==="assistant"&&text){const role2=message.role;const splittable=role2==="user"&&Array.isArray(message.content)&&message.content.length>1&&message.content.every(part=>typeof part==="object"&&part!==null&&(part.type==="input_text"||part.type==="output_text"||part.type==="input_image"));if(splittable){for(const rawPart of message.content){const part=typeof rawPart==="object"&&rawPart!==null?rawPart:void 0;if(!part)continue;if((part.type==="input_text"||part.type==="output_text")&&typeof part.text==="string"&&part.text.length>0){const base=deriveCanonicalMessageId("user","text",part.text);msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:part.text})}else if(part.type==="input_image"&&typeof part.image_url==="string"){const image=parseDataUrl(part.image_url);const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(image?image.base64:part.image_url)});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}let effText=text;if(role2==="assistant"){const split=splitDemotedThinking(text);if(split){msgs.push({id:clusters.next(deriveCanonicalMessageId("assistant","reasoning",split.reasoning)),role:"assistant",contentType:"reasoning",text:split.reasoning,rawResponsesItem:item});effText=split.text}}const hasImage=Array.isArray(message.content)&&message.content.some(part=>part.type==="input_image");if(effText||role2==="user"&&hasImage){const displayText=role2==="user"?userDisplayText(message.content,effText):effText;const mediaFingerprint=Array.isArray(message.content)?message.content.flatMap(part=>{if(part?.type==="input_image"&&typeof part.image_url==="string"){const raw2=part.image_url;const decoded=parseDataUrl(raw2);return[imageMediaFingerprint(decoded?decoded.base64:raw2)]}return[]}).join(",")||void 0:void 0;coreId=clusters.next(deriveCanonicalMessageId(role2,"text",displayText,{mediaFingerprint}));const imageUrl=Array.isArray(message.content)?message.content.find(part=>part.type==="input_image"&&typeof part.image_url==="string")?.image_url:void 0;const image=typeof imageUrl==="string"?parseDataUrl(imageUrl):void 0;msgs.push({id:coreId,role:role2,contentType:"text",text:displayText,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}case"function_call":{const call=item;coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(call.arguments??""),{toolName:call.name}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:call.name,toolCallId:call.call_id,text:call.arguments??"",rawResponsesItem:item});toolNames.set(call.call_id,call.name);break}case"function_call_output":{const output=item;const text=typeof output.output==="string"?output.output:JSON.stringify(output.output);coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",text,{toolName:toolNames.get(output.call_id)}));const name=toolNames.get(output.call_id);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:output.call_id,text,...name?{toolName:name}:{},rawResponsesItem:item});break}case"computer_call":case"computer_call_output":case"file_search_call":case"web_search_call":case"image_generation_call":case"code_interpreter_call":case"mcp_call":{const rid=canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","responses-call",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"custom_tool_call":{const ctc=item;const callId=ctc.call_id??`call_${idx}`;customToolCallIds.add(callId);const argText=ctc.input??ctc.arguments??"";coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",argText,{toolName:ctc.name??"custom"}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:ctc.name??"custom",toolCallId:callId,text:argText,rawResponsesItem:item});toolNames.set(callId,ctc.name??"custom");break}case"custom_tool_call_output":{const ctco=item;const callId=ctco.call_id??`call_${idx}`;customToolCallIds.add(callId);const outText=typeof ctco.output==="string"?ctco.output:JSON.stringify(ctco.output??"");coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",outText,{toolName:toolNames.get(callId)}));const name=toolNames.get(callId);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:callId,text:outText,...name?{toolName:name}:{},rawResponsesItem:item});break}default:if(!isOpaqueItem(item))preamble.push(item);break}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}const role=item.role;const isSysDevMsgItem=(item.type===void 0||item.type==="message")&&(role==="system"||role==="developer");if(!isSysDevMsgItem&&item.type!=="additional_tools"&&item.type!=="mcp_list_tools")sysDevHead=false;const produced=msgs.slice(before).map(m3=>m3.id);layout.push({original:item,...produced.length>0?{coreId:produced[0]}:{},...produced.length>1?{coreIds:produced}:{}});idx++}return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning}}function createSubagentNamespaces(){const anchors=new Map;return{namespaceFor(identityValue,instructions){if(typeof instructions!=="string"||instructions.trim().length===0)return identityValue;const fp=hashId(instructions);const anchor=anchors.get(identityValue);if(anchor===void 0){anchors.set(identityValue,fp);return identityValue}return anchor===fp?identityValue:`${identityValue}|sub:${fp}`}}}var defaultNamespaces=createSubagentNamespaces();function detectWireFormat(payload){if(payload===null||typeof payload!=="object")return void 0;const p2=payload;if(Array.isArray(p2.contents))return"google";if(Array.isArray(p2.input))return"responses";const messages=p2.messages;if(!Array.isArray(messages))return void 0;if("system"in p2||"anthropic_version"in p2)return"anthropic";for(const m3 of messages){if(m3===null||typeof m3!=="object")continue;const c=m3.content;if(Array.isArray(c)){for(const b3 of c){if(b3&&typeof b3==="object"&&typeof b3.type==="string"){if(b3.type==="tool_use"||b3.type==="tool_result"||b3.type==="thinking")return"anthropic";if(b3.type==="text"&&"cache_control"in b3)return"anthropic"}}}if(Array.isArray(m3.tool_calls))return"openai";if(m3.role==="tool"&&typeof m3.tool_call_id==="string")return"openai";if(m3.role==="system"||m3.role==="developer")return"openai"}return"openai"}var DEFAULT_MAX_FUTURE_SKEW_MS=2*60*1e3;var DEFAULT_RECENT_CHECKPOINT_WINDOW_MS=10*60*1e3;var MAX_CHECKPOINT_CHARS=512;var TAG_OPEN="<bili-chain ";var TAG_CLOSE="/>";var ATTRS=["v","processor","issued-at","request-id","digest"];function validAttrValue(name,raw){switch(name){case"v":return/^\d+$/.test(raw)&&Number(raw)>=1;case"issued-at":return/^\d{1,16}$/.test(raw);case"processor":return/^[A-Za-z0-9._-]{1,64}$/.test(raw);case"request-id":return/^[A-Za-z0-9._:-]{1,64}$/.test(raw);case"digest":return/^sha256:[0-9a-f]{64}$/.test(raw)}}function parseChainCheckpoint(text){if(typeof text!=="string"||text.length===0||text.length>MAX_CHECKPOINT_CHARS)return null;if(!text.startsWith(TAG_OPEN)||!text.endsWith(TAG_CLOSE))return null;const inner=text.slice(TAG_OPEN.length,-TAG_CLOSE.length);const found={};for(const token of inner.split(/\s+/)){const m3=/^([a-z][a-z0-9-]*)="([^"]*)"$/.exec(token);if(!m3)return null;const name=m3[1];if(!ATTRS.includes(name))return null;if(Object.hasOwn(found,name))return null;found[name]=m3[2]}for(const attr of ATTRS){const raw=found[attr];if(raw===void 0||!validAttrValue(attr,raw))return null}return{v:Number(found.v),processor:found.processor,issuedAt:Number(found["issued-at"]),requestId:found["request-id"],digest:found.digest}}function stripEmbeddedChainCarriers(parsed,wire){if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return 0;const body=parsed;let stripped=0;if(wire==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(let i=contents.length-1;i>=0;i--){const c=contents[i];if(!c||typeof c!=="object"||Array.isArray(c))continue;const ct2=c;const role=typeof ct2.role==="string"?ct2.role:"user";if(role!=="user"&&role!=="model")continue;const parts=ct2.parts;if(!Array.isArray(parts))continue;let removed=0;for(let j3=parts.length-1;j3>=0;j3--){const p2=parts[j3];if(p2&&typeof p2==="object"&&!Array.isArray(p2)&&Object.keys(p2).length===1&&typeof p2.text==="string"){if(parseChainCheckpoint(p2.text)){parts.splice(j3,1);removed++}}}if(removed>0){if(parts.length===0)contents.splice(i,1);stripped+=removed}}return stripped}if(wire==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(let i=input.length-1;i>=0;i--){const item=input[i];if(!item||typeof item!=="object"||Array.isArray(item))continue;const it2=item;if(it2.type!=="message")continue;const role=typeof it2.role==="string"?it2.role:"";if(role!=="user"&&role!=="assistant")continue;const content=it2.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){input.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j3=content.length-1;j3>=0;j3--){const p2=content[j3];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="input_text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j3,1);removed++}}}if(removed>0){if(content.length===0)input.splice(i,1);stripped+=removed}}return stripped}const messages=body.messages;if(!Array.isArray(messages))return 0;for(let i=messages.length-1;i>=0;i--){const rec=messages[i];if(!rec||typeof rec!=="object"||Array.isArray(rec))continue;const m3=rec;if(m3.role!=="user"&&m3.role!=="assistant")continue;const content=m3.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){messages.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j3=content.length-1;j3>=0;j3--){const p2=content[j3];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j3,1);removed++}}}if(removed>0){if(content.length===0)messages.splice(i,1);stripped+=removed}}return stripped}var ZERO_DIGEST="sha256:"+"0".repeat(64);import{randomUUID as randomUUID4}from"crypto";init_logger();import{createHash as createHash15}from"crypto";import{createHash as createHash14,randomUUID as randomUUID3}from"crypto";import{closeSync,existsSync as existsSync4,fsyncSync,mkdirSync as mkdirSync4,openSync,readdirSync,readFileSync as readFileSync6,renameSync as renameSync3,rmSync,statSync as statSync4,writeFileSync as writeFileSync3}from"fs";import{readdir as readdir2,readFile as readFile3,rm as rm2}from"fs/promises";import*as path16 from"path";init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;init_logger();init_state_hydration();init_shadow();init_backend();init_ingest();init_store();import{createHash as createHash13,randomUUID as randomUUID2}from"crypto";init_logger();import{createHash as createHash12}from"crypto";import{createHash as createHash11}from"crypto";init_client_config();import fs7 from"fs";import path15 from"path";import path14 from"path";import{fileURLToPath as fileURLToPath3}from"url";var originWaiter;async function awaitNativeProxyOrigin(){return originWaiter===void 0?void 0:originWaiter.wait()}init_dsh_channel();var SCAN_CACHE_TTL_MS=5*60*1e3;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;init_util();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 BOOT_ID=randomUUID2();var SEAM_BODY_CAP=512*1024;var BODY_FULL_CAP=8*1024*1024;var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var{join:join3}=path16;init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path17 from"path";init_turn_separator();init_turn_separator();var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var SPLIT_CANARY_FRESH_MS=10*60*1e3;init_knobs();var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";var FORGED_SUMMARY_HEADER="[Compressed conversation section]";function buildAcplikeName(){const cores=["acp","apc","cap","cpa","pac","pca"];const ci2=ch=>`[${ch}${ch.toUpperCase()}]`;const attestedDrift=["[aA][cC][cC][eE][sS][sS][pP]","[aA][cC][aA][cC][pP]","[aA][cC][bB]"];const fourLetter=new Set;const threeLetter=new Set;for(const c of cores){threeLetter.add(ci2(c.charAt(0))+ci2(c.charAt(1))+ci2(c.charAt(2)));for(let pos=0;pos<=c.length;pos++){fourLetter.add(c.slice(0,pos).split("").map(ci2).join("")+"[aAcCpPiI]"+c.slice(pos).split("").map(ci2).join(""))}}return[...attestedDrift,...fourLetter,...threeLetter].join("|")}var ACP_NAME_ALT=`(?:${buildAcplikeName()})`;var NAME=ACP_NAME_ALT;var REF_TOKEN="m\\d{4,}";var REFS_RUN=REF_TOKEN+"(?:\\s*[\\u2013\\u2014,\\-]?\\s*"+REF_TOKEN+")*";var REFS_ONLY=new RegExp("^\\s*"+REFS_RUN+"\\s*$");var PENDING_REF_SPAN=new RegExp("^\\s*"+REFS_RUN+"(?:\\s*[\\u2013\\u2014,\\-]?\\s*(?:m\\d{0,3})?)?\\s*$");var PAIRED_BODY="\\s*(?:"+REFS_RUN+")?\\s*";var PAIRED=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>("+PAIRED_BODY+")<\\/"+NAME+">");var ORPHAN_REF_CLOSE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var ORPHAN_RUN_BEFORE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*$");var LONE_OPEN=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>");var LONE_CLOSE=new RegExp("<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var DEGEN_PAIR=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>\\s*m\\d{4,}\\s*<\\/[^<>]{1,32}>","g");var SELF_CLOSE=new RegExp("<"+NAME+"(?:\\s[^<>]*)?\\/>");var PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<"+NAME+"\\s*=\\s*[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?|(?<![\\w>])\\s*"+REFS_RUN+"\\s*<[^<>]*|(?<![\\w>])\\s*"+REFS_RUN+"(?:\\s*[\\u2013\\u2014,\\-]?\\s*(?:m\\d{0,3})?)?\\s*|(?<![\\w>])\\s*m\\d{0,3})$");var TRUNC_OPEN=new RegExp("<"+NAME+"\\s[^<>]*$|<"+NAME+"\\s*=\\s*[^<>]*$");var TRUNC_CLOSE=new RegExp("<\\/"+NAME+"(?:\\s[^<>]{0,32})?$");var TRUNC_REF_CLOSE=new RegExp("m\\d{4,}\\s*\\x3c\\/([a-zA-Z]{0,32})$");var DEAD_REF_CLOSE=new RegExp("(?<![\\w>])m\\d{4,}\\s*\\x3c\\/[a-zA-Z]{0,32}(?![a-zA-Z])(?![^\\x3c\\x3e]{0,32}\\x3e)","g");var BROKEN_ATTRS=new RegExp("<"+NAME+"\\s[^<>]*(?=<)");var MANGLED_OPEN=new RegExp("<"+NAME+"\\s*=\\s*[^<>]*>");var DEFINITE_TAIL=new RegExp("^<"+NAME+"\\s|^<"+NAME+"=|^<\\/"+NAME);var OPEN_WITH_ATTRS=new RegExp("^<"+NAME+"\\s");var CLOSE_NAME_ANCHORED=new RegExp("^"+NAME);var MARKER_HEAD=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\]","u");var MARKER_LINE=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\][^\\n]*\\n?","gmu");function stripMarkerLines(text){return text.replace(MARKER_LINE,"")}var RENDER_TAG_DETECT=new RegExp("<\\/?"+NAME+"(?=[\\s>])|\\\\u003c\\/?"+NAME+"(?=[\\s>\\\\])|<"+NAME+"\\s*\\/|\\\\u003c"+NAME+"\\s*\\/");var BROAD_TAG_HEAD_TAIL=new RegExp("<\\/?[A-Za-z0-9]{0,16}$");var RAW_WS="(?:\\\\[a-z]|\\s|\\\\)*";var TC_PARAM_REF_RAW=new RegExp(`\\x3c(?:antml:)?parameter(?:\\s*=\\s*["']?ref["']?|\\s+name\\s*=\\s*["']ref["'])?[^<>]*\\x3e`+RAW_WS+"m\\d{4,}"+RAW_WS+"\\x3c\\/(?:antml:)?parameter","i");var CHAIN_OPEN_ESCAPED="\\u003c"+TAG_OPEN.slice(1);function reEscape(s3){return s3.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function prefixAlts(s3,minLen){const out=[];for(let k2=minLen;k2<s3.length;k2++)out.push(reEscape(s3.slice(0,k2)));return out}var CHAIN_PARTIAL_TAIL=new RegExp("("+[...new Set([...prefixAlts(TAG_OPEN,1),reEscape(TAG_OPEN),...prefixAlts(CHAIN_OPEN_ESCAPED,1),reEscape(CHAIN_OPEN_ESCAPED)])].join("|")+")$");var HEAD_PREFIX_TAIL=new RegExp("(?:^|\n)("+[...new Set([...prefixAlts(CODEX_FORGED_HANDOFF_HEADER,1),...prefixAlts(FORGED_SUMMARY_HEADER,1)])].join("|")+")$");var TAG_PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?)$");var PANEL_BOX_TOP="\u256D";var PANEL_BOX_TITLE="ACP Context Analysis";var PANEL_BOX_FOOTER="Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.";var PANEL_FALLBACK_HEADER="\u{1F4CA} ACP status";var CACHE_REPORT_OPEN="[acp-cache]";var CACHE_REPORT_CLOSE="[/acp-cache]";var RULE_REPORT_OPEN="[acp-rule]";var RULE_REPORT_CLOSE="[/acp-rule]";function wrapCacheReport(report){return`${CACHE_REPORT_OPEN}
128
128
  ${report}