@wengine-ai/llms 2.1.36 → 2.1.37

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.
@@ -5,25 +5,25 @@
5
5
  `:case"\r":throw Ne(z());case"\u2028":case"\u2029":wC(Ce);break;case void 0:throw Ne(z())}he+=z()},start(){switch(Ce){case"{":case"[":return Ie("punctuator",z())}me="value"},beforePropertyName(){switch(Ce){case"$":case"_":he=z(),me="identifierName";return;case"\\":z(),me="identifierNameStartEscape";return;case"}":return Ie("punctuator",z());case'"':case"'":Bo=z()==='"',me="string";return}if(ze.isIdStartChar(Ce)){he+=z(),me="identifierName";return}throw Ne(z())},afterPropertyName(){if(Ce===":")return Ie("punctuator",z());throw Ne(z())},beforePropertyValue(){me="value"},afterPropertyValue(){switch(Ce){case",":case"}":return Ie("punctuator",z())}throw Ne(z())},beforeArrayValue(){if(Ce==="]")return Ie("punctuator",z());me="value"},afterArrayValue(){switch(Ce){case",":case"]":return Ie("punctuator",z())}throw Ne(z())},end(){throw Ne(z())}};function Ie(t,e){return{type:t,value:e,line:Wn,column:$t}}function fr(t){for(let e of t){if(En()!==e)throw Ne(z());z()}}function _C(){switch(En()){case"b":return z(),"\b";case"f":return z(),"\f";case"n":return z(),`
6
6
  `;case"r":return z(),"\r";case"t":return z()," ";case"v":return z(),"\v";case"0":if(z(),ze.isDigit(En()))throw Ne(z());return"\0";case"x":return z(),bC();case"u":return z(),oc();case`
7
7
  `:case"\u2028":case"\u2029":return z(),"";case"\r":return z(),En()===`
8
- `&&z(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Ne(z());case void 0:throw Ne(z())}return z()}function bC(){let t="",e=En();if(!ze.isHexDigit(e)||(t+=z(),e=En(),!ze.isHexDigit(e)))throw Ne(z());return t+=z(),String.fromCodePoint(parseInt(t,16))}function oc(){let t="",e=4;for(;e-- >0;){let n=En();if(!ze.isHexDigit(n))throw Ne(z());t+=z()}return String.fromCodePoint(parseInt(t,16))}var CC={start(){if(We.type==="eof")throw hr();tc()},beforePropertyName(){switch(We.type){case"identifier":case"string":sc=We.value,nt="afterPropertyName";return;case"punctuator":li();return;case"eof":throw hr()}},afterPropertyName(){if(We.type==="eof")throw hr();nt="beforePropertyValue"},beforePropertyValue(){if(We.type==="eof")throw hr();tc()},beforeArrayValue(){if(We.type==="eof")throw hr();if(We.type==="punctuator"&&We.value==="]"){li();return}tc()},afterPropertyValue(){if(We.type==="eof")throw hr();switch(We.value){case",":nt="beforePropertyName";return;case"}":li()}},afterArrayValue(){if(We.type==="eof")throw hr();switch(We.value){case",":nt="beforeArrayValue";return;case"]":li()}},end(){}};function tc(){let t;switch(We.type){case"punctuator":switch(We.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=We.value;break}if(Mo===void 0)Mo=t;else{let e=wn[wn.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,sc,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")wn.push(t),Array.isArray(t)?nt="beforeArrayValue":nt="beforePropertyName";else{let e=wn[wn.length-1];e==null?nt="end":Array.isArray(e)?nt="afterArrayValue":nt="afterPropertyValue"}}function li(){wn.pop();let t=wn[wn.length-1];t==null?nt="end":Array.isArray(t)?nt="afterArrayValue":nt="afterPropertyValue"}function Ne(t){return fi(t===void 0?`JSON5: invalid end of input at ${Wn}:${$t}`:`JSON5: invalid character '${Uh(t)}' at ${Wn}:${$t}`)}function hr(){return fi(`JSON5: invalid end of input at ${Wn}:${$t}`)}function jh(){return $t-=5,fi(`JSON5: invalid identifier character at ${Wn}:${$t}`)}function wC(t){console.warn(`JSON5: '${Uh(t)}' in strings is not valid ECMAScript; consider escaping`)}function Uh(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function fi(t){let e=new SyntaxError(t);return e.lineNumber=Wn,e.columnNumber=$t,e}});var Wh=K((mR,zh)=>{var ic=ec();zh.exports=function(e,n,r){let o=[],s="",a,c,l="",d;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,d=n.quote,n=n.replacer),typeof n=="function")c=n;else if(Array.isArray(n)){a=[];for(let b of n){let y;typeof b=="string"?y=b:(typeof b=="number"||b instanceof String||b instanceof Number)&&(y=String(b)),y!==void 0&&a.indexOf(y)<0&&a.push(y)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),l=" ".substr(0,r)):typeof r=="string"&&(l=r.substr(0,10)),f("",{"":e});function f(b,y){let m=y[b];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(b):typeof m.toJSON=="function"&&(m=m.toJSON(b))),c&&(m=c.call(y,b,m)),m instanceof Number?m=Number(m):m instanceof String?m=String(m):m instanceof Boolean&&(m=m.valueOf()),m){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof m=="string")return p(m,!1);if(typeof m=="number")return String(m);if(typeof m=="object")return Array.isArray(m)?C(m):g(m)}function p(b){let y={"'":.1,'"':.2},m={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},k="";for(let A=0;A<b.length;A++){let T=b[A];switch(T){case"'":case'"':y[T]++,k+=T;continue;case"\0":if(ic.isDigit(b[A+1])){k+="\\x00";continue}}if(m[T]){k+=m[T];continue}if(T<" "){let R=T.charCodeAt(0).toString(16);k+="\\x"+("00"+R).substring(R.length);continue}k+=T}let w=d||Object.keys(y).reduce((A,T)=>y[A]<y[T]?A:T);return k=k.replace(new RegExp(w,"g"),m[w]),w+k+w}function g(b){if(o.indexOf(b)>=0)throw TypeError("Converting circular structure to JSON5");o.push(b);let y=s;s=s+l;let m=a||Object.keys(b),k=[];for(let A of m){let T=f(A,b);if(T!==void 0){let R=_(A)+":";l!==""&&(R+=" "),R+=T,k.push(R)}}let w;if(k.length===0)w="{}";else{let A;if(l==="")A=k.join(","),w="{"+A+"}";else{let T=`,
9
- `+s;A=k.join(T),w=`{
10
- `+s+A+`,
11
- `+y+"}"}}return o.pop(),s=y,w}function _(b){if(b.length===0)return p(b,!0);let y=String.fromCodePoint(b.codePointAt(0));if(!ic.isIdStartChar(y))return p(b,!0);for(let m=y.length;m<b.length;m++)if(!ic.isIdContinueChar(String.fromCodePoint(b.codePointAt(m))))return p(b,!0);return b}function C(b){if(o.indexOf(b)>=0)throw TypeError("Converting circular structure to JSON5");o.push(b);let y=s;s=s+l;let m=[];for(let w=0;w<b.length;w++){let A=f(String(w),b);m.push(A!==void 0?A:"null")}let k;if(m.length===0)k="[]";else if(l==="")k="["+m.join(",")+"]";else{let w=`,
12
- `+s,A=m.join(w);k=`[
13
- `+s+A+`,
14
- `+y+"]"}return o.pop(),s=y,k}}});var ac=K((gR,Gh)=>{var EC=Hh(),AC=Wh(),SC={parse:EC,stringify:AC};Gh.exports=SC});var up={};ui(up,{getFallbackPromotionStore:()=>jo,resetFallbackPromotionStore:()=>RC});function jo(t){return mr||(mr=new lc,t&&mr.configure(t)),mr}function RC(){mr&&(mr.clearAll(),mr=null)}var DC,lc,mr,mi=Me(()=>{"use strict";Gn();DC=600*1e3,lc=class{promotions=new Map;enabled=!0;ttlMs=DC;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,n,r){return`${e},${n}:${r}`}promote(e,n,r,o,s,a){if(!this.enabled)return;let c=this.getKey(e,n,r),l=`${o},${s}`;this.promotions.set(c,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,n,r,o){if(!this.enabled)return null;let s=this.getKey(e,n,r),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...d]=a.promotedModel.split(","),f=d.join(",");if(!Ge().isAvailable(l,f))return this.promotions.delete(s),null;let g=o.find(C=>C.name.toLowerCase()===l.toLowerCase()),_=g?.models?.find(C=>String(C).toLowerCase()===f.toLowerCase());return!g||!_||g.enabled===!1?(this.promotions.delete(s),null):`${g.name},${_}`}clear(e,n,r){let o=this.getKey(e,n,r);this.promotions.delete(o)}clearByPrimary(e,n){let r=`${e},${n}:`,o=0;for(let s of this.promotions.keys())s.startsWith(r)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[n,r]of this.promotions)e-r.timestamp>=r.ttlMs&&this.promotions.delete(n)}getAllPromotions(){let e=Date.now(),n=[];for(let[r,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&n.push({key:r,promotedModel:o.promotedModel,remainingMs:s})}return n}},mr=null});function FC(t){try{if(!(0,An.existsSync)(hc))return;let e=JSON.parse((0,An.readFileSync)(hc,"utf-8"));if(!Array.isArray(e))return;let n=Date.now();for(let r of e){if(!r||!r.provider||!r.model)continue;let o=r.updatedAt||r.lastFailureTime||0;o&&n-o>1440*60*1e3||t.restore({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount??0,successCount:r.successCount??0,lastFailureTime:r.lastFailureTime??0,lastProbeTime:r.lastProbeTime??0,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil})}}catch{}}function lp(t){try{let e=t.getAllStates();if(e.length===0)return;(0,An.existsSync)(fc)||(0,An.mkdirSync)(fc,{recursive:!0});let n=e.map(r=>({...r,updatedAt:Date.now()}));(0,An.writeFileSync)(hc,JSON.stringify(n,null,2),"utf-8")}catch{}}function gi(){if(cp)return;cp=!0;let t=Ge();FC(t),PC=setInterval(()=>lp(t),6e4),process.on("exit",()=>lp(t))}function Ge(t){return dc||(dc=new $o(t)),dc}var An,pc,dp,xC,OC,$o,fc,hc,cp,PC,dc,Gn=Me(()=>{"use strict";An=require("fs"),pc=require("path"),dp=require("@wengine-ai/claude-code-router-shared"),xC=120,OC={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},$o=class{states=new Map;config;probeTimer;constructor(e){this.config={...OC,...e}}getKey(e,n){return`${e},${n}`}recordSuccess(e,n){if(!this.config.enabled)return;let r=this.getKey(e,n),o=this.states.get(r);o&&(o.successCount++,!o.rateLimitUntil&&(o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,n),this.states.delete(r)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0)))}clearPromotionsForPrimary(e,n){try{let{getFallbackPromotionStore:r}=(mi(),Bh(up));r().clearByPrimary(e,n)}catch{}}recordFailure(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s||(s={provider:e,model:n,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,n){return this.states.get(this.getKey(e,n))}isAvailable(e,n){if(!this.config.enabled)return!0;let r=this.getState(e,n);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.status!=="open":!0}getPriority(e,n){if(!this.config.enabled)return 0;let r=this.getState(e,n);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&e.push(n);return e}getHalfOpenModels(){let e=[];for(let[n,r]of this.states)r.status==="half-open"&&e.push(n);return e}forceOpen(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=r,s.lastProbeTime=0):(s={provider:e,model:n,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r},this.states.set(o,s))}markRateLimited(e,n,r,o){if(!this.config.enabled)return;let s=this.getKey(e,n),a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=o||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:n,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o||"rate-limited"},this.states.set(s,a));let c=(r??xC)*1e3;a.rateLimitUntil=Date.now()+c}getRateLimitedModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&r.rateLimitUntil&&e.push(n);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,n){let r=this.getKey(e,n),o=this.states.get(r);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,n){let r=this.getKey(e,n);this.states.delete(r)}getAllStates(){return Array.from(this.states.values())}restore(e){this.states.set(this.getKey(e.provider,e.model),{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},fc=(0,pc.join)(dp.HOME_DIR,"runtime"),hc=(0,pc.join)(fc,"provider-health.json"),cp=!1,PC=null;dc=null});var Ec=K((rx,Np)=>{"use strict";var vi=Object.prototype.hasOwnProperty,Ip=Object.prototype.toString,Dp=Object.defineProperty,Rp=Object.getOwnPropertyDescriptor,xp=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Ip.call(e)==="[object Array]"},Op=function(e){if(!e||Ip.call(e)!=="[object Object]")return!1;var n=vi.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&vi.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||vi.call(e,o)},Pp=function(e,n){Dp&&n.name==="__proto__"?Dp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Fp=function(e,n){if(n==="__proto__")if(vi.call(e,n)){if(Rp)return Rp(e,n).value}else return;return e[n]};Np.exports=function t(){var e,n,r,o,s,a,c=arguments[0],l=1,d=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<d;++l)if(e=arguments[l],e!=null)for(n in e)r=Fp(c,n),o=Fp(e,n),c!==o&&(f&&o&&(Op(o)||(s=xp(o)))?(s?(s=!1,a=r&&xp(r)?r:[]):a=r&&Op(r)?r:{},Pp(c,{name:n,newValue:t(f,a,o)})):typeof o<"u"&&Pp(c,{name:n,newValue:o}));return c}});var Bp=K((ox,YC)=>{YC.exports={name:"gaxios",version:"7.1.2",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var Lp=K((sx,Mp)=>{"use strict";var QC=Bp();Mp.exports={pkg:QC}});var kc=K(vt=>{"use strict";var $p=vt&&vt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vt,"__esModule",{value:!0});vt.GaxiosError=vt.GAXIOS_ERROR_SYMBOL=void 0;vt.defaultErrorRedactor=Up;var jp=$p(Ec()),XC=$p(Lp()),Ac=XC.default.pkg;vt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ac.name}-gaxios-error`);var Sc=class t extends Error{config;response;code;status;error;[vt.GAXIOS_ERROR_SYMBOL]=Ac.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&vt.GAXIOS_ERROR_SYMBOL in e&&e[vt.GAXIOS_ERROR_SYMBOL]===Ac.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,jp.default)(!0,{},n),this.response&&(this.response.config=(0,jp.default)(!0,{},this.response.config)),this.response){try{this.response.data=ZC(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let a=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&a.push(c.message);return Object.assign({message:a.join(`
15
- `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};vt.GaxiosError=Sc;function ZC(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Up(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function r(s,a){if(typeof s=="object"&&s!==null&&typeof s[a]=="string"){let c=s[a];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(s[a]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((a,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&s.set(c,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(Up({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var Hp=K(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.getRetryConfig=ew;async function ew(t){let e=qp(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||tw)(t))return{shouldRetry:!1,config:t.config};let o=nw(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function tw(t){let e=qp(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function qp(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function nw(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var Dc=K(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.GaxiosInterceptorManager=void 0;var Tc=class extends Set{};Ti.GaxiosInterceptorManager=Tc});var Wp=K((cx,zp)=>{var Kr=1e3,Yr=Kr*60,Qr=Yr*60,yr=Qr*24,rw=yr*7,ow=yr*365.25;zp.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return sw(t);if(n==="number"&&isFinite(t))return e.long?aw(t):iw(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function sw(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*ow;case"weeks":case"week":case"w":return n*rw;case"days":case"day":case"d":return n*yr;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Qr;case"minutes":case"minute":case"mins":case"min":case"m":return n*Yr;case"seconds":case"second":case"secs":case"sec":case"s":return n*Kr;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function iw(t){var e=Math.abs(t);return e>=yr?Math.round(t/yr)+"d":e>=Qr?Math.round(t/Qr)+"h":e>=Yr?Math.round(t/Yr)+"m":e>=Kr?Math.round(t/Kr)+"s":t+"ms"}function aw(t){var e=Math.abs(t);return e>=yr?Di(t,e,yr,"day"):e>=Qr?Di(t,e,Qr,"hour"):e>=Yr?Di(t,e,Yr,"minute"):e>=Kr?Di(t,e,Kr,"second"):t+" ms"}function Di(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var Rc=K((lx,Gp)=>{function uw(t){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=o,n.enabled=c,n.humanize=Wp(),n.destroy=d,Object.keys(t).forEach(f=>{n[f]=t[f]}),n.names=[],n.skips=[],n.formatters={};function e(f){let p=0;for(let g=0;g<f.length;g++)p=(p<<5)-p+f.charCodeAt(g),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(f){let p,g=null,_,C;function b(...y){if(!b.enabled)return;let m=b,k=Number(new Date),w=k-(p||k);m.diff=w,m.prev=p,m.curr=k,p=k,y[0]=n.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let A=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(R,U)=>{if(R==="%%")return"%";A++;let J=n.formatters[U];if(typeof J=="function"){let F=y[A];R=J.call(m,F),y.splice(A,1),A--}return R}),n.formatArgs.call(m,y),(m.log||n.log).apply(m,y)}return b.namespace=f,b.useColors=n.useColors(),b.color=n.selectColor(f),b.extend=r,b.destroy=n.destroy,Object.defineProperty(b,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(_!==n.namespaces&&(_=n.namespaces,C=n.enabled(f)),C),set:y=>{g=y}}),typeof n.init=="function"&&n.init(b),b}function r(f,p){let g=n(this.namespace+(typeof p>"u"?":":p)+f);return g.log=this.log,g}function o(f){n.save(f),n.namespaces=f,n.names=[],n.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let g of p)g[0]==="-"?n.skips.push(g.slice(1)):n.names.push(g)}function s(f,p){let g=0,_=0,C=-1,b=0;for(;g<f.length;)if(_<p.length&&(p[_]===f[g]||p[_]==="*"))p[_]==="*"?(C=_,b=g,_++):(g++,_++);else if(C!==-1)_=C+1,b++,g=b;else return!1;for(;_<p.length&&p[_]==="*";)_++;return _===p.length}function a(){let f=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),f}function c(f){for(let p of n.skips)if(s(f,p))return!1;for(let p of n.names)if(s(f,p))return!0;return!1}function l(f){return f instanceof Error?f.stack||f.message:f}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}Gp.exports=uw});var Jp=K((at,Ri)=>{at.formatArgs=lw;at.save=dw;at.load=fw;at.useColors=cw;at.storage=hw();at.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();at.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function cw(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function lw(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Ri.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}at.log=console.debug||console.log||(()=>{});function dw(t){try{t?at.storage.setItem("debug",t):at.storage.removeItem("debug")}catch{}}function fw(){let t;try{t=at.storage.getItem("debug")||at.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function hw(){try{return localStorage}catch{}}Ri.exports=Rc()(at);var{formatters:pw}=Ri.exports;pw.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Kp=K((dx,Vp)=>{"use strict";Vp.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var Xp=K((fx,Qp)=>{"use strict";var mw=require("os"),Yp=require("tty"),Tt=Kp(),{env:Je}=process,Jn;Tt("no-color")||Tt("no-colors")||Tt("color=false")||Tt("color=never")?Jn=0:(Tt("color")||Tt("colors")||Tt("color=true")||Tt("color=always"))&&(Jn=1);"FORCE_COLOR"in Je&&(Je.FORCE_COLOR==="true"?Jn=1:Je.FORCE_COLOR==="false"?Jn=0:Jn=Je.FORCE_COLOR.length===0?1:Math.min(parseInt(Je.FORCE_COLOR,10),3));function xc(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Oc(t,e){if(Jn===0)return 0;if(Tt("color=16m")||Tt("color=full")||Tt("color=truecolor"))return 3;if(Tt("color=256"))return 2;if(t&&!e&&Jn===void 0)return 0;let n=Jn||0;if(Je.TERM==="dumb")return n;if(process.platform==="win32"){let r=mw.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in Je)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in Je)||Je.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in Je)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Je.TEAMCITY_VERSION)?1:0;if(Je.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Je){let r=parseInt((Je.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Je.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Je.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Je.TERM)||"COLORTERM"in Je?1:n}function gw(t){let e=Oc(t,t&&t.isTTY);return xc(e)}Qp.exports={supportsColor:gw,stdout:xc(Oc(!0,Yp.isatty(1))),stderr:xc(Oc(!0,Yp.isatty(2)))}});var em=K((Ve,Oi)=>{var yw=require("tty"),xi=require("util");Ve.init=Sw;Ve.log=ww;Ve.formatArgs=bw;Ve.save=Ew;Ve.load=Aw;Ve.useColors=_w;Ve.destroy=xi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ve.colors=[6,2,3,4,5,1];try{let t=Xp();t&&(t.stderr||t).level>=2&&(Ve.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Ve.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function _w(){return"colors"in Ve.inspectOpts?!!Ve.inspectOpts.colors:yw.isatty(process.stderr.fd)}function bw(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
8
+ `&&z(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Ne(z());case void 0:throw Ne(z())}return z()}function bC(){let t="",e=En();if(!ze.isHexDigit(e)||(t+=z(),e=En(),!ze.isHexDigit(e)))throw Ne(z());return t+=z(),String.fromCodePoint(parseInt(t,16))}function oc(){let t="",e=4;for(;e-- >0;){let n=En();if(!ze.isHexDigit(n))throw Ne(z());t+=z()}return String.fromCodePoint(parseInt(t,16))}var CC={start(){if(We.type==="eof")throw hr();tc()},beforePropertyName(){switch(We.type){case"identifier":case"string":sc=We.value,nt="afterPropertyName";return;case"punctuator":li();return;case"eof":throw hr()}},afterPropertyName(){if(We.type==="eof")throw hr();nt="beforePropertyValue"},beforePropertyValue(){if(We.type==="eof")throw hr();tc()},beforeArrayValue(){if(We.type==="eof")throw hr();if(We.type==="punctuator"&&We.value==="]"){li();return}tc()},afterPropertyValue(){if(We.type==="eof")throw hr();switch(We.value){case",":nt="beforePropertyName";return;case"}":li()}},afterArrayValue(){if(We.type==="eof")throw hr();switch(We.value){case",":nt="beforeArrayValue";return;case"]":li()}},end(){}};function tc(){let t;switch(We.type){case"punctuator":switch(We.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=We.value;break}if(Mo===void 0)Mo=t;else{let e=wn[wn.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,sc,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")wn.push(t),Array.isArray(t)?nt="beforeArrayValue":nt="beforePropertyName";else{let e=wn[wn.length-1];e==null?nt="end":Array.isArray(e)?nt="afterArrayValue":nt="afterPropertyValue"}}function li(){wn.pop();let t=wn[wn.length-1];t==null?nt="end":Array.isArray(t)?nt="afterArrayValue":nt="afterPropertyValue"}function Ne(t){return fi(t===void 0?`JSON5: invalid end of input at ${Wn}:${$t}`:`JSON5: invalid character '${Uh(t)}' at ${Wn}:${$t}`)}function hr(){return fi(`JSON5: invalid end of input at ${Wn}:${$t}`)}function jh(){return $t-=5,fi(`JSON5: invalid identifier character at ${Wn}:${$t}`)}function wC(t){console.warn(`JSON5: '${Uh(t)}' in strings is not valid ECMAScript; consider escaping`)}function Uh(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function fi(t){let e=new SyntaxError(t);return e.lineNumber=Wn,e.columnNumber=$t,e}});var Wh=K((mR,zh)=>{var ic=ec();zh.exports=function(e,n,r){let o=[],s="",a,c,l="",d;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,d=n.quote,n=n.replacer),typeof n=="function")c=n;else if(Array.isArray(n)){a=[];for(let y of n){let _;typeof y=="string"?_=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(_=String(y)),_!==void 0&&a.indexOf(_)<0&&a.push(_)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),l=" ".substr(0,r)):typeof r=="string"&&(l=r.substr(0,10)),f("",{"":e});function f(y,_){let g=_[y];switch(g!=null&&(typeof g.toJSON5=="function"?g=g.toJSON5(y):typeof g.toJSON=="function"&&(g=g.toJSON(y))),c&&(g=c.call(_,y,g)),g instanceof Number?g=Number(g):g instanceof String?g=String(g):g instanceof Boolean&&(g=g.valueOf()),g){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof g=="string")return p(g,!1);if(typeof g=="number")return String(g);if(typeof g=="object")return Array.isArray(g)?C(g):m(g)}function p(y){let _={"'":.1,'"':.2},g={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},S="";for(let E=0;E<y.length;E++){let T=y[E];switch(T){case"'":case'"':_[T]++,S+=T;continue;case"\0":if(ic.isDigit(y[E+1])){S+="\\x00";continue}}if(g[T]){S+=g[T];continue}if(T<" "){let R=T.charCodeAt(0).toString(16);S+="\\x"+("00"+R).substring(R.length);continue}S+=T}let w=d||Object.keys(_).reduce((E,T)=>_[E]<_[T]?E:T);return S=S.replace(new RegExp(w,"g"),g[w]),w+S+w}function m(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let _=s;s=s+l;let g=a||Object.keys(y),S=[];for(let E of g){let T=f(E,y);if(T!==void 0){let R=b(E)+":";l!==""&&(R+=" "),R+=T,S.push(R)}}let w;if(S.length===0)w="{}";else{let E;if(l==="")E=S.join(","),w="{"+E+"}";else{let T=`,
9
+ `+s;E=S.join(T),w=`{
10
+ `+s+E+`,
11
+ `+_+"}"}}return o.pop(),s=_,w}function b(y){if(y.length===0)return p(y,!0);let _=String.fromCodePoint(y.codePointAt(0));if(!ic.isIdStartChar(_))return p(y,!0);for(let g=_.length;g<y.length;g++)if(!ic.isIdContinueChar(String.fromCodePoint(y.codePointAt(g))))return p(y,!0);return y}function C(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let _=s;s=s+l;let g=[];for(let w=0;w<y.length;w++){let E=f(String(w),y);g.push(E!==void 0?E:"null")}let S;if(g.length===0)S="[]";else if(l==="")S="["+g.join(",")+"]";else{let w=`,
12
+ `+s,E=g.join(w);S=`[
13
+ `+s+E+`,
14
+ `+_+"]"}return o.pop(),s=_,S}}});var ac=K((gR,Gh)=>{var EC=Hh(),AC=Wh(),SC={parse:EC,stringify:AC};Gh.exports=SC});var up={};ui(up,{getFallbackPromotionStore:()=>jo,resetFallbackPromotionStore:()=>RC});function jo(t){return mr||(mr=new lc,t&&mr.configure(t)),mr}function RC(){mr&&(mr.clearAll(),mr=null)}var DC,lc,mr,mi=Me(()=>{"use strict";Gn();DC=600*1e3,lc=class{promotions=new Map;enabled=!0;ttlMs=DC;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,n,r){return`${e},${n}:${r}`}promote(e,n,r,o,s,a){if(!this.enabled)return;let c=this.getKey(e,n,r),l=`${o},${s}`;this.promotions.set(c,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,n,r,o){if(!this.enabled)return null;let s=this.getKey(e,n,r),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...d]=a.promotedModel.split(","),f=d.join(",");if(!Ge().isAvailable(l,f))return this.promotions.delete(s),null;let m=o.find(C=>C.name.toLowerCase()===l.toLowerCase()),b=m?.models?.find(C=>String(C).toLowerCase()===f.toLowerCase());return!m||!b||m.enabled===!1?(this.promotions.delete(s),null):`${m.name},${b}`}clear(e,n,r){let o=this.getKey(e,n,r);this.promotions.delete(o)}clearByPrimary(e,n){let r=`${e},${n}:`,o=0;for(let s of this.promotions.keys())s.startsWith(r)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[n,r]of this.promotions)e-r.timestamp>=r.ttlMs&&this.promotions.delete(n)}getAllPromotions(){let e=Date.now(),n=[];for(let[r,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&n.push({key:r,promotedModel:o.promotedModel,remainingMs:s})}return n}},mr=null});function FC(t){try{if(!(0,An.existsSync)(hc))return;let e=JSON.parse((0,An.readFileSync)(hc,"utf-8"));if(!Array.isArray(e))return;let n=Date.now();for(let r of e){if(!r||!r.provider||!r.model)continue;let o=r.updatedAt||r.lastFailureTime||0;o&&n-o>1440*60*1e3||t.restore({provider:r.provider,model:r.model,status:r.status,failureCount:r.failureCount??0,successCount:r.successCount??0,lastFailureTime:r.lastFailureTime??0,lastProbeTime:r.lastProbeTime??0,lastError:r.lastError,rateLimitUntil:r.rateLimitUntil})}}catch{}}function lp(t){try{let e=t.getAllStates();if(e.length===0)return;(0,An.existsSync)(fc)||(0,An.mkdirSync)(fc,{recursive:!0});let n=e.map(r=>({...r,updatedAt:Date.now()}));(0,An.writeFileSync)(hc,JSON.stringify(n,null,2),"utf-8")}catch{}}function gi(){if(cp)return;cp=!0;let t=Ge();FC(t),PC=setInterval(()=>lp(t),6e4),process.on("exit",()=>lp(t))}function Ge(t){return dc||(dc=new $o(t)),dc}var An,pc,dp,xC,OC,$o,fc,hc,cp,PC,dc,Gn=Me(()=>{"use strict";An=require("fs"),pc=require("path"),dp=require("@wengine-ai/claude-code-router-shared"),xC=120,OC={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},$o=class{states=new Map;config;probeTimer;constructor(e){this.config={...OC,...e}}getKey(e,n){return`${e},${n}`}recordSuccess(e,n){if(!this.config.enabled)return;let r=this.getKey(e,n),o=this.states.get(r);o&&(o.successCount++,!o.rateLimitUntil&&(o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,n),this.states.delete(r)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0)))}clearPromotionsForPrimary(e,n){try{let{getFallbackPromotionStore:r}=(mi(),Bh(up));r().clearByPrimary(e,n)}catch{}}recordFailure(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s||(s={provider:e,model:n,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=r,s.status==="half-open"?(s.status="open",s.successCount=0,s.lastProbeTime=0):s.status==="closed"&&s.failureCount>=this.config.failureThreshold&&(s.status="open",s.lastProbeTime=0)}getState(e,n){return this.states.get(this.getKey(e,n))}isAvailable(e,n){if(!this.config.enabled)return!0;let r=this.getState(e,n);return r?r.status==="open"&&r.rateLimitUntil?!(Date.now()<r.rateLimitUntil):r.status!=="open":!0}getPriority(e,n){if(!this.config.enabled)return 0;let r=this.getState(e,n);if(!r)return 0;switch(r.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&e.push(n);return e}getHalfOpenModels(){let e=[];for(let[n,r]of this.states)r.status==="half-open"&&e.push(n);return e}forceOpen(e,n,r){if(!this.config.enabled)return;let o=this.getKey(e,n),s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=r,s.lastProbeTime=0):(s={provider:e,model:n,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:r},this.states.set(o,s))}markRateLimited(e,n,r,o){if(!this.config.enabled)return;let s=this.getKey(e,n),a=this.states.get(s);a?(a.status="open",a.lastFailureTime=Date.now(),a.lastError=o||"rate-limited",a.lastProbeTime=0):(a={provider:e,model:n,status:"open",failureCount:0,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:o||"rate-limited"},this.states.set(s,a));let c=(r??xC)*1e3;a.rateLimitUntil=Date.now()+c}getRateLimitedModels(){let e=[];for(let[n,r]of this.states)r.status==="open"&&r.rateLimitUntil&&e.push(n);return e}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,n){let r=this.getKey(e,n),o=this.states.get(r);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}recover(e,n){let r=this.getKey(e,n);this.states.delete(r)}getAllStates(){return Array.from(this.states.values())}restore(e){this.states.set(this.getKey(e.provider,e.model),{...e})}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},fc=(0,pc.join)(dp.HOME_DIR,"runtime"),hc=(0,pc.join)(fc,"provider-health.json"),cp=!1,PC=null;dc=null});var Ec=K((rx,Np)=>{"use strict";var vi=Object.prototype.hasOwnProperty,Ip=Object.prototype.toString,Dp=Object.defineProperty,Rp=Object.getOwnPropertyDescriptor,xp=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Ip.call(e)==="[object Array]"},Op=function(e){if(!e||Ip.call(e)!=="[object Object]")return!1;var n=vi.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&vi.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||vi.call(e,o)},Pp=function(e,n){Dp&&n.name==="__proto__"?Dp(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},Fp=function(e,n){if(n==="__proto__")if(vi.call(e,n)){if(Rp)return Rp(e,n).value}else return;return e[n]};Np.exports=function t(){var e,n,r,o,s,a,c=arguments[0],l=1,d=arguments.length,f=!1;for(typeof c=="boolean"&&(f=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<d;++l)if(e=arguments[l],e!=null)for(n in e)r=Fp(c,n),o=Fp(e,n),c!==o&&(f&&o&&(Op(o)||(s=xp(o)))?(s?(s=!1,a=r&&xp(r)?r:[]):a=r&&Op(r)?r:{},Pp(c,{name:n,newValue:t(f,a,o)})):typeof o<"u"&&Pp(c,{name:n,newValue:o}));return c}});var Bp=K((ox,YC)=>{YC.exports={name:"gaxios",version:"7.1.2",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var Lp=K((sx,Mp)=>{"use strict";var QC=Bp();Mp.exports={pkg:QC}});var kc=K(vt=>{"use strict";var $p=vt&&vt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vt,"__esModule",{value:!0});vt.GaxiosError=vt.GAXIOS_ERROR_SYMBOL=void 0;vt.defaultErrorRedactor=Up;var jp=$p(Ec()),XC=$p(Lp()),Ac=XC.default.pkg;vt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ac.name}-gaxios-error`);var Sc=class t extends Error{config;response;code;status;error;[vt.GAXIOS_ERROR_SYMBOL]=Ac.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&vt.GAXIOS_ERROR_SYMBOL in e&&e[vt.GAXIOS_ERROR_SYMBOL]===Ac.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,jp.default)(!0,{},n),this.response&&(this.response.config=(0,jp.default)(!0,{},this.response.config)),this.response){try{this.response.data=ZC(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let a=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&a.push(c.message);return Object.assign({message:a.join(`
15
+ `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};vt.GaxiosError=Sc;function ZC(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Up(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function r(s,a){if(typeof s=="object"&&s!==null&&typeof s[a]=="string"){let c=s[a];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(s[a]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((a,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&s.set(c,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(Up({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var Hp=K(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.getRetryConfig=ew;async function ew(t){let e=qp(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||tw)(t))return{shouldRetry:!1,config:t.config};let o=nw(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function tw(t){let e=qp(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function qp(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function nw(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var Dc=K(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.GaxiosInterceptorManager=void 0;var Tc=class extends Set{};Ti.GaxiosInterceptorManager=Tc});var Wp=K((cx,zp)=>{var Kr=1e3,Yr=Kr*60,Qr=Yr*60,yr=Qr*24,rw=yr*7,ow=yr*365.25;zp.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return sw(t);if(n==="number"&&isFinite(t))return e.long?aw(t):iw(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function sw(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*ow;case"weeks":case"week":case"w":return n*rw;case"days":case"day":case"d":return n*yr;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Qr;case"minutes":case"minute":case"mins":case"min":case"m":return n*Yr;case"seconds":case"second":case"secs":case"sec":case"s":return n*Kr;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function iw(t){var e=Math.abs(t);return e>=yr?Math.round(t/yr)+"d":e>=Qr?Math.round(t/Qr)+"h":e>=Yr?Math.round(t/Yr)+"m":e>=Kr?Math.round(t/Kr)+"s":t+"ms"}function aw(t){var e=Math.abs(t);return e>=yr?Di(t,e,yr,"day"):e>=Qr?Di(t,e,Qr,"hour"):e>=Yr?Di(t,e,Yr,"minute"):e>=Kr?Di(t,e,Kr,"second"):t+" ms"}function Di(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var Rc=K((lx,Gp)=>{function uw(t){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=o,n.enabled=c,n.humanize=Wp(),n.destroy=d,Object.keys(t).forEach(f=>{n[f]=t[f]}),n.names=[],n.skips=[],n.formatters={};function e(f){let p=0;for(let m=0;m<f.length;m++)p=(p<<5)-p+f.charCodeAt(m),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(f){let p,m=null,b,C;function y(..._){if(!y.enabled)return;let g=y,S=Number(new Date),w=S-(p||S);g.diff=w,g.prev=p,g.curr=S,p=S,_[0]=n.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let E=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(R,U)=>{if(R==="%%")return"%";E++;let J=n.formatters[U];if(typeof J=="function"){let F=_[E];R=J.call(g,F),_.splice(E,1),E--}return R}),n.formatArgs.call(g,_),(g.log||n.log).apply(g,_)}return y.namespace=f,y.useColors=n.useColors(),y.color=n.selectColor(f),y.extend=r,y.destroy=n.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(b!==n.namespaces&&(b=n.namespaces,C=n.enabled(f)),C),set:_=>{m=_}}),typeof n.init=="function"&&n.init(y),y}function r(f,p){let m=n(this.namespace+(typeof p>"u"?":":p)+f);return m.log=this.log,m}function o(f){n.save(f),n.namespaces=f,n.names=[],n.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of p)m[0]==="-"?n.skips.push(m.slice(1)):n.names.push(m)}function s(f,p){let m=0,b=0,C=-1,y=0;for(;m<f.length;)if(b<p.length&&(p[b]===f[m]||p[b]==="*"))p[b]==="*"?(C=b,y=m,b++):(m++,b++);else if(C!==-1)b=C+1,y++,m=y;else return!1;for(;b<p.length&&p[b]==="*";)b++;return b===p.length}function a(){let f=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),f}function c(f){for(let p of n.skips)if(s(f,p))return!1;for(let p of n.names)if(s(f,p))return!0;return!1}function l(f){return f instanceof Error?f.stack||f.message:f}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}Gp.exports=uw});var Jp=K((at,Ri)=>{at.formatArgs=lw;at.save=dw;at.load=fw;at.useColors=cw;at.storage=hw();at.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();at.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function cw(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function lw(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Ri.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}at.log=console.debug||console.log||(()=>{});function dw(t){try{t?at.storage.setItem("debug",t):at.storage.removeItem("debug")}catch{}}function fw(){let t;try{t=at.storage.getItem("debug")||at.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function hw(){try{return localStorage}catch{}}Ri.exports=Rc()(at);var{formatters:pw}=Ri.exports;pw.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Kp=K((dx,Vp)=>{"use strict";Vp.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var Xp=K((fx,Qp)=>{"use strict";var mw=require("os"),Yp=require("tty"),Tt=Kp(),{env:Je}=process,Jn;Tt("no-color")||Tt("no-colors")||Tt("color=false")||Tt("color=never")?Jn=0:(Tt("color")||Tt("colors")||Tt("color=true")||Tt("color=always"))&&(Jn=1);"FORCE_COLOR"in Je&&(Je.FORCE_COLOR==="true"?Jn=1:Je.FORCE_COLOR==="false"?Jn=0:Jn=Je.FORCE_COLOR.length===0?1:Math.min(parseInt(Je.FORCE_COLOR,10),3));function xc(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Oc(t,e){if(Jn===0)return 0;if(Tt("color=16m")||Tt("color=full")||Tt("color=truecolor"))return 3;if(Tt("color=256"))return 2;if(t&&!e&&Jn===void 0)return 0;let n=Jn||0;if(Je.TERM==="dumb")return n;if(process.platform==="win32"){let r=mw.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in Je)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in Je)||Je.CI_NAME==="codeship"?1:n;if("TEAMCITY_VERSION"in Je)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Je.TEAMCITY_VERSION)?1:0;if(Je.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Je){let r=parseInt((Je.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Je.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Je.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Je.TERM)||"COLORTERM"in Je?1:n}function gw(t){let e=Oc(t,t&&t.isTTY);return xc(e)}Qp.exports={supportsColor:gw,stdout:xc(Oc(!0,Yp.isatty(1))),stderr:xc(Oc(!0,Yp.isatty(2)))}});var em=K((Ve,Oi)=>{var yw=require("tty"),xi=require("util");Ve.init=Sw;Ve.log=ww;Ve.formatArgs=bw;Ve.save=Ew;Ve.load=Aw;Ve.useColors=_w;Ve.destroy=xi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ve.colors=[6,2,3,4,5,1];try{let t=Xp();t&&(t.stderr||t).level>=2&&(Ve.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Ve.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function _w(){return"colors"in Ve.inspectOpts?!!Ve.inspectOpts.colors:yw.isatty(process.stderr.fd)}function bw(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
16
16
  `).join(`
17
17
  `+s),t.push(o+"m+"+Oi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=Cw()+e+" "+t[0]}function Cw(){return Ve.inspectOpts.hideDate?"":new Date().toISOString()+" "}function ww(...t){return process.stderr.write(xi.formatWithOptions(Ve.inspectOpts,...t)+`
18
18
  `)}function Ew(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function Aw(){return process.env.DEBUG}function Sw(t){t.inspectOpts={};let e=Object.keys(Ve.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=Ve.inspectOpts[e[n]]}Oi.exports=Rc()(Ve);var{formatters:Zp}=Oi.exports;Zp.o=function(t){return this.inspectOpts.colors=this.useColors,xi.inspect(t,this.inspectOpts).split(`
19
19
  `).map(e=>e.trim()).join(" ")};Zp.O=function(t){return this.inspectOpts.colors=this.useColors,xi.inspect(t,this.inspectOpts)}});var Fc=K((hx,Pc)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Pc.exports=Jp():Pc.exports=em()});var rm=K(ut=>{"use strict";var kw=ut&&ut.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),vw=ut&&ut.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tm=ut&&ut.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&kw(e,t,n);return vw(e,t),e};Object.defineProperty(ut,"__esModule",{value:!0});ut.req=ut.json=ut.toBuffer=void 0;var Tw=tm(require("http")),Dw=tm(require("https"));async function nm(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}ut.toBuffer=nm;async function Rw(t){let n=(await nm(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}ut.json=Rw;function xw(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?Dw:Tw).request(t,e),o=new Promise((s,a)=>{r.once("response",s).once("error",a).end()});return r.then=o.then.bind(o),r}ut.req=xw});var am=K(ht=>{"use strict";var sm=ht&&ht.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ow=ht&&ht.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),im=ht&&ht.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&sm(e,t,n);return Ow(e,t),e},Pw=ht&&ht.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&sm(e,t,n)};Object.defineProperty(ht,"__esModule",{value:!0});ht.Agent=void 0;var Fw=im(require("net")),om=im(require("http")),Iw=require("https");Pw(rm(),ht);var Zt=Symbol("AgentBaseInternalState"),Ic=class extends om.Agent{constructor(e){super(e),this[Zt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
20
- `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new Fw.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Iw.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof om.Agent)try{return c.addRequest(e,o)}catch(l){return r(l)}this[Zt].currentSocket=c,super.createSocket(e,n,r)},c=>{this.decrementSockets(s,a),r(c)})}createConnection(){let e=this[Zt].currentSocket;if(this[Zt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Zt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Zt]&&(this[Zt].defaultPort=e)}get protocol(){return this[Zt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Zt]&&(this[Zt].protocol=e)}};ht.Agent=Ic});var um=K(Xr=>{"use strict";var Nw=Xr&&Xr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Xr,"__esModule",{value:!0});Xr.parseProxyResponse=void 0;var Bw=Nw(Fc()),Pi=(0,Bw.default)("https-proxy-agent:parse-proxy-response");function Mw(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let f=t.read();f?d(f):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),Pi("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(f){a(),Pi("onerror %o",f),n(f)}function d(f){o.push(f),r+=f.length;let p=Buffer.concat(o,r),g=p.indexOf(`\r
20
+ `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new Fw.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Iw.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof om.Agent)try{return c.addRequest(e,o)}catch(l){return r(l)}this[Zt].currentSocket=c,super.createSocket(e,n,r)},c=>{this.decrementSockets(s,a),r(c)})}createConnection(){let e=this[Zt].currentSocket;if(this[Zt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Zt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Zt]&&(this[Zt].defaultPort=e)}get protocol(){return this[Zt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Zt]&&(this[Zt].protocol=e)}};ht.Agent=Ic});var um=K(Xr=>{"use strict";var Nw=Xr&&Xr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Xr,"__esModule",{value:!0});Xr.parseProxyResponse=void 0;var Bw=Nw(Fc()),Pi=(0,Bw.default)("https-proxy-agent:parse-proxy-response");function Mw(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let f=t.read();f?d(f):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),Pi("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(f){a(),Pi("onerror %o",f),n(f)}function d(f){o.push(f),r+=f.length;let p=Buffer.concat(o,r),m=p.indexOf(`\r
21
21
  \r
22
- `);if(g===-1){Pi("have not received end of HTTP headers yet..."),s();return}let _=p.slice(0,g).toString("ascii").split(`\r
23
- `),C=_.shift();if(!C)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let b=C.split(" "),y=+b[1],m=b.slice(2).join(" "),k={};for(let w of _){if(!w)continue;let A=w.indexOf(":");if(A===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${w}"`));let T=w.slice(0,A).toLowerCase(),R=w.slice(A+1).trimStart(),U=k[T];typeof U=="string"?k[T]=[U,R]:Array.isArray(U)?U.push(R):k[T]=R}Pi("got proxy server response: %o %o",C,k),a(),e({connect:{statusCode:y,statusText:m,headers:k},buffered:p})}t.on("error",l),t.on("end",c),s()})}Xr.parseProxyResponse=Mw});var pm=K(Dt=>{"use strict";var Lw=Dt&&Dt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),jw=Dt&&Dt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fm=Dt&&Dt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Lw(e,t,n);return jw(e,t),e},hm=Dt&&Dt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.HttpsProxyAgent=void 0;var Fi=fm(require("net")),cm=fm(require("tls")),$w=hm(require("assert")),Uw=hm(Fc()),qw=am(),Hw=require("url"),zw=um(),Ho=(0,Uw.default)("https-proxy-agent"),lm=t=>t.servername===void 0&&t.host&&!Fi.isIP(t.host)?{...t,servername:t.host}:t,Ii=class extends qw.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new Hw.URL(e):e,this.proxyHeaders=n?.headers??{},Ho("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?dm(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(Ho("Creating `tls.Socket`: %o",this.connectOpts),o=cm.connect(lm(this.connectOpts))):(Ho("Creating `net.Socket`: %o",this.connectOpts),o=Fi.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=Fi.isIPv6(n.host)?`[${n.host}]`:n.host,c=`CONNECT ${a}:${n.port} HTTP/1.1\r
24
- `;if(r.username||r.password){let g=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(g).toString("base64")}`}s.Host=`${a}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let g of Object.keys(s))c+=`${g}: ${s[g]}\r
22
+ `);if(m===-1){Pi("have not received end of HTTP headers yet..."),s();return}let b=p.slice(0,m).toString("ascii").split(`\r
23
+ `),C=b.shift();if(!C)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let y=C.split(" "),_=+y[1],g=y.slice(2).join(" "),S={};for(let w of b){if(!w)continue;let E=w.indexOf(":");if(E===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${w}"`));let T=w.slice(0,E).toLowerCase(),R=w.slice(E+1).trimStart(),U=S[T];typeof U=="string"?S[T]=[U,R]:Array.isArray(U)?U.push(R):S[T]=R}Pi("got proxy server response: %o %o",C,S),a(),e({connect:{statusCode:_,statusText:g,headers:S},buffered:p})}t.on("error",l),t.on("end",c),s()})}Xr.parseProxyResponse=Mw});var pm=K(Dt=>{"use strict";var Lw=Dt&&Dt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),jw=Dt&&Dt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fm=Dt&&Dt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Lw(e,t,n);return jw(e,t),e},hm=Dt&&Dt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.HttpsProxyAgent=void 0;var Fi=fm(require("net")),cm=fm(require("tls")),$w=hm(require("assert")),Uw=hm(Fc()),qw=am(),Hw=require("url"),zw=um(),Ho=(0,Uw.default)("https-proxy-agent"),lm=t=>t.servername===void 0&&t.host&&!Fi.isIP(t.host)?{...t,servername:t.host}:t,Ii=class extends qw.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new Hw.URL(e):e,this.proxyHeaders=n?.headers??{},Ho("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?dm(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(Ho("Creating `tls.Socket`: %o",this.connectOpts),o=cm.connect(lm(this.connectOpts))):(Ho("Creating `net.Socket`: %o",this.connectOpts),o=Fi.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=Fi.isIPv6(n.host)?`[${n.host}]`:n.host,c=`CONNECT ${a}:${n.port} HTTP/1.1\r
24
+ `;if(r.username||r.password){let m=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(m).toString("base64")}`}s.Host=`${a}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let m of Object.keys(s))c+=`${m}: ${s[m]}\r
25
25
  `;let l=(0,zw.parseProxyResponse)(o);o.write(`${c}\r
26
- `);let{connect:d,buffered:f}=await l;if(e.emit("proxyConnect",d),this.emit("proxyConnect",d,e),d.statusCode===200)return e.once("socket",Ww),n.secureEndpoint?(Ho("Upgrading socket connection to TLS"),cm.connect({...dm(lm(n),"host","path","port"),socket:o})):o;o.destroy();let p=new Fi.Socket({writable:!1});return p.readable=!0,e.once("socket",g=>{Ho("Replaying proxy buffer for failed request"),(0,$w.default)(g.listenerCount("data")>0),g.push(f),g.push(null)}),p}};Ii.protocols=["http","https"];Dt.HttpsProxyAgent=Ii;function Ww(t){t.resume()}function dm(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function Gw(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",a=s;for(let f=1;f<n.length;f++)n[f]==="base64"?o=!0:n[f]&&(a+=`;${n[f]}`,n[f].indexOf("charset=")===0&&(r=n[f].substring(8)));!n[0]&&!r.length&&(a+=";charset=US-ASCII",r="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),d=Buffer.from(l,c);return d.type=s,d.typeFull=a,d.charset=r,d}var mm,gm=Me(()=>{mm=Gw});var _m=K((Ni,ym)=>{(function(t,e){typeof Ni=="object"&&typeof ym<"u"?e(Ni):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Ni,(function(t){"use strict";function e(){}function n(i){return typeof i=="object"&&i!==null||typeof i=="function"}let r=e;function o(i,u){try{Object.defineProperty(i,"name",{value:u,configurable:!0})}catch{}}let s=Promise,a=Promise.prototype.then,c=Promise.reject.bind(s);function l(i){return new s(i)}function d(i){return l(u=>u(i))}function f(i){return c(i)}function p(i,u,h){return a.call(i,u,h)}function g(i,u,h){p(p(i,u,h),void 0,r)}function _(i,u){g(i,u)}function C(i,u){g(i,void 0,u)}function b(i,u,h){return p(i,u,h)}function y(i){p(i,void 0,r)}let m=i=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let u=d(void 0);m=h=>p(u,h)}return m(i)};function k(i,u,h){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,h)}function w(i,u,h){try{return d(k(i,u,h))}catch(S){return f(S)}}let A=16384;class T{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(u){let h=this._back,S=h;h._elements.length===A-1&&(S={_elements:[],_next:void 0}),h._elements.push(u),S!==h&&(this._back=S,h._next=S),++this._size}shift(){let u=this._front,h=u,S=this._cursor,x=S+1,j=u._elements,q=j[S];return x===A&&(h=u._next,x=0),--this._size,this._cursor=x,u!==h&&(this._front=h),j[S]=void 0,q}forEach(u){let h=this._cursor,S=this._front,x=S._elements;for(;(h!==x.length||S._next!==void 0)&&!(h===x.length&&(S=S._next,x=S._elements,h=0,x.length===0));)u(x[h]),++h}peek(){let u=this._front,h=this._cursor;return u._elements[h]}}let R=Symbol("[[AbortSteps]]"),U=Symbol("[[ErrorSteps]]"),J=Symbol("[[CancelSteps]]"),F=Symbol("[[PullSteps]]"),V=Symbol("[[ReleaseSteps]]");function Y(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?Ae(i):u._state==="closed"?pe(i):ae(i,u._storedError)}function X(i,u){let h=i._ownerReadableStream;return Lt(h,u)}function ee(i){let u=i._ownerReadableStream;u._state==="readable"?W(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Q(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[V](),u._reader=void 0,i._ownerReadableStream=void 0}function de(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function Ae(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h})}function ae(i,u){Ae(i),W(i,u)}function pe(i){Ae(i),re(i)}function W(i,u){i._closedPromise_reject!==void 0&&(y(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function Q(i,u){ae(i,u)}function re(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let $e=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},ke=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function G(i){return typeof i=="object"||typeof i=="function"}function le(i,u){if(i!==void 0&&!G(i))throw new TypeError(`${u} is not an object.`)}function _e(i,u){if(typeof i!="function")throw new TypeError(`${u} is not a function.`)}function Bt(i){return typeof i=="object"&&i!==null||typeof i=="function"}function Re(i,u){if(!Bt(i))throw new TypeError(`${u} is not an object.`)}function Le(i,u,h){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${h}'.`)}function E(i,u,h){if(i===void 0)throw new TypeError(`${u} is required in '${h}'.`)}function v(i){return Number(i)}function D(i){return i===0?0:i}function M(i){return D(ke(i))}function P(i,u){let S=Number.MAX_SAFE_INTEGER,x=Number(i);if(x=D(x),!$e(x))throw new TypeError(`${u} is not a finite number`);if(x=M(x),x<0||x>S)throw new TypeError(`${u} is outside the accepted range of 0 to ${S}, inclusive`);return!$e(x)||x===0?0:x}function N(i,u){if(!Un(i))throw new TypeError(`${u} is not a ReadableStream.`)}function $(i){return new H(i)}function O(i,u){i._reader._readRequests.push(u)}function I(i,u,h){let x=i._reader._readRequests.shift();h?x._closeSteps():x._chunkSteps(u)}function L(i){return i._reader._readRequests.length}function B(i){let u=i._reader;return!(u===void 0||!te(u))}class H{constructor(u){if(Le(u,1,"ReadableStreamDefaultReader"),N(u,"First parameter"),qn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");Y(this,u),this._readRequests=new T}get closed(){return te(this)?this._closedPromise:f(Be("closed"))}cancel(u=void 0){return te(this)?this._ownerReadableStream===void 0?f(de("cancel")):X(this,u):f(Be("cancel"))}read(){if(!te(this))return f(Be("read"));if(this._ownerReadableStream===void 0)return f(de("read from"));let u,h,S=l((j,q)=>{u=j,h=q});return ne(this,{_chunkSteps:j=>u({value:j,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:j=>h(j)}),S}releaseLock(){if(!te(this))throw Be("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(H.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(H.prototype.cancel,"cancel"),o(H.prototype.read,"read"),o(H.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(H.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function te(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof H}function ne(i,u){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?u._closeSteps():h._state==="errored"?u._errorSteps(h._storedError):h._readableStreamController[F](u)}function Ee(i){ee(i);let u=new TypeError("Reader was released");Fe(i,u)}function Fe(i,u){let h=i._readRequests;i._readRequests=new T,h.forEach(S=>{S._errorSteps(u)})}function Be(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let we=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(u,h){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=u,this._preventCancel=h}next(){let u=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?b(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let h=()=>this._returnSteps(u);return this._ongoingPromise?b(this._ongoingPromise,h,h):h()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,h,S,x=l((q,Z)=>{h=q,S=Z});return ne(u,{_chunkSteps:q=>{this._ongoingPromise=void 0,m(()=>h({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ee(u),h({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,ee(u),S(q)}}),x}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let S=X(h,u);return ee(h),b(S,()=>({value:u,done:!0}))}return ee(h),d({value:u,done:!0})}}let Ue={next(){return Pr(this)?this._asyncIteratorImpl.next():f(Fr("next"))},return(i){return Pr(this)?this._asyncIteratorImpl.return(i):f(Fr("return"))}};Object.setPrototypeOf(Ue,we);function Or(i,u){let h=$(i),S=new Se(h,u),x=Object.create(Ue);return x._asyncIteratorImpl=S,x}function Pr(i){if(!n(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Se}catch{return!1}}function Fr(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let dt=Number.isNaN||function(i){return i!==i};var hn,Xe,qe;function ve(i){return i.slice()}function Ff(i,u,h,S,x){new Uint8Array(i).set(new Uint8Array(h,S,x),u)}let pn=i=>(typeof i.transfer=="function"?pn=u=>u.transfer():typeof structuredClone=="function"?pn=u=>structuredClone(u,{transfer:[u]}):pn=u=>u,pn(i)),Mn=i=>(typeof i.detached=="boolean"?Mn=u=>u.detached:Mn=u=>u.byteLength===0,Mn(i));function If(i,u,h){if(i.slice)return i.slice(u,h);let S=h-u,x=new ArrayBuffer(S);return Ff(x,0,i,u,S),x}function Is(i,u){let h=i[u];if(h!=null){if(typeof h!="function")throw new TypeError(`${String(u)} is not a function`);return h}}function O_(i){let u={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*u})(),S=h.next;return{iterator:h,nextMethod:S,done:!1}}let vu=(qe=(hn=Symbol.asyncIterator)!==null&&hn!==void 0?hn:(Xe=Symbol.for)===null||Xe===void 0?void 0:Xe.call(Symbol,"Symbol.asyncIterator"))!==null&&qe!==void 0?qe:"@@asyncIterator";function Nf(i,u="sync",h){if(h===void 0)if(u==="async"){if(h=Is(i,vu),h===void 0){let j=Is(i,Symbol.iterator),q=Nf(i,"sync",j);return O_(q)}}else h=Is(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let S=k(h,i,[]);if(!n(S))throw new TypeError("The iterator method must return an object");let x=S.next;return{iterator:S,nextMethod:x,done:!1}}function P_(i){let u=k(i.nextMethod,i.iterator,[]);if(!n(u))throw new TypeError("The iterator.next() method must return an object");return u}function F_(i){return!!i.done}function I_(i){return i.value}function N_(i){return!(typeof i!="number"||dt(i)||i<0)}function Bf(i){let u=If(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function Tu(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function Du(i,u,h){if(!N_(h)||h===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");i._queue.push({value:u,size:h}),i._queueTotalSize+=h}function B_(i){return i._queue.peek().value}function Ln(i){i._queue=new T,i._queueTotalSize=0}function Mf(i){return i===DataView}function M_(i){return Mf(i.constructor)}function L_(i){return Mf(i)?1:i.BYTES_PER_ELEMENT}class or{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ru(this))throw Iu("view");return this._view}respond(u){if(!Ru(this))throw Iu("respond");if(Le(u,1,"respond"),u=P(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Mn(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ls(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!Ru(this))throw Iu("respondWithNewView");if(Le(u,1,"respondWithNewView"),!ArrayBuffer.isView(u))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Mn(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");js(this._associatedReadableByteStreamController,u)}}Object.defineProperties(or.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(or.prototype.respond,"respond"),o(or.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(or.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class mn{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!sr(this))throw Ro("byobRequest");return Fu(this)}get desiredSize(){if(!sr(this))throw Ro("desiredSize");return Jf(this)}close(){if(!sr(this))throw Ro("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let u=this._controlledReadableByteStream._state;if(u!=="readable")throw new TypeError(`The stream (in ${u} state) is not in the readable state and cannot be closed`);Do(this)}enqueue(u){if(!sr(this))throw Ro("enqueue");if(Le(u,1,"enqueue"),!ArrayBuffer.isView(u))throw new TypeError("chunk must be an array buffer view");if(u.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(u.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let h=this._controlledReadableByteStream._state;if(h!=="readable")throw new TypeError(`The stream (in ${h} state) is not in the readable state and cannot be enqueued to`);Ms(this,u)}error(u=void 0){if(!sr(this))throw Ro("error");St(this,u)}[J](u){Lf(this),Ln(this);let h=this._cancelAlgorithm(u);return Bs(this),h}[F](u){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){Gf(this,u);return}let S=this._autoAllocateChunkSize;if(S!==void 0){let x;try{x=new ArrayBuffer(S)}catch(q){u._errorSteps(q);return}let j={buffer:x,bufferByteLength:S,byteOffset:0,byteLength:S,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(j)}O(h,u),ir(this)}[V](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new T,this._pendingPullIntos.push(u)}}}Object.defineProperties(mn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(mn.prototype.close,"close"),o(mn.prototype.enqueue,"enqueue"),o(mn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function sr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof mn}function Ru(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof or}function ir(i){if(!H_(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();g(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,ir(i)),null),S=>(St(i,S),null))}function Lf(i){Ou(i),i._pendingPullIntos=new T}function xu(i,u){let h=!1;i._state==="closed"&&(h=!0);let S=jf(u);u.readerType==="default"?I(i,S,h):K_(i,S,h)}function jf(i){let u=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/h)}function Ns(i,u,h,S){i._queue.push({buffer:u,byteOffset:h,byteLength:S}),i._queueTotalSize+=S}function $f(i,u,h,S){let x;try{x=If(u,h,h+S)}catch(j){throw St(i,j),j}Ns(i,x,0,S)}function Uf(i,u){u.bytesFilled>0&&$f(i,u.buffer,u.byteOffset,u.bytesFilled),Ir(i)}function qf(i,u){let h=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),S=u.bytesFilled+h,x=h,j=!1,q=S%u.elementSize,Z=S-q;Z>=u.minimumFill&&(x=Z-u.bytesFilled,j=!0);let ce=i._queue;for(;x>0;){let se=ce.peek(),fe=Math.min(x,se.byteLength),ge=u.byteOffset+u.bytesFilled;Ff(u.buffer,ge,se.buffer,se.byteOffset,fe),se.byteLength===fe?ce.shift():(se.byteOffset+=fe,se.byteLength-=fe),i._queueTotalSize-=fe,Hf(i,fe,u),x-=fe}return j}function Hf(i,u,h){h.bytesFilled+=u}function zf(i){i._queueTotalSize===0&&i._closeRequested?(Bs(i),No(i._controlledReadableByteStream)):ir(i)}function Ou(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function Pu(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();qf(i,u)&&(Ir(i),xu(i._controlledReadableByteStream,u))}}function j_(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=u._readRequests.shift();Gf(i,h)}}function $_(i,u,h,S){let x=i._controlledReadableByteStream,j=u.constructor,q=L_(j),{byteOffset:Z,byteLength:ce}=u,se=h*q,fe;try{fe=pn(u.buffer)}catch(De){S._errorSteps(De);return}let ge={buffer:fe,bufferByteLength:fe.byteLength,byteOffset:Z,byteLength:ce,bytesFilled:0,minimumFill:se,elementSize:q,viewConstructor:j,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(ge),Yf(x,S);return}if(x._state==="closed"){let De=new j(ge.buffer,ge.byteOffset,0);S._closeSteps(De);return}if(i._queueTotalSize>0){if(qf(i,ge)){let De=jf(ge);zf(i),S._chunkSteps(De);return}if(i._closeRequested){let De=new TypeError("Insufficient bytes to fill elements in the given buffer");St(i,De),S._errorSteps(De);return}}i._pendingPullIntos.push(ge),Yf(x,S),ir(i)}function U_(i,u){u.readerType==="none"&&Ir(i);let h=i._controlledReadableByteStream;if(Nu(h))for(;Qf(h)>0;){let S=Ir(i);xu(h,S)}}function q_(i,u,h){if(Hf(i,u,h),h.readerType==="none"){Uf(i,h),Pu(i);return}if(h.bytesFilled<h.minimumFill)return;Ir(i);let S=h.bytesFilled%h.elementSize;if(S>0){let x=h.byteOffset+h.bytesFilled;$f(i,h.buffer,x-S,S)}h.bytesFilled-=S,xu(i._controlledReadableByteStream,h),Pu(i)}function Wf(i,u){let h=i._pendingPullIntos.peek();Ou(i),i._controlledReadableByteStream._state==="closed"?U_(i,h):q_(i,u,h),ir(i)}function Ir(i){return i._pendingPullIntos.shift()}function H_(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(B(u)&&L(u)>0||Nu(u)&&Qf(u)>0||Jf(i)>0)}function Bs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function Do(i){let u=i._controlledReadableByteStream;if(!(i._closeRequested||u._state!=="readable")){if(i._queueTotalSize>0){i._closeRequested=!0;return}if(i._pendingPullIntos.length>0){let h=i._pendingPullIntos.peek();if(h.bytesFilled%h.elementSize!==0){let S=new TypeError("Insufficient bytes to fill elements in the given buffer");throw St(i,S),S}}Bs(i),No(u)}}function Ms(i,u){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:S,byteOffset:x,byteLength:j}=u;if(Mn(S))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=pn(S);if(i._pendingPullIntos.length>0){let Z=i._pendingPullIntos.peek();if(Mn(Z.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ou(i),Z.buffer=pn(Z.buffer),Z.readerType==="none"&&Uf(i,Z)}if(B(h))if(j_(i),L(h)===0)Ns(i,q,x,j);else{i._pendingPullIntos.length>0&&Ir(i);let Z=new Uint8Array(q,x,j);I(h,Z,!1)}else Nu(h)?(Ns(i,q,x,j),Pu(i)):Ns(i,q,x,j);ir(i)}function St(i,u){let h=i._controlledReadableByteStream;h._state==="readable"&&(Lf(i),Ln(i),Bs(i),wh(h,u))}function Gf(i,u){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,zf(i);let S=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);u._chunkSteps(S)}function Fu(i){if(i._byobRequest===null&&i._pendingPullIntos.length>0){let u=i._pendingPullIntos.peek(),h=new Uint8Array(u.buffer,u.byteOffset+u.bytesFilled,u.byteLength-u.bytesFilled),S=Object.create(or.prototype);W_(S,i,h),i._byobRequest=S}return i._byobRequest}function Jf(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function Ls(i,u){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(u===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(h.bytesFilled+u>h.byteLength)throw new RangeError("bytesWritten out of range")}h.buffer=pn(h.buffer),Wf(i,u)}function js(i,u){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(u.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(h.byteOffset+h.bytesFilled!==u.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(h.bufferByteLength!==u.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(h.bytesFilled+u.byteLength>h.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let x=u.byteLength;h.buffer=pn(u.buffer),Wf(i,x)}function Vf(i,u,h,S,x,j,q){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Ln(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=j,u._pullAlgorithm=S,u._cancelAlgorithm=x,u._autoAllocateChunkSize=q,u._pendingPullIntos=new T,i._readableStreamController=u;let Z=h();g(d(Z),()=>(u._started=!0,ir(u),null),ce=>(St(u,ce),null))}function z_(i,u,h){let S=Object.create(mn.prototype),x,j,q;u.start!==void 0?x=()=>u.start(S):x=()=>{},u.pull!==void 0?j=()=>u.pull(S):j=()=>d(void 0),u.cancel!==void 0?q=ce=>u.cancel(ce):q=()=>d(void 0);let Z=u.autoAllocateChunkSize;if(Z===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Vf(i,S,x,j,q,h,Z)}function W_(i,u,h){i._associatedReadableByteStreamController=u,i._view=h}function Iu(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}function Ro(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function G_(i,u){le(i,u);let h=i?.mode;return{mode:h===void 0?void 0:J_(h,`${u} has member 'mode' that`)}}function J_(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function V_(i,u){var h;le(i,u);let S=(h=i?.min)!==null&&h!==void 0?h:1;return{min:P(S,`${u} has member 'min' that`)}}function Kf(i){return new jn(i)}function Yf(i,u){i._reader._readIntoRequests.push(u)}function K_(i,u,h){let x=i._reader._readIntoRequests.shift();h?x._closeSteps(u):x._chunkSteps(u)}function Qf(i){return i._reader._readIntoRequests.length}function Nu(i){let u=i._reader;return!(u===void 0||!ar(u))}class jn{constructor(u){if(Le(u,1,"ReadableStreamBYOBReader"),N(u,"First parameter"),qn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!sr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");Y(this,u),this._readIntoRequests=new T}get closed(){return ar(this)?this._closedPromise:f($s("closed"))}cancel(u=void 0){return ar(this)?this._ownerReadableStream===void 0?f(de("cancel")):X(this,u):f($s("cancel"))}read(u,h={}){if(!ar(this))return f($s("read"));if(!ArrayBuffer.isView(u))return f(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(Mn(u.buffer))return f(new TypeError("view's buffer has been detached"));let S;try{S=V_(h,"options")}catch(se){return f(se)}let x=S.min;if(x===0)return f(new TypeError("options.min must be greater than 0"));if(M_(u)){if(x>u.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(x>u.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(de("read from"));let j,q,Z=l((se,fe)=>{j=se,q=fe});return Xf(this,u,x,{_chunkSteps:se=>j({value:se,done:!1}),_closeSteps:se=>j({value:se,done:!0}),_errorSteps:se=>q(se)}),Z}releaseLock(){if(!ar(this))throw $s("releaseLock");this._ownerReadableStream!==void 0&&Y_(this)}}Object.defineProperties(jn.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(jn.prototype.cancel,"cancel"),o(jn.prototype.read,"read"),o(jn.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jn.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function ar(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof jn}function Xf(i,u,h,S){let x=i._ownerReadableStream;x._disturbed=!0,x._state==="errored"?S._errorSteps(x._storedError):$_(x._readableStreamController,u,h,S)}function Y_(i){ee(i);let u=new TypeError("Reader was released");Zf(i,u)}function Zf(i,u){let h=i._readIntoRequests;i._readIntoRequests=new T,h.forEach(S=>{S._errorSteps(u)})}function $s(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function xo(i,u){let{highWaterMark:h}=i;if(h===void 0)return u;if(dt(h)||h<0)throw new RangeError("Invalid highWaterMark");return h}function Us(i){let{size:u}=i;return u||(()=>1)}function qs(i,u){le(i,u);let h=i?.highWaterMark,S=i?.size;return{highWaterMark:h===void 0?void 0:v(h),size:S===void 0?void 0:Q_(S,`${u} has member 'size' that`)}}function Q_(i,u){return _e(i,u),h=>v(i(h))}function X_(i,u){le(i,u);let h=i?.abort,S=i?.close,x=i?.start,j=i?.type,q=i?.write;return{abort:h===void 0?void 0:Z_(h,i,`${u} has member 'abort' that`),close:S===void 0?void 0:eb(S,i,`${u} has member 'close' that`),start:x===void 0?void 0:tb(x,i,`${u} has member 'start' that`),write:q===void 0?void 0:nb(q,i,`${u} has member 'write' that`),type:j}}function Z_(i,u,h){return _e(i,h),S=>w(i,u,[S])}function eb(i,u,h){return _e(i,h),()=>w(i,u,[])}function tb(i,u,h){return _e(i,h),S=>k(i,u,[S])}function nb(i,u,h){return _e(i,h),(S,x)=>w(i,u,[S,x])}function eh(i,u){if(!Nr(i))throw new TypeError(`${u} is not a WritableStream.`)}function rb(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let ob=typeof AbortController=="function";function sb(){if(ob)return new AbortController}class $n{constructor(u={},h={}){u===void 0?u=null:Re(u,"First parameter");let S=qs(h,"Second parameter"),x=X_(u,"First parameter");if(nh(this),x.type!==void 0)throw new RangeError("Invalid type is specified");let q=Us(S),Z=xo(S,1);bb(this,x,Z,q)}get locked(){if(!Nr(this))throw Js("locked");return Br(this)}abort(u=void 0){return Nr(this)?Br(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Hs(this,u):f(Js("abort"))}close(){return Nr(this)?Br(this)?f(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?f(new TypeError("Cannot close an already-closing stream")):rh(this):f(Js("close"))}getWriter(){if(!Nr(this))throw Js("getWriter");return th(this)}}Object.defineProperties($n.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o($n.prototype.abort,"abort"),o($n.prototype.close,"close"),o($n.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty($n.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function th(i){return new gn(i)}function ib(i,u,h,S,x=1,j=()=>1){let q=Object.create($n.prototype);nh(q);let Z=Object.create(Mr.prototype);return ch(q,Z,i,u,h,S,x,j),q}function nh(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new T,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function Nr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof $n}function Br(i){return i._writer!==void 0}function Hs(i,u){var h;if(i._state==="closed"||i._state==="errored")return d(void 0);i._writableStreamController._abortReason=u,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(u);let S=i._state;if(S==="closed"||S==="errored")return d(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let x=!1;S==="erroring"&&(x=!0,u=void 0);let j=l((q,Z)=>{i._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:Z,_reason:u,_wasAlreadyErroring:x}});return i._pendingAbortRequest._promise=j,x||Mu(i,u),j}function rh(i){let u=i._state;if(u==="closed"||u==="errored")return f(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let h=l((x,j)=>{let q={_resolve:x,_reject:j};i._closeRequest=q}),S=i._writer;return S!==void 0&&i._backpressure&&u==="writable"&&Wu(S),Cb(i._writableStreamController),h}function ab(i){return l((h,S)=>{let x={_resolve:h,_reject:S};i._writeRequests.push(x)})}function Bu(i,u){if(i._state==="writable"){Mu(i,u);return}Lu(i)}function Mu(i,u){let h=i._writableStreamController;i._state="erroring",i._storedError=u;let S=i._writer;S!==void 0&&sh(S,u),!fb(i)&&h._started&&Lu(i)}function Lu(i){i._state="errored",i._writableStreamController[U]();let u=i._storedError;if(i._writeRequests.forEach(x=>{x._reject(u)}),i._writeRequests=new T,i._pendingAbortRequest===void 0){zs(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(u),zs(i);return}let S=i._writableStreamController[R](h._reason);g(S,()=>(h._resolve(),zs(i),null),x=>(h._reject(x),zs(i),null))}function ub(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function cb(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,Bu(i,u)}function lb(i){i._inFlightCloseRequest._resolve(void 0),i._inFlightCloseRequest=void 0,i._state==="erroring"&&(i._storedError=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._resolve(),i._pendingAbortRequest=void 0)),i._state="closed";let h=i._writer;h!==void 0&&hh(h)}function db(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),Bu(i,u)}function Xt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function fb(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function hb(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function pb(i){i._inFlightWriteRequest=i._writeRequests.shift()}function zs(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&Hu(u,i._storedError)}function ju(i,u){let h=i._writer;h!==void 0&&u!==i._backpressure&&(u?Tb(h):Wu(h)),i._backpressure=u}class gn{constructor(u){if(Le(u,1,"WritableStreamDefaultWriter"),eh(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=u,u._writer=this;let h=u._state;if(h==="writable")!Xt(u)&&u._backpressure?Ks(this):ph(this),Vs(this);else if(h==="erroring")zu(this,u._storedError),Vs(this);else if(h==="closed")ph(this),kb(this);else{let S=u._storedError;zu(this,S),fh(this,S)}}get closed(){return ur(this)?this._closedPromise:f(cr("closed"))}get desiredSize(){if(!ur(this))throw cr("desiredSize");if(this._ownerWritableStream===void 0)throw Po("desiredSize");return _b(this)}get ready(){return ur(this)?this._readyPromise:f(cr("ready"))}abort(u=void 0){return ur(this)?this._ownerWritableStream===void 0?f(Po("abort")):mb(this,u):f(cr("abort"))}close(){if(!ur(this))return f(cr("close"));let u=this._ownerWritableStream;return u===void 0?f(Po("close")):Xt(u)?f(new TypeError("Cannot close an already-closing stream")):oh(this)}releaseLock(){if(!ur(this))throw cr("releaseLock");this._ownerWritableStream!==void 0&&ih(this)}write(u=void 0){return ur(this)?this._ownerWritableStream===void 0?f(Po("write to")):ah(this,u):f(cr("write"))}}Object.defineProperties(gn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(gn.prototype.abort,"abort"),o(gn.prototype.close,"close"),o(gn.prototype.releaseLock,"releaseLock"),o(gn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function ur(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof gn}function mb(i,u){let h=i._ownerWritableStream;return Hs(h,u)}function oh(i){let u=i._ownerWritableStream;return rh(u)}function gb(i){let u=i._ownerWritableStream,h=u._state;return Xt(u)||h==="closed"?d(void 0):h==="errored"?f(u._storedError):oh(i)}function yb(i,u){i._closedPromiseState==="pending"?Hu(i,u):vb(i,u)}function sh(i,u){i._readyPromiseState==="pending"?mh(i,u):Db(i,u)}function _b(i){let u=i._ownerWritableStream,h=u._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:lh(u._writableStreamController)}function ih(i){let u=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");sh(i,h),yb(i,h),u._writer=void 0,i._ownerWritableStream=void 0}function ah(i,u){let h=i._ownerWritableStream,S=h._writableStreamController,x=wb(S,u);if(h!==i._ownerWritableStream)return f(Po("write to"));let j=h._state;if(j==="errored")return f(h._storedError);if(Xt(h)||j==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(j==="erroring")return f(h._storedError);let q=ab(h);return Eb(S,u,x),q}let uh={};class Mr{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!$u(this))throw qu("abortReason");return this._abortReason}get signal(){if(!$u(this))throw qu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!$u(this))throw qu("error");this._controlledWritableStream._state==="writable"&&dh(this,u)}[R](u){let h=this._abortAlgorithm(u);return Ws(this),h}[U](){Ln(this)}}Object.defineProperties(Mr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function $u(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Mr}function ch(i,u,h,S,x,j,q,Z){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Ln(u),u._abortReason=void 0,u._abortController=sb(),u._started=!1,u._strategySizeAlgorithm=Z,u._strategyHWM=q,u._writeAlgorithm=S,u._closeAlgorithm=x,u._abortAlgorithm=j;let ce=Uu(u);ju(i,ce);let se=h(),fe=d(se);g(fe,()=>(u._started=!0,Gs(u),null),ge=>(u._started=!0,Bu(i,ge),null))}function bb(i,u,h,S){let x=Object.create(Mr.prototype),j,q,Z,ce;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.write!==void 0?q=se=>u.write(se,x):q=()=>d(void 0),u.close!==void 0?Z=()=>u.close():Z=()=>d(void 0),u.abort!==void 0?ce=se=>u.abort(se):ce=()=>d(void 0),ch(i,x,j,q,Z,ce,h,S)}function Ws(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function Cb(i){Du(i,uh,0),Gs(i)}function wb(i,u){try{return i._strategySizeAlgorithm(u)}catch(h){return Oo(i,h),1}}function lh(i){return i._strategyHWM-i._queueTotalSize}function Eb(i,u,h){try{Du(i,u,h)}catch(x){Oo(i,x);return}let S=i._controlledWritableStream;if(!Xt(S)&&S._state==="writable"){let x=Uu(i);ju(S,x)}Gs(i)}function Gs(i){let u=i._controlledWritableStream;if(!i._started||u._inFlightWriteRequest!==void 0)return;if(u._state==="erroring"){Lu(u);return}if(i._queue.length===0)return;let S=B_(i);S===uh?Ab(i):Sb(i,S)}function Oo(i,u){i._controlledWritableStream._state==="writable"&&dh(i,u)}function Ab(i){let u=i._controlledWritableStream;hb(u),Tu(i);let h=i._closeAlgorithm();Ws(i),g(h,()=>(lb(u),null),S=>(db(u,S),null))}function Sb(i,u){let h=i._controlledWritableStream;pb(h);let S=i._writeAlgorithm(u);g(S,()=>{ub(h);let x=h._state;if(Tu(i),!Xt(h)&&x==="writable"){let j=Uu(i);ju(h,j)}return Gs(i),null},x=>(h._state==="writable"&&Ws(i),cb(h,x),null))}function Uu(i){return lh(i)<=0}function dh(i,u){let h=i._controlledWritableStream;Ws(i),Mu(h,u)}function Js(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function qu(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function cr(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function Po(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Vs(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function fh(i,u){Vs(i),Hu(i,u)}function kb(i){Vs(i),hh(i)}function Hu(i,u){i._closedPromise_reject!==void 0&&(y(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function vb(i,u){fh(i,u)}function hh(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="resolved")}function Ks(i){i._readyPromise=l((u,h)=>{i._readyPromise_resolve=u,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function zu(i,u){Ks(i),mh(i,u)}function ph(i){Ks(i),Wu(i)}function mh(i,u){i._readyPromise_reject!==void 0&&(y(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function Tb(i){Ks(i)}function Db(i,u){zu(i,u)}function Wu(i){i._readyPromise_resolve!==void 0&&(i._readyPromise_resolve(void 0),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="fulfilled")}function Rb(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Gu=Rb();function xb(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function Ob(){let i=Gu?.DOMException;return xb(i)?i:void 0}function Pb(){let i=function(h,S){this.message=h||"",this.name=S||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(i,"DOMException"),i.prototype=Object.create(Error.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,writable:!0,configurable:!0}),i}let Fb=Ob()||Pb();function gh(i,u,h,S,x,j){let q=$(i),Z=th(u);i._disturbed=!0;let ce=!1,se=d(void 0);return l((fe,ge)=>{let De;if(j!==void 0){if(De=()=>{let ie=j.reason!==void 0?j.reason:new Fb("Aborted","AbortError"),be=[];S||be.push(()=>u._state==="writable"?Hs(u,ie):d(void 0)),x||be.push(()=>i._state==="readable"?Lt(i,ie):d(void 0)),it(()=>Promise.all(be.map(xe=>xe())),!0,ie)},j.aborted){De();return}j.addEventListener("abort",De)}function jt(){return l((ie,be)=>{function xe(ft){ft?ie():p(Ur(),xe,be)}xe(!1)})}function Ur(){return ce?d(!0):p(Z._readyPromise,()=>l((ie,be)=>{ne(q,{_chunkSteps:xe=>{se=p(ah(Z,xe),void 0,e),ie(!1)},_closeSteps:()=>ie(!0),_errorSteps:be})}))}if(_n(i,q._closedPromise,ie=>(S?kt(!0,ie):it(()=>Hs(u,ie),!0,ie),null)),_n(u,Z._closedPromise,ie=>(x?kt(!0,ie):it(()=>Lt(i,ie),!0,ie),null)),tt(i,q._closedPromise,()=>(h?kt():it(()=>gb(Z)),null)),Xt(u)||u._state==="closed"){let ie=new TypeError("the destination writable stream closed before all data could be piped to it");x?kt(!0,ie):it(()=>Lt(i,ie),!0,ie)}y(jt());function zn(){let ie=se;return p(se,()=>ie!==se?zn():void 0)}function _n(ie,be,xe){ie._state==="errored"?xe(ie._storedError):C(be,xe)}function tt(ie,be,xe){ie._state==="closed"?xe():_(be,xe)}function it(ie,be,xe){if(ce)return;ce=!0,u._state==="writable"&&!Xt(u)?_(zn(),ft):ft();function ft(){return g(ie(),()=>bn(be,xe),qr=>bn(!0,qr)),null}}function kt(ie,be){ce||(ce=!0,u._state==="writable"&&!Xt(u)?_(zn(),()=>bn(ie,be)):bn(ie,be))}function bn(ie,be){return ih(Z),ee(q),j!==void 0&&j.removeEventListener("abort",De),ie?ge(be):fe(void 0),null}})}class yn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ys(this))throw Xs("desiredSize");return Ju(this)}close(){if(!Ys(this))throw Xs("close");if(!jr(this))throw new TypeError("The stream is not in a state that permits close");lr(this)}enqueue(u=void 0){if(!Ys(this))throw Xs("enqueue");if(!jr(this))throw new TypeError("The stream is not in a state that permits enqueue");return Lr(this,u)}error(u=void 0){if(!Ys(this))throw Xs("error");Mt(this,u)}[J](u){Ln(this);let h=this._cancelAlgorithm(u);return Qs(this),h}[F](u){let h=this._controlledReadableStream;if(this._queue.length>0){let S=Tu(this);this._closeRequested&&this._queue.length===0?(Qs(this),No(h)):Fo(this),u._chunkSteps(S)}else O(h,u),Fo(this)}[V](){}}Object.defineProperties(yn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(yn.prototype.close,"close"),o(yn.prototype.enqueue,"enqueue"),o(yn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ys(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof yn}function Fo(i){if(!yh(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();g(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,Fo(i)),null),S=>(Mt(i,S),null))}function yh(i){let u=i._controlledReadableStream;return!jr(i)||!i._started?!1:!!(qn(u)&&L(u)>0||Ju(i)>0)}function Qs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function lr(i){if(!jr(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Qs(i),No(u))}function Lr(i,u){if(!jr(i))return;let h=i._controlledReadableStream;if(qn(h)&&L(h)>0)I(h,u,!1);else{let S;try{S=i._strategySizeAlgorithm(u)}catch(x){throw Mt(i,x),x}try{Du(i,u,S)}catch(x){throw Mt(i,x),x}}Fo(i)}function Mt(i,u){let h=i._controlledReadableStream;h._state==="readable"&&(Ln(i),Qs(i),wh(h,u))}function Ju(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function Ib(i){return!yh(i)}function jr(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function _h(i,u,h,S,x,j,q){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Ln(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=q,u._strategyHWM=j,u._pullAlgorithm=S,u._cancelAlgorithm=x,i._readableStreamController=u;let Z=h();g(d(Z),()=>(u._started=!0,Fo(u),null),ce=>(Mt(u,ce),null))}function Nb(i,u,h,S){let x=Object.create(yn.prototype),j,q,Z;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.pull!==void 0?q=()=>u.pull(x):q=()=>d(void 0),u.cancel!==void 0?Z=ce=>u.cancel(ce):Z=()=>d(void 0),_h(i,x,j,q,Z,h,S)}function Xs(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function Bb(i,u){return sr(i._readableStreamController)?Lb(i):Mb(i)}function Mb(i,u){let h=$(i),S=!1,x=!1,j=!1,q=!1,Z,ce,se,fe,ge,De=l(tt=>{ge=tt});function jt(){return S?(x=!0,d(void 0)):(S=!0,ne(h,{_chunkSteps:it=>{m(()=>{x=!1;let kt=it,bn=it;j||Lr(se._readableStreamController,kt),q||Lr(fe._readableStreamController,bn),S=!1,x&&jt()})},_closeSteps:()=>{S=!1,j||lr(se._readableStreamController),q||lr(fe._readableStreamController),(!j||!q)&&ge(void 0)},_errorSteps:()=>{S=!1}}),d(void 0))}function Ur(tt){if(j=!0,Z=tt,q){let it=ve([Z,ce]),kt=Lt(i,it);ge(kt)}return De}function zn(tt){if(q=!0,ce=tt,j){let it=ve([Z,ce]),kt=Lt(i,it);ge(kt)}return De}function _n(){}return se=Io(_n,jt,Ur),fe=Io(_n,jt,zn),C(h._closedPromise,tt=>(Mt(se._readableStreamController,tt),Mt(fe._readableStreamController,tt),(!j||!q)&&ge(void 0),null)),[se,fe]}function Lb(i){let u=$(i),h=!1,S=!1,x=!1,j=!1,q=!1,Z,ce,se,fe,ge,De=l(ie=>{ge=ie});function jt(ie){C(ie._closedPromise,be=>(ie!==u||(St(se._readableStreamController,be),St(fe._readableStreamController,be),(!j||!q)&&ge(void 0)),null))}function Ur(){ar(u)&&(ee(u),u=$(i),jt(u)),ne(u,{_chunkSteps:be=>{m(()=>{S=!1,x=!1;let xe=be,ft=be;if(!j&&!q)try{ft=Bf(be)}catch(qr){St(se._readableStreamController,qr),St(fe._readableStreamController,qr),ge(Lt(i,qr));return}j||Ms(se._readableStreamController,xe),q||Ms(fe._readableStreamController,ft),h=!1,S?_n():x&&tt()})},_closeSteps:()=>{h=!1,j||Do(se._readableStreamController),q||Do(fe._readableStreamController),se._readableStreamController._pendingPullIntos.length>0&&Ls(se._readableStreamController,0),fe._readableStreamController._pendingPullIntos.length>0&&Ls(fe._readableStreamController,0),(!j||!q)&&ge(void 0)},_errorSteps:()=>{h=!1}})}function zn(ie,be){te(u)&&(ee(u),u=Kf(i),jt(u));let xe=be?fe:se,ft=be?se:fe;Xf(u,ie,1,{_chunkSteps:Hr=>{m(()=>{S=!1,x=!1;let zr=be?q:j;if(be?j:q)zr||js(xe._readableStreamController,Hr);else{let Ih;try{Ih=Bf(Hr)}catch(Xu){St(xe._readableStreamController,Xu),St(ft._readableStreamController,Xu),ge(Lt(i,Xu));return}zr||js(xe._readableStreamController,Hr),Ms(ft._readableStreamController,Ih)}h=!1,S?_n():x&&tt()})},_closeSteps:Hr=>{h=!1;let zr=be?q:j,ii=be?j:q;zr||Do(xe._readableStreamController),ii||Do(ft._readableStreamController),Hr!==void 0&&(zr||js(xe._readableStreamController,Hr),!ii&&ft._readableStreamController._pendingPullIntos.length>0&&Ls(ft._readableStreamController,0)),(!zr||!ii)&&ge(void 0)},_errorSteps:()=>{h=!1}})}function _n(){if(h)return S=!0,d(void 0);h=!0;let ie=Fu(se._readableStreamController);return ie===null?Ur():zn(ie._view,!1),d(void 0)}function tt(){if(h)return x=!0,d(void 0);h=!0;let ie=Fu(fe._readableStreamController);return ie===null?Ur():zn(ie._view,!0),d(void 0)}function it(ie){if(j=!0,Z=ie,q){let be=ve([Z,ce]),xe=Lt(i,be);ge(xe)}return De}function kt(ie){if(q=!0,ce=ie,j){let be=ve([Z,ce]),xe=Lt(i,be);ge(xe)}return De}function bn(){}return se=Ch(bn,_n,it),fe=Ch(bn,tt,kt),jt(u),[se,fe]}function jb(i){return n(i)&&typeof i.getReader<"u"}function $b(i){return jb(i)?qb(i.getReader()):Ub(i)}function Ub(i){let u,h=Nf(i,"async"),S=e;function x(){let q;try{q=P_(h)}catch(ce){return f(ce)}let Z=d(q);return b(Z,ce=>{if(!n(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(F_(ce))lr(u._readableStreamController);else{let fe=I_(ce);Lr(u._readableStreamController,fe)}})}function j(q){let Z=h.iterator,ce;try{ce=Is(Z,"return")}catch(ge){return f(ge)}if(ce===void 0)return d(void 0);let se;try{se=k(ce,Z,[q])}catch(ge){return f(ge)}let fe=d(se);return b(fe,ge=>{if(!n(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=Io(S,x,j,0),u}function qb(i){let u,h=e;function S(){let j;try{j=i.read()}catch(q){return f(q)}return b(j,q=>{if(!n(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)lr(u._readableStreamController);else{let Z=q.value;Lr(u._readableStreamController,Z)}})}function x(j){try{return d(i.cancel(j))}catch(q){return f(q)}}return u=Io(h,S,x,0),u}function Hb(i,u){le(i,u);let h=i,S=h?.autoAllocateChunkSize,x=h?.cancel,j=h?.pull,q=h?.start,Z=h?.type;return{autoAllocateChunkSize:S===void 0?void 0:P(S,`${u} has member 'autoAllocateChunkSize' that`),cancel:x===void 0?void 0:zb(x,h,`${u} has member 'cancel' that`),pull:j===void 0?void 0:Wb(j,h,`${u} has member 'pull' that`),start:q===void 0?void 0:Gb(q,h,`${u} has member 'start' that`),type:Z===void 0?void 0:Jb(Z,`${u} has member 'type' that`)}}function zb(i,u,h){return _e(i,h),S=>w(i,u,[S])}function Wb(i,u,h){return _e(i,h),S=>w(i,u,[S])}function Gb(i,u,h){return _e(i,h),S=>k(i,u,[S])}function Jb(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function Vb(i,u){return le(i,u),{preventCancel:!!i?.preventCancel}}function bh(i,u){le(i,u);let h=i?.preventAbort,S=i?.preventCancel,x=i?.preventClose,j=i?.signal;return j!==void 0&&Kb(j,`${u} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!S,preventClose:!!x,signal:j}}function Kb(i,u){if(!rb(i))throw new TypeError(`${u} is not an AbortSignal.`)}function Yb(i,u){le(i,u);let h=i?.readable;E(h,"readable","ReadableWritablePair"),N(h,`${u} has member 'readable' that`);let S=i?.writable;return E(S,"writable","ReadableWritablePair"),eh(S,`${u} has member 'writable' that`),{readable:h,writable:S}}class Ze{constructor(u={},h={}){u===void 0?u=null:Re(u,"First parameter");let S=qs(h,"Second parameter"),x=Hb(u,"First parameter");if(Vu(this),x.type==="bytes"){if(S.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let j=xo(S,0);z_(this,x,j)}else{let j=Us(S),q=xo(S,1);Nb(this,x,q,j)}}get locked(){if(!Un(this))throw dr("locked");return qn(this)}cancel(u=void 0){return Un(this)?qn(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Lt(this,u):f(dr("cancel"))}getReader(u=void 0){if(!Un(this))throw dr("getReader");return G_(u,"First parameter").mode===void 0?$(this):Kf(this)}pipeThrough(u,h={}){if(!Un(this))throw dr("pipeThrough");Le(u,1,"pipeThrough");let S=Yb(u,"First parameter"),x=bh(h,"Second parameter");if(qn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Br(S.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let j=gh(this,S.writable,x.preventClose,x.preventAbort,x.preventCancel,x.signal);return y(j),S.readable}pipeTo(u,h={}){if(!Un(this))return f(dr("pipeTo"));if(u===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Nr(u))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let S;try{S=bh(h,"Second parameter")}catch(x){return f(x)}return qn(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Br(u)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):gh(this,u,S.preventClose,S.preventAbort,S.preventCancel,S.signal)}tee(){if(!Un(this))throw dr("tee");let u=Bb(this);return ve(u)}values(u=void 0){if(!Un(this))throw dr("values");let h=Vb(u,"First parameter");return Or(this,h.preventCancel)}[vu](u){return this.values(u)}static from(u){return $b(u)}}Object.defineProperties(Ze,{from:{enumerable:!0}}),Object.defineProperties(Ze.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Ze.from,"from"),o(Ze.prototype.cancel,"cancel"),o(Ze.prototype.getReader,"getReader"),o(Ze.prototype.pipeThrough,"pipeThrough"),o(Ze.prototype.pipeTo,"pipeTo"),o(Ze.prototype.tee,"tee"),o(Ze.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ze.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ze.prototype,vu,{value:Ze.prototype.values,writable:!0,configurable:!0});function Io(i,u,h,S=1,x=()=>1){let j=Object.create(Ze.prototype);Vu(j);let q=Object.create(yn.prototype);return _h(j,q,i,u,h,S,x),j}function Ch(i,u,h){let S=Object.create(Ze.prototype);Vu(S);let x=Object.create(mn.prototype);return Vf(S,x,i,u,h,0,void 0),S}function Vu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Un(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof Ze}function qn(i){return i._reader!==void 0}function Lt(i,u){if(i._disturbed=!0,i._state==="closed")return d(void 0);if(i._state==="errored")return f(i._storedError);No(i);let h=i._reader;if(h!==void 0&&ar(h)){let x=h._readIntoRequests;h._readIntoRequests=new T,x.forEach(j=>{j._closeSteps(void 0)})}let S=i._readableStreamController[J](u);return b(S,e)}function No(i){i._state="closed";let u=i._reader;if(u!==void 0&&(re(u),te(u))){let h=u._readRequests;u._readRequests=new T,h.forEach(S=>{S._closeSteps()})}}function wh(i,u){i._state="errored",i._storedError=u;let h=i._reader;h!==void 0&&(W(h,u),te(h)?Fe(h,u):Zf(h,u))}function dr(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function Eh(i,u){le(i,u);let h=i?.highWaterMark;return E(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:v(h)}}let Ah=i=>i.byteLength;o(Ah,"size");class Zs{constructor(u){Le(u,1,"ByteLengthQueuingStrategy"),u=Eh(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!kh(this))throw Sh("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!kh(this))throw Sh("size");return Ah}}Object.defineProperties(Zs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Zs.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Sh(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function kh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof Zs}let vh=()=>1;o(vh,"size");class ei{constructor(u){Le(u,1,"CountQueuingStrategy"),u=Eh(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Dh(this))throw Th("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Dh(this))throw Th("size");return vh}}Object.defineProperties(ei.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ei.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Th(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function Dh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof ei}function Qb(i,u){le(i,u);let h=i?.cancel,S=i?.flush,x=i?.readableType,j=i?.start,q=i?.transform,Z=i?.writableType;return{cancel:h===void 0?void 0:tC(h,i,`${u} has member 'cancel' that`),flush:S===void 0?void 0:Xb(S,i,`${u} has member 'flush' that`),readableType:x,start:j===void 0?void 0:Zb(j,i,`${u} has member 'start' that`),transform:q===void 0?void 0:eC(q,i,`${u} has member 'transform' that`),writableType:Z}}function Xb(i,u,h){return _e(i,h),S=>w(i,u,[S])}function Zb(i,u,h){return _e(i,h),S=>k(i,u,[S])}function eC(i,u,h){return _e(i,h),(S,x)=>w(i,u,[S,x])}function tC(i,u,h){return _e(i,h),S=>w(i,u,[S])}class ti{constructor(u={},h={},S={}){u===void 0&&(u=null);let x=qs(h,"Second parameter"),j=qs(S,"Third parameter"),q=Qb(u,"First parameter");if(q.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(q.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Z=xo(j,0),ce=Us(j),se=xo(x,1),fe=Us(x),ge,De=l(jt=>{ge=jt});nC(this,De,se,fe,Z,ce),oC(this,q),q.start!==void 0?ge(q.start(this._transformStreamController)):ge(void 0)}get readable(){if(!Rh(this))throw Fh("readable");return this._readable}get writable(){if(!Rh(this))throw Fh("writable");return this._writable}}Object.defineProperties(ti.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ti.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function nC(i,u,h,S,x,j){function q(){return u}function Z(De){return aC(i,De)}function ce(De){return uC(i,De)}function se(){return cC(i)}i._writable=ib(q,Z,se,ce,h,S);function fe(){return lC(i)}function ge(De){return dC(i,De)}i._readable=Io(q,fe,ge,x,j),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,ni(i,!0),i._transformStreamController=void 0}function Rh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof ti}function xh(i,u){Mt(i._readable._readableStreamController,u),Ku(i,u)}function Ku(i,u){oi(i._transformStreamController),Oo(i._writable._writableStreamController,u),Yu(i)}function Yu(i){i._backpressure&&ni(i,!1)}function ni(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=u}class Hn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ri(this))throw si("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return Ju(u)}enqueue(u=void 0){if(!ri(this))throw si("enqueue");Oh(this,u)}error(u=void 0){if(!ri(this))throw si("error");sC(this,u)}terminate(){if(!ri(this))throw si("terminate");iC(this)}}Object.defineProperties(Hn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Hn.prototype.enqueue,"enqueue"),o(Hn.prototype.error,"error"),o(Hn.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Hn.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ri(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof Hn}function rC(i,u,h,S,x){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=h,u._flushAlgorithm=S,u._cancelAlgorithm=x,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function oC(i,u){let h=Object.create(Hn.prototype),S,x,j;u.transform!==void 0?S=q=>u.transform(q,h):S=q=>{try{return Oh(h,q),d(void 0)}catch(Z){return f(Z)}},u.flush!==void 0?x=()=>u.flush(h):x=()=>d(void 0),u.cancel!==void 0?j=q=>u.cancel(q):j=()=>d(void 0),rC(i,h,S,x,j)}function oi(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function Oh(i,u){let h=i._controlledTransformStream,S=h._readable._readableStreamController;if(!jr(S))throw new TypeError("Readable side is not in a state that permits enqueue");try{Lr(S,u)}catch(j){throw Ku(h,j),h._readable._storedError}Ib(S)!==h._backpressure&&ni(h,!0)}function sC(i,u){xh(i._controlledTransformStream,u)}function Ph(i,u){let h=i._transformAlgorithm(u);return b(h,void 0,S=>{throw xh(i._controlledTransformStream,S),S})}function iC(i){let u=i._controlledTransformStream,h=u._readable._readableStreamController;lr(h);let S=new TypeError("TransformStream terminated");Ku(u,S)}function aC(i,u){let h=i._transformStreamController;if(i._backpressure){let S=i._backpressureChangePromise;return b(S,()=>{let x=i._writable;if(x._state==="erroring")throw x._storedError;return Ph(h,u)})}return Ph(h,u)}function uC(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let S=i._readable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return oi(h),g(x,()=>(S._state==="errored"?$r(h,S._storedError):(Mt(S._readableStreamController,u),Qu(h)),null),j=>(Mt(S._readableStreamController,j),$r(h,j),null)),h._finishPromise}function cC(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let h=i._readable;u._finishPromise=l((x,j)=>{u._finishPromise_resolve=x,u._finishPromise_reject=j});let S=u._flushAlgorithm();return oi(u),g(S,()=>(h._state==="errored"?$r(u,h._storedError):(lr(h._readableStreamController),Qu(u)),null),x=>(Mt(h._readableStreamController,x),$r(u,x),null)),u._finishPromise}function lC(i){return ni(i,!1),i._backpressureChangePromise}function dC(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let S=i._writable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return oi(h),g(x,()=>(S._state==="errored"?$r(h,S._storedError):(Oo(S._writableStreamController,u),Yu(i),Qu(h)),null),j=>(Oo(S._writableStreamController,j),Yu(i),$r(h,j),null)),h._finishPromise}function si(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function Qu(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function $r(i,u){i._finishPromise_reject!==void 0&&(y(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Fh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=Zs,t.CountQueuingStrategy=ei,t.ReadableByteStreamController=mn,t.ReadableStream=Ze,t.ReadableStreamBYOBReader=jn,t.ReadableStreamBYOBRequest=or,t.ReadableStreamDefaultController=yn,t.ReadableStreamDefaultReader=H,t.TransformStream=ti,t.TransformStreamDefaultController=Hn,t.WritableStream=$n,t.WritableStreamDefaultController=Mr,t.WritableStreamDefaultWriter=gn}))});var bm=K(()=>{if(!globalThis.ReadableStream)try{let t=require("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),t.emitWarning=e}catch(n){throw t.emitWarning=e,n}}catch{Object.assign(globalThis,_m())}try{let{Blob:t}=require("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(r,Math.min(o.size,r+65536)).arrayBuffer();r+=c.byteLength,s.enqueue(new Uint8Array(c)),r===o.size&&s.close()}})})}catch{}});async function*Nc(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,Cm),a=n.buffer.slice(r,r+s);r+=a.byteLength,yield new Uint8Array(a)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let a=await o.slice(r,Math.min(o.size,r+Cm)).arrayBuffer();r+=a.byteLength,yield new Uint8Array(a)}}}var wx,Cm,wm,Jw,qt,zo=Me(()=>{wx=Oe(bm(),1);Cm=65536;wm=class Bc{#e=[];#t="";#n=0;#r="transparent";constructor(e=[],n={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof n!="object"&&typeof n!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");n===null&&(n={});let r=new TextEncoder;for(let s of e){let a;ArrayBuffer.isView(s)?a=new Uint8Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)):s instanceof ArrayBuffer?a=new Uint8Array(s.slice(0)):s instanceof Bc?a=s:a=r.encode(`${s}`),this.#n+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#r=`${n.endings===void 0?"transparent":n.endings}`;let o=n.type===void 0?"":String(n.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#n}get type(){return this.#t}async text(){let e=new TextDecoder,n="";for await(let r of Nc(this.#e,!1))n+=e.decode(r,{stream:!0});return n+=e.decode(),n}async arrayBuffer(){let e=new Uint8Array(this.size),n=0;for await(let r of Nc(this.#e,!1))e.set(r,n),n+=r.length;return e.buffer}stream(){let e=Nc(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(n){let r=await e.next();r.done?n.close():n.enqueue(r.value)},async cancel(){await e.return()}})}slice(e=0,n=this.size,r=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=n<0?Math.max(o+n,0):Math.min(n,o),c=Math.max(a-s,0),l=this.#e,d=[],f=0;for(let g of l){if(f>=c)break;let _=ArrayBuffer.isView(g)?g.byteLength:g.size;if(s&&_<=s)s-=_,a-=_;else{let C;ArrayBuffer.isView(g)?(C=g.subarray(s,Math.min(_,a)),f+=C.byteLength):(C=g.slice(s,Math.min(_,a)),f+=C.size),a-=_,d.push(C),s=0}}let p=new Bc([],{type:String(r).toLowerCase()});return p.#n=c,p.#e=d,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(wm.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Jw=wm,qt=Jw});var Vw,Kw,Vn,Mc=Me(()=>{zo();Vw=class extends qt{#e=0;#t="";constructor(e,n,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),r===null&&(r={});let o=r.lastModified===void 0?Date.now():Number(r.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(n)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof qt&&/^(File)$/.test(e[Symbol.toStringTag])}},Kw=Vw,Vn=Kw});function Sm(t,e=qt){var n=`${Em()}${Em()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
26
+ `);let{connect:d,buffered:f}=await l;if(e.emit("proxyConnect",d),this.emit("proxyConnect",d,e),d.statusCode===200)return e.once("socket",Ww),n.secureEndpoint?(Ho("Upgrading socket connection to TLS"),cm.connect({...dm(lm(n),"host","path","port"),socket:o})):o;o.destroy();let p=new Fi.Socket({writable:!1});return p.readable=!0,e.once("socket",m=>{Ho("Replaying proxy buffer for failed request"),(0,$w.default)(m.listenerCount("data")>0),m.push(f),m.push(null)}),p}};Ii.protocols=["http","https"];Dt.HttpsProxyAgent=Ii;function Ww(t){t.resume()}function dm(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function Gw(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",a=s;for(let f=1;f<n.length;f++)n[f]==="base64"?o=!0:n[f]&&(a+=`;${n[f]}`,n[f].indexOf("charset=")===0&&(r=n[f].substring(8)));!n[0]&&!r.length&&(a+=";charset=US-ASCII",r="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),d=Buffer.from(l,c);return d.type=s,d.typeFull=a,d.charset=r,d}var mm,gm=Me(()=>{mm=Gw});var _m=K((Ni,ym)=>{(function(t,e){typeof Ni=="object"&&typeof ym<"u"?e(Ni):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(Ni,(function(t){"use strict";function e(){}function n(i){return typeof i=="object"&&i!==null||typeof i=="function"}let r=e;function o(i,u){try{Object.defineProperty(i,"name",{value:u,configurable:!0})}catch{}}let s=Promise,a=Promise.prototype.then,c=Promise.reject.bind(s);function l(i){return new s(i)}function d(i){return l(u=>u(i))}function f(i){return c(i)}function p(i,u,h){return a.call(i,u,h)}function m(i,u,h){p(p(i,u,h),void 0,r)}function b(i,u){m(i,u)}function C(i,u){m(i,void 0,u)}function y(i,u,h){return p(i,u,h)}function _(i){p(i,void 0,r)}let g=i=>{if(typeof queueMicrotask=="function")g=queueMicrotask;else{let u=d(void 0);g=h=>p(u,h)}return g(i)};function S(i,u,h){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,h)}function w(i,u,h){try{return d(S(i,u,h))}catch(k){return f(k)}}let E=16384;class T{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(u){let h=this._back,k=h;h._elements.length===E-1&&(k={_elements:[],_next:void 0}),h._elements.push(u),k!==h&&(this._back=k,h._next=k),++this._size}shift(){let u=this._front,h=u,k=this._cursor,x=k+1,j=u._elements,q=j[k];return x===E&&(h=u._next,x=0),--this._size,this._cursor=x,u!==h&&(this._front=h),j[k]=void 0,q}forEach(u){let h=this._cursor,k=this._front,x=k._elements;for(;(h!==x.length||k._next!==void 0)&&!(h===x.length&&(k=k._next,x=k._elements,h=0,x.length===0));)u(x[h]),++h}peek(){let u=this._front,h=this._cursor;return u._elements[h]}}let R=Symbol("[[AbortSteps]]"),U=Symbol("[[ErrorSteps]]"),J=Symbol("[[CancelSteps]]"),F=Symbol("[[PullSteps]]"),V=Symbol("[[ReleaseSteps]]");function Y(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?Ae(i):u._state==="closed"?pe(i):ae(i,u._storedError)}function X(i,u){let h=i._ownerReadableStream;return Lt(h,u)}function ee(i){let u=i._ownerReadableStream;u._state==="readable"?W(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Q(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[V](),u._reader=void 0,i._ownerReadableStream=void 0}function de(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function Ae(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h})}function ae(i,u){Ae(i),W(i,u)}function pe(i){Ae(i),re(i)}function W(i,u){i._closedPromise_reject!==void 0&&(_(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function Q(i,u){ae(i,u)}function re(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let $e=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},ke=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function G(i){return typeof i=="object"||typeof i=="function"}function le(i,u){if(i!==void 0&&!G(i))throw new TypeError(`${u} is not an object.`)}function _e(i,u){if(typeof i!="function")throw new TypeError(`${u} is not a function.`)}function Bt(i){return typeof i=="object"&&i!==null||typeof i=="function"}function Re(i,u){if(!Bt(i))throw new TypeError(`${u} is not an object.`)}function Le(i,u,h){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${h}'.`)}function A(i,u,h){if(i===void 0)throw new TypeError(`${u} is required in '${h}'.`)}function v(i){return Number(i)}function D(i){return i===0?0:i}function M(i){return D(ke(i))}function P(i,u){let k=Number.MAX_SAFE_INTEGER,x=Number(i);if(x=D(x),!$e(x))throw new TypeError(`${u} is not a finite number`);if(x=M(x),x<0||x>k)throw new TypeError(`${u} is outside the accepted range of 0 to ${k}, inclusive`);return!$e(x)||x===0?0:x}function N(i,u){if(!Un(i))throw new TypeError(`${u} is not a ReadableStream.`)}function $(i){return new H(i)}function O(i,u){i._reader._readRequests.push(u)}function I(i,u,h){let x=i._reader._readRequests.shift();h?x._closeSteps():x._chunkSteps(u)}function L(i){return i._reader._readRequests.length}function B(i){let u=i._reader;return!(u===void 0||!te(u))}class H{constructor(u){if(Le(u,1,"ReadableStreamDefaultReader"),N(u,"First parameter"),qn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");Y(this,u),this._readRequests=new T}get closed(){return te(this)?this._closedPromise:f(Be("closed"))}cancel(u=void 0){return te(this)?this._ownerReadableStream===void 0?f(de("cancel")):X(this,u):f(Be("cancel"))}read(){if(!te(this))return f(Be("read"));if(this._ownerReadableStream===void 0)return f(de("read from"));let u,h,k=l((j,q)=>{u=j,h=q});return ne(this,{_chunkSteps:j=>u({value:j,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:j=>h(j)}),k}releaseLock(){if(!te(this))throw Be("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(H.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(H.prototype.cancel,"cancel"),o(H.prototype.read,"read"),o(H.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(H.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function te(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof H}function ne(i,u){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?u._closeSteps():h._state==="errored"?u._errorSteps(h._storedError):h._readableStreamController[F](u)}function Ee(i){ee(i);let u=new TypeError("Reader was released");Fe(i,u)}function Fe(i,u){let h=i._readRequests;i._readRequests=new T,h.forEach(k=>{k._errorSteps(u)})}function Be(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}let we=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Se{constructor(u,h){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=u,this._preventCancel=h}next(){let u=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?y(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let h=()=>this._returnSteps(u);return this._ongoingPromise?y(this._ongoingPromise,h,h):h()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,h,k,x=l((q,Z)=>{h=q,k=Z});return ne(u,{_chunkSteps:q=>{this._ongoingPromise=void 0,g(()=>h({value:q,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ee(u),h({value:void 0,done:!0})},_errorSteps:q=>{this._ongoingPromise=void 0,this._isFinished=!0,ee(u),k(q)}}),x}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let k=X(h,u);return ee(h),y(k,()=>({value:u,done:!0}))}return ee(h),d({value:u,done:!0})}}let Ue={next(){return Pr(this)?this._asyncIteratorImpl.next():f(Fr("next"))},return(i){return Pr(this)?this._asyncIteratorImpl.return(i):f(Fr("return"))}};Object.setPrototypeOf(Ue,we);function Or(i,u){let h=$(i),k=new Se(h,u),x=Object.create(Ue);return x._asyncIteratorImpl=k,x}function Pr(i){if(!n(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Se}catch{return!1}}function Fr(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let dt=Number.isNaN||function(i){return i!==i};var hn,Xe,qe;function ve(i){return i.slice()}function Ff(i,u,h,k,x){new Uint8Array(i).set(new Uint8Array(h,k,x),u)}let pn=i=>(typeof i.transfer=="function"?pn=u=>u.transfer():typeof structuredClone=="function"?pn=u=>structuredClone(u,{transfer:[u]}):pn=u=>u,pn(i)),Mn=i=>(typeof i.detached=="boolean"?Mn=u=>u.detached:Mn=u=>u.byteLength===0,Mn(i));function If(i,u,h){if(i.slice)return i.slice(u,h);let k=h-u,x=new ArrayBuffer(k);return Ff(x,0,i,u,k),x}function Is(i,u){let h=i[u];if(h!=null){if(typeof h!="function")throw new TypeError(`${String(u)} is not a function`);return h}}function O_(i){let u={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*u})(),k=h.next;return{iterator:h,nextMethod:k,done:!1}}let vu=(qe=(hn=Symbol.asyncIterator)!==null&&hn!==void 0?hn:(Xe=Symbol.for)===null||Xe===void 0?void 0:Xe.call(Symbol,"Symbol.asyncIterator"))!==null&&qe!==void 0?qe:"@@asyncIterator";function Nf(i,u="sync",h){if(h===void 0)if(u==="async"){if(h=Is(i,vu),h===void 0){let j=Is(i,Symbol.iterator),q=Nf(i,"sync",j);return O_(q)}}else h=Is(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let k=S(h,i,[]);if(!n(k))throw new TypeError("The iterator method must return an object");let x=k.next;return{iterator:k,nextMethod:x,done:!1}}function P_(i){let u=S(i.nextMethod,i.iterator,[]);if(!n(u))throw new TypeError("The iterator.next() method must return an object");return u}function F_(i){return!!i.done}function I_(i){return i.value}function N_(i){return!(typeof i!="number"||dt(i)||i<0)}function Bf(i){let u=If(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function Tu(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function Du(i,u,h){if(!N_(h)||h===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");i._queue.push({value:u,size:h}),i._queueTotalSize+=h}function B_(i){return i._queue.peek().value}function Ln(i){i._queue=new T,i._queueTotalSize=0}function Mf(i){return i===DataView}function M_(i){return Mf(i.constructor)}function L_(i){return Mf(i)?1:i.BYTES_PER_ELEMENT}class or{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ru(this))throw Iu("view");return this._view}respond(u){if(!Ru(this))throw Iu("respond");if(Le(u,1,"respond"),u=P(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Mn(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ls(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!Ru(this))throw Iu("respondWithNewView");if(Le(u,1,"respondWithNewView"),!ArrayBuffer.isView(u))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Mn(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");js(this._associatedReadableByteStreamController,u)}}Object.defineProperties(or.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(or.prototype.respond,"respond"),o(or.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(or.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class mn{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!sr(this))throw Ro("byobRequest");return Fu(this)}get desiredSize(){if(!sr(this))throw Ro("desiredSize");return Jf(this)}close(){if(!sr(this))throw Ro("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let u=this._controlledReadableByteStream._state;if(u!=="readable")throw new TypeError(`The stream (in ${u} state) is not in the readable state and cannot be closed`);Do(this)}enqueue(u){if(!sr(this))throw Ro("enqueue");if(Le(u,1,"enqueue"),!ArrayBuffer.isView(u))throw new TypeError("chunk must be an array buffer view");if(u.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(u.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let h=this._controlledReadableByteStream._state;if(h!=="readable")throw new TypeError(`The stream (in ${h} state) is not in the readable state and cannot be enqueued to`);Ms(this,u)}error(u=void 0){if(!sr(this))throw Ro("error");St(this,u)}[J](u){Lf(this),Ln(this);let h=this._cancelAlgorithm(u);return Bs(this),h}[F](u){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){Gf(this,u);return}let k=this._autoAllocateChunkSize;if(k!==void 0){let x;try{x=new ArrayBuffer(k)}catch(q){u._errorSteps(q);return}let j={buffer:x,bufferByteLength:k,byteOffset:0,byteLength:k,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(j)}O(h,u),ir(this)}[V](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new T,this._pendingPullIntos.push(u)}}}Object.defineProperties(mn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(mn.prototype.close,"close"),o(mn.prototype.enqueue,"enqueue"),o(mn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function sr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof mn}function Ru(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof or}function ir(i){if(!H_(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,ir(i)),null),k=>(St(i,k),null))}function Lf(i){Ou(i),i._pendingPullIntos=new T}function xu(i,u){let h=!1;i._state==="closed"&&(h=!0);let k=jf(u);u.readerType==="default"?I(i,k,h):K_(i,k,h)}function jf(i){let u=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/h)}function Ns(i,u,h,k){i._queue.push({buffer:u,byteOffset:h,byteLength:k}),i._queueTotalSize+=k}function $f(i,u,h,k){let x;try{x=If(u,h,h+k)}catch(j){throw St(i,j),j}Ns(i,x,0,k)}function Uf(i,u){u.bytesFilled>0&&$f(i,u.buffer,u.byteOffset,u.bytesFilled),Ir(i)}function qf(i,u){let h=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),k=u.bytesFilled+h,x=h,j=!1,q=k%u.elementSize,Z=k-q;Z>=u.minimumFill&&(x=Z-u.bytesFilled,j=!0);let ce=i._queue;for(;x>0;){let se=ce.peek(),fe=Math.min(x,se.byteLength),ge=u.byteOffset+u.bytesFilled;Ff(u.buffer,ge,se.buffer,se.byteOffset,fe),se.byteLength===fe?ce.shift():(se.byteOffset+=fe,se.byteLength-=fe),i._queueTotalSize-=fe,Hf(i,fe,u),x-=fe}return j}function Hf(i,u,h){h.bytesFilled+=u}function zf(i){i._queueTotalSize===0&&i._closeRequested?(Bs(i),No(i._controlledReadableByteStream)):ir(i)}function Ou(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function Pu(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();qf(i,u)&&(Ir(i),xu(i._controlledReadableByteStream,u))}}function j_(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=u._readRequests.shift();Gf(i,h)}}function $_(i,u,h,k){let x=i._controlledReadableByteStream,j=u.constructor,q=L_(j),{byteOffset:Z,byteLength:ce}=u,se=h*q,fe;try{fe=pn(u.buffer)}catch(De){k._errorSteps(De);return}let ge={buffer:fe,bufferByteLength:fe.byteLength,byteOffset:Z,byteLength:ce,bytesFilled:0,minimumFill:se,elementSize:q,viewConstructor:j,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(ge),Yf(x,k);return}if(x._state==="closed"){let De=new j(ge.buffer,ge.byteOffset,0);k._closeSteps(De);return}if(i._queueTotalSize>0){if(qf(i,ge)){let De=jf(ge);zf(i),k._chunkSteps(De);return}if(i._closeRequested){let De=new TypeError("Insufficient bytes to fill elements in the given buffer");St(i,De),k._errorSteps(De);return}}i._pendingPullIntos.push(ge),Yf(x,k),ir(i)}function U_(i,u){u.readerType==="none"&&Ir(i);let h=i._controlledReadableByteStream;if(Nu(h))for(;Qf(h)>0;){let k=Ir(i);xu(h,k)}}function q_(i,u,h){if(Hf(i,u,h),h.readerType==="none"){Uf(i,h),Pu(i);return}if(h.bytesFilled<h.minimumFill)return;Ir(i);let k=h.bytesFilled%h.elementSize;if(k>0){let x=h.byteOffset+h.bytesFilled;$f(i,h.buffer,x-k,k)}h.bytesFilled-=k,xu(i._controlledReadableByteStream,h),Pu(i)}function Wf(i,u){let h=i._pendingPullIntos.peek();Ou(i),i._controlledReadableByteStream._state==="closed"?U_(i,h):q_(i,u,h),ir(i)}function Ir(i){return i._pendingPullIntos.shift()}function H_(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(B(u)&&L(u)>0||Nu(u)&&Qf(u)>0||Jf(i)>0)}function Bs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function Do(i){let u=i._controlledReadableByteStream;if(!(i._closeRequested||u._state!=="readable")){if(i._queueTotalSize>0){i._closeRequested=!0;return}if(i._pendingPullIntos.length>0){let h=i._pendingPullIntos.peek();if(h.bytesFilled%h.elementSize!==0){let k=new TypeError("Insufficient bytes to fill elements in the given buffer");throw St(i,k),k}}Bs(i),No(u)}}function Ms(i,u){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:k,byteOffset:x,byteLength:j}=u;if(Mn(k))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let q=pn(k);if(i._pendingPullIntos.length>0){let Z=i._pendingPullIntos.peek();if(Mn(Z.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ou(i),Z.buffer=pn(Z.buffer),Z.readerType==="none"&&Uf(i,Z)}if(B(h))if(j_(i),L(h)===0)Ns(i,q,x,j);else{i._pendingPullIntos.length>0&&Ir(i);let Z=new Uint8Array(q,x,j);I(h,Z,!1)}else Nu(h)?(Ns(i,q,x,j),Pu(i)):Ns(i,q,x,j);ir(i)}function St(i,u){let h=i._controlledReadableByteStream;h._state==="readable"&&(Lf(i),Ln(i),Bs(i),wh(h,u))}function Gf(i,u){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,zf(i);let k=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);u._chunkSteps(k)}function Fu(i){if(i._byobRequest===null&&i._pendingPullIntos.length>0){let u=i._pendingPullIntos.peek(),h=new Uint8Array(u.buffer,u.byteOffset+u.bytesFilled,u.byteLength-u.bytesFilled),k=Object.create(or.prototype);W_(k,i,h),i._byobRequest=k}return i._byobRequest}function Jf(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function Ls(i,u){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(u===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(h.bytesFilled+u>h.byteLength)throw new RangeError("bytesWritten out of range")}h.buffer=pn(h.buffer),Wf(i,u)}function js(i,u){let h=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(u.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(h.byteOffset+h.bytesFilled!==u.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(h.bufferByteLength!==u.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(h.bytesFilled+u.byteLength>h.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let x=u.byteLength;h.buffer=pn(u.buffer),Wf(i,x)}function Vf(i,u,h,k,x,j,q){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Ln(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=j,u._pullAlgorithm=k,u._cancelAlgorithm=x,u._autoAllocateChunkSize=q,u._pendingPullIntos=new T,i._readableStreamController=u;let Z=h();m(d(Z),()=>(u._started=!0,ir(u),null),ce=>(St(u,ce),null))}function z_(i,u,h){let k=Object.create(mn.prototype),x,j,q;u.start!==void 0?x=()=>u.start(k):x=()=>{},u.pull!==void 0?j=()=>u.pull(k):j=()=>d(void 0),u.cancel!==void 0?q=ce=>u.cancel(ce):q=()=>d(void 0);let Z=u.autoAllocateChunkSize;if(Z===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Vf(i,k,x,j,q,h,Z)}function W_(i,u,h){i._associatedReadableByteStreamController=u,i._view=h}function Iu(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}function Ro(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function G_(i,u){le(i,u);let h=i?.mode;return{mode:h===void 0?void 0:J_(h,`${u} has member 'mode' that`)}}function J_(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function V_(i,u){var h;le(i,u);let k=(h=i?.min)!==null&&h!==void 0?h:1;return{min:P(k,`${u} has member 'min' that`)}}function Kf(i){return new jn(i)}function Yf(i,u){i._reader._readIntoRequests.push(u)}function K_(i,u,h){let x=i._reader._readIntoRequests.shift();h?x._closeSteps(u):x._chunkSteps(u)}function Qf(i){return i._reader._readIntoRequests.length}function Nu(i){let u=i._reader;return!(u===void 0||!ar(u))}class jn{constructor(u){if(Le(u,1,"ReadableStreamBYOBReader"),N(u,"First parameter"),qn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!sr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");Y(this,u),this._readIntoRequests=new T}get closed(){return ar(this)?this._closedPromise:f($s("closed"))}cancel(u=void 0){return ar(this)?this._ownerReadableStream===void 0?f(de("cancel")):X(this,u):f($s("cancel"))}read(u,h={}){if(!ar(this))return f($s("read"));if(!ArrayBuffer.isView(u))return f(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return f(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return f(new TypeError("view's buffer must have non-zero byteLength"));if(Mn(u.buffer))return f(new TypeError("view's buffer has been detached"));let k;try{k=V_(h,"options")}catch(se){return f(se)}let x=k.min;if(x===0)return f(new TypeError("options.min must be greater than 0"));if(M_(u)){if(x>u.byteLength)return f(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(x>u.length)return f(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return f(de("read from"));let j,q,Z=l((se,fe)=>{j=se,q=fe});return Xf(this,u,x,{_chunkSteps:se=>j({value:se,done:!1}),_closeSteps:se=>j({value:se,done:!0}),_errorSteps:se=>q(se)}),Z}releaseLock(){if(!ar(this))throw $s("releaseLock");this._ownerReadableStream!==void 0&&Y_(this)}}Object.defineProperties(jn.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(jn.prototype.cancel,"cancel"),o(jn.prototype.read,"read"),o(jn.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jn.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function ar(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof jn}function Xf(i,u,h,k){let x=i._ownerReadableStream;x._disturbed=!0,x._state==="errored"?k._errorSteps(x._storedError):$_(x._readableStreamController,u,h,k)}function Y_(i){ee(i);let u=new TypeError("Reader was released");Zf(i,u)}function Zf(i,u){let h=i._readIntoRequests;i._readIntoRequests=new T,h.forEach(k=>{k._errorSteps(u)})}function $s(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function xo(i,u){let{highWaterMark:h}=i;if(h===void 0)return u;if(dt(h)||h<0)throw new RangeError("Invalid highWaterMark");return h}function Us(i){let{size:u}=i;return u||(()=>1)}function qs(i,u){le(i,u);let h=i?.highWaterMark,k=i?.size;return{highWaterMark:h===void 0?void 0:v(h),size:k===void 0?void 0:Q_(k,`${u} has member 'size' that`)}}function Q_(i,u){return _e(i,u),h=>v(i(h))}function X_(i,u){le(i,u);let h=i?.abort,k=i?.close,x=i?.start,j=i?.type,q=i?.write;return{abort:h===void 0?void 0:Z_(h,i,`${u} has member 'abort' that`),close:k===void 0?void 0:eb(k,i,`${u} has member 'close' that`),start:x===void 0?void 0:tb(x,i,`${u} has member 'start' that`),write:q===void 0?void 0:nb(q,i,`${u} has member 'write' that`),type:j}}function Z_(i,u,h){return _e(i,h),k=>w(i,u,[k])}function eb(i,u,h){return _e(i,h),()=>w(i,u,[])}function tb(i,u,h){return _e(i,h),k=>S(i,u,[k])}function nb(i,u,h){return _e(i,h),(k,x)=>w(i,u,[k,x])}function eh(i,u){if(!Nr(i))throw new TypeError(`${u} is not a WritableStream.`)}function rb(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let ob=typeof AbortController=="function";function sb(){if(ob)return new AbortController}class $n{constructor(u={},h={}){u===void 0?u=null:Re(u,"First parameter");let k=qs(h,"Second parameter"),x=X_(u,"First parameter");if(nh(this),x.type!==void 0)throw new RangeError("Invalid type is specified");let q=Us(k),Z=xo(k,1);bb(this,x,Z,q)}get locked(){if(!Nr(this))throw Js("locked");return Br(this)}abort(u=void 0){return Nr(this)?Br(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Hs(this,u):f(Js("abort"))}close(){return Nr(this)?Br(this)?f(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?f(new TypeError("Cannot close an already-closing stream")):rh(this):f(Js("close"))}getWriter(){if(!Nr(this))throw Js("getWriter");return th(this)}}Object.defineProperties($n.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o($n.prototype.abort,"abort"),o($n.prototype.close,"close"),o($n.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty($n.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function th(i){return new gn(i)}function ib(i,u,h,k,x=1,j=()=>1){let q=Object.create($n.prototype);nh(q);let Z=Object.create(Mr.prototype);return ch(q,Z,i,u,h,k,x,j),q}function nh(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new T,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function Nr(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof $n}function Br(i){return i._writer!==void 0}function Hs(i,u){var h;if(i._state==="closed"||i._state==="errored")return d(void 0);i._writableStreamController._abortReason=u,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(u);let k=i._state;if(k==="closed"||k==="errored")return d(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let x=!1;k==="erroring"&&(x=!0,u=void 0);let j=l((q,Z)=>{i._pendingAbortRequest={_promise:void 0,_resolve:q,_reject:Z,_reason:u,_wasAlreadyErroring:x}});return i._pendingAbortRequest._promise=j,x||Mu(i,u),j}function rh(i){let u=i._state;if(u==="closed"||u==="errored")return f(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let h=l((x,j)=>{let q={_resolve:x,_reject:j};i._closeRequest=q}),k=i._writer;return k!==void 0&&i._backpressure&&u==="writable"&&Wu(k),Cb(i._writableStreamController),h}function ab(i){return l((h,k)=>{let x={_resolve:h,_reject:k};i._writeRequests.push(x)})}function Bu(i,u){if(i._state==="writable"){Mu(i,u);return}Lu(i)}function Mu(i,u){let h=i._writableStreamController;i._state="erroring",i._storedError=u;let k=i._writer;k!==void 0&&sh(k,u),!fb(i)&&h._started&&Lu(i)}function Lu(i){i._state="errored",i._writableStreamController[U]();let u=i._storedError;if(i._writeRequests.forEach(x=>{x._reject(u)}),i._writeRequests=new T,i._pendingAbortRequest===void 0){zs(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(u),zs(i);return}let k=i._writableStreamController[R](h._reason);m(k,()=>(h._resolve(),zs(i),null),x=>(h._reject(x),zs(i),null))}function ub(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function cb(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,Bu(i,u)}function lb(i){i._inFlightCloseRequest._resolve(void 0),i._inFlightCloseRequest=void 0,i._state==="erroring"&&(i._storedError=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._resolve(),i._pendingAbortRequest=void 0)),i._state="closed";let h=i._writer;h!==void 0&&hh(h)}function db(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),Bu(i,u)}function Xt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function fb(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function hb(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function pb(i){i._inFlightWriteRequest=i._writeRequests.shift()}function zs(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&Hu(u,i._storedError)}function ju(i,u){let h=i._writer;h!==void 0&&u!==i._backpressure&&(u?Tb(h):Wu(h)),i._backpressure=u}class gn{constructor(u){if(Le(u,1,"WritableStreamDefaultWriter"),eh(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=u,u._writer=this;let h=u._state;if(h==="writable")!Xt(u)&&u._backpressure?Ks(this):ph(this),Vs(this);else if(h==="erroring")zu(this,u._storedError),Vs(this);else if(h==="closed")ph(this),kb(this);else{let k=u._storedError;zu(this,k),fh(this,k)}}get closed(){return ur(this)?this._closedPromise:f(cr("closed"))}get desiredSize(){if(!ur(this))throw cr("desiredSize");if(this._ownerWritableStream===void 0)throw Po("desiredSize");return _b(this)}get ready(){return ur(this)?this._readyPromise:f(cr("ready"))}abort(u=void 0){return ur(this)?this._ownerWritableStream===void 0?f(Po("abort")):mb(this,u):f(cr("abort"))}close(){if(!ur(this))return f(cr("close"));let u=this._ownerWritableStream;return u===void 0?f(Po("close")):Xt(u)?f(new TypeError("Cannot close an already-closing stream")):oh(this)}releaseLock(){if(!ur(this))throw cr("releaseLock");this._ownerWritableStream!==void 0&&ih(this)}write(u=void 0){return ur(this)?this._ownerWritableStream===void 0?f(Po("write to")):ah(this,u):f(cr("write"))}}Object.defineProperties(gn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(gn.prototype.abort,"abort"),o(gn.prototype.close,"close"),o(gn.prototype.releaseLock,"releaseLock"),o(gn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function ur(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof gn}function mb(i,u){let h=i._ownerWritableStream;return Hs(h,u)}function oh(i){let u=i._ownerWritableStream;return rh(u)}function gb(i){let u=i._ownerWritableStream,h=u._state;return Xt(u)||h==="closed"?d(void 0):h==="errored"?f(u._storedError):oh(i)}function yb(i,u){i._closedPromiseState==="pending"?Hu(i,u):vb(i,u)}function sh(i,u){i._readyPromiseState==="pending"?mh(i,u):Db(i,u)}function _b(i){let u=i._ownerWritableStream,h=u._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:lh(u._writableStreamController)}function ih(i){let u=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");sh(i,h),yb(i,h),u._writer=void 0,i._ownerWritableStream=void 0}function ah(i,u){let h=i._ownerWritableStream,k=h._writableStreamController,x=wb(k,u);if(h!==i._ownerWritableStream)return f(Po("write to"));let j=h._state;if(j==="errored")return f(h._storedError);if(Xt(h)||j==="closed")return f(new TypeError("The stream is closing or closed and cannot be written to"));if(j==="erroring")return f(h._storedError);let q=ab(h);return Eb(k,u,x),q}let uh={};class Mr{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!$u(this))throw qu("abortReason");return this._abortReason}get signal(){if(!$u(this))throw qu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!$u(this))throw qu("error");this._controlledWritableStream._state==="writable"&&dh(this,u)}[R](u){let h=this._abortAlgorithm(u);return Ws(this),h}[U](){Ln(this)}}Object.defineProperties(Mr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function $u(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Mr}function ch(i,u,h,k,x,j,q,Z){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Ln(u),u._abortReason=void 0,u._abortController=sb(),u._started=!1,u._strategySizeAlgorithm=Z,u._strategyHWM=q,u._writeAlgorithm=k,u._closeAlgorithm=x,u._abortAlgorithm=j;let ce=Uu(u);ju(i,ce);let se=h(),fe=d(se);m(fe,()=>(u._started=!0,Gs(u),null),ge=>(u._started=!0,Bu(i,ge),null))}function bb(i,u,h,k){let x=Object.create(Mr.prototype),j,q,Z,ce;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.write!==void 0?q=se=>u.write(se,x):q=()=>d(void 0),u.close!==void 0?Z=()=>u.close():Z=()=>d(void 0),u.abort!==void 0?ce=se=>u.abort(se):ce=()=>d(void 0),ch(i,x,j,q,Z,ce,h,k)}function Ws(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function Cb(i){Du(i,uh,0),Gs(i)}function wb(i,u){try{return i._strategySizeAlgorithm(u)}catch(h){return Oo(i,h),1}}function lh(i){return i._strategyHWM-i._queueTotalSize}function Eb(i,u,h){try{Du(i,u,h)}catch(x){Oo(i,x);return}let k=i._controlledWritableStream;if(!Xt(k)&&k._state==="writable"){let x=Uu(i);ju(k,x)}Gs(i)}function Gs(i){let u=i._controlledWritableStream;if(!i._started||u._inFlightWriteRequest!==void 0)return;if(u._state==="erroring"){Lu(u);return}if(i._queue.length===0)return;let k=B_(i);k===uh?Ab(i):Sb(i,k)}function Oo(i,u){i._controlledWritableStream._state==="writable"&&dh(i,u)}function Ab(i){let u=i._controlledWritableStream;hb(u),Tu(i);let h=i._closeAlgorithm();Ws(i),m(h,()=>(lb(u),null),k=>(db(u,k),null))}function Sb(i,u){let h=i._controlledWritableStream;pb(h);let k=i._writeAlgorithm(u);m(k,()=>{ub(h);let x=h._state;if(Tu(i),!Xt(h)&&x==="writable"){let j=Uu(i);ju(h,j)}return Gs(i),null},x=>(h._state==="writable"&&Ws(i),cb(h,x),null))}function Uu(i){return lh(i)<=0}function dh(i,u){let h=i._controlledWritableStream;Ws(i),Mu(h,u)}function Js(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function qu(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function cr(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function Po(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Vs(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function fh(i,u){Vs(i),Hu(i,u)}function kb(i){Vs(i),hh(i)}function Hu(i,u){i._closedPromise_reject!==void 0&&(_(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function vb(i,u){fh(i,u)}function hh(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="resolved")}function Ks(i){i._readyPromise=l((u,h)=>{i._readyPromise_resolve=u,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function zu(i,u){Ks(i),mh(i,u)}function ph(i){Ks(i),Wu(i)}function mh(i,u){i._readyPromise_reject!==void 0&&(_(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function Tb(i){Ks(i)}function Db(i,u){zu(i,u)}function Wu(i){i._readyPromise_resolve!==void 0&&(i._readyPromise_resolve(void 0),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="fulfilled")}function Rb(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Gu=Rb();function xb(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function Ob(){let i=Gu?.DOMException;return xb(i)?i:void 0}function Pb(){let i=function(h,k){this.message=h||"",this.name=k||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(i,"DOMException"),i.prototype=Object.create(Error.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,writable:!0,configurable:!0}),i}let Fb=Ob()||Pb();function gh(i,u,h,k,x,j){let q=$(i),Z=th(u);i._disturbed=!0;let ce=!1,se=d(void 0);return l((fe,ge)=>{let De;if(j!==void 0){if(De=()=>{let ie=j.reason!==void 0?j.reason:new Fb("Aborted","AbortError"),be=[];k||be.push(()=>u._state==="writable"?Hs(u,ie):d(void 0)),x||be.push(()=>i._state==="readable"?Lt(i,ie):d(void 0)),it(()=>Promise.all(be.map(xe=>xe())),!0,ie)},j.aborted){De();return}j.addEventListener("abort",De)}function jt(){return l((ie,be)=>{function xe(ft){ft?ie():p(Ur(),xe,be)}xe(!1)})}function Ur(){return ce?d(!0):p(Z._readyPromise,()=>l((ie,be)=>{ne(q,{_chunkSteps:xe=>{se=p(ah(Z,xe),void 0,e),ie(!1)},_closeSteps:()=>ie(!0),_errorSteps:be})}))}if(_n(i,q._closedPromise,ie=>(k?kt(!0,ie):it(()=>Hs(u,ie),!0,ie),null)),_n(u,Z._closedPromise,ie=>(x?kt(!0,ie):it(()=>Lt(i,ie),!0,ie),null)),tt(i,q._closedPromise,()=>(h?kt():it(()=>gb(Z)),null)),Xt(u)||u._state==="closed"){let ie=new TypeError("the destination writable stream closed before all data could be piped to it");x?kt(!0,ie):it(()=>Lt(i,ie),!0,ie)}_(jt());function zn(){let ie=se;return p(se,()=>ie!==se?zn():void 0)}function _n(ie,be,xe){ie._state==="errored"?xe(ie._storedError):C(be,xe)}function tt(ie,be,xe){ie._state==="closed"?xe():b(be,xe)}function it(ie,be,xe){if(ce)return;ce=!0,u._state==="writable"&&!Xt(u)?b(zn(),ft):ft();function ft(){return m(ie(),()=>bn(be,xe),qr=>bn(!0,qr)),null}}function kt(ie,be){ce||(ce=!0,u._state==="writable"&&!Xt(u)?b(zn(),()=>bn(ie,be)):bn(ie,be))}function bn(ie,be){return ih(Z),ee(q),j!==void 0&&j.removeEventListener("abort",De),ie?ge(be):fe(void 0),null}})}class yn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ys(this))throw Xs("desiredSize");return Ju(this)}close(){if(!Ys(this))throw Xs("close");if(!jr(this))throw new TypeError("The stream is not in a state that permits close");lr(this)}enqueue(u=void 0){if(!Ys(this))throw Xs("enqueue");if(!jr(this))throw new TypeError("The stream is not in a state that permits enqueue");return Lr(this,u)}error(u=void 0){if(!Ys(this))throw Xs("error");Mt(this,u)}[J](u){Ln(this);let h=this._cancelAlgorithm(u);return Qs(this),h}[F](u){let h=this._controlledReadableStream;if(this._queue.length>0){let k=Tu(this);this._closeRequested&&this._queue.length===0?(Qs(this),No(h)):Fo(this),u._chunkSteps(k)}else O(h,u),Fo(this)}[V](){}}Object.defineProperties(yn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(yn.prototype.close,"close"),o(yn.prototype.enqueue,"enqueue"),o(yn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ys(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof yn}function Fo(i){if(!yh(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();m(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,Fo(i)),null),k=>(Mt(i,k),null))}function yh(i){let u=i._controlledReadableStream;return!jr(i)||!i._started?!1:!!(qn(u)&&L(u)>0||Ju(i)>0)}function Qs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function lr(i){if(!jr(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Qs(i),No(u))}function Lr(i,u){if(!jr(i))return;let h=i._controlledReadableStream;if(qn(h)&&L(h)>0)I(h,u,!1);else{let k;try{k=i._strategySizeAlgorithm(u)}catch(x){throw Mt(i,x),x}try{Du(i,u,k)}catch(x){throw Mt(i,x),x}}Fo(i)}function Mt(i,u){let h=i._controlledReadableStream;h._state==="readable"&&(Ln(i),Qs(i),wh(h,u))}function Ju(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function Ib(i){return!yh(i)}function jr(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function _h(i,u,h,k,x,j,q){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Ln(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=q,u._strategyHWM=j,u._pullAlgorithm=k,u._cancelAlgorithm=x,i._readableStreamController=u;let Z=h();m(d(Z),()=>(u._started=!0,Fo(u),null),ce=>(Mt(u,ce),null))}function Nb(i,u,h,k){let x=Object.create(yn.prototype),j,q,Z;u.start!==void 0?j=()=>u.start(x):j=()=>{},u.pull!==void 0?q=()=>u.pull(x):q=()=>d(void 0),u.cancel!==void 0?Z=ce=>u.cancel(ce):Z=()=>d(void 0),_h(i,x,j,q,Z,h,k)}function Xs(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function Bb(i,u){return sr(i._readableStreamController)?Lb(i):Mb(i)}function Mb(i,u){let h=$(i),k=!1,x=!1,j=!1,q=!1,Z,ce,se,fe,ge,De=l(tt=>{ge=tt});function jt(){return k?(x=!0,d(void 0)):(k=!0,ne(h,{_chunkSteps:it=>{g(()=>{x=!1;let kt=it,bn=it;j||Lr(se._readableStreamController,kt),q||Lr(fe._readableStreamController,bn),k=!1,x&&jt()})},_closeSteps:()=>{k=!1,j||lr(se._readableStreamController),q||lr(fe._readableStreamController),(!j||!q)&&ge(void 0)},_errorSteps:()=>{k=!1}}),d(void 0))}function Ur(tt){if(j=!0,Z=tt,q){let it=ve([Z,ce]),kt=Lt(i,it);ge(kt)}return De}function zn(tt){if(q=!0,ce=tt,j){let it=ve([Z,ce]),kt=Lt(i,it);ge(kt)}return De}function _n(){}return se=Io(_n,jt,Ur),fe=Io(_n,jt,zn),C(h._closedPromise,tt=>(Mt(se._readableStreamController,tt),Mt(fe._readableStreamController,tt),(!j||!q)&&ge(void 0),null)),[se,fe]}function Lb(i){let u=$(i),h=!1,k=!1,x=!1,j=!1,q=!1,Z,ce,se,fe,ge,De=l(ie=>{ge=ie});function jt(ie){C(ie._closedPromise,be=>(ie!==u||(St(se._readableStreamController,be),St(fe._readableStreamController,be),(!j||!q)&&ge(void 0)),null))}function Ur(){ar(u)&&(ee(u),u=$(i),jt(u)),ne(u,{_chunkSteps:be=>{g(()=>{k=!1,x=!1;let xe=be,ft=be;if(!j&&!q)try{ft=Bf(be)}catch(qr){St(se._readableStreamController,qr),St(fe._readableStreamController,qr),ge(Lt(i,qr));return}j||Ms(se._readableStreamController,xe),q||Ms(fe._readableStreamController,ft),h=!1,k?_n():x&&tt()})},_closeSteps:()=>{h=!1,j||Do(se._readableStreamController),q||Do(fe._readableStreamController),se._readableStreamController._pendingPullIntos.length>0&&Ls(se._readableStreamController,0),fe._readableStreamController._pendingPullIntos.length>0&&Ls(fe._readableStreamController,0),(!j||!q)&&ge(void 0)},_errorSteps:()=>{h=!1}})}function zn(ie,be){te(u)&&(ee(u),u=Kf(i),jt(u));let xe=be?fe:se,ft=be?se:fe;Xf(u,ie,1,{_chunkSteps:Hr=>{g(()=>{k=!1,x=!1;let zr=be?q:j;if(be?j:q)zr||js(xe._readableStreamController,Hr);else{let Ih;try{Ih=Bf(Hr)}catch(Xu){St(xe._readableStreamController,Xu),St(ft._readableStreamController,Xu),ge(Lt(i,Xu));return}zr||js(xe._readableStreamController,Hr),Ms(ft._readableStreamController,Ih)}h=!1,k?_n():x&&tt()})},_closeSteps:Hr=>{h=!1;let zr=be?q:j,ii=be?j:q;zr||Do(xe._readableStreamController),ii||Do(ft._readableStreamController),Hr!==void 0&&(zr||js(xe._readableStreamController,Hr),!ii&&ft._readableStreamController._pendingPullIntos.length>0&&Ls(ft._readableStreamController,0)),(!zr||!ii)&&ge(void 0)},_errorSteps:()=>{h=!1}})}function _n(){if(h)return k=!0,d(void 0);h=!0;let ie=Fu(se._readableStreamController);return ie===null?Ur():zn(ie._view,!1),d(void 0)}function tt(){if(h)return x=!0,d(void 0);h=!0;let ie=Fu(fe._readableStreamController);return ie===null?Ur():zn(ie._view,!0),d(void 0)}function it(ie){if(j=!0,Z=ie,q){let be=ve([Z,ce]),xe=Lt(i,be);ge(xe)}return De}function kt(ie){if(q=!0,ce=ie,j){let be=ve([Z,ce]),xe=Lt(i,be);ge(xe)}return De}function bn(){}return se=Ch(bn,_n,it),fe=Ch(bn,tt,kt),jt(u),[se,fe]}function jb(i){return n(i)&&typeof i.getReader<"u"}function $b(i){return jb(i)?qb(i.getReader()):Ub(i)}function Ub(i){let u,h=Nf(i,"async"),k=e;function x(){let q;try{q=P_(h)}catch(ce){return f(ce)}let Z=d(q);return y(Z,ce=>{if(!n(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(F_(ce))lr(u._readableStreamController);else{let fe=I_(ce);Lr(u._readableStreamController,fe)}})}function j(q){let Z=h.iterator,ce;try{ce=Is(Z,"return")}catch(ge){return f(ge)}if(ce===void 0)return d(void 0);let se;try{se=S(ce,Z,[q])}catch(ge){return f(ge)}let fe=d(se);return y(fe,ge=>{if(!n(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=Io(k,x,j,0),u}function qb(i){let u,h=e;function k(){let j;try{j=i.read()}catch(q){return f(q)}return y(j,q=>{if(!n(q))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(q.done)lr(u._readableStreamController);else{let Z=q.value;Lr(u._readableStreamController,Z)}})}function x(j){try{return d(i.cancel(j))}catch(q){return f(q)}}return u=Io(h,k,x,0),u}function Hb(i,u){le(i,u);let h=i,k=h?.autoAllocateChunkSize,x=h?.cancel,j=h?.pull,q=h?.start,Z=h?.type;return{autoAllocateChunkSize:k===void 0?void 0:P(k,`${u} has member 'autoAllocateChunkSize' that`),cancel:x===void 0?void 0:zb(x,h,`${u} has member 'cancel' that`),pull:j===void 0?void 0:Wb(j,h,`${u} has member 'pull' that`),start:q===void 0?void 0:Gb(q,h,`${u} has member 'start' that`),type:Z===void 0?void 0:Jb(Z,`${u} has member 'type' that`)}}function zb(i,u,h){return _e(i,h),k=>w(i,u,[k])}function Wb(i,u,h){return _e(i,h),k=>w(i,u,[k])}function Gb(i,u,h){return _e(i,h),k=>S(i,u,[k])}function Jb(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function Vb(i,u){return le(i,u),{preventCancel:!!i?.preventCancel}}function bh(i,u){le(i,u);let h=i?.preventAbort,k=i?.preventCancel,x=i?.preventClose,j=i?.signal;return j!==void 0&&Kb(j,`${u} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!k,preventClose:!!x,signal:j}}function Kb(i,u){if(!rb(i))throw new TypeError(`${u} is not an AbortSignal.`)}function Yb(i,u){le(i,u);let h=i?.readable;A(h,"readable","ReadableWritablePair"),N(h,`${u} has member 'readable' that`);let k=i?.writable;return A(k,"writable","ReadableWritablePair"),eh(k,`${u} has member 'writable' that`),{readable:h,writable:k}}class Ze{constructor(u={},h={}){u===void 0?u=null:Re(u,"First parameter");let k=qs(h,"Second parameter"),x=Hb(u,"First parameter");if(Vu(this),x.type==="bytes"){if(k.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let j=xo(k,0);z_(this,x,j)}else{let j=Us(k),q=xo(k,1);Nb(this,x,q,j)}}get locked(){if(!Un(this))throw dr("locked");return qn(this)}cancel(u=void 0){return Un(this)?qn(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Lt(this,u):f(dr("cancel"))}getReader(u=void 0){if(!Un(this))throw dr("getReader");return G_(u,"First parameter").mode===void 0?$(this):Kf(this)}pipeThrough(u,h={}){if(!Un(this))throw dr("pipeThrough");Le(u,1,"pipeThrough");let k=Yb(u,"First parameter"),x=bh(h,"Second parameter");if(qn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Br(k.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let j=gh(this,k.writable,x.preventClose,x.preventAbort,x.preventCancel,x.signal);return _(j),k.readable}pipeTo(u,h={}){if(!Un(this))return f(dr("pipeTo"));if(u===void 0)return f("Parameter 1 is required in 'pipeTo'.");if(!Nr(u))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let k;try{k=bh(h,"Second parameter")}catch(x){return f(x)}return qn(this)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Br(u)?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):gh(this,u,k.preventClose,k.preventAbort,k.preventCancel,k.signal)}tee(){if(!Un(this))throw dr("tee");let u=Bb(this);return ve(u)}values(u=void 0){if(!Un(this))throw dr("values");let h=Vb(u,"First parameter");return Or(this,h.preventCancel)}[vu](u){return this.values(u)}static from(u){return $b(u)}}Object.defineProperties(Ze,{from:{enumerable:!0}}),Object.defineProperties(Ze.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Ze.from,"from"),o(Ze.prototype.cancel,"cancel"),o(Ze.prototype.getReader,"getReader"),o(Ze.prototype.pipeThrough,"pipeThrough"),o(Ze.prototype.pipeTo,"pipeTo"),o(Ze.prototype.tee,"tee"),o(Ze.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ze.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ze.prototype,vu,{value:Ze.prototype.values,writable:!0,configurable:!0});function Io(i,u,h,k=1,x=()=>1){let j=Object.create(Ze.prototype);Vu(j);let q=Object.create(yn.prototype);return _h(j,q,i,u,h,k,x),j}function Ch(i,u,h){let k=Object.create(Ze.prototype);Vu(k);let x=Object.create(mn.prototype);return Vf(k,x,i,u,h,0,void 0),k}function Vu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Un(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof Ze}function qn(i){return i._reader!==void 0}function Lt(i,u){if(i._disturbed=!0,i._state==="closed")return d(void 0);if(i._state==="errored")return f(i._storedError);No(i);let h=i._reader;if(h!==void 0&&ar(h)){let x=h._readIntoRequests;h._readIntoRequests=new T,x.forEach(j=>{j._closeSteps(void 0)})}let k=i._readableStreamController[J](u);return y(k,e)}function No(i){i._state="closed";let u=i._reader;if(u!==void 0&&(re(u),te(u))){let h=u._readRequests;u._readRequests=new T,h.forEach(k=>{k._closeSteps()})}}function wh(i,u){i._state="errored",i._storedError=u;let h=i._reader;h!==void 0&&(W(h,u),te(h)?Fe(h,u):Zf(h,u))}function dr(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function Eh(i,u){le(i,u);let h=i?.highWaterMark;return A(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:v(h)}}let Ah=i=>i.byteLength;o(Ah,"size");class Zs{constructor(u){Le(u,1,"ByteLengthQueuingStrategy"),u=Eh(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!kh(this))throw Sh("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!kh(this))throw Sh("size");return Ah}}Object.defineProperties(Zs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Zs.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Sh(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function kh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof Zs}let vh=()=>1;o(vh,"size");class ei{constructor(u){Le(u,1,"CountQueuingStrategy"),u=Eh(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Dh(this))throw Th("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Dh(this))throw Th("size");return vh}}Object.defineProperties(ei.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ei.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Th(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function Dh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof ei}function Qb(i,u){le(i,u);let h=i?.cancel,k=i?.flush,x=i?.readableType,j=i?.start,q=i?.transform,Z=i?.writableType;return{cancel:h===void 0?void 0:tC(h,i,`${u} has member 'cancel' that`),flush:k===void 0?void 0:Xb(k,i,`${u} has member 'flush' that`),readableType:x,start:j===void 0?void 0:Zb(j,i,`${u} has member 'start' that`),transform:q===void 0?void 0:eC(q,i,`${u} has member 'transform' that`),writableType:Z}}function Xb(i,u,h){return _e(i,h),k=>w(i,u,[k])}function Zb(i,u,h){return _e(i,h),k=>S(i,u,[k])}function eC(i,u,h){return _e(i,h),(k,x)=>w(i,u,[k,x])}function tC(i,u,h){return _e(i,h),k=>w(i,u,[k])}class ti{constructor(u={},h={},k={}){u===void 0&&(u=null);let x=qs(h,"Second parameter"),j=qs(k,"Third parameter"),q=Qb(u,"First parameter");if(q.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(q.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Z=xo(j,0),ce=Us(j),se=xo(x,1),fe=Us(x),ge,De=l(jt=>{ge=jt});nC(this,De,se,fe,Z,ce),oC(this,q),q.start!==void 0?ge(q.start(this._transformStreamController)):ge(void 0)}get readable(){if(!Rh(this))throw Fh("readable");return this._readable}get writable(){if(!Rh(this))throw Fh("writable");return this._writable}}Object.defineProperties(ti.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ti.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function nC(i,u,h,k,x,j){function q(){return u}function Z(De){return aC(i,De)}function ce(De){return uC(i,De)}function se(){return cC(i)}i._writable=ib(q,Z,se,ce,h,k);function fe(){return lC(i)}function ge(De){return dC(i,De)}i._readable=Io(q,fe,ge,x,j),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,ni(i,!0),i._transformStreamController=void 0}function Rh(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof ti}function xh(i,u){Mt(i._readable._readableStreamController,u),Ku(i,u)}function Ku(i,u){oi(i._transformStreamController),Oo(i._writable._writableStreamController,u),Yu(i)}function Yu(i){i._backpressure&&ni(i,!1)}function ni(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=u}class Hn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ri(this))throw si("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return Ju(u)}enqueue(u=void 0){if(!ri(this))throw si("enqueue");Oh(this,u)}error(u=void 0){if(!ri(this))throw si("error");sC(this,u)}terminate(){if(!ri(this))throw si("terminate");iC(this)}}Object.defineProperties(Hn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Hn.prototype.enqueue,"enqueue"),o(Hn.prototype.error,"error"),o(Hn.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Hn.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function ri(i){return!n(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof Hn}function rC(i,u,h,k,x){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=h,u._flushAlgorithm=k,u._cancelAlgorithm=x,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function oC(i,u){let h=Object.create(Hn.prototype),k,x,j;u.transform!==void 0?k=q=>u.transform(q,h):k=q=>{try{return Oh(h,q),d(void 0)}catch(Z){return f(Z)}},u.flush!==void 0?x=()=>u.flush(h):x=()=>d(void 0),u.cancel!==void 0?j=q=>u.cancel(q):j=()=>d(void 0),rC(i,h,k,x,j)}function oi(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function Oh(i,u){let h=i._controlledTransformStream,k=h._readable._readableStreamController;if(!jr(k))throw new TypeError("Readable side is not in a state that permits enqueue");try{Lr(k,u)}catch(j){throw Ku(h,j),h._readable._storedError}Ib(k)!==h._backpressure&&ni(h,!0)}function sC(i,u){xh(i._controlledTransformStream,u)}function Ph(i,u){let h=i._transformAlgorithm(u);return y(h,void 0,k=>{throw xh(i._controlledTransformStream,k),k})}function iC(i){let u=i._controlledTransformStream,h=u._readable._readableStreamController;lr(h);let k=new TypeError("TransformStream terminated");Ku(u,k)}function aC(i,u){let h=i._transformStreamController;if(i._backpressure){let k=i._backpressureChangePromise;return y(k,()=>{let x=i._writable;if(x._state==="erroring")throw x._storedError;return Ph(h,u)})}return Ph(h,u)}function uC(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let k=i._readable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return oi(h),m(x,()=>(k._state==="errored"?$r(h,k._storedError):(Mt(k._readableStreamController,u),Qu(h)),null),j=>(Mt(k._readableStreamController,j),$r(h,j),null)),h._finishPromise}function cC(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let h=i._readable;u._finishPromise=l((x,j)=>{u._finishPromise_resolve=x,u._finishPromise_reject=j});let k=u._flushAlgorithm();return oi(u),m(k,()=>(h._state==="errored"?$r(u,h._storedError):(lr(h._readableStreamController),Qu(u)),null),x=>(Mt(h._readableStreamController,x),$r(u,x),null)),u._finishPromise}function lC(i){return ni(i,!1),i._backpressureChangePromise}function dC(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let k=i._writable;h._finishPromise=l((j,q)=>{h._finishPromise_resolve=j,h._finishPromise_reject=q});let x=h._cancelAlgorithm(u);return oi(h),m(x,()=>(k._state==="errored"?$r(h,k._storedError):(Oo(k._writableStreamController,u),Yu(i),Qu(h)),null),j=>(Oo(k._writableStreamController,j),Yu(i),$r(h,j),null)),h._finishPromise}function si(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function Qu(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function $r(i,u){i._finishPromise_reject!==void 0&&(_(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Fh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=Zs,t.CountQueuingStrategy=ei,t.ReadableByteStreamController=mn,t.ReadableStream=Ze,t.ReadableStreamBYOBReader=jn,t.ReadableStreamBYOBRequest=or,t.ReadableStreamDefaultController=yn,t.ReadableStreamDefaultReader=H,t.TransformStream=ti,t.TransformStreamDefaultController=Hn,t.WritableStream=$n,t.WritableStreamDefaultController=Mr,t.WritableStreamDefaultWriter=gn}))});var bm=K(()=>{if(!globalThis.ReadableStream)try{let t=require("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),t.emitWarning=e}catch(n){throw t.emitWarning=e,n}}catch{Object.assign(globalThis,_m())}try{let{Blob:t}=require("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(r,Math.min(o.size,r+65536)).arrayBuffer();r+=c.byteLength,s.enqueue(new Uint8Array(c)),r===o.size&&s.close()}})})}catch{}});async function*Nc(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,Cm),a=n.buffer.slice(r,r+s);r+=a.byteLength,yield new Uint8Array(a)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let a=await o.slice(r,Math.min(o.size,r+Cm)).arrayBuffer();r+=a.byteLength,yield new Uint8Array(a)}}}var wx,Cm,wm,Jw,qt,zo=Me(()=>{wx=Oe(bm(),1);Cm=65536;wm=class Bc{#e=[];#t="";#n=0;#r="transparent";constructor(e=[],n={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof n!="object"&&typeof n!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");n===null&&(n={});let r=new TextEncoder;for(let s of e){let a;ArrayBuffer.isView(s)?a=new Uint8Array(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)):s instanceof ArrayBuffer?a=new Uint8Array(s.slice(0)):s instanceof Bc?a=s:a=r.encode(`${s}`),this.#n+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#r=`${n.endings===void 0?"transparent":n.endings}`;let o=n.type===void 0?"":String(n.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#n}get type(){return this.#t}async text(){let e=new TextDecoder,n="";for await(let r of Nc(this.#e,!1))n+=e.decode(r,{stream:!0});return n+=e.decode(),n}async arrayBuffer(){let e=new Uint8Array(this.size),n=0;for await(let r of Nc(this.#e,!1))e.set(r,n),n+=r.length;return e.buffer}stream(){let e=Nc(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(n){let r=await e.next();r.done?n.close():n.enqueue(r.value)},async cancel(){await e.return()}})}slice(e=0,n=this.size,r=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=n<0?Math.max(o+n,0):Math.min(n,o),c=Math.max(a-s,0),l=this.#e,d=[],f=0;for(let m of l){if(f>=c)break;let b=ArrayBuffer.isView(m)?m.byteLength:m.size;if(s&&b<=s)s-=b,a-=b;else{let C;ArrayBuffer.isView(m)?(C=m.subarray(s,Math.min(b,a)),f+=C.byteLength):(C=m.slice(s,Math.min(b,a)),f+=C.size),a-=b,d.push(C),s=0}}let p=new Bc([],{type:String(r).toLowerCase()});return p.#n=c,p.#e=d,p}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(wm.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Jw=wm,qt=Jw});var Vw,Kw,Vn,Mc=Me(()=>{zo();Vw=class extends qt{#e=0;#t="";constructor(e,n,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),r===null&&(r={});let o=r.lastModified===void 0?Date.now():Number(r.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(n)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof qt&&/^(File)$/.test(e[Symbol.toStringTag])}},Kw=Vw,Vn=Kw});function Sm(t,e=qt){var n=`${Em()}${Em()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
27
27
  Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?r.push(o+Lc(a)+`"\r
28
28
  \r
29
29
  ${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
@@ -33,32 +33,32 @@ Content-Type: ${s.type||"application/octet-stream"}\r
33
33
  \r
34
34
  `,s,`\r
35
35
  `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}var Wo,Yw,Qw,Em,Xw,Am,Lc,_r,Kn,Bi=Me(()=>{zo();Mc();({toStringTag:Wo,iterator:Yw,hasInstance:Qw}=Symbol),Em=Math.random,Xw="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Am=(t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[Wo])?[(n=n!==void 0?n+"":e[Wo]=="File"?e.name:"blob",t),e.name!==n||e[Wo]=="blob"?new Vn([e],n,e):e]:[t,e+""]),Lc=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
36
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),_r=(t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},Kn=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Wo](){return"FormData"}[Yw](){return this.entries()}static[Qw](e){return e&&typeof e=="object"&&e[Wo]==="FormData"&&!Xw.some(n=>typeof e[n]!="function")}append(...e){_r("append",arguments,2),this.#e.push(Am(...e))}delete(e){_r("delete",arguments,1),e+="",this.#e=this.#e.filter(([n])=>n!==e)}get(e){_r("get",arguments,1),e+="";for(var n=this.#e,r=n.length,o=0;o<r;o++)if(n[o][0]===e)return n[o][1];return null}getAll(e,n){return _r("getAll",arguments,1),n=[],e+="",this.#e.forEach(r=>r[0]===e&&n.push(r[1])),n}has(e){return _r("has",arguments,1),e+="",this.#e.some(n=>n[0]===e)}forEach(e,n){_r("forEach",arguments,1);for(var[r,o]of this)e.call(n,o,r,this)}set(...e){_r("set",arguments,2);var n=[],r=!0;e=Am(...e),this.#e.forEach(o=>{o[0]===e[0]?r&&(r=!n.push(e)):n.push(o)}),r&&n.push(e),this.#e=n}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var kn,Mi=Me(()=>{kn=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var rt,jc=Me(()=>{Mi();rt=class extends kn{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}});var Li,$c,Go,km,vm,Tm,ji=Me(()=>{Li=Symbol.toStringTag,$c=t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[Li]==="URLSearchParams",Go=t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[Li]),km=t=>typeof t=="object"&&(t[Li]==="AbortSignal"||t[Li]==="EventTarget"),vm=(t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},Tm=(t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r}});var Rm=K((Ix,Dm)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Dm.exports=globalThis.DOMException});var br,xm,Om,Uc,Pm,Fm,Im,Nm,Bm,Mm,$i,qc=Me(()=>{br=require("node:fs"),xm=require("node:path"),Om=Oe(Rm(),1);Mc();zo();({stat:Uc}=br.promises),Pm=(t,e)=>Bm((0,br.statSync)(t),t,e),Fm=(t,e)=>Uc(t).then(n=>Bm(n,t,e)),Im=(t,e)=>Uc(t).then(n=>Mm(n,t,e)),Nm=(t,e)=>Mm((0,br.statSync)(t),t,e),Bm=(t,e,n="")=>new qt([new $i({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),Mm=(t,e,n="")=>new Vn([new $i({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,xm.basename)(e),{type:n,lastModified:t.mtimeMs}),$i=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new t({path:this.#e,lastModified:this.lastModified,size:n-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await Uc(this.#e);if(e>this.lastModified)throw new Om.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,br.createReadStream)(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var jm={};ui(jm,{toFormData:()=>sE});function oE(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function sE(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new Hc(n[1]||n[2]),o,s,a,c,l,d,f=[],p=new Kn,g=m=>{a+=y.decode(m,{stream:!0})},_=m=>{f.push(m)},C=()=>{let m=new Vn(f,d,{type:l});p.append(c,m)},b=()=>{p.append(c,a)},y=new TextDecoder("utf-8");y.decode(),r.onPartBegin=function(){r.onPartData=g,r.onPartEnd=b,o="",s="",a="",c="",l="",d=null,f.length=0},r.onHeaderField=function(m){o+=y.decode(m,{stream:!0})},r.onHeaderValue=function(m){s+=y.decode(m,{stream:!0})},r.onHeaderEnd=function(){if(s+=y.decode(),o=o.toLowerCase(),o==="content-disposition"){let m=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),d=oE(s),d&&(r.onPartData=_,r.onPartEnd=C)}else o==="content-type"&&(l=s);s="",o=""};for await(let m of t)r.write(m);return r.end(),p}var en,Pe,Lm,Yn,Ui,qi,Zw,Jo,eE,tE,nE,rE,Cr,Hc,$m=Me(()=>{qc();Bi();en=0,Pe={START_BOUNDARY:en++,HEADER_FIELD_START:en++,HEADER_FIELD:en++,HEADER_VALUE_START:en++,HEADER_VALUE:en++,HEADER_VALUE_ALMOST_DONE:en++,HEADERS_ALMOST_DONE:en++,PART_DATA_START:en++,PART_DATA:en++,END:en++},Lm=1,Yn={PART_BOUNDARY:Lm,LAST_BOUNDARY:Lm*=2},Ui=10,qi=13,Zw=32,Jo=45,eE=58,tE=97,nE=122,rE=t=>t|32,Cr=()=>{},Hc=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Cr,this.onHeaderField=Cr,this.onHeadersEnd=Cr,this.onHeaderValue=Cr,this.onPartBegin=Cr,this.onPartData=Cr,this.onPartEnd=Cr,this.boundaryChars={},e=`\r
37
- --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Pe.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:d,flags:f}=this,p=this.boundary.length,g=p-1,_=e.length,C,b,y=A=>{this[A+"Mark"]=n},m=A=>{delete this[A+"Mark"]},k=(A,T,R,U)=>{(T===void 0||T!==R)&&this[A](U&&U.subarray(T,R))},w=(A,T)=>{let R=A+"Mark";R in this&&(T?(k(A,this[R],n,e),delete this[R]):(k(A,this[R],e.length,e),this[R]=0))};for(n=0;n<r;n++)switch(C=e[n],d){case Pe.START_BOUNDARY:if(l===a.length-2){if(C===Jo)f|=Yn.LAST_BOUNDARY;else if(C!==qi)return;l++;break}else if(l-1===a.length-2){if(f&Yn.LAST_BOUNDARY&&C===Jo)d=Pe.END,f=0;else if(!(f&Yn.LAST_BOUNDARY)&&C===Ui)l=0,k("onPartBegin"),d=Pe.HEADER_FIELD_START;else return;break}C!==a[l+2]&&(l=-2),C===a[l+2]&&l++;break;case Pe.HEADER_FIELD_START:d=Pe.HEADER_FIELD,y("onHeaderField"),l=0;case Pe.HEADER_FIELD:if(C===qi){m("onHeaderField"),d=Pe.HEADERS_ALMOST_DONE;break}if(l++,C===Jo)break;if(C===eE){if(l===1)return;w("onHeaderField",!0),d=Pe.HEADER_VALUE_START;break}if(b=rE(C),b<tE||b>nE)return;break;case Pe.HEADER_VALUE_START:if(C===Zw)break;y("onHeaderValue"),d=Pe.HEADER_VALUE;case Pe.HEADER_VALUE:C===qi&&(w("onHeaderValue",!0),k("onHeaderEnd"),d=Pe.HEADER_VALUE_ALMOST_DONE);break;case Pe.HEADER_VALUE_ALMOST_DONE:if(C!==Ui)return;d=Pe.HEADER_FIELD_START;break;case Pe.HEADERS_ALMOST_DONE:if(C!==Ui)return;k("onHeadersEnd"),d=Pe.PART_DATA_START;break;case Pe.PART_DATA_START:d=Pe.PART_DATA,y("onPartData");case Pe.PART_DATA:if(o=l,l===0){for(n+=g;n<_&&!(e[n]in c);)n+=p;n-=g,C=e[n]}if(l<a.length)a[l]===C?(l===0&&w("onPartData",!0),l++):l=0;else if(l===a.length)l++,C===qi?f|=Yn.PART_BOUNDARY:C===Jo?f|=Yn.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(f&Yn.PART_BOUNDARY){if(l=0,C===Ui){f&=~Yn.PART_BOUNDARY,k("onPartEnd"),k("onPartBegin"),d=Pe.HEADER_FIELD_START;break}}else f&Yn.LAST_BOUNDARY&&C===Jo?(k("onPartEnd"),d=Pe.END,f=0):l=0;if(l>0)s[l-1]=C;else if(o>0){let A=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);k("onPartData",0,o,A),o=0,y("onPartData"),n--}break;case Pe.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}w("onHeaderField"),w("onHeaderValue"),w("onPartData"),this.index=l,this.state=d,this.flags=f}end(){if(this.state===Pe.HEADER_FIELD_START&&this.index===0||this.state===Pe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Pe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});async function zc(t){if(t[ct].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[ct].disturbed=!0,t[ct].error)throw t[ct].error;let{body:e}=t;if(e===null)return pt.Buffer.alloc(0);if(!(e instanceof Rt.default))return pt.Buffer.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new rt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof kn?o:new rt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?pt.Buffer.from(n.join("")):pt.Buffer.concat(n,r)}catch(o){throw new rt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new rt(`Premature close of server response while trying to fetch ${t.url}`)}var Rt,vn,pt,iE,ct,tn,Zr,aE,Hi,Um,qm,zi=Me(()=>{Rt=Oe(require("node:stream"),1),vn=require("node:util"),pt=require("node:buffer");zo();Bi();jc();Mi();ji();iE=(0,vn.promisify)(Rt.default.pipeline),ct=Symbol("Body internals"),tn=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:$c(e)?e=pt.Buffer.from(e.toString()):Go(e)||pt.Buffer.isBuffer(e)||(vn.types.isAnyArrayBuffer(e)?e=pt.Buffer.from(e):ArrayBuffer.isView(e)?e=pt.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Rt.default||(e instanceof Kn?(e=Sm(e),r=e.type.split("=")[1]):e=pt.Buffer.from(String(e))));let o=e;pt.Buffer.isBuffer(e)?o=Rt.default.Readable.from(e):Go(e)&&(o=Rt.default.Readable.from(e.stream())),this[ct]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Rt.default&&e.on("error",s=>{let a=s instanceof kn?s:new rt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[ct].error=a})}get body(){return this[ct].stream}get bodyUsed(){return this[ct].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await zc(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Kn,o=new URLSearchParams(await this.text());for(let[s,a]of o)r.append(s,a);return r}let{toFormData:n}=await Promise.resolve().then(()=>($m(),jm));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[ct].body&&this[ct].body.type||"",n=await this.arrayBuffer();return new qt([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await zc(this);return new TextDecoder().decode(e)}buffer(){return zc(this)}};tn.prototype.buffer=(0,vn.deprecate)(tn.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(tn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,vn.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Zr=(t,e)=>{let n,r,{body:o}=t[ct];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Rt.default&&typeof o.getBoundary!="function"&&(n=new Rt.PassThrough({highWaterMark:e}),r=new Rt.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[ct].stream=n,o=r),o},aE=(0,vn.deprecate)(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),Hi=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":$c(t)?"application/x-www-form-urlencoded;charset=UTF-8":Go(t)?t.type||null:pt.Buffer.isBuffer(t)||vn.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Kn?`multipart/form-data; boundary=${e[ct].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${aE(t)}`:t instanceof Rt.default?null:"text/plain;charset=UTF-8",Um=t=>{let{body:e}=t[ct];return e===null?0:Go(e)?e.size:pt.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},qm=async(t,{body:e})=>{e===null?t.end():await iE(e,t)}});function Hm(t=[]){return new lt(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return Wi(e),Gc(e,String(n)),!0}catch{return!1}}))}var Wc,Vo,Wi,Gc,lt,Gi=Me(()=>{Wc=require("node:util"),Vo=Oe(require("node:http"),1),Wi=typeof Vo.default.validateHeaderName=="function"?Vo.default.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Gc=typeof Vo.default.validateHeaderValue=="function"?Vo.default.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},lt=class t extends URLSearchParams{constructor(e){let n=[];if(e instanceof t){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!Wc.types.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||Wc.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(Wi(r),Gc(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(a,c)=>(Wi(a),Gc(a,String(c)),URLSearchParams.prototype[o].call(r,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(Wi(a),URLSearchParams.prototype[o].call(r,String(a).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};Object.defineProperties(lt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var uE,Ko,Jc=Me(()=>{uE=new Set([301,302,303,307,308]),Ko=t=>uE.has(t)});var Ht,mt,zm=Me(()=>{Gi();zi();Jc();Ht=Symbol("Response internals"),mt=class t extends tn{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new lt(n.headers);if(e!==null&&!o.has("Content-Type")){let s=Hi(e,this);s&&o.append("Content-Type",s)}this[Ht]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[Ht].type}get url(){return this[Ht].url||""}get status(){return this[Ht].status}get ok(){return this[Ht].status>=200&&this[Ht].status<300}get redirected(){return this[Ht].counter>0}get statusText(){return this[Ht].statusText}get headers(){return this[Ht].headers}get highWaterMark(){return this[Ht].highWaterMark}clone(){return new t(Zr(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,n=302){if(!Ko(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new t(null,{status:0,statusText:""});return e[Ht].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new lt(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(mt.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var Wm,Gm=Me(()=>{Wm=t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""}});function Jm(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function Qm(t){if(!Km.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function cE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,Vm.isIP)(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function eo(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:cE(t)}function Xm(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Jm(o),a=Jm(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),n&&(a=n(a));let c=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return eo(s)&&!eo(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:eo(s)&&!eo(c)?"no-referrer":a;case"same-origin":return s.origin===c.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===c.origin?s:a;case"no-referrer-when-downgrade":return eo(s)&&!eo(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function Zm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&Km.has(r)&&(n=r);return n}var Vm,Km,Ym,Vc=Me(()=>{Vm=require("node:net");Km=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Ym="strict-origin-when-cross-origin"});var eg,tg,Ke,Yo,lE,Qn,ng,rg=Me(()=>{eg=require("node:url"),tg=require("node:util");Gi();zi();ji();Gm();Vc();Ke=Symbol("Request internals"),Yo=t=>typeof t=="object"&&typeof t[Ke]=="object",lE=(0,tg.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Qn=class t extends tn{constructor(e,n={}){let r;if(Yo(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!Yo(n)&&"data"in n&&lE(),(n.body!=null||Yo(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:Yo(e)&&e.body!==null?Zr(e):null;super(s,{size:n.size||e.size||0});let a=new lt(n.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let d=Hi(s,this);d&&a.set("Content-Type",d)}let c=Yo(e)?e.signal:null;if("signal"in n&&(c=n.signal),c!=null&&!km(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=n.referrer==null?e.referrer:n.referrer;if(l==="")l="no-referrer";else if(l){let d=new URL(l);l=/^about:(\/\/)?client$/.test(d)?"client":d}else l=void 0;this[Ke]={method:o,redirect:n.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:c,referrer:l},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ke].method}get url(){return(0,eg.format)(this[Ke].parsedURL)}get headers(){return this[Ke].headers}get redirect(){return this[Ke].redirect}get signal(){return this[Ke].signal}get referrer(){if(this[Ke].referrer==="no-referrer")return"";if(this[Ke].referrer==="client")return"about:client";if(this[Ke].referrer)return this[Ke].referrer.toString()}get referrerPolicy(){return this[Ke].referrerPolicy}set referrerPolicy(e){this[Ke].referrerPolicy=Qm(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Qn.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});ng=t=>{let{parsedURL:e}=t[Ke],n=new lt(t[Ke].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let c=Um(t);typeof c=="number"&&!Number.isNaN(c)&&(r=String(c))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=Ym),t.referrer&&t.referrer!=="no-referrer"?t[Ke].referrer=Xm(t):t[Ke].referrer="no-referrer",t[Ke].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=Wm(e),a={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var Qo,og=Me(()=>{Mi();Qo=class extends kn{constructor(e,n="aborted"){super(e,n)}}});var ag={};ui(ag,{AbortError:()=>Qo,Blob:()=>qt,FetchError:()=>rt,File:()=>Vn,FormData:()=>Kn,Headers:()=>lt,Request:()=>Qn,Response:()=>mt,blobFrom:()=>Fm,blobFromSync:()=>Pm,default:()=>Kc,fileFrom:()=>Im,fileFromSync:()=>Nm,isRedirect:()=>Ko});async function Kc(t,e){return new Promise((n,r)=>{let o=new Qn(t,e),{parsedURL:s,options:a}=ng(o);if(!dE.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let C=mm(o.url),b=new mt(C,{headers:{"Content-Type":C.typeFull}});n(b);return}let c=(s.protocol==="https:"?ig.default:sg.default).request,{signal:l}=o,d=null,f=()=>{let C=new Qo("The operation was aborted.");r(C),o.body&&o.body instanceof gt.default.Readable&&o.body.destroy(C),!(!d||!d.body)&&d.body.emit("error",C)};if(l&&l.aborted){f();return}let p=()=>{f(),_()},g=c(s.toString(),a);l&&l.addEventListener("abort",p);let _=()=>{g.abort(),l&&l.removeEventListener("abort",p)};g.on("error",C=>{r(new rt(`request to ${o.url} failed, reason: ${C.message}`,"system",C)),_()}),fE(g,C=>{d&&d.body&&d.body.destroy(C)}),process.version<"v14"&&g.on("socket",C=>{let b;C.prependListener("end",()=>{b=C._eventsCount}),C.prependListener("close",y=>{if(d&&b<C._eventsCount&&!y){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",m)}})}),g.on("response",C=>{g.setTimeout(0);let b=Hm(C.rawHeaders);if(Ko(C.statusCode)){let A=b.get("Location"),T=null;try{T=A===null?null:new URL(A,o.url)}catch{if(o.redirect!=="manual"){r(new rt(`uri requested responds with an invalid redirect URL: ${A}`,"invalid-redirect")),_();return}}switch(o.redirect){case"error":r(new rt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),_();return;case"manual":break;case"follow":{if(T===null)break;if(o.counter>=o.follow){r(new rt(`maximum redirect reached at: ${o.url}`,"max-redirect")),_();return}let R={headers:new lt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Zr(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!vm(o.url,T)||!Tm(o.url,T))for(let J of["authorization","www-authenticate","cookie","cookie2"])R.headers.delete(J);if(C.statusCode!==303&&o.body&&e.body instanceof gt.default.Readable){r(new rt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),_();return}(C.statusCode===303||(C.statusCode===301||C.statusCode===302)&&o.method==="POST")&&(R.method="GET",R.body=void 0,R.headers.delete("content-length"));let U=Zm(b);U&&(R.referrerPolicy=U),n(Kc(new Qn(T,R))),_();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&C.once("end",()=>{l.removeEventListener("abort",p)});let y=(0,gt.pipeline)(C,new gt.PassThrough,A=>{A&&r(A)});process.version<"v12.10"&&C.on("aborted",p);let m={url:o.url,status:C.statusCode,statusText:C.statusMessage,headers:b,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},k=b.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||k===null||C.statusCode===204||C.statusCode===304){d=new mt(y,m),n(d);return}let w={flush:wr.default.Z_SYNC_FLUSH,finishFlush:wr.default.Z_SYNC_FLUSH};if(k==="gzip"||k==="x-gzip"){y=(0,gt.pipeline)(y,wr.default.createGunzip(w),A=>{A&&r(A)}),d=new mt(y,m),n(d);return}if(k==="deflate"||k==="x-deflate"){let A=(0,gt.pipeline)(C,new gt.PassThrough,T=>{T&&r(T)});A.once("data",T=>{(T[0]&15)===8?y=(0,gt.pipeline)(y,wr.default.createInflate(),R=>{R&&r(R)}):y=(0,gt.pipeline)(y,wr.default.createInflateRaw(),R=>{R&&r(R)}),d=new mt(y,m),n(d)}),A.once("end",()=>{d||(d=new mt(y,m),n(d))});return}if(k==="br"){y=(0,gt.pipeline)(y,wr.default.createBrotliDecompress(),A=>{A&&r(A)}),d=new mt(y,m),n(d);return}d=new mt(y,m),n(d)}),qm(g,o).catch(r)})}function fE(t,e){let n=Xo.Buffer.from(`0\r
36
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),_r=(t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},Kn=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Wo](){return"FormData"}[Yw](){return this.entries()}static[Qw](e){return e&&typeof e=="object"&&e[Wo]==="FormData"&&!Xw.some(n=>typeof e[n]!="function")}append(...e){_r("append",arguments,2),this.#e.push(Am(...e))}delete(e){_r("delete",arguments,1),e+="",this.#e=this.#e.filter(([n])=>n!==e)}get(e){_r("get",arguments,1),e+="";for(var n=this.#e,r=n.length,o=0;o<r;o++)if(n[o][0]===e)return n[o][1];return null}getAll(e,n){return _r("getAll",arguments,1),n=[],e+="",this.#e.forEach(r=>r[0]===e&&n.push(r[1])),n}has(e){return _r("has",arguments,1),e+="",this.#e.some(n=>n[0]===e)}forEach(e,n){_r("forEach",arguments,1);for(var[r,o]of this)e.call(n,o,r,this)}set(...e){_r("set",arguments,2);var n=[],r=!0;e=Am(...e),this.#e.forEach(o=>{o[0]===e[0]?r&&(r=!n.push(e)):n.push(o)}),r&&n.push(e),this.#e=n}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var kn,Mi=Me(()=>{kn=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var rt,jc=Me(()=>{Mi();rt=class extends kn{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}});var Li,$c,Go,km,vm,Tm,ji=Me(()=>{Li=Symbol.toStringTag,$c=t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[Li]==="URLSearchParams",Go=t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[Li]),km=t=>typeof t=="object"&&(t[Li]==="AbortSignal"||t[Li]==="EventTarget"),vm=(t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},Tm=(t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r}});var Rm=K((Ix,Dm)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Dm.exports=globalThis.DOMException});var br,xm,Om,Uc,Pm,Fm,Im,Nm,Bm,Mm,$i,qc=Me(()=>{br=require("node:fs"),xm=require("node:path"),Om=Oe(Rm(),1);Mc();zo();({stat:Uc}=br.promises),Pm=(t,e)=>Bm((0,br.statSync)(t),t,e),Fm=(t,e)=>Uc(t).then(n=>Bm(n,t,e)),Im=(t,e)=>Uc(t).then(n=>Mm(n,t,e)),Nm=(t,e)=>Mm((0,br.statSync)(t),t,e),Bm=(t,e,n="")=>new qt([new $i({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),Mm=(t,e,n="")=>new Vn([new $i({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,xm.basename)(e),{type:n,lastModified:t.mtimeMs}),$i=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new t({path:this.#e,lastModified:this.lastModified,size:n-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await Uc(this.#e);if(e>this.lastModified)throw new Om.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,br.createReadStream)(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var jm={};ui(jm,{toFormData:()=>sE});function oE(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function sE(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new Hc(n[1]||n[2]),o,s,a,c,l,d,f=[],p=new Kn,m=g=>{a+=_.decode(g,{stream:!0})},b=g=>{f.push(g)},C=()=>{let g=new Vn(f,d,{type:l});p.append(c,g)},y=()=>{p.append(c,a)},_=new TextDecoder("utf-8");_.decode(),r.onPartBegin=function(){r.onPartData=m,r.onPartEnd=y,o="",s="",a="",c="",l="",d=null,f.length=0},r.onHeaderField=function(g){o+=_.decode(g,{stream:!0})},r.onHeaderValue=function(g){s+=_.decode(g,{stream:!0})},r.onHeaderEnd=function(){if(s+=_.decode(),o=o.toLowerCase(),o==="content-disposition"){let g=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);g&&(c=g[2]||g[3]||""),d=oE(s),d&&(r.onPartData=b,r.onPartEnd=C)}else o==="content-type"&&(l=s);s="",o=""};for await(let g of t)r.write(g);return r.end(),p}var en,Pe,Lm,Yn,Ui,qi,Zw,Jo,eE,tE,nE,rE,Cr,Hc,$m=Me(()=>{qc();Bi();en=0,Pe={START_BOUNDARY:en++,HEADER_FIELD_START:en++,HEADER_FIELD:en++,HEADER_VALUE_START:en++,HEADER_VALUE:en++,HEADER_VALUE_ALMOST_DONE:en++,HEADERS_ALMOST_DONE:en++,PART_DATA_START:en++,PART_DATA:en++,END:en++},Lm=1,Yn={PART_BOUNDARY:Lm,LAST_BOUNDARY:Lm*=2},Ui=10,qi=13,Zw=32,Jo=45,eE=58,tE=97,nE=122,rE=t=>t|32,Cr=()=>{},Hc=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Cr,this.onHeaderField=Cr,this.onHeadersEnd=Cr,this.onHeaderValue=Cr,this.onPartBegin=Cr,this.onPartData=Cr,this.onPartEnd=Cr,this.boundaryChars={},e=`\r
37
+ --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Pe.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:d,flags:f}=this,p=this.boundary.length,m=p-1,b=e.length,C,y,_=E=>{this[E+"Mark"]=n},g=E=>{delete this[E+"Mark"]},S=(E,T,R,U)=>{(T===void 0||T!==R)&&this[E](U&&U.subarray(T,R))},w=(E,T)=>{let R=E+"Mark";R in this&&(T?(S(E,this[R],n,e),delete this[R]):(S(E,this[R],e.length,e),this[R]=0))};for(n=0;n<r;n++)switch(C=e[n],d){case Pe.START_BOUNDARY:if(l===a.length-2){if(C===Jo)f|=Yn.LAST_BOUNDARY;else if(C!==qi)return;l++;break}else if(l-1===a.length-2){if(f&Yn.LAST_BOUNDARY&&C===Jo)d=Pe.END,f=0;else if(!(f&Yn.LAST_BOUNDARY)&&C===Ui)l=0,S("onPartBegin"),d=Pe.HEADER_FIELD_START;else return;break}C!==a[l+2]&&(l=-2),C===a[l+2]&&l++;break;case Pe.HEADER_FIELD_START:d=Pe.HEADER_FIELD,_("onHeaderField"),l=0;case Pe.HEADER_FIELD:if(C===qi){g("onHeaderField"),d=Pe.HEADERS_ALMOST_DONE;break}if(l++,C===Jo)break;if(C===eE){if(l===1)return;w("onHeaderField",!0),d=Pe.HEADER_VALUE_START;break}if(y=rE(C),y<tE||y>nE)return;break;case Pe.HEADER_VALUE_START:if(C===Zw)break;_("onHeaderValue"),d=Pe.HEADER_VALUE;case Pe.HEADER_VALUE:C===qi&&(w("onHeaderValue",!0),S("onHeaderEnd"),d=Pe.HEADER_VALUE_ALMOST_DONE);break;case Pe.HEADER_VALUE_ALMOST_DONE:if(C!==Ui)return;d=Pe.HEADER_FIELD_START;break;case Pe.HEADERS_ALMOST_DONE:if(C!==Ui)return;S("onHeadersEnd"),d=Pe.PART_DATA_START;break;case Pe.PART_DATA_START:d=Pe.PART_DATA,_("onPartData");case Pe.PART_DATA:if(o=l,l===0){for(n+=m;n<b&&!(e[n]in c);)n+=p;n-=m,C=e[n]}if(l<a.length)a[l]===C?(l===0&&w("onPartData",!0),l++):l=0;else if(l===a.length)l++,C===qi?f|=Yn.PART_BOUNDARY:C===Jo?f|=Yn.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(f&Yn.PART_BOUNDARY){if(l=0,C===Ui){f&=~Yn.PART_BOUNDARY,S("onPartEnd"),S("onPartBegin"),d=Pe.HEADER_FIELD_START;break}}else f&Yn.LAST_BOUNDARY&&C===Jo?(S("onPartEnd"),d=Pe.END,f=0):l=0;if(l>0)s[l-1]=C;else if(o>0){let E=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);S("onPartData",0,o,E),o=0,_("onPartData"),n--}break;case Pe.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}w("onHeaderField"),w("onHeaderValue"),w("onPartData"),this.index=l,this.state=d,this.flags=f}end(){if(this.state===Pe.HEADER_FIELD_START&&this.index===0||this.state===Pe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Pe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});async function zc(t){if(t[ct].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[ct].disturbed=!0,t[ct].error)throw t[ct].error;let{body:e}=t;if(e===null)return pt.Buffer.alloc(0);if(!(e instanceof Rt.default))return pt.Buffer.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new rt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof kn?o:new rt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?pt.Buffer.from(n.join("")):pt.Buffer.concat(n,r)}catch(o){throw new rt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new rt(`Premature close of server response while trying to fetch ${t.url}`)}var Rt,vn,pt,iE,ct,tn,Zr,aE,Hi,Um,qm,zi=Me(()=>{Rt=Oe(require("node:stream"),1),vn=require("node:util"),pt=require("node:buffer");zo();Bi();jc();Mi();ji();iE=(0,vn.promisify)(Rt.default.pipeline),ct=Symbol("Body internals"),tn=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:$c(e)?e=pt.Buffer.from(e.toString()):Go(e)||pt.Buffer.isBuffer(e)||(vn.types.isAnyArrayBuffer(e)?e=pt.Buffer.from(e):ArrayBuffer.isView(e)?e=pt.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Rt.default||(e instanceof Kn?(e=Sm(e),r=e.type.split("=")[1]):e=pt.Buffer.from(String(e))));let o=e;pt.Buffer.isBuffer(e)?o=Rt.default.Readable.from(e):Go(e)&&(o=Rt.default.Readable.from(e.stream())),this[ct]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Rt.default&&e.on("error",s=>{let a=s instanceof kn?s:new rt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[ct].error=a})}get body(){return this[ct].stream}get bodyUsed(){return this[ct].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await zc(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Kn,o=new URLSearchParams(await this.text());for(let[s,a]of o)r.append(s,a);return r}let{toFormData:n}=await Promise.resolve().then(()=>($m(),jm));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[ct].body&&this[ct].body.type||"",n=await this.arrayBuffer();return new qt([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await zc(this);return new TextDecoder().decode(e)}buffer(){return zc(this)}};tn.prototype.buffer=(0,vn.deprecate)(tn.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(tn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,vn.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Zr=(t,e)=>{let n,r,{body:o}=t[ct];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Rt.default&&typeof o.getBoundary!="function"&&(n=new Rt.PassThrough({highWaterMark:e}),r=new Rt.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[ct].stream=n,o=r),o},aE=(0,vn.deprecate)(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),Hi=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":$c(t)?"application/x-www-form-urlencoded;charset=UTF-8":Go(t)?t.type||null:pt.Buffer.isBuffer(t)||vn.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Kn?`multipart/form-data; boundary=${e[ct].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${aE(t)}`:t instanceof Rt.default?null:"text/plain;charset=UTF-8",Um=t=>{let{body:e}=t[ct];return e===null?0:Go(e)?e.size:pt.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},qm=async(t,{body:e})=>{e===null?t.end():await iE(e,t)}});function Hm(t=[]){return new lt(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return Wi(e),Gc(e,String(n)),!0}catch{return!1}}))}var Wc,Vo,Wi,Gc,lt,Gi=Me(()=>{Wc=require("node:util"),Vo=Oe(require("node:http"),1),Wi=typeof Vo.default.validateHeaderName=="function"?Vo.default.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Gc=typeof Vo.default.validateHeaderValue=="function"?Vo.default.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},lt=class t extends URLSearchParams{constructor(e){let n=[];if(e instanceof t){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!Wc.types.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||Wc.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(Wi(r),Gc(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(a,c)=>(Wi(a),Gc(a,String(c)),URLSearchParams.prototype[o].call(r,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(Wi(a),URLSearchParams.prototype[o].call(r,String(a).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};Object.defineProperties(lt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var uE,Ko,Jc=Me(()=>{uE=new Set([301,302,303,307,308]),Ko=t=>uE.has(t)});var Ht,mt,zm=Me(()=>{Gi();zi();Jc();Ht=Symbol("Response internals"),mt=class t extends tn{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new lt(n.headers);if(e!==null&&!o.has("Content-Type")){let s=Hi(e,this);s&&o.append("Content-Type",s)}this[Ht]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[Ht].type}get url(){return this[Ht].url||""}get status(){return this[Ht].status}get ok(){return this[Ht].status>=200&&this[Ht].status<300}get redirected(){return this[Ht].counter>0}get statusText(){return this[Ht].statusText}get headers(){return this[Ht].headers}get highWaterMark(){return this[Ht].highWaterMark}clone(){return new t(Zr(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,n=302){if(!Ko(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new t(null,{status:0,statusText:""});return e[Ht].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new lt(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(mt.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var Wm,Gm=Me(()=>{Wm=t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""}});function Jm(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function Qm(t){if(!Km.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function cE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,Vm.isIP)(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function eo(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:cE(t)}function Xm(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Jm(o),a=Jm(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),n&&(a=n(a));let c=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return eo(s)&&!eo(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:eo(s)&&!eo(c)?"no-referrer":a;case"same-origin":return s.origin===c.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===c.origin?s:a;case"no-referrer-when-downgrade":return eo(s)&&!eo(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function Zm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&Km.has(r)&&(n=r);return n}var Vm,Km,Ym,Vc=Me(()=>{Vm=require("node:net");Km=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Ym="strict-origin-when-cross-origin"});var eg,tg,Ke,Yo,lE,Qn,ng,rg=Me(()=>{eg=require("node:url"),tg=require("node:util");Gi();zi();ji();Gm();Vc();Ke=Symbol("Request internals"),Yo=t=>typeof t=="object"&&typeof t[Ke]=="object",lE=(0,tg.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Qn=class t extends tn{constructor(e,n={}){let r;if(Yo(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!Yo(n)&&"data"in n&&lE(),(n.body!=null||Yo(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:Yo(e)&&e.body!==null?Zr(e):null;super(s,{size:n.size||e.size||0});let a=new lt(n.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let d=Hi(s,this);d&&a.set("Content-Type",d)}let c=Yo(e)?e.signal:null;if("signal"in n&&(c=n.signal),c!=null&&!km(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=n.referrer==null?e.referrer:n.referrer;if(l==="")l="no-referrer";else if(l){let d=new URL(l);l=/^about:(\/\/)?client$/.test(d)?"client":d}else l=void 0;this[Ke]={method:o,redirect:n.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:c,referrer:l},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[Ke].method}get url(){return(0,eg.format)(this[Ke].parsedURL)}get headers(){return this[Ke].headers}get redirect(){return this[Ke].redirect}get signal(){return this[Ke].signal}get referrer(){if(this[Ke].referrer==="no-referrer")return"";if(this[Ke].referrer==="client")return"about:client";if(this[Ke].referrer)return this[Ke].referrer.toString()}get referrerPolicy(){return this[Ke].referrerPolicy}set referrerPolicy(e){this[Ke].referrerPolicy=Qm(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Qn.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});ng=t=>{let{parsedURL:e}=t[Ke],n=new lt(t[Ke].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let c=Um(t);typeof c=="number"&&!Number.isNaN(c)&&(r=String(c))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=Ym),t.referrer&&t.referrer!=="no-referrer"?t[Ke].referrer=Xm(t):t[Ke].referrer="no-referrer",t[Ke].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=Wm(e),a={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var Qo,og=Me(()=>{Mi();Qo=class extends kn{constructor(e,n="aborted"){super(e,n)}}});var ag={};ui(ag,{AbortError:()=>Qo,Blob:()=>qt,FetchError:()=>rt,File:()=>Vn,FormData:()=>Kn,Headers:()=>lt,Request:()=>Qn,Response:()=>mt,blobFrom:()=>Fm,blobFromSync:()=>Pm,default:()=>Kc,fileFrom:()=>Im,fileFromSync:()=>Nm,isRedirect:()=>Ko});async function Kc(t,e){return new Promise((n,r)=>{let o=new Qn(t,e),{parsedURL:s,options:a}=ng(o);if(!dE.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let C=mm(o.url),y=new mt(C,{headers:{"Content-Type":C.typeFull}});n(y);return}let c=(s.protocol==="https:"?ig.default:sg.default).request,{signal:l}=o,d=null,f=()=>{let C=new Qo("The operation was aborted.");r(C),o.body&&o.body instanceof gt.default.Readable&&o.body.destroy(C),!(!d||!d.body)&&d.body.emit("error",C)};if(l&&l.aborted){f();return}let p=()=>{f(),b()},m=c(s.toString(),a);l&&l.addEventListener("abort",p);let b=()=>{m.abort(),l&&l.removeEventListener("abort",p)};m.on("error",C=>{r(new rt(`request to ${o.url} failed, reason: ${C.message}`,"system",C)),b()}),fE(m,C=>{d&&d.body&&d.body.destroy(C)}),process.version<"v14"&&m.on("socket",C=>{let y;C.prependListener("end",()=>{y=C._eventsCount}),C.prependListener("close",_=>{if(d&&y<C._eventsCount&&!_){let g=new Error("Premature close");g.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",g)}})}),m.on("response",C=>{m.setTimeout(0);let y=Hm(C.rawHeaders);if(Ko(C.statusCode)){let E=y.get("Location"),T=null;try{T=E===null?null:new URL(E,o.url)}catch{if(o.redirect!=="manual"){r(new rt(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),b();return}}switch(o.redirect){case"error":r(new rt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),b();return;case"manual":break;case"follow":{if(T===null)break;if(o.counter>=o.follow){r(new rt(`maximum redirect reached at: ${o.url}`,"max-redirect")),b();return}let R={headers:new lt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Zr(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!vm(o.url,T)||!Tm(o.url,T))for(let J of["authorization","www-authenticate","cookie","cookie2"])R.headers.delete(J);if(C.statusCode!==303&&o.body&&e.body instanceof gt.default.Readable){r(new rt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),b();return}(C.statusCode===303||(C.statusCode===301||C.statusCode===302)&&o.method==="POST")&&(R.method="GET",R.body=void 0,R.headers.delete("content-length"));let U=Zm(y);U&&(R.referrerPolicy=U),n(Kc(new Qn(T,R))),b();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&C.once("end",()=>{l.removeEventListener("abort",p)});let _=(0,gt.pipeline)(C,new gt.PassThrough,E=>{E&&r(E)});process.version<"v12.10"&&C.on("aborted",p);let g={url:o.url,status:C.statusCode,statusText:C.statusMessage,headers:y,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},S=y.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||S===null||C.statusCode===204||C.statusCode===304){d=new mt(_,g),n(d);return}let w={flush:wr.default.Z_SYNC_FLUSH,finishFlush:wr.default.Z_SYNC_FLUSH};if(S==="gzip"||S==="x-gzip"){_=(0,gt.pipeline)(_,wr.default.createGunzip(w),E=>{E&&r(E)}),d=new mt(_,g),n(d);return}if(S==="deflate"||S==="x-deflate"){let E=(0,gt.pipeline)(C,new gt.PassThrough,T=>{T&&r(T)});E.once("data",T=>{(T[0]&15)===8?_=(0,gt.pipeline)(_,wr.default.createInflate(),R=>{R&&r(R)}):_=(0,gt.pipeline)(_,wr.default.createInflateRaw(),R=>{R&&r(R)}),d=new mt(_,g),n(d)}),E.once("end",()=>{d||(d=new mt(_,g),n(d))});return}if(S==="br"){_=(0,gt.pipeline)(_,wr.default.createBrotliDecompress(),E=>{E&&r(E)}),d=new mt(_,g),n(d);return}d=new mt(_,g),n(d)}),qm(m,o).catch(r)})}function fE(t,e){let n=Xo.Buffer.from(`0\r
38
38
  \r
39
39
  `),r=!1,o=!1,s;t.on("response",a=>{let{headers:c}=a;r=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",a=>{let c=()=>{if(r&&!o){let d=new Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",e(d)}},l=d=>{o=Xo.Buffer.compare(d.slice(-5),n)===0,!o&&s&&(o=Xo.Buffer.compare(s.slice(-3),n.slice(0,3))===0&&Xo.Buffer.compare(d.slice(-2),n.slice(3))===0),s=d};a.prependListener("close",c),a.on("data",l),t.on("close",()=>{a.removeListener("close",c),a.removeListener("data",l)})})}var sg,ig,wr,gt,Xo,dE,ug=Me(()=>{sg=Oe(require("node:http"),1),ig=Oe(require("node:https"),1),wr=Oe(require("node:zlib"),1),gt=Oe(require("node:stream"),1),Xo=require("node:buffer");gm();zi();zm();Gi();rg();jc();og();Jc();Bi();ji();Vc();qc();dE=new Set(["data:","http:","https:"])});var dg=K(no=>{"use strict";var hE=no&&no.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},to;Object.defineProperty(no,"__esModule",{value:!0});no.Gaxios=void 0;var pE=hE(Ec()),mE=require("https"),Er=kc(),gE=Hp(),cg=require("stream"),lg=Dc(),yE=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Ji=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new lg.GaxiosInterceptorManager,response:new lg.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&to.mergeHeaders(s,n.headers),r&&to.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await to.#u(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=o.toString()}let r=Er.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Er.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof Er.GaxiosError?r=n:n instanceof Error?r=new Er.GaxiosError(n.message,e,void 0,n):r=new Er.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,gE.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Er.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":return n.json();case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of s)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(r.toString()))return!1}else if(a instanceof URL){if(a.origin===r.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let c=a.replace(/^\*\./,".");if(r.hostname.endsWith(c))return!1}else if(a===r.origin||a===r.hostname||a===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);to.mergeHeaders(n,e.headers);let r=(0,pE.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let a=r.paramsSerializer(r.params);a.startsWith("?")&&(a=a.slice(1));let c=r.url.toString().includes("?")?"&":"?";r.url=r.url+c+a}else{let a=r.url instanceof URL?r.url:new URL(r.url);for(let[c,l]of new URLSearchParams(r.params))a.searchParams.append(c,l);r.url=a}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof cg.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let a=await yE();n.set("content-type",`multipart/related; boundary=${a}`),r.body=cg.Readable.from(this.getMultipartRequest(r.multipart,a))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let a=await to.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new a(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new mE.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=Er.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
40
40
  Content-Type: ${s}\r
41
41
  \r
42
42
  `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
43
- `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>Oe(pm()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(ug(),ag))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};no.Gaxios=Ji;to=Ji});var Qe=K(ot=>{"use strict";var _E=ot&&ot.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),bE=ot&&ot.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_E(e,t,n)};Object.defineProperty(ot,"__esModule",{value:!0});ot.instance=ot.Gaxios=ot.GaxiosError=void 0;ot.request=wE;var fg=dg();Object.defineProperty(ot,"Gaxios",{enumerable:!0,get:function(){return fg.Gaxios}});var CE=kc();Object.defineProperty(ot,"GaxiosError",{enumerable:!0,get:function(){return CE.GaxiosError}});bE(Dc(),ot);ot.instance=new fg.Gaxios;async function wE(t){return ot.instance.request(t)}});var Yc=K((hg,Vi)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,g=1e9;function _(T){var R,U,J,F=G.prototype={constructor:G,toString:null,valueOf:null},V=new G(1),Y=20,X=4,ee=-7,de=21,Ae=-1e7,ae=1e7,pe=!1,W=1,Q=0,re={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},$e="0123456789abcdefghijklmnopqrstuvwxyz",ke=!0;function G(E,v){var D,M,P,N,$,O,I,L,B=this;if(!(B instanceof G))return new G(E,v);if(v==null){if(E&&E._isBigNumber===!0){B.s=E.s,!E.c||E.e>ae?B.c=B.e=null:E.e<Ae?B.c=[B.e=0]:(B.e=E.e,B.c=E.c.slice());return}if((O=typeof E=="number")&&E*0==0){if(B.s=1/E<0?(E=-E,-1):1,E===~~E){for(N=0,$=E;$>=10;$/=10,N++);N>ae?B.c=B.e=null:(B.e=N,B.c=[E]);return}L=String(E)}else{if(!n.test(L=String(E)))return J(B,L,O);B.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(N=L.indexOf("."))>-1&&(L=L.replace(".","")),($=L.search(/e/i))>0?(N<0&&(N=$),N+=+L.slice($+1),L=L.substring(0,$)):N<0&&(N=L.length)}else{if(m(v,2,$e.length,"Base"),v==10&&ke)return B=new G(E),Re(B,Y+B.e+1,X);if(L=String(E),O=typeof E=="number"){if(E*0!=0)return J(B,L,O,v);if(B.s=1/E<0?(L=L.slice(1),-1):1,G.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+E)}else B.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(D=$e.slice(0,v),N=$=0,I=L.length;$<I;$++)if(D.indexOf(M=L.charAt($))<0){if(M=="."){if($>N){N=I;continue}}else if(!P&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){P=!0,$=-1,N=0;continue}return J(B,String(E),O,v)}O=!1,L=U(L,v,10,B.s),(N=L.indexOf("."))>-1?L=L.replace(".",""):N=L.length}for($=0;L.charCodeAt($)===48;$++);for(I=L.length;L.charCodeAt(--I)===48;);if(L=L.slice($,++I)){if(I-=$,O&&G.DEBUG&&I>15&&(E>d||E!==o(E)))throw Error(a+B.s*E);if((N=N-$-1)>ae)B.c=B.e=null;else if(N<Ae)B.c=[B.e=0];else{if(B.e=N,B.c=[],$=(N+1)%l,N<0&&($+=l),$<I){for($&&B.c.push(+L.slice(0,$)),I-=l;$<I;)B.c.push(+L.slice($,$+=l));$=l-(L=L.slice($)).length}else $-=I;for(;$--;L+="0");B.c.push(+L)}}else B.c=[B.e=0]}G.clone=_,G.ROUND_UP=0,G.ROUND_DOWN=1,G.ROUND_CEIL=2,G.ROUND_FLOOR=3,G.ROUND_HALF_UP=4,G.ROUND_HALF_DOWN=5,G.ROUND_HALF_EVEN=6,G.ROUND_HALF_CEIL=7,G.ROUND_HALF_FLOOR=8,G.EUCLID=9,G.config=G.set=function(E){var v,D;if(E!=null)if(typeof E=="object"){if(E.hasOwnProperty(v="DECIMAL_PLACES")&&(D=E[v],m(D,0,g,v),Y=D),E.hasOwnProperty(v="ROUNDING_MODE")&&(D=E[v],m(D,0,8,v),X=D),E.hasOwnProperty(v="EXPONENTIAL_AT")&&(D=E[v],D&&D.pop?(m(D[0],-g,0,v),m(D[1],0,g,v),ee=D[0],de=D[1]):(m(D,-g,g,v),ee=-(de=D<0?-D:D))),E.hasOwnProperty(v="RANGE"))if(D=E[v],D&&D.pop)m(D[0],-g,-1,v),m(D[1],1,g,v),Ae=D[0],ae=D[1];else if(m(D,-g,g,v),D)Ae=-(ae=D<0?-D:D);else throw Error(s+v+" cannot be zero: "+D);if(E.hasOwnProperty(v="CRYPTO"))if(D=E[v],D===!!D)if(D)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))pe=D;else throw pe=!D,Error(s+"crypto unavailable");else pe=D;else throw Error(s+v+" not true or false: "+D);if(E.hasOwnProperty(v="MODULO_MODE")&&(D=E[v],m(D,0,9,v),W=D),E.hasOwnProperty(v="POW_PRECISION")&&(D=E[v],m(D,0,g,v),Q=D),E.hasOwnProperty(v="FORMAT"))if(D=E[v],typeof D=="object")re=D;else throw Error(s+v+" not an object: "+D);if(E.hasOwnProperty(v="ALPHABET"))if(D=E[v],typeof D=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(D))ke=D.slice(0,10)=="0123456789",$e=D;else throw Error(s+v+" invalid: "+D)}else throw Error(s+"Object expected: "+E);return{DECIMAL_PLACES:Y,ROUNDING_MODE:X,EXPONENTIAL_AT:[ee,de],RANGE:[Ae,ae],CRYPTO:pe,MODULO_MODE:W,POW_PRECISION:Q,FORMAT:re,ALPHABET:$e}},G.isBigNumber=function(E){if(!E||E._isBigNumber!==!0)return!1;if(!G.DEBUG)return!0;var v,D,M=E.c,P=E.e,N=E.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&P>=-g&&P<=g&&P===o(P)){if(M[0]===0){if(P===0&&M.length===1)return!0;break e}if(v=(P+1)%l,v<1&&(v+=l),String(M[0]).length==v){for(v=0;v<M.length;v++)if(D=M[v],D<0||D>=c||D!==o(D))break e;if(D!==0)return!0}}}else if(M===null&&P===null&&(N===null||N===1||N===-1))return!0;throw Error(s+"Invalid BigNumber: "+E)},G.maximum=G.max=function(){return _e(arguments,-1)},G.minimum=G.min=function(){return _e(arguments,1)},G.random=(function(){var E=9007199254740992,v=Math.random()*E&2097151?function(){return o(Math.random()*E)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var M,P,N,$,O,I=0,L=[],B=new G(V);if(D==null?D=Y:m(D,0,g),$=r(D/l),pe)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array($*=2));I<$;)O=M[I]*131072+(M[I+1]>>>11),O>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),M[I]=P[0],M[I+1]=P[1]):(L.push(O%1e14),I+=2);I=$/2}else if(crypto.randomBytes){for(M=crypto.randomBytes($*=7);I<$;)O=(M[I]&31)*281474976710656+M[I+1]*1099511627776+M[I+2]*4294967296+M[I+3]*16777216+(M[I+4]<<16)+(M[I+5]<<8)+M[I+6],O>=9e15?crypto.randomBytes(7).copy(M,I):(L.push(O%1e14),I+=7);I=$/7}else throw pe=!1,Error(s+"crypto unavailable");if(!pe)for(;I<$;)O=v(),O<9e15&&(L[I++]=O%1e14);for($=L[--I],D%=l,$&&D&&(O=f[l-D],L[I]=o($/O)*O);L[I]===0;L.pop(),I--);if(I<0)L=[N=0];else{for(N=-1;L[0]===0;L.splice(0,1),N-=l);for(I=1,O=L[0];O>=10;O/=10,I++);I<l&&(N-=l-I)}return B.e=N,B.c=L,B}})(),G.sum=function(){for(var E=1,v=arguments,D=new G(v[0]);E<v.length;)D=D.plus(v[E++]);return D},U=(function(){var E="0123456789";function v(D,M,P,N){for(var $,O=[0],I,L=0,B=D.length;L<B;){for(I=O.length;I--;O[I]*=M);for(O[0]+=N.indexOf(D.charAt(L++)),$=0;$<O.length;$++)O[$]>P-1&&(O[$+1]==null&&(O[$+1]=0),O[$+1]+=O[$]/P|0,O[$]%=P)}return O.reverse()}return function(D,M,P,N,$){var O,I,L,B,H,te,ne,Ee,Fe=D.indexOf("."),Be=Y,we=X;for(Fe>=0&&(B=Q,Q=0,D=D.replace(".",""),Ee=new G(M),te=Ee.pow(D.length-Fe),Q=B,Ee.c=v(A(b(te.c),te.e,"0"),10,P,E),Ee.e=Ee.c.length),ne=v(D,M,P,$?(O=$e,E):(O=E,$e)),L=B=ne.length;ne[--B]==0;ne.pop());if(!ne[0])return O.charAt(0);if(Fe<0?--L:(te.c=ne,te.e=L,te.s=N,te=R(te,Ee,Be,we,P),ne=te.c,H=te.r,L=te.e),I=L+Be+1,Fe=ne[I],B=P/2,H=H||I<0||ne[I+1]!=null,H=we<4?(Fe!=null||H)&&(we==0||we==(te.s<0?3:2)):Fe>B||Fe==B&&(we==4||H||we==6&&ne[I-1]&1||we==(te.s<0?8:7)),I<1||!ne[0])D=H?A(O.charAt(1),-Be,O.charAt(0)):O.charAt(0);else{if(ne.length=I,H)for(--P;++ne[--I]>P;)ne[I]=0,I||(++L,ne=[1].concat(ne));for(B=ne.length;!ne[--B];);for(Fe=0,D="";Fe<=B;D+=O.charAt(ne[Fe++]));D=A(D,L,O.charAt(0))}return D}})(),R=(function(){function E(M,P,N){var $,O,I,L,B=0,H=M.length,te=P%p,ne=P/p|0;for(M=M.slice();H--;)I=M[H]%p,L=M[H]/p|0,$=ne*I+L*te,O=te*I+$%p*p+B,B=(O/N|0)+($/p|0)+ne*L,M[H]=O%N;return B&&(M=[B].concat(M)),M}function v(M,P,N,$){var O,I;if(N!=$)I=N>$?1:-1;else for(O=I=0;O<N;O++)if(M[O]!=P[O]){I=M[O]>P[O]?1:-1;break}return I}function D(M,P,N,$){for(var O=0;N--;)M[N]-=O,O=M[N]<P[N]?1:0,M[N]=O*$+M[N]-P[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,P,N,$,O){var I,L,B,H,te,ne,Ee,Fe,Be,we,Se,Ue,Or,Pr,Fr,dt,hn,Xe=M.s==P.s?1:-1,qe=M.c,ve=P.c;if(!qe||!qe[0]||!ve||!ve[0])return new G(!M.s||!P.s||(qe?ve&&qe[0]==ve[0]:!ve)?NaN:qe&&qe[0]==0||!ve?Xe*0:Xe/0);for(Fe=new G(Xe),Be=Fe.c=[],L=M.e-P.e,Xe=N+L+1,O||(O=c,L=C(M.e/l)-C(P.e/l),Xe=Xe/l|0),B=0;ve[B]==(qe[B]||0);B++);if(ve[B]>(qe[B]||0)&&L--,Xe<0)Be.push(1),H=!0;else{for(Pr=qe.length,dt=ve.length,B=0,Xe+=2,te=o(O/(ve[0]+1)),te>1&&(ve=E(ve,te,O),qe=E(qe,te,O),dt=ve.length,Pr=qe.length),Or=dt,we=qe.slice(0,dt),Se=we.length;Se<dt;we[Se++]=0);hn=ve.slice(),hn=[0].concat(hn),Fr=ve[0],ve[1]>=O/2&&Fr++;do{if(te=0,I=v(ve,we,dt,Se),I<0){if(Ue=we[0],dt!=Se&&(Ue=Ue*O+(we[1]||0)),te=o(Ue/Fr),te>1)for(te>=O&&(te=O-1),ne=E(ve,te,O),Ee=ne.length,Se=we.length;v(ne,we,Ee,Se)==1;)te--,D(ne,dt<Ee?hn:ve,Ee,O),Ee=ne.length,I=1;else te==0&&(I=te=1),ne=ve.slice(),Ee=ne.length;if(Ee<Se&&(ne=[0].concat(ne)),D(we,ne,Se,O),Se=we.length,I==-1)for(;v(ve,we,dt,Se)<1;)te++,D(we,dt<Se?hn:ve,Se,O),Se=we.length}else I===0&&(te++,we=[0]);Be[B++]=te,we[0]?we[Se++]=qe[Or]||0:(we=[qe[Or]],Se=1)}while((Or++<Pr||we[0]!=null)&&Xe--);H=we[0]!=null,Be[0]||Be.splice(0,1)}if(O==c){for(B=1,Xe=Be[0];Xe>=10;Xe/=10,B++);Re(Fe,N+(Fe.e=B+L*l-1)+1,$,H)}else Fe.e=L,Fe.r=+H;return Fe}})();function le(E,v,D,M){var P,N,$,O,I;if(D==null?D=X:m(D,0,8),!E.c)return E.toString();if(P=E.c[0],$=E.e,v==null)I=b(E.c),I=M==1||M==2&&($<=ee||$>=de)?w(I,$):A(I,$,"0");else if(E=Re(new G(E),v,D),N=E.e,I=b(E.c),O=I.length,M==1||M==2&&(v<=N||N<=ee)){for(;O<v;I+="0",O++);I=w(I,N)}else if(v-=$+(M===2&&N>$),I=A(I,N,"0"),N+1>O){if(--v>0)for(I+=".";v--;I+="0");}else if(v+=N-O,v>0)for(N+1==O&&(I+=".");v--;I+="0");return E.s<0&&P?"-"+I:I}function _e(E,v){for(var D,M,P=1,N=new G(E[0]);P<E.length;P++)M=new G(E[P]),(!M.s||(D=y(N,M))===v||D===0&&N.s===v)&&(N=M);return N}function Bt(E,v,D){for(var M=1,P=v.length;!v[--P];v.pop());for(P=v[0];P>=10;P/=10,M++);return(D=M+D*l-1)>ae?E.c=E.e=null:D<Ae?E.c=[E.e=0]:(E.e=D,E.c=v),E}J=(function(){var E=/^(-?)0([xbo])(?=\w[\w.]*$)/i,v=/^([^.]+)\.$/,D=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,$,O,I){var L,B=O?$:$.replace(P,"");if(M.test(B))N.s=isNaN(B)?null:B<0?-1:1;else{if(!O&&(B=B.replace(E,function(H,te,ne){return L=(ne=ne.toLowerCase())=="x"?16:ne=="b"?2:8,!I||I==L?te:H}),I&&(L=I,B=B.replace(v,"$1").replace(D,"0.$1")),$!=B))return new G(B,L);if(G.DEBUG)throw Error(s+"Not a"+(I?" base "+I:"")+" number: "+$);N.s=null}N.c=N.e=null}})();function Re(E,v,D,M){var P,N,$,O,I,L,B,H=E.c,te=f;if(H){e:{for(P=1,O=H[0];O>=10;O/=10,P++);if(N=v-P,N<0)N+=l,$=v,I=H[L=0],B=o(I/te[P-$-1]%10);else if(L=r((N+1)/l),L>=H.length)if(M){for(;H.length<=L;H.push(0));I=B=0,P=1,N%=l,$=N-l+1}else break e;else{for(I=O=H[L],P=1;O>=10;O/=10,P++);N%=l,$=N-l+P,B=$<0?0:o(I/te[P-$-1]%10)}if(M=M||v<0||H[L+1]!=null||($<0?I:I%te[P-$-1]),M=D<4?(B||M)&&(D==0||D==(E.s<0?3:2)):B>5||B==5&&(D==4||M||D==6&&(N>0?$>0?I/te[P-$]:0:H[L-1])%10&1||D==(E.s<0?8:7)),v<1||!H[0])return H.length=0,M?(v-=E.e+1,H[0]=te[(l-v%l)%l],E.e=-v||0):H[0]=E.e=0,E;if(N==0?(H.length=L,O=1,L--):(H.length=L+1,O=te[l-N],H[L]=$>0?o(I/te[P-$]%te[$])*O:0),M)for(;;)if(L==0){for(N=1,$=H[0];$>=10;$/=10,N++);for($=H[0]+=O,O=1;$>=10;$/=10,O++);N!=O&&(E.e++,H[0]==c&&(H[0]=1));break}else{if(H[L]+=O,H[L]!=c)break;H[L--]=0,O=1}for(N=H.length;H[--N]===0;H.pop());}E.e>ae?E.c=E.e=null:E.e<Ae&&(E.c=[E.e=0])}return E}function Le(E){var v,D=E.e;return D===null?E.toString():(v=b(E.c),v=D<=ee||D>=de?w(v,D):A(v,D,"0"),E.s<0?"-"+v:v)}return F.absoluteValue=F.abs=function(){var E=new G(this);return E.s<0&&(E.s=1),E},F.comparedTo=function(E,v){return y(this,new G(E,v))},F.decimalPlaces=F.dp=function(E,v){var D,M,P,N=this;if(E!=null)return m(E,0,g),v==null?v=X:m(v,0,8),Re(new G(N),E+N.e+1,v);if(!(D=N.c))return null;if(M=((P=D.length-1)-C(this.e/l))*l,P=D[P])for(;P%10==0;P/=10,M--);return M<0&&(M=0),M},F.dividedBy=F.div=function(E,v){return R(this,new G(E,v),Y,X)},F.dividedToIntegerBy=F.idiv=function(E,v){return R(this,new G(E,v),0,1)},F.exponentiatedBy=F.pow=function(E,v){var D,M,P,N,$,O,I,L,B,H=this;if(E=new G(E),E.c&&!E.isInteger())throw Error(s+"Exponent not an integer: "+Le(E));if(v!=null&&(v=new G(v)),O=E.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!E.c||!E.c[0])return B=new G(Math.pow(+Le(H),O?E.s*(2-k(E)):+Le(E))),v?B.mod(v):B;if(I=E.s<0,v){if(v.c?!v.c[0]:!v.s)return new G(NaN);M=!I&&H.isInteger()&&v.isInteger(),M&&(H=H.mod(v))}else{if(E.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||O&&H.c[1]>=24e7:H.c[0]<8e13||O&&H.c[0]<=9999975e7)))return N=H.s<0&&k(E)?-0:0,H.e>-1&&(N=1/N),new G(I?1/N:N);Q&&(N=r(Q/l+2))}for(O?(D=new G(.5),I&&(E.s=1),L=k(E)):(P=Math.abs(+Le(E)),L=P%2),B=new G(V);;){if(L){if(B=B.times(H),!B.c)break;N?B.c.length>N&&(B.c.length=N):M&&(B=B.mod(v))}if(P){if(P=o(P/2),P===0)break;L=P%2}else if(E=E.times(D),Re(E,E.e+1,1),E.e>14)L=k(E);else{if(P=+Le(E),P===0)break;L=P%2}H=H.times(H),N?H.c&&H.c.length>N&&(H.c.length=N):M&&(H=H.mod(v))}return M?B:(I&&(B=V.div(B)),v?B.mod(v):N?Re(B,Q,X,$):B)},F.integerValue=function(E){var v=new G(this);return E==null?E=X:m(E,0,8),Re(v,v.e+1,E)},F.isEqualTo=F.eq=function(E,v){return y(this,new G(E,v))===0},F.isFinite=function(){return!!this.c},F.isGreaterThan=F.gt=function(E,v){return y(this,new G(E,v))>0},F.isGreaterThanOrEqualTo=F.gte=function(E,v){return(v=y(this,new G(E,v)))===1||v===0},F.isInteger=function(){return!!this.c&&C(this.e/l)>this.c.length-2},F.isLessThan=F.lt=function(E,v){return y(this,new G(E,v))<0},F.isLessThanOrEqualTo=F.lte=function(E,v){return(v=y(this,new G(E,v)))===-1||v===0},F.isNaN=function(){return!this.s},F.isNegative=function(){return this.s<0},F.isPositive=function(){return this.s>0},F.isZero=function(){return!!this.c&&this.c[0]==0},F.minus=function(E,v){var D,M,P,N,$=this,O=$.s;if(E=new G(E,v),v=E.s,!O||!v)return new G(NaN);if(O!=v)return E.s=-v,$.plus(E);var I=$.e/l,L=E.e/l,B=$.c,H=E.c;if(!I||!L){if(!B||!H)return B?(E.s=-v,E):new G(H?$:NaN);if(!B[0]||!H[0])return H[0]?(E.s=-v,E):new G(B[0]?$:X==3?-0:0)}if(I=C(I),L=C(L),B=B.slice(),O=I-L){for((N=O<0)?(O=-O,P=B):(L=I,P=H),P.reverse(),v=O;v--;P.push(0));P.reverse()}else for(M=(N=(O=B.length)<(v=H.length))?O:v,O=v=0;v<M;v++)if(B[v]!=H[v]){N=B[v]<H[v];break}if(N&&(P=B,B=H,H=P,E.s=-E.s),v=(M=H.length)-(D=B.length),v>0)for(;v--;B[D++]=0);for(v=c-1;M>O;){if(B[--M]<H[M]){for(D=M;D&&!B[--D];B[D]=v);--B[D],B[M]+=c}B[M]-=H[M]}for(;B[0]==0;B.splice(0,1),--L);return B[0]?Bt(E,B,L):(E.s=X==3?-1:1,E.c=[E.e=0],E)},F.modulo=F.mod=function(E,v){var D,M,P=this;return E=new G(E,v),!P.c||!E.s||E.c&&!E.c[0]?new G(NaN):!E.c||P.c&&!P.c[0]?new G(P):(W==9?(M=E.s,E.s=1,D=R(P,E,0,3),E.s=M,D.s*=M):D=R(P,E,0,W),E=P.minus(D.times(E)),!E.c[0]&&W==1&&(E.s=P.s),E)},F.multipliedBy=F.times=function(E,v){var D,M,P,N,$,O,I,L,B,H,te,ne,Ee,Fe,Be,we=this,Se=we.c,Ue=(E=new G(E,v)).c;if(!Se||!Ue||!Se[0]||!Ue[0])return!we.s||!E.s||Se&&!Se[0]&&!Ue||Ue&&!Ue[0]&&!Se?E.c=E.e=E.s=null:(E.s*=we.s,!Se||!Ue?E.c=E.e=null:(E.c=[0],E.e=0)),E;for(M=C(we.e/l)+C(E.e/l),E.s*=we.s,I=Se.length,H=Ue.length,I<H&&(Ee=Se,Se=Ue,Ue=Ee,P=I,I=H,H=P),P=I+H,Ee=[];P--;Ee.push(0));for(Fe=c,Be=p,P=H;--P>=0;){for(D=0,te=Ue[P]%Be,ne=Ue[P]/Be|0,$=I,N=P+$;N>P;)L=Se[--$]%Be,B=Se[$]/Be|0,O=ne*L+B*te,L=te*L+O%Be*Be+Ee[N]+D,D=(L/Fe|0)+(O/Be|0)+ne*B,Ee[N--]=L%Fe;Ee[N]=D}return D?++M:Ee.splice(0,1),Bt(E,Ee,M)},F.negated=function(){var E=new G(this);return E.s=-E.s||null,E},F.plus=function(E,v){var D,M=this,P=M.s;if(E=new G(E,v),v=E.s,!P||!v)return new G(NaN);if(P!=v)return E.s=-v,M.minus(E);var N=M.e/l,$=E.e/l,O=M.c,I=E.c;if(!N||!$){if(!O||!I)return new G(P/0);if(!O[0]||!I[0])return I[0]?E:new G(O[0]?M:P*0)}if(N=C(N),$=C($),O=O.slice(),P=N-$){for(P>0?($=N,D=I):(P=-P,D=O),D.reverse();P--;D.push(0));D.reverse()}for(P=O.length,v=I.length,P-v<0&&(D=I,I=O,O=D,v=P),P=0;v;)P=(O[--v]=O[v]+I[v]+P)/c|0,O[v]=c===O[v]?0:O[v]%c;return P&&(O=[P].concat(O),++$),Bt(E,O,$)},F.precision=F.sd=function(E,v){var D,M,P,N=this;if(E!=null&&E!==!!E)return m(E,1,g),v==null?v=X:m(v,0,8),Re(new G(N),E,v);if(!(D=N.c))return null;if(P=D.length-1,M=P*l+1,P=D[P]){for(;P%10==0;P/=10,M--);for(P=D[0];P>=10;P/=10,M++);}return E&&N.e+1>M&&(M=N.e+1),M},F.shiftedBy=function(E){return m(E,-d,d),this.times("1e"+E)},F.squareRoot=F.sqrt=function(){var E,v,D,M,P,N=this,$=N.c,O=N.s,I=N.e,L=Y+4,B=new G("0.5");if(O!==1||!$||!$[0])return new G(!O||O<0&&(!$||$[0])?NaN:$?N:1/0);if(O=Math.sqrt(+Le(N)),O==0||O==1/0?(v=b($),(v.length+I)%2==0&&(v+="0"),O=Math.sqrt(+v),I=C((I+1)/2)-(I<0||I%2),O==1/0?v="5e"+I:(v=O.toExponential(),v=v.slice(0,v.indexOf("e")+1)+I),D=new G(v)):D=new G(O+""),D.c[0]){for(I=D.e,O=I+L,O<3&&(O=0);;)if(P=D,D=B.times(P.plus(R(N,P,L,1))),b(P.c).slice(0,O)===(v=b(D.c)).slice(0,O))if(D.e<I&&--O,v=v.slice(O-3,O+1),v=="9999"||!M&&v=="4999"){if(!M&&(Re(P,P.e+Y+2,0),P.times(P).eq(N))){D=P;break}L+=4,O+=4,M=1}else{(!+v||!+v.slice(1)&&v.charAt(0)=="5")&&(Re(D,D.e+Y+2,1),E=!D.times(D).eq(N));break}}return Re(D,D.e+Y+1,X,E)},F.toExponential=function(E,v){return E!=null&&(m(E,0,g),E++),le(this,E,v,1)},F.toFixed=function(E,v){return E!=null&&(m(E,0,g),E=E+this.e+1),le(this,E,v)},F.toFormat=function(E,v,D){var M,P=this;if(D==null)E!=null&&v&&typeof v=="object"?(D=v,v=null):E&&typeof E=="object"?(D=E,E=v=null):D=re;else if(typeof D!="object")throw Error(s+"Argument not an object: "+D);if(M=P.toFixed(E,v),P.c){var N,$=M.split("."),O=+D.groupSize,I=+D.secondaryGroupSize,L=D.groupSeparator||"",B=$[0],H=$[1],te=P.s<0,ne=te?B.slice(1):B,Ee=ne.length;if(I&&(N=O,O=I,I=N,Ee-=N),O>0&&Ee>0){for(N=Ee%O||O,B=ne.substr(0,N);N<Ee;N+=O)B+=L+ne.substr(N,O);I>0&&(B+=L+ne.slice(N)),te&&(B="-"+B)}M=H?B+(D.decimalSeparator||"")+((I=+D.fractionGroupSize)?H.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):H):B}return(D.prefix||"")+M+(D.suffix||"")},F.toFraction=function(E){var v,D,M,P,N,$,O,I,L,B,H,te,ne=this,Ee=ne.c;if(E!=null&&(O=new G(E),!O.isInteger()&&(O.c||O.s!==1)||O.lt(V)))throw Error(s+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Le(O));if(!Ee)return new G(ne);for(v=new G(V),L=D=new G(V),M=I=new G(V),te=b(Ee),N=v.e=te.length-ne.e-1,v.c[0]=f[($=N%l)<0?l+$:$],E=!E||O.comparedTo(v)>0?N>0?v:L:O,$=ae,ae=1/0,O=new G(te),I.c[0]=0;B=R(O,v,0,1),P=D.plus(B.times(M)),P.comparedTo(E)!=1;)D=M,M=P,L=I.plus(B.times(P=L)),I=P,v=O.minus(B.times(P=v)),O=P;return P=R(E.minus(D),M,0,1),I=I.plus(P.times(L)),D=D.plus(P.times(M)),I.s=L.s=ne.s,N=N*2,H=R(L,M,N,X).minus(ne).abs().comparedTo(R(I,D,N,X).minus(ne).abs())<1?[L,M]:[I,D],ae=$,H},F.toNumber=function(){return+Le(this)},F.toPrecision=function(E,v){return E!=null&&m(E,1,g),le(this,E,v,2)},F.toString=function(E){var v,D=this,M=D.s,P=D.e;return P===null?M?(v="Infinity",M<0&&(v="-"+v)):v="NaN":(E==null?v=P<=ee||P>=de?w(b(D.c),P):A(b(D.c),P,"0"):E===10&&ke?(D=Re(new G(D),Y+P+1,X),v=A(b(D.c),D.e,"0")):(m(E,2,$e.length,"Base"),v=U(A(b(D.c),P,"0"),10,E,M,!0)),M<0&&D.c[0]&&(v="-"+v)),v},F.valueOf=F.toJSON=function(){return Le(this)},F._isBigNumber=!0,T!=null&&G.set(T),G}function C(T){var R=T|0;return T>0||T===R?R:R-1}function b(T){for(var R,U,J=1,F=T.length,V=T[0]+"";J<F;){for(R=T[J++]+"",U=l-R.length;U--;R="0"+R);V+=R}for(F=V.length;V.charCodeAt(--F)===48;);return V.slice(0,F+1||1)}function y(T,R){var U,J,F=T.c,V=R.c,Y=T.s,X=R.s,ee=T.e,de=R.e;if(!Y||!X)return null;if(U=F&&!F[0],J=V&&!V[0],U||J)return U?J?0:-X:Y;if(Y!=X)return Y;if(U=Y<0,J=ee==de,!F||!V)return J?0:!F^U?1:-1;if(!J)return ee>de^U?1:-1;for(X=(ee=F.length)<(de=V.length)?ee:de,Y=0;Y<X;Y++)if(F[Y]!=V[Y])return F[Y]>V[Y]^U?1:-1;return ee==de?0:ee>de^U?1:-1}function m(T,R,U,J){if(T<R||T>U||T!==o(T))throw Error(s+(J||"Argument")+(typeof T=="number"?T<R||T>U?" out of range: ":" not an integer: ":" not a primitive number: ")+String(T))}function k(T){var R=T.c.length-1;return C(T.e/l)==R&&T.c[R]%2!=0}function w(T,R){return(T.length>1?T.charAt(0)+"."+T.slice(1):T)+(R<0?"e":"e+")+R}function A(T,R,U){var J,F;if(R<0){for(F=U+".";++R;F+=U);T=F+T}else if(J=T.length,++R>J){for(F=U,R-=J;--R;F+=U);T+=F}else R<J&&(T=T.slice(0,R)+"."+T.slice(R));return T}e=_(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Vi<"u"&&Vi.exports?Vi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(hg)});var yg=K((E1,gg)=>{var pg=Yc(),mg=gg.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function l(d,f){var p,g,_,C,b=r,y,m=f[d],k=m!=null&&(m instanceof pg||pg.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(d)),typeof a=="function"&&(m=a.call(f,d,m)),typeof m){case"string":return k?m:c(m);case"number":return isFinite(m)?String(m):"null";case"boolean":case"null":case"bigint":return String(m);case"object":if(!m)return"null";if(r+=o,y=[],Object.prototype.toString.apply(m)==="[object Array]"){for(C=m.length,p=0;p<C;p+=1)y[p]=l(p,m)||"null";return _=y.length===0?"[]":r?`[
44
- `+r+y.join(`,
43
+ `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>Oe(pm()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(ug(),ag))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};no.Gaxios=Ji;to=Ji});var Qe=K(ot=>{"use strict";var _E=ot&&ot.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),bE=ot&&ot.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_E(e,t,n)};Object.defineProperty(ot,"__esModule",{value:!0});ot.instance=ot.Gaxios=ot.GaxiosError=void 0;ot.request=wE;var fg=dg();Object.defineProperty(ot,"Gaxios",{enumerable:!0,get:function(){return fg.Gaxios}});var CE=kc();Object.defineProperty(ot,"GaxiosError",{enumerable:!0,get:function(){return CE.GaxiosError}});bE(Dc(),ot);ot.instance=new fg.Gaxios;async function wE(t){return ot.instance.request(t)}});var Yc=K((hg,Vi)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,m=1e9;function b(T){var R,U,J,F=G.prototype={constructor:G,toString:null,valueOf:null},V=new G(1),Y=20,X=4,ee=-7,de=21,Ae=-1e7,ae=1e7,pe=!1,W=1,Q=0,re={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},$e="0123456789abcdefghijklmnopqrstuvwxyz",ke=!0;function G(A,v){var D,M,P,N,$,O,I,L,B=this;if(!(B instanceof G))return new G(A,v);if(v==null){if(A&&A._isBigNumber===!0){B.s=A.s,!A.c||A.e>ae?B.c=B.e=null:A.e<Ae?B.c=[B.e=0]:(B.e=A.e,B.c=A.c.slice());return}if((O=typeof A=="number")&&A*0==0){if(B.s=1/A<0?(A=-A,-1):1,A===~~A){for(N=0,$=A;$>=10;$/=10,N++);N>ae?B.c=B.e=null:(B.e=N,B.c=[A]);return}L=String(A)}else{if(!n.test(L=String(A)))return J(B,L,O);B.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(N=L.indexOf("."))>-1&&(L=L.replace(".","")),($=L.search(/e/i))>0?(N<0&&(N=$),N+=+L.slice($+1),L=L.substring(0,$)):N<0&&(N=L.length)}else{if(g(v,2,$e.length,"Base"),v==10&&ke)return B=new G(A),Re(B,Y+B.e+1,X);if(L=String(A),O=typeof A=="number"){if(A*0!=0)return J(B,L,O,v);if(B.s=1/A<0?(L=L.slice(1),-1):1,G.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+A)}else B.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(D=$e.slice(0,v),N=$=0,I=L.length;$<I;$++)if(D.indexOf(M=L.charAt($))<0){if(M=="."){if($>N){N=I;continue}}else if(!P&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){P=!0,$=-1,N=0;continue}return J(B,String(A),O,v)}O=!1,L=U(L,v,10,B.s),(N=L.indexOf("."))>-1?L=L.replace(".",""):N=L.length}for($=0;L.charCodeAt($)===48;$++);for(I=L.length;L.charCodeAt(--I)===48;);if(L=L.slice($,++I)){if(I-=$,O&&G.DEBUG&&I>15&&(A>d||A!==o(A)))throw Error(a+B.s*A);if((N=N-$-1)>ae)B.c=B.e=null;else if(N<Ae)B.c=[B.e=0];else{if(B.e=N,B.c=[],$=(N+1)%l,N<0&&($+=l),$<I){for($&&B.c.push(+L.slice(0,$)),I-=l;$<I;)B.c.push(+L.slice($,$+=l));$=l-(L=L.slice($)).length}else $-=I;for(;$--;L+="0");B.c.push(+L)}}else B.c=[B.e=0]}G.clone=b,G.ROUND_UP=0,G.ROUND_DOWN=1,G.ROUND_CEIL=2,G.ROUND_FLOOR=3,G.ROUND_HALF_UP=4,G.ROUND_HALF_DOWN=5,G.ROUND_HALF_EVEN=6,G.ROUND_HALF_CEIL=7,G.ROUND_HALF_FLOOR=8,G.EUCLID=9,G.config=G.set=function(A){var v,D;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(v="DECIMAL_PLACES")&&(D=A[v],g(D,0,m,v),Y=D),A.hasOwnProperty(v="ROUNDING_MODE")&&(D=A[v],g(D,0,8,v),X=D),A.hasOwnProperty(v="EXPONENTIAL_AT")&&(D=A[v],D&&D.pop?(g(D[0],-m,0,v),g(D[1],0,m,v),ee=D[0],de=D[1]):(g(D,-m,m,v),ee=-(de=D<0?-D:D))),A.hasOwnProperty(v="RANGE"))if(D=A[v],D&&D.pop)g(D[0],-m,-1,v),g(D[1],1,m,v),Ae=D[0],ae=D[1];else if(g(D,-m,m,v),D)Ae=-(ae=D<0?-D:D);else throw Error(s+v+" cannot be zero: "+D);if(A.hasOwnProperty(v="CRYPTO"))if(D=A[v],D===!!D)if(D)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))pe=D;else throw pe=!D,Error(s+"crypto unavailable");else pe=D;else throw Error(s+v+" not true or false: "+D);if(A.hasOwnProperty(v="MODULO_MODE")&&(D=A[v],g(D,0,9,v),W=D),A.hasOwnProperty(v="POW_PRECISION")&&(D=A[v],g(D,0,m,v),Q=D),A.hasOwnProperty(v="FORMAT"))if(D=A[v],typeof D=="object")re=D;else throw Error(s+v+" not an object: "+D);if(A.hasOwnProperty(v="ALPHABET"))if(D=A[v],typeof D=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(D))ke=D.slice(0,10)=="0123456789",$e=D;else throw Error(s+v+" invalid: "+D)}else throw Error(s+"Object expected: "+A);return{DECIMAL_PLACES:Y,ROUNDING_MODE:X,EXPONENTIAL_AT:[ee,de],RANGE:[Ae,ae],CRYPTO:pe,MODULO_MODE:W,POW_PRECISION:Q,FORMAT:re,ALPHABET:$e}},G.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!G.DEBUG)return!0;var v,D,M=A.c,P=A.e,N=A.s;e:if({}.toString.call(M)=="[object Array]"){if((N===1||N===-1)&&P>=-m&&P<=m&&P===o(P)){if(M[0]===0){if(P===0&&M.length===1)return!0;break e}if(v=(P+1)%l,v<1&&(v+=l),String(M[0]).length==v){for(v=0;v<M.length;v++)if(D=M[v],D<0||D>=c||D!==o(D))break e;if(D!==0)return!0}}}else if(M===null&&P===null&&(N===null||N===1||N===-1))return!0;throw Error(s+"Invalid BigNumber: "+A)},G.maximum=G.max=function(){return _e(arguments,-1)},G.minimum=G.min=function(){return _e(arguments,1)},G.random=(function(){var A=9007199254740992,v=Math.random()*A&2097151?function(){return o(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var M,P,N,$,O,I=0,L=[],B=new G(V);if(D==null?D=Y:g(D,0,m),$=r(D/l),pe)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array($*=2));I<$;)O=M[I]*131072+(M[I+1]>>>11),O>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),M[I]=P[0],M[I+1]=P[1]):(L.push(O%1e14),I+=2);I=$/2}else if(crypto.randomBytes){for(M=crypto.randomBytes($*=7);I<$;)O=(M[I]&31)*281474976710656+M[I+1]*1099511627776+M[I+2]*4294967296+M[I+3]*16777216+(M[I+4]<<16)+(M[I+5]<<8)+M[I+6],O>=9e15?crypto.randomBytes(7).copy(M,I):(L.push(O%1e14),I+=7);I=$/7}else throw pe=!1,Error(s+"crypto unavailable");if(!pe)for(;I<$;)O=v(),O<9e15&&(L[I++]=O%1e14);for($=L[--I],D%=l,$&&D&&(O=f[l-D],L[I]=o($/O)*O);L[I]===0;L.pop(),I--);if(I<0)L=[N=0];else{for(N=-1;L[0]===0;L.splice(0,1),N-=l);for(I=1,O=L[0];O>=10;O/=10,I++);I<l&&(N-=l-I)}return B.e=N,B.c=L,B}})(),G.sum=function(){for(var A=1,v=arguments,D=new G(v[0]);A<v.length;)D=D.plus(v[A++]);return D},U=(function(){var A="0123456789";function v(D,M,P,N){for(var $,O=[0],I,L=0,B=D.length;L<B;){for(I=O.length;I--;O[I]*=M);for(O[0]+=N.indexOf(D.charAt(L++)),$=0;$<O.length;$++)O[$]>P-1&&(O[$+1]==null&&(O[$+1]=0),O[$+1]+=O[$]/P|0,O[$]%=P)}return O.reverse()}return function(D,M,P,N,$){var O,I,L,B,H,te,ne,Ee,Fe=D.indexOf("."),Be=Y,we=X;for(Fe>=0&&(B=Q,Q=0,D=D.replace(".",""),Ee=new G(M),te=Ee.pow(D.length-Fe),Q=B,Ee.c=v(E(y(te.c),te.e,"0"),10,P,A),Ee.e=Ee.c.length),ne=v(D,M,P,$?(O=$e,A):(O=A,$e)),L=B=ne.length;ne[--B]==0;ne.pop());if(!ne[0])return O.charAt(0);if(Fe<0?--L:(te.c=ne,te.e=L,te.s=N,te=R(te,Ee,Be,we,P),ne=te.c,H=te.r,L=te.e),I=L+Be+1,Fe=ne[I],B=P/2,H=H||I<0||ne[I+1]!=null,H=we<4?(Fe!=null||H)&&(we==0||we==(te.s<0?3:2)):Fe>B||Fe==B&&(we==4||H||we==6&&ne[I-1]&1||we==(te.s<0?8:7)),I<1||!ne[0])D=H?E(O.charAt(1),-Be,O.charAt(0)):O.charAt(0);else{if(ne.length=I,H)for(--P;++ne[--I]>P;)ne[I]=0,I||(++L,ne=[1].concat(ne));for(B=ne.length;!ne[--B];);for(Fe=0,D="";Fe<=B;D+=O.charAt(ne[Fe++]));D=E(D,L,O.charAt(0))}return D}})(),R=(function(){function A(M,P,N){var $,O,I,L,B=0,H=M.length,te=P%p,ne=P/p|0;for(M=M.slice();H--;)I=M[H]%p,L=M[H]/p|0,$=ne*I+L*te,O=te*I+$%p*p+B,B=(O/N|0)+($/p|0)+ne*L,M[H]=O%N;return B&&(M=[B].concat(M)),M}function v(M,P,N,$){var O,I;if(N!=$)I=N>$?1:-1;else for(O=I=0;O<N;O++)if(M[O]!=P[O]){I=M[O]>P[O]?1:-1;break}return I}function D(M,P,N,$){for(var O=0;N--;)M[N]-=O,O=M[N]<P[N]?1:0,M[N]=O*$+M[N]-P[N];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,P,N,$,O){var I,L,B,H,te,ne,Ee,Fe,Be,we,Se,Ue,Or,Pr,Fr,dt,hn,Xe=M.s==P.s?1:-1,qe=M.c,ve=P.c;if(!qe||!qe[0]||!ve||!ve[0])return new G(!M.s||!P.s||(qe?ve&&qe[0]==ve[0]:!ve)?NaN:qe&&qe[0]==0||!ve?Xe*0:Xe/0);for(Fe=new G(Xe),Be=Fe.c=[],L=M.e-P.e,Xe=N+L+1,O||(O=c,L=C(M.e/l)-C(P.e/l),Xe=Xe/l|0),B=0;ve[B]==(qe[B]||0);B++);if(ve[B]>(qe[B]||0)&&L--,Xe<0)Be.push(1),H=!0;else{for(Pr=qe.length,dt=ve.length,B=0,Xe+=2,te=o(O/(ve[0]+1)),te>1&&(ve=A(ve,te,O),qe=A(qe,te,O),dt=ve.length,Pr=qe.length),Or=dt,we=qe.slice(0,dt),Se=we.length;Se<dt;we[Se++]=0);hn=ve.slice(),hn=[0].concat(hn),Fr=ve[0],ve[1]>=O/2&&Fr++;do{if(te=0,I=v(ve,we,dt,Se),I<0){if(Ue=we[0],dt!=Se&&(Ue=Ue*O+(we[1]||0)),te=o(Ue/Fr),te>1)for(te>=O&&(te=O-1),ne=A(ve,te,O),Ee=ne.length,Se=we.length;v(ne,we,Ee,Se)==1;)te--,D(ne,dt<Ee?hn:ve,Ee,O),Ee=ne.length,I=1;else te==0&&(I=te=1),ne=ve.slice(),Ee=ne.length;if(Ee<Se&&(ne=[0].concat(ne)),D(we,ne,Se,O),Se=we.length,I==-1)for(;v(ve,we,dt,Se)<1;)te++,D(we,dt<Se?hn:ve,Se,O),Se=we.length}else I===0&&(te++,we=[0]);Be[B++]=te,we[0]?we[Se++]=qe[Or]||0:(we=[qe[Or]],Se=1)}while((Or++<Pr||we[0]!=null)&&Xe--);H=we[0]!=null,Be[0]||Be.splice(0,1)}if(O==c){for(B=1,Xe=Be[0];Xe>=10;Xe/=10,B++);Re(Fe,N+(Fe.e=B+L*l-1)+1,$,H)}else Fe.e=L,Fe.r=+H;return Fe}})();function le(A,v,D,M){var P,N,$,O,I;if(D==null?D=X:g(D,0,8),!A.c)return A.toString();if(P=A.c[0],$=A.e,v==null)I=y(A.c),I=M==1||M==2&&($<=ee||$>=de)?w(I,$):E(I,$,"0");else if(A=Re(new G(A),v,D),N=A.e,I=y(A.c),O=I.length,M==1||M==2&&(v<=N||N<=ee)){for(;O<v;I+="0",O++);I=w(I,N)}else if(v-=$+(M===2&&N>$),I=E(I,N,"0"),N+1>O){if(--v>0)for(I+=".";v--;I+="0");}else if(v+=N-O,v>0)for(N+1==O&&(I+=".");v--;I+="0");return A.s<0&&P?"-"+I:I}function _e(A,v){for(var D,M,P=1,N=new G(A[0]);P<A.length;P++)M=new G(A[P]),(!M.s||(D=_(N,M))===v||D===0&&N.s===v)&&(N=M);return N}function Bt(A,v,D){for(var M=1,P=v.length;!v[--P];v.pop());for(P=v[0];P>=10;P/=10,M++);return(D=M+D*l-1)>ae?A.c=A.e=null:D<Ae?A.c=[A.e=0]:(A.e=D,A.c=v),A}J=(function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,v=/^([^.]+)\.$/,D=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(N,$,O,I){var L,B=O?$:$.replace(P,"");if(M.test(B))N.s=isNaN(B)?null:B<0?-1:1;else{if(!O&&(B=B.replace(A,function(H,te,ne){return L=(ne=ne.toLowerCase())=="x"?16:ne=="b"?2:8,!I||I==L?te:H}),I&&(L=I,B=B.replace(v,"$1").replace(D,"0.$1")),$!=B))return new G(B,L);if(G.DEBUG)throw Error(s+"Not a"+(I?" base "+I:"")+" number: "+$);N.s=null}N.c=N.e=null}})();function Re(A,v,D,M){var P,N,$,O,I,L,B,H=A.c,te=f;if(H){e:{for(P=1,O=H[0];O>=10;O/=10,P++);if(N=v-P,N<0)N+=l,$=v,I=H[L=0],B=o(I/te[P-$-1]%10);else if(L=r((N+1)/l),L>=H.length)if(M){for(;H.length<=L;H.push(0));I=B=0,P=1,N%=l,$=N-l+1}else break e;else{for(I=O=H[L],P=1;O>=10;O/=10,P++);N%=l,$=N-l+P,B=$<0?0:o(I/te[P-$-1]%10)}if(M=M||v<0||H[L+1]!=null||($<0?I:I%te[P-$-1]),M=D<4?(B||M)&&(D==0||D==(A.s<0?3:2)):B>5||B==5&&(D==4||M||D==6&&(N>0?$>0?I/te[P-$]:0:H[L-1])%10&1||D==(A.s<0?8:7)),v<1||!H[0])return H.length=0,M?(v-=A.e+1,H[0]=te[(l-v%l)%l],A.e=-v||0):H[0]=A.e=0,A;if(N==0?(H.length=L,O=1,L--):(H.length=L+1,O=te[l-N],H[L]=$>0?o(I/te[P-$]%te[$])*O:0),M)for(;;)if(L==0){for(N=1,$=H[0];$>=10;$/=10,N++);for($=H[0]+=O,O=1;$>=10;$/=10,O++);N!=O&&(A.e++,H[0]==c&&(H[0]=1));break}else{if(H[L]+=O,H[L]!=c)break;H[L--]=0,O=1}for(N=H.length;H[--N]===0;H.pop());}A.e>ae?A.c=A.e=null:A.e<Ae&&(A.c=[A.e=0])}return A}function Le(A){var v,D=A.e;return D===null?A.toString():(v=y(A.c),v=D<=ee||D>=de?w(v,D):E(v,D,"0"),A.s<0?"-"+v:v)}return F.absoluteValue=F.abs=function(){var A=new G(this);return A.s<0&&(A.s=1),A},F.comparedTo=function(A,v){return _(this,new G(A,v))},F.decimalPlaces=F.dp=function(A,v){var D,M,P,N=this;if(A!=null)return g(A,0,m),v==null?v=X:g(v,0,8),Re(new G(N),A+N.e+1,v);if(!(D=N.c))return null;if(M=((P=D.length-1)-C(this.e/l))*l,P=D[P])for(;P%10==0;P/=10,M--);return M<0&&(M=0),M},F.dividedBy=F.div=function(A,v){return R(this,new G(A,v),Y,X)},F.dividedToIntegerBy=F.idiv=function(A,v){return R(this,new G(A,v),0,1)},F.exponentiatedBy=F.pow=function(A,v){var D,M,P,N,$,O,I,L,B,H=this;if(A=new G(A),A.c&&!A.isInteger())throw Error(s+"Exponent not an integer: "+Le(A));if(v!=null&&(v=new G(v)),O=A.e>14,!H.c||!H.c[0]||H.c[0]==1&&!H.e&&H.c.length==1||!A.c||!A.c[0])return B=new G(Math.pow(+Le(H),O?A.s*(2-S(A)):+Le(A))),v?B.mod(v):B;if(I=A.s<0,v){if(v.c?!v.c[0]:!v.s)return new G(NaN);M=!I&&H.isInteger()&&v.isInteger(),M&&(H=H.mod(v))}else{if(A.e>9&&(H.e>0||H.e<-1||(H.e==0?H.c[0]>1||O&&H.c[1]>=24e7:H.c[0]<8e13||O&&H.c[0]<=9999975e7)))return N=H.s<0&&S(A)?-0:0,H.e>-1&&(N=1/N),new G(I?1/N:N);Q&&(N=r(Q/l+2))}for(O?(D=new G(.5),I&&(A.s=1),L=S(A)):(P=Math.abs(+Le(A)),L=P%2),B=new G(V);;){if(L){if(B=B.times(H),!B.c)break;N?B.c.length>N&&(B.c.length=N):M&&(B=B.mod(v))}if(P){if(P=o(P/2),P===0)break;L=P%2}else if(A=A.times(D),Re(A,A.e+1,1),A.e>14)L=S(A);else{if(P=+Le(A),P===0)break;L=P%2}H=H.times(H),N?H.c&&H.c.length>N&&(H.c.length=N):M&&(H=H.mod(v))}return M?B:(I&&(B=V.div(B)),v?B.mod(v):N?Re(B,Q,X,$):B)},F.integerValue=function(A){var v=new G(this);return A==null?A=X:g(A,0,8),Re(v,v.e+1,A)},F.isEqualTo=F.eq=function(A,v){return _(this,new G(A,v))===0},F.isFinite=function(){return!!this.c},F.isGreaterThan=F.gt=function(A,v){return _(this,new G(A,v))>0},F.isGreaterThanOrEqualTo=F.gte=function(A,v){return(v=_(this,new G(A,v)))===1||v===0},F.isInteger=function(){return!!this.c&&C(this.e/l)>this.c.length-2},F.isLessThan=F.lt=function(A,v){return _(this,new G(A,v))<0},F.isLessThanOrEqualTo=F.lte=function(A,v){return(v=_(this,new G(A,v)))===-1||v===0},F.isNaN=function(){return!this.s},F.isNegative=function(){return this.s<0},F.isPositive=function(){return this.s>0},F.isZero=function(){return!!this.c&&this.c[0]==0},F.minus=function(A,v){var D,M,P,N,$=this,O=$.s;if(A=new G(A,v),v=A.s,!O||!v)return new G(NaN);if(O!=v)return A.s=-v,$.plus(A);var I=$.e/l,L=A.e/l,B=$.c,H=A.c;if(!I||!L){if(!B||!H)return B?(A.s=-v,A):new G(H?$:NaN);if(!B[0]||!H[0])return H[0]?(A.s=-v,A):new G(B[0]?$:X==3?-0:0)}if(I=C(I),L=C(L),B=B.slice(),O=I-L){for((N=O<0)?(O=-O,P=B):(L=I,P=H),P.reverse(),v=O;v--;P.push(0));P.reverse()}else for(M=(N=(O=B.length)<(v=H.length))?O:v,O=v=0;v<M;v++)if(B[v]!=H[v]){N=B[v]<H[v];break}if(N&&(P=B,B=H,H=P,A.s=-A.s),v=(M=H.length)-(D=B.length),v>0)for(;v--;B[D++]=0);for(v=c-1;M>O;){if(B[--M]<H[M]){for(D=M;D&&!B[--D];B[D]=v);--B[D],B[M]+=c}B[M]-=H[M]}for(;B[0]==0;B.splice(0,1),--L);return B[0]?Bt(A,B,L):(A.s=X==3?-1:1,A.c=[A.e=0],A)},F.modulo=F.mod=function(A,v){var D,M,P=this;return A=new G(A,v),!P.c||!A.s||A.c&&!A.c[0]?new G(NaN):!A.c||P.c&&!P.c[0]?new G(P):(W==9?(M=A.s,A.s=1,D=R(P,A,0,3),A.s=M,D.s*=M):D=R(P,A,0,W),A=P.minus(D.times(A)),!A.c[0]&&W==1&&(A.s=P.s),A)},F.multipliedBy=F.times=function(A,v){var D,M,P,N,$,O,I,L,B,H,te,ne,Ee,Fe,Be,we=this,Se=we.c,Ue=(A=new G(A,v)).c;if(!Se||!Ue||!Se[0]||!Ue[0])return!we.s||!A.s||Se&&!Se[0]&&!Ue||Ue&&!Ue[0]&&!Se?A.c=A.e=A.s=null:(A.s*=we.s,!Se||!Ue?A.c=A.e=null:(A.c=[0],A.e=0)),A;for(M=C(we.e/l)+C(A.e/l),A.s*=we.s,I=Se.length,H=Ue.length,I<H&&(Ee=Se,Se=Ue,Ue=Ee,P=I,I=H,H=P),P=I+H,Ee=[];P--;Ee.push(0));for(Fe=c,Be=p,P=H;--P>=0;){for(D=0,te=Ue[P]%Be,ne=Ue[P]/Be|0,$=I,N=P+$;N>P;)L=Se[--$]%Be,B=Se[$]/Be|0,O=ne*L+B*te,L=te*L+O%Be*Be+Ee[N]+D,D=(L/Fe|0)+(O/Be|0)+ne*B,Ee[N--]=L%Fe;Ee[N]=D}return D?++M:Ee.splice(0,1),Bt(A,Ee,M)},F.negated=function(){var A=new G(this);return A.s=-A.s||null,A},F.plus=function(A,v){var D,M=this,P=M.s;if(A=new G(A,v),v=A.s,!P||!v)return new G(NaN);if(P!=v)return A.s=-v,M.minus(A);var N=M.e/l,$=A.e/l,O=M.c,I=A.c;if(!N||!$){if(!O||!I)return new G(P/0);if(!O[0]||!I[0])return I[0]?A:new G(O[0]?M:P*0)}if(N=C(N),$=C($),O=O.slice(),P=N-$){for(P>0?($=N,D=I):(P=-P,D=O),D.reverse();P--;D.push(0));D.reverse()}for(P=O.length,v=I.length,P-v<0&&(D=I,I=O,O=D,v=P),P=0;v;)P=(O[--v]=O[v]+I[v]+P)/c|0,O[v]=c===O[v]?0:O[v]%c;return P&&(O=[P].concat(O),++$),Bt(A,O,$)},F.precision=F.sd=function(A,v){var D,M,P,N=this;if(A!=null&&A!==!!A)return g(A,1,m),v==null?v=X:g(v,0,8),Re(new G(N),A,v);if(!(D=N.c))return null;if(P=D.length-1,M=P*l+1,P=D[P]){for(;P%10==0;P/=10,M--);for(P=D[0];P>=10;P/=10,M++);}return A&&N.e+1>M&&(M=N.e+1),M},F.shiftedBy=function(A){return g(A,-d,d),this.times("1e"+A)},F.squareRoot=F.sqrt=function(){var A,v,D,M,P,N=this,$=N.c,O=N.s,I=N.e,L=Y+4,B=new G("0.5");if(O!==1||!$||!$[0])return new G(!O||O<0&&(!$||$[0])?NaN:$?N:1/0);if(O=Math.sqrt(+Le(N)),O==0||O==1/0?(v=y($),(v.length+I)%2==0&&(v+="0"),O=Math.sqrt(+v),I=C((I+1)/2)-(I<0||I%2),O==1/0?v="5e"+I:(v=O.toExponential(),v=v.slice(0,v.indexOf("e")+1)+I),D=new G(v)):D=new G(O+""),D.c[0]){for(I=D.e,O=I+L,O<3&&(O=0);;)if(P=D,D=B.times(P.plus(R(N,P,L,1))),y(P.c).slice(0,O)===(v=y(D.c)).slice(0,O))if(D.e<I&&--O,v=v.slice(O-3,O+1),v=="9999"||!M&&v=="4999"){if(!M&&(Re(P,P.e+Y+2,0),P.times(P).eq(N))){D=P;break}L+=4,O+=4,M=1}else{(!+v||!+v.slice(1)&&v.charAt(0)=="5")&&(Re(D,D.e+Y+2,1),A=!D.times(D).eq(N));break}}return Re(D,D.e+Y+1,X,A)},F.toExponential=function(A,v){return A!=null&&(g(A,0,m),A++),le(this,A,v,1)},F.toFixed=function(A,v){return A!=null&&(g(A,0,m),A=A+this.e+1),le(this,A,v)},F.toFormat=function(A,v,D){var M,P=this;if(D==null)A!=null&&v&&typeof v=="object"?(D=v,v=null):A&&typeof A=="object"?(D=A,A=v=null):D=re;else if(typeof D!="object")throw Error(s+"Argument not an object: "+D);if(M=P.toFixed(A,v),P.c){var N,$=M.split("."),O=+D.groupSize,I=+D.secondaryGroupSize,L=D.groupSeparator||"",B=$[0],H=$[1],te=P.s<0,ne=te?B.slice(1):B,Ee=ne.length;if(I&&(N=O,O=I,I=N,Ee-=N),O>0&&Ee>0){for(N=Ee%O||O,B=ne.substr(0,N);N<Ee;N+=O)B+=L+ne.substr(N,O);I>0&&(B+=L+ne.slice(N)),te&&(B="-"+B)}M=H?B+(D.decimalSeparator||"")+((I=+D.fractionGroupSize)?H.replace(new RegExp("\\d{"+I+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):H):B}return(D.prefix||"")+M+(D.suffix||"")},F.toFraction=function(A){var v,D,M,P,N,$,O,I,L,B,H,te,ne=this,Ee=ne.c;if(A!=null&&(O=new G(A),!O.isInteger()&&(O.c||O.s!==1)||O.lt(V)))throw Error(s+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+Le(O));if(!Ee)return new G(ne);for(v=new G(V),L=D=new G(V),M=I=new G(V),te=y(Ee),N=v.e=te.length-ne.e-1,v.c[0]=f[($=N%l)<0?l+$:$],A=!A||O.comparedTo(v)>0?N>0?v:L:O,$=ae,ae=1/0,O=new G(te),I.c[0]=0;B=R(O,v,0,1),P=D.plus(B.times(M)),P.comparedTo(A)!=1;)D=M,M=P,L=I.plus(B.times(P=L)),I=P,v=O.minus(B.times(P=v)),O=P;return P=R(A.minus(D),M,0,1),I=I.plus(P.times(L)),D=D.plus(P.times(M)),I.s=L.s=ne.s,N=N*2,H=R(L,M,N,X).minus(ne).abs().comparedTo(R(I,D,N,X).minus(ne).abs())<1?[L,M]:[I,D],ae=$,H},F.toNumber=function(){return+Le(this)},F.toPrecision=function(A,v){return A!=null&&g(A,1,m),le(this,A,v,2)},F.toString=function(A){var v,D=this,M=D.s,P=D.e;return P===null?M?(v="Infinity",M<0&&(v="-"+v)):v="NaN":(A==null?v=P<=ee||P>=de?w(y(D.c),P):E(y(D.c),P,"0"):A===10&&ke?(D=Re(new G(D),Y+P+1,X),v=E(y(D.c),D.e,"0")):(g(A,2,$e.length,"Base"),v=U(E(y(D.c),P,"0"),10,A,M,!0)),M<0&&D.c[0]&&(v="-"+v)),v},F.valueOf=F.toJSON=function(){return Le(this)},F._isBigNumber=!0,T!=null&&G.set(T),G}function C(T){var R=T|0;return T>0||T===R?R:R-1}function y(T){for(var R,U,J=1,F=T.length,V=T[0]+"";J<F;){for(R=T[J++]+"",U=l-R.length;U--;R="0"+R);V+=R}for(F=V.length;V.charCodeAt(--F)===48;);return V.slice(0,F+1||1)}function _(T,R){var U,J,F=T.c,V=R.c,Y=T.s,X=R.s,ee=T.e,de=R.e;if(!Y||!X)return null;if(U=F&&!F[0],J=V&&!V[0],U||J)return U?J?0:-X:Y;if(Y!=X)return Y;if(U=Y<0,J=ee==de,!F||!V)return J?0:!F^U?1:-1;if(!J)return ee>de^U?1:-1;for(X=(ee=F.length)<(de=V.length)?ee:de,Y=0;Y<X;Y++)if(F[Y]!=V[Y])return F[Y]>V[Y]^U?1:-1;return ee==de?0:ee>de^U?1:-1}function g(T,R,U,J){if(T<R||T>U||T!==o(T))throw Error(s+(J||"Argument")+(typeof T=="number"?T<R||T>U?" out of range: ":" not an integer: ":" not a primitive number: ")+String(T))}function S(T){var R=T.c.length-1;return C(T.e/l)==R&&T.c[R]%2!=0}function w(T,R){return(T.length>1?T.charAt(0)+"."+T.slice(1):T)+(R<0?"e":"e+")+R}function E(T,R,U){var J,F;if(R<0){for(F=U+".";++R;F+=U);T=F+T}else if(J=T.length,++R>J){for(F=U,R-=J;--R;F+=U);T+=F}else R<J&&(T=T.slice(0,R)+"."+T.slice(R));return T}e=b(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Vi<"u"&&Vi.exports?Vi.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(hg)});var yg=K((E1,gg)=>{var pg=Yc(),mg=gg.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function l(d,f){var p,m,b,C,y=r,_,g=f[d],S=g!=null&&(g instanceof pg||pg.isBigNumber(g));switch(g&&typeof g=="object"&&typeof g.toJSON=="function"&&(g=g.toJSON(d)),typeof a=="function"&&(g=a.call(f,d,g)),typeof g){case"string":return S?g:c(g);case"number":return isFinite(g)?String(g):"null";case"boolean":case"null":case"bigint":return String(g);case"object":if(!g)return"null";if(r+=o,_=[],Object.prototype.toString.apply(g)==="[object Array]"){for(C=g.length,p=0;p<C;p+=1)_[p]=l(p,g)||"null";return b=_.length===0?"[]":r?`[
44
+ `+r+_.join(`,
45
45
  `+r)+`
46
- `+b+"]":"["+y.join(",")+"]",r=b,_}if(a&&typeof a=="object")for(C=a.length,p=0;p<C;p+=1)typeof a[p]=="string"&&(g=a[p],_=l(g,m),_&&y.push(c(g)+(r?": ":":")+_));else Object.keys(m).forEach(function(w){var A=l(w,m);A&&y.push(c(w)+(r?": ":":")+A)});return _=y.length===0?"{}":r?`{
47
- `+r+y.join(`,
46
+ `+y+"]":"["+_.join(",")+"]",r=y,b}if(a&&typeof a=="object")for(C=a.length,p=0;p<C;p+=1)typeof a[p]=="string"&&(m=a[p],b=l(m,g),b&&_.push(c(m)+(r?": ":":")+b));else Object.keys(g).forEach(function(w){var E=l(w,g);E&&_.push(c(w)+(r?": ":":")+E)});return b=_.length===0?"{}":r?`{
47
+ `+r+_.join(`,
48
48
  `+r)+`
49
- `+b+"}":"{"+y.join(",")+"}",r=b,_}}typeof mg.stringify!="function"&&(mg.stringify=function(d,f,p){var g;if(r="",o="",typeof p=="number")for(g=0;g<p;g+=1)o+=" ";else typeof p=="string"&&(o=p);if(a=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return l("",{"":d})})})()});var bg=K((A1,_g)=>{var Ki=null,EE=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,AE=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,SE=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
- `,r:"\r",t:" "},s,a=function(b){throw{name:"SyntaxError",message:b,at:n,text:s}},c=function(b){return b&&b!==r&&a("Expected '"+b+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},l=function(){var b,y="";for(r==="-"&&(y="-",c("-"));r>="0"&&r<="9";)y+=r,c();if(r===".")for(y+=".";c()&&r>="0"&&r<="9";)y+=r;if(r==="e"||r==="E")for(y+=r,c(),(r==="-"||r==="+")&&(y+=r,c());r>="0"&&r<="9";)y+=r,c();if(b=+y,!isFinite(b))a("Bad number");else return Ki==null&&(Ki=Yc()),y.length>15?e.storeAsString?y:e.useNativeBigInt?BigInt(y):new Ki(y):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(b):new Ki(b):b},d=function(){var b,y,m="",k;if(r==='"')for(var w=n;c();){if(r==='"')return n-1>w&&(m+=s.substring(w,n-1)),c(),m;if(r==="\\"){if(n-1>w&&(m+=s.substring(w,n-1)),c(),r==="u"){for(k=0,y=0;y<4&&(b=parseInt(c(),16),!!isFinite(b));y+=1)k=k*16+b;m+=String.fromCharCode(k)}else if(typeof o[r]=="string")m+=o[r];else break;w=n}}a("Bad string")},f=function(){for(;r&&r<=" ";)c()},p=function(){switch(r){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}a("Unexpected '"+r+"'")},g,_=function(){var b=[];if(r==="["){if(c("["),f(),r==="]")return c("]"),b;for(;r;){if(b.push(g()),f(),r==="]")return c("]"),b;c(","),f()}}a("Bad array")},C=function(){var b,y=Object.create(null);if(r==="{"){if(c("{"),f(),r==="}")return c("}"),y;for(;r;){if(b=d(),f(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(y,b)&&a('Duplicate key "'+b+'"'),EE.test(b)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?g():y[b]=g():AE.test(b)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?g():y[b]=g():y[b]=g(),f(),r==="}")return c("}"),y;c(","),f()}}a("Bad object")};return g=function(){switch(f(),r){case"{":return C();case"[":return _();case'"':return d();case"-":return l();default:return r>="0"&&r<="9"?l():p()}},function(b,y){var m;return s=b+"",n=0,r=" ",m=g(),f(),r&&a("Syntax error"),typeof y=="function"?(function k(w,A){var T,R,U=w[A];return U&&typeof U=="object"&&Object.keys(U).forEach(function(J){R=k(U,J),R!==void 0?U[J]=R:delete U[J]}),y.call(w,A,U)})({"":m},""):m}};_g.exports=SE});var Eg=K((S1,Yi)=>{var Cg=yg().stringify,wg=bg();Yi.exports=function(t){return{parse:wg(t),stringify:Cg}};Yi.exports.parse=wg();Yi.exports.stringify=Cg});var Qc=K(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.GCE_LINUX_BIOS_PATHS=void 0;zt.isGoogleCloudServerless=kg;zt.isGoogleComputeEngineLinux=vg;zt.isGoogleComputeEngineMACAddress=Tg;zt.isGoogleComputeEngine=Dg;zt.detectGCPResidency=vE;var Ag=require("fs"),Sg=require("os");zt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var kE=/^42:01/;function kg(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function vg(){if((0,Sg.platform)()!=="linux")return!1;try{(0,Ag.statSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Ag.readFileSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Tg(){let t=(0,Sg.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(kE.test(n))return!0}return!1}function Dg(){return vg()||Tg()}function vE(){return kg()||Dg()}});var Rg=K(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Colours=void 0;var et=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Qi.Colours=et;et.enabled=!1;et.reset="";et.bright="";et.dim="";et.red="";et.green="";et.yellow="";et.blue="";et.magenta="";et.cyan="";et.white="";et.grey="";et.refresh()});var Fg=K(Te=>{"use strict";var TE=Te&&Te.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),DE=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xg=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&TE(n,e,r[o]);return DE(n,e),n}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=Zc;Te.getDebugBackend=xE;Te.getStructuredBackend=OE;Te.setBackend=PE;Te.log=Pg;var RE=require("events"),Zo=xg(require("process")),Og=xg(require("util")),yt=Rg(),Wt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Wt||(Te.LogSeverity=Wt={}));var es=class extends RE.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(Wt.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Wt.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Wt.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Wt.ERROR,...r),this.func.sublog=r=>Pg(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Te.AdhocDebugLogger=es;Te.placeholder=new es("",()=>{}).func;var ro=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=Zo.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};Te.DebugLogBackendBase=ro;var Xc=class extends ro{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var o;let s=`${yt.Colours.green}${e}${yt.Colours.reset}`,a=`${yt.Colours.yellow}${Zo.pid}${yt.Colours.reset}`,c;switch(n.severity){case Wt.ERROR:c=`${yt.Colours.red}${n.severity}${yt.Colours.reset}`;break;case Wt.INFO:c=`${yt.Colours.magenta}${n.severity}${yt.Colours.reset}`;break;case Wt.WARNING:c=`${yt.Colours.yellow}${n.severity}${yt.Colours.reset}`;break;default:c=(o=n.severity)!==null&&o!==void 0?o:Wt.DEFAULT;break}let l=Og.formatWithOptions({colors:yt.Colours.enabled},...r),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${yt.Colours.grey}${f}${yt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function Zc(){return new Xc}var el=class extends ro{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=Zo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Zo.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function xE(t){return new el(t)}var tl=class extends ro{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:Wt.INFO,l=Object.assign({severity:c,message:Og.format(...s)},o),d=JSON.stringify(l);r?r(o,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function OE(t){return new tl(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var nl=new Map,_t;function PE(t){_t=t,nl.clear()}function Pg(t,e){if(!_t&&!Zo.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=nl.get(t);if(n)return n.func;if(_t===null)return Te.placeholder;_t===void 0&&(_t=Zc());let r=(()=>{let o;return new es(t,(a,...c)=>{if(o!==_t){if(_t===null)return;_t===void 0&&(_t=Zc()),o=_t}_t?.log(t,a,...c)})})();return nl.set(t,r),r.func}});var rl=K(Ar=>{"use strict";var FE=Ar&&Ar.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),IE=Ar&&Ar.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&FE(e,t,n)};Object.defineProperty(Ar,"__esModule",{value:!0});IE(Fg(),Ar)});var ns=K(ue=>{"use strict";var Ng=ue&&ue.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),NE=ue&&ue.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),BE=ue&&ue.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&Ng(n,e,r[o]);return NE(n,e),n}})(),ME=ue&&ue.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ng(e,t,n)};Object.defineProperty(ue,"__esModule",{value:!0});ue.gcpResidencyCache=ue.METADATA_SERVER_DETECTION=ue.HEADERS=ue.HEADER_VALUE=ue.HEADER_NAME=ue.SECONDARY_HOST_ADDRESS=ue.HOST_ADDRESS=ue.BASE_PATH=void 0;ue.instance=HE;ue.project=zE;ue.universe=WE;ue.bulk=GE;ue.isAvailable=VE;ue.resetIsAvailableCache=KE;ue.getGCPResidency=il;ue.setGCPResidency=Bg;ue.requestTimeout=Mg;var ol=Qe(),LE=Eg(),jE=Qc(),$E=BE(rl());ue.BASE_PATH="/computeMetadata/v1";ue.HOST_ADDRESS="http://169.254.169.254";ue.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ue.HEADER_NAME="Metadata-Flavor";ue.HEADER_VALUE="Google";ue.HEADERS=Object.freeze({[ue.HEADER_NAME]:ue.HEADER_VALUE});var Ig=$E.log("gcp-metadata");ue.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function sl(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ue.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ue.BASE_PATH,t).href}function UE(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ts(t,e={},n=3,r=!1){let o=new Headers(ue.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((g,_)=>o.set(_,g)),s=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(UE(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,g)=>o.set(g,p)),a=e.params||a);let c=r?qE:ol.request,l={url:`${sl()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:Mg()};Ig.info("instance request %j",l);let d=await c(l);Ig.info("instance metadata is %s",d.data);let f=d.headers.get(ue.HEADER_NAME);if(f!==ue.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ue.HEADER_NAME} header. Expected '${ue.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return LE.parse(d.data)}catch{}return d.data}async function qE(t){let e={...t,url:t.url?.toString().replace(sl(),sl(ue.SECONDARY_HOST_ADDRESS))},n=(0,ol.request)(t),r=(0,ol.request)(e);return Promise.any([n,r])}function HE(t){return ts("instance",t)}function zE(t){return ts("project",t)}function WE(t){return ts("universe",t)}async function GE(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await ts(n),o=n.metadataKey;e[o]=r})())),e}function JE(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Xi;async function VE(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ue.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ue.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return il();case"ping-only":}}try{return Xi===void 0&&(Xi=ts("instance",void 0,JE(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Xi,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function KE(){Xi=void 0}ue.gcpResidencyCache=null;function il(){return ue.gcpResidencyCache===null&&Bg(),ue.gcpResidencyCache}function Bg(t=null){ue.gcpResidencyCache=t!==null?t:(0,jE.detectGCPResidency)()}function Mg(){return il()?0:3e3}ME(Qc(),ue)});var $g=K(Zi=>{"use strict";Zi.byteLength=QE;Zi.toByteArray=ZE;Zi.fromByteArray=nA;var nn=[],xt=[],YE=typeof Uint8Array<"u"?Uint8Array:Array,al="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Sr=0,Lg=al.length;Sr<Lg;++Sr)nn[Sr]=al[Sr],xt[al.charCodeAt(Sr)]=Sr;var Sr,Lg;xt[45]=62;xt[95]=63;function jg(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function QE(t){var e=jg(t),n=e[0],r=e[1];return(n+r)*3/4-r}function XE(t,e,n){return(e+n)*3/4-n}function ZE(t){var e,n=jg(t),r=n[0],o=n[1],s=new YE(XE(t,r,o)),a=0,c=o>0?r-4:r,l;for(l=0;l<c;l+=4)e=xt[t.charCodeAt(l)]<<18|xt[t.charCodeAt(l+1)]<<12|xt[t.charCodeAt(l+2)]<<6|xt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=xt[t.charCodeAt(l)]<<2|xt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=xt[t.charCodeAt(l)]<<10|xt[t.charCodeAt(l+1)]<<4|xt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function eA(t){return nn[t>>18&63]+nn[t>>12&63]+nn[t>>6&63]+nn[t&63]}function tA(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(eA(r));return o.join("")}function nA(t){for(var e,n=t.length,r=n%3,o=[],s=16383,a=0,c=n-r;a<c;a+=s)o.push(tA(t,a,a+s>c?c:a+s));return r===1?(e=t[n-1],o.push(nn[e>>2]+nn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(nn[e>>10]+nn[e>>4&63]+nn[e<<2&63]+"=")),o.join("")}});var cl=K(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.fromArrayBufferToHex=rA;function rA(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Ug=K(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.BrowserCrypto=void 0;var oo=$g(),oA=cl(),ll=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return oo.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),oo.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),a=oo.toByteArray(t.padBase64(r)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,s,o);return oo.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=oo.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return oo.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,oA.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};ea.BrowserCrypto=ll});var qg=K(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.NodeCrypto=void 0;var so=require("crypto"),dl=class{async sha256DigestBase64(e){return so.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return so.randomBytes(e).toString("base64")}async verify(e,n,r){let o=so.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=so.createSign("RSA-SHA256");return r.update(n),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return so.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:iA(e);return sA(so.createHmac("sha256",r).update(n).digest())}};ta.NodeCrypto=dl;function sA(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function iA(t){return Buffer.from(t)}});var rs=K(Tn=>{"use strict";var aA=Tn&&Tn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),uA=Tn&&Tn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&aA(e,t,n)};Object.defineProperty(Tn,"__esModule",{value:!0});Tn.createCrypto=dA;Tn.hasBrowserCrypto=Hg;var cA=Ug(),lA=qg();uA(cl(),Tn);function dA(){return Hg()?new cA.BrowserCrypto:new lA.NodeCrypto}function Hg(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var io=K((fl,Wg)=>{var na=require("buffer"),rn=na.Buffer;function zg(t,e){for(var n in t)e[n]=t[n]}rn.from&&rn.alloc&&rn.allocUnsafe&&rn.allocUnsafeSlow?Wg.exports=na:(zg(na,fl),fl.Buffer=kr);function kr(t,e,n){return rn(t,e,n)}kr.prototype=Object.create(rn.prototype);zg(rn,kr);kr.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return rn(t,e,n)};kr.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=rn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};kr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return rn(t)};kr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return na.SlowBuffer(t)}});var Jg=K((N1,Gg)=>{"use strict";function hl(t){var e=(t/8|0)+(t%8===0?0:1);return e}var fA={ES256:hl(256),ES384:hl(384),ES512:hl(521)};function hA(t){var e=fA[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Gg.exports=hA});var pl=K((B1,Zg)=>{"use strict";var ra=io().Buffer,Kg=Jg(),oa=128,Yg=0,pA=32,mA=16,gA=2,Qg=mA|pA|Yg<<6,sa=gA|Yg<<6;function yA(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xg(t){if(ra.isBuffer(t))return t;if(typeof t=="string")return ra.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function _A(t,e){t=Xg(t);var n=Kg(e),r=n+1,o=t.length,s=0;if(t[s++]!==Qg)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(oa|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==sa)throw new Error('Could not find expected "int" for "r"');var c=t[s++];if(o-s-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(o-s-2)+'" available');if(r<c)throw new Error('"r" specified length of "'+c+'", max of "'+r+'" is acceptable');var l=s;if(s+=c,t[s++]!==sa)throw new Error('Could not find expected "int" for "s"');var d=t[s++];if(o-s!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(o-s)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=s;if(s+=d,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-c,g=n-d,_=ra.allocUnsafe(p+c+g+d);for(s=0;s<p;++s)_[s]=0;t.copy(_,s,l+Math.max(-p,0),l+c),s=n;for(var C=s;s<C+g;++s)_[s]=0;return t.copy(_,s,f+Math.max(-g,0),f+d),_=_.toString("base64"),_=yA(_),_}function Vg(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=oa;return o&&--r,r}function bA(t,e){t=Xg(t);var n=Kg(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=Vg(t,0,n),s=Vg(t,n,t.length),a=n-o,c=n-s,l=2+a+1+1+c,d=l<oa,f=ra.allocUnsafe((d?2:3)+l),p=0;return f[p++]=Qg,d?f[p++]=l:(f[p++]=oa|1,f[p++]=l&255),f[p++]=sa,f[p++]=a,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=sa,f[p++]=c,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}Zg.exports={derToJose:_A,joseToDer:bA}});var Gt=K(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.LRUCache=void 0;Dn.snakeToCamel=ty;Dn.originalOrCamelOptions=AA;Dn.removeUndefinedValuesInObject=SA;Dn.isValidFile=kA;Dn.getWellKnownCertificateConfigFileLocation=vA;var CA=require("fs"),wA=require("os"),ml=require("path"),EA="certificate_config.json",ey="gcloud";function ty(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function AA(t){function e(n){let r=t||{};return r[n]??r[ty(n)]}return{get:e}}var gl=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};Dn.LRUCache=gl;function SA(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function kA(t){try{return(await CA.promises.lstat(t)).isFile()}catch{return!1}}function vA(){let t=process.env.CLOUDSDK_CONFIG||(TA()?ml.join(process.env.APPDATA||"",ey):ml.join(process.env.HOME||"",".config",ey));return ml.join(t,EA)}function TA(){return wA.platform().startsWith("win")}});var ny=K((L1,DA)=>{DA.exports={name:"google-auth-library",version:"10.4.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var yl=K(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.USER_AGENT=Xn.PRODUCT_NAME=Xn.pkg=void 0;var ry=ny();Xn.pkg=ry;var oy="google-api-nodejs-client";Xn.PRODUCT_NAME=oy;var RA=`${oy}/${ry.version}`;Xn.USER_AGENT=RA});var bt=K(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.AuthClient=Jt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Jt.DEFAULT_UNIVERSE=void 0;var xA=require("events"),_l=Qe(),OA=Gt(),PA=rl(),bl=yl();Jt.DEFAULT_UNIVERSE="googleapis.com";Jt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Cl=class t extends xA.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Jt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Jt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,OA.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??Jt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new _l.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&_l.Gaxios.mergeHeaders(s,n.headers),r&&_l.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,PA.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${bl.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${bl.USER_AGENT}`):e.headers.set("User-Agent",bl.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,a):t.log.info("[%s] request %j",s,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Jt.AuthClient=Cl});var El=K(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.LoginTicket=void 0;var wl=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};ia.LoginTicket=wl});var vr=K(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.OAuth2Client=on.ClientAuthentication=on.CertificateFormat=on.CodeChallengeMethod=void 0;var sy=Qe(),FA=require("querystring"),IA=require("stream"),NA=pl(),iy=Gt(),Al=rs(),ao=bt(),BA=El(),ay;(function(t){t.Plain="plain",t.S256="S256"})(ay||(on.CodeChallengeMethod=ay={}));var Rn;(function(t){t.PEM="PEM",t.JWK="JWK"})(Rn||(on.CertificateFormat=Rn={}));var os;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(os||(on.ClientAuthentication=os={}));var Sl=class t extends ao.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Rn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||os.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+FA.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Al.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===os.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===os.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,iy.removeUndefinedValuesInObject)(o)),headers:r};ao.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),c=a.data;return a.data&&a.data.expires_in&&(c.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,iy.removeUndefinedValuesInObject)(r))};ao.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof sy.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let c=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(c){let l=c;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(ao.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=sy.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=o.config.data instanceof IA.Readable,d=s===401||s===403;if(!n&&d&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!l&&c){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,Al.hasBrowserCrypto)()?Rn.JWK:Rn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Rn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Rn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};ao.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let s=r?.headers.get("cache-control"),a=-1;if(s){let d=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let c={};switch(n){case Rn.PEM:c=r.data;break;case Rn.JWK:for(let d of r.data.keys)c[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=n,{certs:c,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};ao.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let a=(0,Al.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=c[0]+"."+c[1],d=c[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token envelope: ${c[0]}': ${w.message}`),w}if(!f)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token payload '${c[0]}`),w}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let g=n[f.kid];if(f.alg==="ES256"&&(d=NA.joseToDer(d,"ES256").toString("base64")),!await a.verify(g,l,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let C=Number(p.iat);if(isNaN(C))throw new Error("iat field using invalid format");let b=Number(p.exp);if(isNaN(b))throw new Error("exp field using invalid format");let y=new Date().getTime()/1e3;if(b>=y+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=C-t.CLOCK_SKEW_SECS_,k=b+t.CLOCK_SKEW_SECS_;if(y<m)throw new Error("Token used too early, "+y+" < "+m+": "+JSON.stringify(p));if(y>k)throw new Error("Token used too late, "+y+" > "+k+": "+JSON.stringify(p));if(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let w=p.aud,A=!1;if(r.constructor===Array?A=r.indexOf(w)>-1:A=w===r,!A)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new BA.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};on.OAuth2Client=Sl});var vl=K(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.Compute=void 0;var MA=Qe(),uy=ns(),LA=vr(),kl=class extends LA.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await uy.instance(o)}catch(o){throw o instanceof MA.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await uy.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};aa.Compute=kl});var Dl=K(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.IdTokenClient=void 0;var jA=vr(),Tl=class extends jA.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};ua.IdTokenClient=Tl});var Rl=K(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.GCPEnv=void 0;uo.clear=$A;uo.getEnv=UA;var cy=ns(),sn;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(sn||(uo.GCPEnv=sn={}));var ss;function $A(){ss=void 0}async function UA(){return ss||(ss=qA(),ss)}async function qA(){let t=sn.NONE;return HA()?t=sn.APP_ENGINE:zA()?t=sn.CLOUD_FUNCTIONS:await VA()?await JA()?t=sn.KUBERNETES_ENGINE:WA()?t=sn.CLOUD_RUN:GA()?t=sn.CLOUD_RUN_JOBS:t=sn.COMPUTE_ENGINE:t=sn.NONE,t}function HA(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function zA(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function WA(){return!!process.env.K_CONFIGURATION}function GA(){return!!process.env.CLOUD_RUN_JOB}async function JA(){try{return await cy.instance("attributes/cluster-name"),!0}catch{return!1}}async function VA(){return cy.isAvailable()}});var xl=K((G1,ly)=>{var ca=io().Buffer,KA=require("stream"),YA=require("util");function la(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=ca.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=ca.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}YA.inherits(la,KA);la.prototype.write=function(e){this.buffer=ca.concat([this.buffer,ca.from(e)]),this.emit("data",e)};la.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};ly.exports=la});var fy=K((J1,dy)=>{"use strict";var is=require("buffer").Buffer,Ol=require("buffer").SlowBuffer;dy.exports=da;function da(t,e){if(!is.isBuffer(t)||!is.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}da.install=function(){is.prototype.equal=Ol.prototype.equal=function(e){return da(this,e)}};var QA=is.prototype.equal,XA=Ol.prototype.equal;da.restore=function(){is.prototype.equal=QA,Ol.prototype.equal=XA}});var Nl=K((V1,wy)=>{var lo=io().Buffer,Ot=require("crypto"),py=pl(),hy=require("util"),ZA=`"%s" is not a valid algorithm.
49
+ `+y+"}":"{"+_.join(",")+"}",r=y,b}}typeof mg.stringify!="function"&&(mg.stringify=function(d,f,p){var m;if(r="",o="",typeof p=="number")for(m=0;m<p;m+=1)o+=" ";else typeof p=="string"&&(o=p);if(a=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return l("",{"":d})})})()});var bg=K((A1,_g)=>{var Ki=null,EE=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,AE=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,SE=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
+ `,r:"\r",t:" "},s,a=function(y){throw{name:"SyntaxError",message:y,at:n,text:s}},c=function(y){return y&&y!==r&&a("Expected '"+y+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},l=function(){var y,_="";for(r==="-"&&(_="-",c("-"));r>="0"&&r<="9";)_+=r,c();if(r===".")for(_+=".";c()&&r>="0"&&r<="9";)_+=r;if(r==="e"||r==="E")for(_+=r,c(),(r==="-"||r==="+")&&(_+=r,c());r>="0"&&r<="9";)_+=r,c();if(y=+_,!isFinite(y))a("Bad number");else return Ki==null&&(Ki=Yc()),_.length>15?e.storeAsString?_:e.useNativeBigInt?BigInt(_):new Ki(_):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new Ki(y):y},d=function(){var y,_,g="",S;if(r==='"')for(var w=n;c();){if(r==='"')return n-1>w&&(g+=s.substring(w,n-1)),c(),g;if(r==="\\"){if(n-1>w&&(g+=s.substring(w,n-1)),c(),r==="u"){for(S=0,_=0;_<4&&(y=parseInt(c(),16),!!isFinite(y));_+=1)S=S*16+y;g+=String.fromCharCode(S)}else if(typeof o[r]=="string")g+=o[r];else break;w=n}}a("Bad string")},f=function(){for(;r&&r<=" ";)c()},p=function(){switch(r){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}a("Unexpected '"+r+"'")},m,b=function(){var y=[];if(r==="["){if(c("["),f(),r==="]")return c("]"),y;for(;r;){if(y.push(m()),f(),r==="]")return c("]"),y;c(","),f()}}a("Bad array")},C=function(){var y,_=Object.create(null);if(r==="{"){if(c("{"),f(),r==="}")return c("}"),_;for(;r;){if(y=d(),f(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(_,y)&&a('Duplicate key "'+y+'"'),EE.test(y)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?m():_[y]=m():AE.test(y)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?m():_[y]=m():_[y]=m(),f(),r==="}")return c("}"),_;c(","),f()}}a("Bad object")};return m=function(){switch(f(),r){case"{":return C();case"[":return b();case'"':return d();case"-":return l();default:return r>="0"&&r<="9"?l():p()}},function(y,_){var g;return s=y+"",n=0,r=" ",g=m(),f(),r&&a("Syntax error"),typeof _=="function"?(function S(w,E){var T,R,U=w[E];return U&&typeof U=="object"&&Object.keys(U).forEach(function(J){R=S(U,J),R!==void 0?U[J]=R:delete U[J]}),_.call(w,E,U)})({"":g},""):g}};_g.exports=SE});var Eg=K((S1,Yi)=>{var Cg=yg().stringify,wg=bg();Yi.exports=function(t){return{parse:wg(t),stringify:Cg}};Yi.exports.parse=wg();Yi.exports.stringify=Cg});var Qc=K(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.GCE_LINUX_BIOS_PATHS=void 0;zt.isGoogleCloudServerless=kg;zt.isGoogleComputeEngineLinux=vg;zt.isGoogleComputeEngineMACAddress=Tg;zt.isGoogleComputeEngine=Dg;zt.detectGCPResidency=vE;var Ag=require("fs"),Sg=require("os");zt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var kE=/^42:01/;function kg(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function vg(){if((0,Sg.platform)()!=="linux")return!1;try{(0,Ag.statSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Ag.readFileSync)(zt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Tg(){let t=(0,Sg.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(kE.test(n))return!0}return!1}function Dg(){return vg()||Tg()}function vE(){return kg()||Dg()}});var Rg=K(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Colours=void 0;var et=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Qi.Colours=et;et.enabled=!1;et.reset="";et.bright="";et.dim="";et.red="";et.green="";et.yellow="";et.blue="";et.magenta="";et.cyan="";et.white="";et.grey="";et.refresh()});var Fg=K(Te=>{"use strict";var TE=Te&&Te.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),DE=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xg=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&TE(n,e,r[o]);return DE(n,e),n}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=Zc;Te.getDebugBackend=xE;Te.getStructuredBackend=OE;Te.setBackend=PE;Te.log=Pg;var RE=require("events"),Zo=xg(require("process")),Og=xg(require("util")),yt=Rg(),Wt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(Wt||(Te.LogSeverity=Wt={}));var es=class extends RE.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(Wt.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Wt.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Wt.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Wt.ERROR,...r),this.func.sublog=r=>Pg(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Te.AdhocDebugLogger=es;Te.placeholder=new es("",()=>{}).func;var ro=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=Zo.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};Te.DebugLogBackendBase=ro;var Xc=class extends ro{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var o;let s=`${yt.Colours.green}${e}${yt.Colours.reset}`,a=`${yt.Colours.yellow}${Zo.pid}${yt.Colours.reset}`,c;switch(n.severity){case Wt.ERROR:c=`${yt.Colours.red}${n.severity}${yt.Colours.reset}`;break;case Wt.INFO:c=`${yt.Colours.magenta}${n.severity}${yt.Colours.reset}`;break;case Wt.WARNING:c=`${yt.Colours.yellow}${n.severity}${yt.Colours.reset}`;break;default:c=(o=n.severity)!==null&&o!==void 0?o:Wt.DEFAULT;break}let l=Og.formatWithOptions({colors:yt.Colours.enabled},...r),d=Object.assign({},n);delete d.severity;let f=Object.getOwnPropertyNames(d).length?JSON.stringify(d):"",p=f?`${yt.Colours.grey}${f}${yt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,f?` ${p}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function Zc(){return new Xc}var el=class extends ro{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=Zo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Zo.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function xE(t){return new el(t)}var tl=class extends ro{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:Wt.INFO,l=Object.assign({severity:c,message:Og.format(...s)},o),d=JSON.stringify(l);r?r(o,d):console.log("%s",d)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function OE(t){return new tl(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var nl=new Map,_t;function PE(t){_t=t,nl.clear()}function Pg(t,e){if(!_t&&!Zo.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=nl.get(t);if(n)return n.func;if(_t===null)return Te.placeholder;_t===void 0&&(_t=Zc());let r=(()=>{let o;return new es(t,(a,...c)=>{if(o!==_t){if(_t===null)return;_t===void 0&&(_t=Zc()),o=_t}_t?.log(t,a,...c)})})();return nl.set(t,r),r.func}});var rl=K(Ar=>{"use strict";var FE=Ar&&Ar.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),IE=Ar&&Ar.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&FE(e,t,n)};Object.defineProperty(Ar,"__esModule",{value:!0});IE(Fg(),Ar)});var ns=K(ue=>{"use strict";var Ng=ue&&ue.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),NE=ue&&ue.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),BE=ue&&ue.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&Ng(n,e,r[o]);return NE(n,e),n}})(),ME=ue&&ue.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ng(e,t,n)};Object.defineProperty(ue,"__esModule",{value:!0});ue.gcpResidencyCache=ue.METADATA_SERVER_DETECTION=ue.HEADERS=ue.HEADER_VALUE=ue.HEADER_NAME=ue.SECONDARY_HOST_ADDRESS=ue.HOST_ADDRESS=ue.BASE_PATH=void 0;ue.instance=HE;ue.project=zE;ue.universe=WE;ue.bulk=GE;ue.isAvailable=VE;ue.resetIsAvailableCache=KE;ue.getGCPResidency=il;ue.setGCPResidency=Bg;ue.requestTimeout=Mg;var ol=Qe(),LE=Eg(),jE=Qc(),$E=BE(rl());ue.BASE_PATH="/computeMetadata/v1";ue.HOST_ADDRESS="http://169.254.169.254";ue.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ue.HEADER_NAME="Metadata-Flavor";ue.HEADER_VALUE="Google";ue.HEADERS=Object.freeze({[ue.HEADER_NAME]:ue.HEADER_VALUE});var Ig=$E.log("gcp-metadata");ue.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function sl(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ue.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ue.BASE_PATH,t).href}function UE(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ts(t,e={},n=3,r=!1){let o=new Headers(ue.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((m,b)=>o.set(b,m)),s=p.metadataKey,a=p.params||a,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(UE(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,m)=>o.set(m,p)),a=e.params||a);let c=r?qE:ol.request,l={url:`${sl()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:Mg()};Ig.info("instance request %j",l);let d=await c(l);Ig.info("instance metadata is %s",d.data);let f=d.headers.get(ue.HEADER_NAME);if(f!==ue.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ue.HEADER_NAME} header. Expected '${ue.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return LE.parse(d.data)}catch{}return d.data}async function qE(t){let e={...t,url:t.url?.toString().replace(sl(),sl(ue.SECONDARY_HOST_ADDRESS))},n=(0,ol.request)(t),r=(0,ol.request)(e);return Promise.any([n,r])}function HE(t){return ts("instance",t)}function zE(t){return ts("project",t)}function WE(t){return ts("universe",t)}async function GE(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await ts(n),o=n.metadataKey;e[o]=r})())),e}function JE(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Xi;async function VE(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ue.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ue.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return il();case"ping-only":}}try{return Xi===void 0&&(Xi=ts("instance",void 0,JE(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Xi,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function KE(){Xi=void 0}ue.gcpResidencyCache=null;function il(){return ue.gcpResidencyCache===null&&Bg(),ue.gcpResidencyCache}function Bg(t=null){ue.gcpResidencyCache=t!==null?t:(0,jE.detectGCPResidency)()}function Mg(){return il()?0:3e3}ME(Qc(),ue)});var $g=K(Zi=>{"use strict";Zi.byteLength=QE;Zi.toByteArray=ZE;Zi.fromByteArray=nA;var nn=[],xt=[],YE=typeof Uint8Array<"u"?Uint8Array:Array,al="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Sr=0,Lg=al.length;Sr<Lg;++Sr)nn[Sr]=al[Sr],xt[al.charCodeAt(Sr)]=Sr;var Sr,Lg;xt[45]=62;xt[95]=63;function jg(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function QE(t){var e=jg(t),n=e[0],r=e[1];return(n+r)*3/4-r}function XE(t,e,n){return(e+n)*3/4-n}function ZE(t){var e,n=jg(t),r=n[0],o=n[1],s=new YE(XE(t,r,o)),a=0,c=o>0?r-4:r,l;for(l=0;l<c;l+=4)e=xt[t.charCodeAt(l)]<<18|xt[t.charCodeAt(l+1)]<<12|xt[t.charCodeAt(l+2)]<<6|xt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=xt[t.charCodeAt(l)]<<2|xt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=xt[t.charCodeAt(l)]<<10|xt[t.charCodeAt(l+1)]<<4|xt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function eA(t){return nn[t>>18&63]+nn[t>>12&63]+nn[t>>6&63]+nn[t&63]}function tA(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(eA(r));return o.join("")}function nA(t){for(var e,n=t.length,r=n%3,o=[],s=16383,a=0,c=n-r;a<c;a+=s)o.push(tA(t,a,a+s>c?c:a+s));return r===1?(e=t[n-1],o.push(nn[e>>2]+nn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(nn[e>>10]+nn[e>>4&63]+nn[e<<2&63]+"=")),o.join("")}});var cl=K(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.fromArrayBufferToHex=rA;function rA(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Ug=K(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.BrowserCrypto=void 0;var oo=$g(),oA=cl(),ll=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return oo.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),oo.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),a=oo.toByteArray(t.padBase64(r)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,s,o);return oo.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=oo.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return oo.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,oA.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};ea.BrowserCrypto=ll});var qg=K(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.NodeCrypto=void 0;var so=require("crypto"),dl=class{async sha256DigestBase64(e){return so.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return so.randomBytes(e).toString("base64")}async verify(e,n,r){let o=so.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=so.createSign("RSA-SHA256");return r.update(n),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return so.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:iA(e);return sA(so.createHmac("sha256",r).update(n).digest())}};ta.NodeCrypto=dl;function sA(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function iA(t){return Buffer.from(t)}});var rs=K(Tn=>{"use strict";var aA=Tn&&Tn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),uA=Tn&&Tn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&aA(e,t,n)};Object.defineProperty(Tn,"__esModule",{value:!0});Tn.createCrypto=dA;Tn.hasBrowserCrypto=Hg;var cA=Ug(),lA=qg();uA(cl(),Tn);function dA(){return Hg()?new cA.BrowserCrypto:new lA.NodeCrypto}function Hg(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var io=K((fl,Wg)=>{var na=require("buffer"),rn=na.Buffer;function zg(t,e){for(var n in t)e[n]=t[n]}rn.from&&rn.alloc&&rn.allocUnsafe&&rn.allocUnsafeSlow?Wg.exports=na:(zg(na,fl),fl.Buffer=kr);function kr(t,e,n){return rn(t,e,n)}kr.prototype=Object.create(rn.prototype);zg(rn,kr);kr.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return rn(t,e,n)};kr.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=rn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};kr.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return rn(t)};kr.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return na.SlowBuffer(t)}});var Jg=K((N1,Gg)=>{"use strict";function hl(t){var e=(t/8|0)+(t%8===0?0:1);return e}var fA={ES256:hl(256),ES384:hl(384),ES512:hl(521)};function hA(t){var e=fA[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Gg.exports=hA});var pl=K((B1,Zg)=>{"use strict";var ra=io().Buffer,Kg=Jg(),oa=128,Yg=0,pA=32,mA=16,gA=2,Qg=mA|pA|Yg<<6,sa=gA|Yg<<6;function yA(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xg(t){if(ra.isBuffer(t))return t;if(typeof t=="string")return ra.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function _A(t,e){t=Xg(t);var n=Kg(e),r=n+1,o=t.length,s=0;if(t[s++]!==Qg)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(oa|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==sa)throw new Error('Could not find expected "int" for "r"');var c=t[s++];if(o-s-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(o-s-2)+'" available');if(r<c)throw new Error('"r" specified length of "'+c+'", max of "'+r+'" is acceptable');var l=s;if(s+=c,t[s++]!==sa)throw new Error('Could not find expected "int" for "s"');var d=t[s++];if(o-s!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(o-s)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=s;if(s+=d,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-c,m=n-d,b=ra.allocUnsafe(p+c+m+d);for(s=0;s<p;++s)b[s]=0;t.copy(b,s,l+Math.max(-p,0),l+c),s=n;for(var C=s;s<C+m;++s)b[s]=0;return t.copy(b,s,f+Math.max(-m,0),f+d),b=b.toString("base64"),b=yA(b),b}function Vg(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=oa;return o&&--r,r}function bA(t,e){t=Xg(t);var n=Kg(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=Vg(t,0,n),s=Vg(t,n,t.length),a=n-o,c=n-s,l=2+a+1+1+c,d=l<oa,f=ra.allocUnsafe((d?2:3)+l),p=0;return f[p++]=Qg,d?f[p++]=l:(f[p++]=oa|1,f[p++]=l&255),f[p++]=sa,f[p++]=a,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=sa,f[p++]=c,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}Zg.exports={derToJose:_A,joseToDer:bA}});var Gt=K(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.LRUCache=void 0;Dn.snakeToCamel=ty;Dn.originalOrCamelOptions=AA;Dn.removeUndefinedValuesInObject=SA;Dn.isValidFile=kA;Dn.getWellKnownCertificateConfigFileLocation=vA;var CA=require("fs"),wA=require("os"),ml=require("path"),EA="certificate_config.json",ey="gcloud";function ty(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function AA(t){function e(n){let r=t||{};return r[n]??r[ty(n)]}return{get:e}}var gl=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};Dn.LRUCache=gl;function SA(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function kA(t){try{return(await CA.promises.lstat(t)).isFile()}catch{return!1}}function vA(){let t=process.env.CLOUDSDK_CONFIG||(TA()?ml.join(process.env.APPDATA||"",ey):ml.join(process.env.HOME||"",".config",ey));return ml.join(t,EA)}function TA(){return wA.platform().startsWith("win")}});var ny=K((L1,DA)=>{DA.exports={name:"google-auth-library",version:"10.4.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var yl=K(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.USER_AGENT=Xn.PRODUCT_NAME=Xn.pkg=void 0;var ry=ny();Xn.pkg=ry;var oy="google-api-nodejs-client";Xn.PRODUCT_NAME=oy;var RA=`${oy}/${ry.version}`;Xn.USER_AGENT=RA});var bt=K(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.AuthClient=Jt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Jt.DEFAULT_UNIVERSE=void 0;var xA=require("events"),_l=Qe(),OA=Gt(),PA=rl(),bl=yl();Jt.DEFAULT_UNIVERSE="googleapis.com";Jt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Cl=class t extends xA.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Jt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Jt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,OA.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??Jt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new _l.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&_l.Gaxios.mergeHeaders(s,n.headers),r&&_l.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,PA.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${bl.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${bl.USER_AGENT}`):e.headers.set("User-Agent",bl.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,a):t.log.info("[%s] request %j",s,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Jt.AuthClient=Cl});var El=K(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.LoginTicket=void 0;var wl=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};ia.LoginTicket=wl});var vr=K(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.OAuth2Client=on.ClientAuthentication=on.CertificateFormat=on.CodeChallengeMethod=void 0;var sy=Qe(),FA=require("querystring"),IA=require("stream"),NA=pl(),iy=Gt(),Al=rs(),ao=bt(),BA=El(),ay;(function(t){t.Plain="plain",t.S256="S256"})(ay||(on.CodeChallengeMethod=ay={}));var Rn;(function(t){t.PEM="PEM",t.JWK="JWK"})(Rn||(on.CertificateFormat=Rn={}));var os;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(os||(on.ClientAuthentication=os={}));var Sl=class t extends ao.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Rn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||os.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+FA.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Al.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===os.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===os.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,iy.removeUndefinedValuesInObject)(o)),headers:r};ao.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),c=a.data;return a.data&&a.data.expires_in&&(c.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,iy.removeUndefinedValuesInObject)(r))};ao.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof sy.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let c=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(c){let l=c;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(ao.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=sy.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=o.config.data instanceof IA.Readable,d=s===401||s===403;if(!n&&d&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!l&&c){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,Al.hasBrowserCrypto)()?Rn.JWK:Rn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Rn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Rn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};ao.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let s=r?.headers.get("cache-control"),a=-1;if(s){let d=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;d&&(a=Number(d)*1e3)}let c={};switch(n){case Rn.PEM:c=r.data;break;case Rn.JWK:for(let d of r.data.keys)c[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=n,{certs:c,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};ao.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let a=(0,Al.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=c[0]+"."+c[1],d=c[2],f,p;try{f=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token envelope: ${c[0]}': ${w.message}`),w}if(!f)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token payload '${c[0]}`),w}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let m=n[f.kid];if(f.alg==="ES256"&&(d=NA.joseToDer(d,"ES256").toString("base64")),!await a.verify(m,l,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let C=Number(p.iat);if(isNaN(C))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let _=new Date().getTime()/1e3;if(y>=_+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let g=C-t.CLOCK_SKEW_SECS_,S=y+t.CLOCK_SKEW_SECS_;if(_<g)throw new Error("Token used too early, "+_+" < "+g+": "+JSON.stringify(p));if(_>S)throw new Error("Token used too late, "+_+" > "+S+": "+JSON.stringify(p));if(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let w=p.aud,E=!1;if(r.constructor===Array?E=r.indexOf(w)>-1:E=w===r,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new BA.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};on.OAuth2Client=Sl});var vl=K(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.Compute=void 0;var MA=Qe(),uy=ns(),LA=vr(),kl=class extends LA.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await uy.instance(o)}catch(o){throw o instanceof MA.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await uy.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};aa.Compute=kl});var Dl=K(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.IdTokenClient=void 0;var jA=vr(),Tl=class extends jA.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};ua.IdTokenClient=Tl});var Rl=K(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.GCPEnv=void 0;uo.clear=$A;uo.getEnv=UA;var cy=ns(),sn;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(sn||(uo.GCPEnv=sn={}));var ss;function $A(){ss=void 0}async function UA(){return ss||(ss=qA(),ss)}async function qA(){let t=sn.NONE;return HA()?t=sn.APP_ENGINE:zA()?t=sn.CLOUD_FUNCTIONS:await VA()?await JA()?t=sn.KUBERNETES_ENGINE:WA()?t=sn.CLOUD_RUN:GA()?t=sn.CLOUD_RUN_JOBS:t=sn.COMPUTE_ENGINE:t=sn.NONE,t}function HA(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function zA(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function WA(){return!!process.env.K_CONFIGURATION}function GA(){return!!process.env.CLOUD_RUN_JOB}async function JA(){try{return await cy.instance("attributes/cluster-name"),!0}catch{return!1}}async function VA(){return cy.isAvailable()}});var xl=K((G1,ly)=>{var ca=io().Buffer,KA=require("stream"),YA=require("util");function la(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=ca.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=ca.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}YA.inherits(la,KA);la.prototype.write=function(e){this.buffer=ca.concat([this.buffer,ca.from(e)]),this.emit("data",e)};la.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};ly.exports=la});var fy=K((J1,dy)=>{"use strict";var is=require("buffer").Buffer,Ol=require("buffer").SlowBuffer;dy.exports=da;function da(t,e){if(!is.isBuffer(t)||!is.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}da.install=function(){is.prototype.equal=Ol.prototype.equal=function(e){return da(this,e)}};var QA=is.prototype.equal,XA=Ol.prototype.equal;da.restore=function(){is.prototype.equal=QA,Ol.prototype.equal=XA}});var Nl=K((V1,wy)=>{var lo=io().Buffer,Ot=require("crypto"),py=pl(),hy=require("util"),ZA=`"%s" is not a valid algorithm.
51
51
  Supported algorithms are:
52
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,as="secret must be a string or buffer",co="key must be a string or a buffer",eS="key must be a string, a buffer or an object",Fl=typeof Ot.createPublicKey=="function";Fl&&(co+=" or a KeyObject",as+="or a KeyObject");function my(t){if(!lo.isBuffer(t)&&typeof t!="string"&&(!Fl||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Vt(co)}function gy(t){if(!lo.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Vt(eS)}function tS(t){if(!lo.isBuffer(t)){if(typeof t=="string")return t;if(!Fl||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Vt(as)}}function Il(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function yy(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Vt(t){var e=[].slice.call(arguments,1),n=hy.format.bind(hy,t).apply(null,e);return new TypeError(n)}function nS(t){return lo.isBuffer(t)||typeof t=="string"}function us(t){return nS(t)||(t=JSON.stringify(t)),t}function _y(t){return function(n,r){tS(r),n=us(n);var o=Ot.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Il(s)}}var Pl,rS="timingSafeEqual"in Ot?function(e,n){return e.byteLength!==n.byteLength?!1:Ot.timingSafeEqual(e,n)}:function(e,n){return Pl||(Pl=fy()),Pl(e,n)};function oS(t){return function(n,r,o){var s=_y(t)(n,o);return rS(lo.from(r),lo.from(s))}}function by(t){return function(n,r){gy(r),n=us(n);var o=Ot.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Il(s)}}function Cy(t){return function(n,r,o){my(o),n=us(n),r=yy(r);var s=Ot.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function sS(t){return function(n,r){gy(r),n=us(n);var o=Ot.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Ot.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ot.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Il(s)}}function iS(t){return function(n,r,o){my(o),n=us(n),r=yy(r);var s=Ot.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Ot.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ot.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function aS(t){var e=by(t);return function(){var r=e.apply(null,arguments);return r=py.derToJose(r,"ES"+t),r}}function uS(t){var e=Cy(t);return function(r,o,s){o=py.joseToDer(o,"ES"+t).toString("base64");var a=e(r,o,s);return a}}function cS(){return function(){return""}}function lS(){return function(e,n){return n===""}}wy.exports=function(e){var n={hs:_y,rs:by,ps:sS,es:aS,none:cS},r={hs:oS,rs:Cy,ps:iS,es:uS,none:lS},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Vt(ZA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:n[s](a),verify:r[s](a)}}});var Bl=K((K1,Ey)=>{var dS=require("buffer").Buffer;Ey.exports=function(e){return typeof e=="string"?e:typeof e=="number"||dS.isBuffer(e)?e.toString():JSON.stringify(e)}});var Dy=K((Y1,Ty)=>{var fS=io().Buffer,Ay=xl(),hS=Nl(),pS=require("stream"),Sy=Bl(),Ml=require("util");function ky(t,e){return fS.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function mS(t,e,n){n=n||"utf8";var r=ky(Sy(t),"binary"),o=ky(Sy(e),n);return Ml.format("%s.%s",r,o)}function vy(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=hS(e.alg),a=mS(e,n,o),c=s.sign(a,r);return Ml.format("%s.%s",a,c)}function fa(t){var e=t.secret||t.privateKey||t.key,n=new Ay(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new Ay(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Ml.inherits(fa,pS);fa.prototype.sign=function(){try{var e=vy({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};fa.sign=vy;Ty.exports=fa});var Ly=K((Q1,My)=>{var xy=io().Buffer,Ry=xl(),gS=Nl(),yS=require("stream"),Oy=Bl(),_S=require("util"),bS=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function CS(t){return Object.prototype.toString.call(t)==="[object Object]"}function wS(t){if(CS(t))return t;try{return JSON.parse(t)}catch{return}}function Py(t){var e=t.split(".",1)[0];return wS(xy.from(e,"base64").toString("binary"))}function ES(t){return t.split(".",2).join(".")}function Fy(t){return t.split(".")[2]}function AS(t,e){e=e||"utf8";var n=t.split(".")[1];return xy.from(n,"base64").toString(e)}function Iy(t){return bS.test(t)&&!!Py(t)}function Ny(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Oy(t);var o=Fy(t),s=ES(t),a=gS(e);return a.verify(s,o,n)}function By(t,e){if(e=e||{},t=Oy(t),!Iy(t))return null;var n=Py(t);if(!n)return null;var r=AS(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Fy(t)}}function fo(t){t=t||{};var e=t.secret||t.publicKey||t.key,n=new Ry(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Ry(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}_S.inherits(fo,yS);fo.prototype.verify=function(){try{var e=Ny(this.signature.buffer,this.algorithm,this.key.buffer),n=By(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};fo.decode=By;fo.isValid=Iy;fo.verify=Ny;My.exports=fo});var Ll=K(Zn=>{var jy=Dy(),ha=Ly(),SS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Zn.ALGORITHMS=SS;Zn.sign=jy.sign;Zn.verify=ha.verify;Zn.decode=ha.decode;Zn.isValid=ha.isValid;Zn.createSign=function(e){return new jy(e)};Zn.createVerify=function(e){return new ha(e)}});var e0=K(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.GoogleToken=void 0;var $y=pa(require("fs")),kS=Qe(),vS=pa(Ll()),TS=pa(require("path")),DS=require("util");function pa(t,e){if(typeof WeakMap=="function")var n=new WeakMap,r=new WeakMap;return(pa=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,d={__proto__:null,default:s};if(s===null||xn(s)!="object"&&typeof s!="function")return d;if(c=a?r:n){if(c.has(s))return c.get(s);c.set(s,d)}for(var f in s)f!=="default"&&{}.hasOwnProperty.call(s,f)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,f))&&(l.get||l.set)?c(d,f,l):d[f]=s[f]);return d})(t,e)}function xn(t){"@babel/helpers - typeof";return xn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},xn(t)}function RS(t,e){Ky(t,e),e.add(t)}function xS(t,e,n){Ky(t,e),e.set(t,n)}function Ky(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Uy(t,e,n){return t.set(Kt(t,e),n),n}function qy(t,e){return t.get(Kt(t,e))}function Kt(t,e,n){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:n;throw new TypeError("Private element is not present on this object")}function Hy(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,Xy(r.key),r)}}function Yy(t,e,n){return e&&Hy(t.prototype,e),n&&Hy(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function Qy(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function OS(t,e,n){return e=fs(e),PS(t,zl()?Reflect.construct(e,n||[],fs(t).constructor):e.apply(t,n))}function PS(t,e){if(e&&(xn(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return FS(t)}function FS(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function IS(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&ds(t,e)}function jl(t){var e=typeof Map=="function"?new Map:void 0;return jl=function(r){if(r===null||!BS(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return NS(r,arguments,fs(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),ds(o,r)},jl(t)}function NS(t,e,n){if(zl())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&ds(o,n.prototype),o}function zl(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(zl=function(){return!!t})()}function BS(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function ds(t,e){return ds=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},ds(t,e)}function fs(t){return fs=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},fs(t)}function Ct(t,e,n){return(e=Xy(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Xy(t){var e=MS(t,"string");return xn(e)=="symbol"?e:e+""}function MS(t,e){if(xn(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(xn(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Et(){var t,e,n=typeof Symbol=="function"?Symbol:{},r=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(_,C,b,y){var m=C&&C.prototype instanceof c?C:c,k=Object.create(m.prototype);return wt(k,"_invoke",(function(w,A,T){var R,U,J,F=0,V=T||[],Y=!1,X={p:0,n:0,v:t,a:ee,f:ee.bind(t,4),d:function(Ae,ae){return R=Ae,U=0,J=t,X.n=ae,a}};function ee(de,Ae){for(U=de,J=Ae,e=0;!Y&&F&&!ae&&e<V.length;e++){var ae,pe=V[e],W=X.p,Q=pe[2];de>3?(ae=Q===Ae)&&(J=pe[(U=pe[4])?5:(U=3,3)],pe[4]=pe[5]=t):pe[0]<=W&&((ae=de<2&&W<pe[1])?(U=0,X.v=Ae,X.n=pe[1]):W<Q&&(ae=de<3||pe[0]>Ae||Ae>Q)&&(pe[4]=de,pe[5]=Ae,X.n=Q,U=0))}if(ae||de>1)return a;throw Y=!0,Ae}return function(de,Ae,ae){if(F>1)throw TypeError("Generator is already running");for(Y&&Ae===1&&ee(Ae,ae),U=Ae,J=ae;(e=U<2?t:J)||!Y;){R||(U?U<3?(U>1&&(X.n=-1),ee(U,J)):X.n=J:X.v=J);try{if(F=2,R){if(U||(de="next"),e=R[de]){if(!(e=e.call(R,J)))throw TypeError("iterator result is not an object");if(!e.done)return e;J=e.value,U<2&&(U=0)}else U===1&&(e=R.return)&&e.call(R),U<2&&(J=TypeError("The iterator does not provide a '"+de+"' method"),U=1);R=t}else if((e=(Y=X.n<0)?J:w.call(A,X))!==a)break}catch(pe){R=t,U=1,J=pe}finally{F=1}}return{value:e,done:Y}}})(_,b,y),!0),k}var a={};function c(){}function l(){}function d(){}e=Object.getPrototypeOf;var f=[][r]?e(e([][r]())):(wt(e={},r,function(){return this}),e),p=d.prototype=c.prototype=Object.create(f);function g(_){return Object.setPrototypeOf?Object.setPrototypeOf(_,d):(_.__proto__=d,wt(_,o,"GeneratorFunction")),_.prototype=Object.create(p),_}return l.prototype=d,wt(p,"constructor",d),wt(d,"constructor",l),l.displayName="GeneratorFunction",wt(d,o,"GeneratorFunction"),wt(p),wt(p,o,"Generator"),wt(p,r,function(){return this}),wt(p,"toString",function(){return"[object Generator]"}),(Et=function(){return{w:s,m:g}})()}function wt(t,e,n,r){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}wt=function(a,c,l,d){if(c)o?o(a,c,{value:l,enumerable:!d,configurable:!d,writable:!d}):a[c]=l;else{var f=function(g,_){wt(a,g,function(C){return this._invoke(g,_,C)})};f("next",0),f("throw",1),f("return",2)}},wt(t,e,n,r)}function zy(t,e,n,r,o,s,a){try{var c=t[s](a),l=c.value}catch(d){return void n(d)}c.done?e(l):Promise.resolve(l).then(r,o)}function ho(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var s=t.apply(e,n);function a(l){zy(s,r,o,a,c,"next",l)}function c(l){zy(s,r,o,a,c,"throw",l)}a(void 0)})}}var Wy=$y.readFile?(0,DS.promisify)($y.readFile):ho(Et().m(function t(){return Et().w(function(e){for(;;)switch(e.n){case 0:throw new ls("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Gy="https://oauth2.googleapis.com/token",LS="https://oauth2.googleapis.com/revoke?token=",ls=(function(t){function e(n,r){var o;return Qy(this,e),o=OS(this,e,[n]),Ct(o,"code",void 0),o.code=r,o}return IS(e,t),Yy(e)})(jl(Error)),cs=new WeakMap,an=new WeakSet,Z1=ma.GoogleToken=(function(){function t(e){Qy(this,t),RS(this,an),Ct(this,"expiresAt",void 0),Ct(this,"key",void 0),Ct(this,"keyFile",void 0),Ct(this,"iss",void 0),Ct(this,"sub",void 0),Ct(this,"scope",void 0),Ct(this,"rawToken",void 0),Ct(this,"tokenExpires",void 0),Ct(this,"email",void 0),Ct(this,"additionalClaims",void 0),Ct(this,"eagerRefreshThresholdMillis",void 0),Ct(this,"transporter",{request:function(r){return(0,kS.request)(r)}}),xS(this,cs,void 0),Kt(an,this,Zy).call(this,e)}return Yy(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var n=new Date().getTime();return this.rawToken&&this.expiresAt?n>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var n,r=new Date().getTime(),o=(n=this.eagerRefreshThresholdMillis)!==null&&n!==void 0?n:0;return this.rawToken&&this.expiresAt?this.expiresAt<=r+o:!0}},{key:"getToken",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(xn(n)==="object"&&(r=n,n=void 0),r=Object.assign({forceRefresh:!1},r),n){var o=n;Kt(an,this,Jy).call(this,r).then(function(s){return o(null,s)},n);return}return Kt(an,this,Jy).call(this,r)}},{key:"getCredentials",value:(function(){var e=ho(Et().m(function r(o){var s,a,c,l,d,f,p;return Et().w(function(g){for(;;)switch(g.n){case 0:s=TS.extname(o),p=s,g.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return g.n=2,Wy(o,"utf8");case 2:if(a=g.v,c=JSON.parse(a),l=c.private_key,d=c.client_email,!(!l||!d)){g.n=3;break}throw new ls("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return g.a(2,{privateKey:l,clientEmail:d});case 4:return g.n=5,Wy(o,"utf8");case 5:return f=g.v,g.a(2,{privateKey:f});case 6:throw new ls("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new ls("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return g.a(2)}},r)}));function n(r){return e.apply(this,arguments)}return n})()},{key:"revokeToken",value:function(n){if(n){Kt(an,this,Vy).call(this).then(function(){return n()},n);return}return Kt(an,this,Vy).call(this)}}])})();function Jy(t){return $l.apply(this,arguments)}function $l(){return $l=ho(Et().m(function t(e){return Et().w(function(n){for(;;)switch(n.n){case 0:if(!(qy(cs,this)&&!e.forceRefresh)){n.n=1;break}return n.a(2,qy(cs,this));case 1:return n.p=1,n.n=2,Uy(cs,this,Kt(an,this,jS).call(this,e));case 2:return n.a(2,n.v);case 3:return n.p=3,Uy(cs,this,void 0),n.f(3);case 4:return n.a(2)}},t,this,[[1,,3,4]])})),$l.apply(this,arguments)}function jS(t){return Ul.apply(this,arguments)}function Ul(){return Ul=ho(Et().m(function t(e){var n;return Et().w(function(r){for(;;)switch(r.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){r.n=1;break}return r.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){r.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){r.n=4;break}return r.n=3,this.getCredentials(this.keyFile);case 3:n=r.v,this.key=n.privateKey,this.iss=n.clientEmail||this.iss,n.clientEmail||Kt(an,this,$S).call(this);case 4:return r.a(2,Kt(an,this,US).call(this))}},t,this)})),Ul.apply(this,arguments)}function $S(){if(!this.iss)throw new ls("email is required.","MISSING_CREDENTIALS")}function Vy(){return ql.apply(this,arguments)}function ql(){return ql=ho(Et().m(function t(){var e;return Et().w(function(n){for(;;)switch(n.n){case 0:if(this.accessToken){n.n=1;break}throw new Error("No token to revoke.");case 1:return e=LS+this.accessToken,n.n=2,this.transporter.request({url:e,retry:!0});case 2:Kt(an,this,Zy).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return n.a(2)}},t,this)})),ql.apply(this,arguments)}function Zy(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,xn(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function US(){return Hl.apply(this,arguments)}function Hl(){return Hl=ho(Et().m(function t(){var e,n,r,o,s,a,c,l,d,f;return Et().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),n=this.additionalClaims||{},r=Object.assign({iss:this.iss,scope:this.scope,aud:Gy,exp:e+3600,iat:e,sub:this.sub},n),o=vS.sign({header:{alg:"RS256"},payload:r,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:Gy,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=p.v,this.rawToken=s.data,this.expiresAt=s.data.expires_in===null||s.data.expires_in===void 0?void 0:(e+s.data.expires_in)*1e3,p.a(2,this.rawToken);case 3:throw p.p=3,f=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=f.response&&(a=f.response)!==null&&a!==void 0&&a.data?(c=f.response)===null||c===void 0?void 0:c.data:{},l.error&&(d=l.error_description?": ".concat(l.error_description):"",f.message="".concat(l.error).concat(d)),f;case 4:return p.a(2)}},t,this,[[1,3]])})),Hl.apply(this,arguments)}});var Gl=K(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.JWTAccess=void 0;var qS=Ll(),HS=Gt(),t0={alg:"RS256",typ:"JWT"},Wl=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new HS.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:l,iat:c}:d={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},n){for(let C in d)if(n[C])throw new Error(`The '${C}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...t0,kid:this.keyId}:t0,p=Object.assign(d,n),g=qS.sign({header:f,payload:p,secret:this.key}),_=new Headers({authorization:`Bearer ${g}`});return this.cache.set(o,{expiration:l*1e3,headers:_}),_}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};ga.JWTAccess=Wl});var Vl=K(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.JWT=void 0;var n0=e0(),zS=Gl(),WS=vr(),ya=bt(),Jl=class t extends WS.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==ya.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ya.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ya.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new zS.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==ya.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new n0.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new n0.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let n=await this.createGToken().getCredentials(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};_a.JWT=Jl});var Yl=K(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.UserRefreshClient=po.USER_REFRESH_ACCOUNT_TYPE=void 0;var GS=vr(),JS=bt();po.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Kl=class t extends GS.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return JS.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};po.UserRefreshClient=Kl});var Xl=K(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.Impersonated=mo.IMPERSONATED_ACCOUNT_TYPE=void 0;var r0=vr(),VS=Qe(),KS=Gt();mo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Ql=class t extends r0.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new r0.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,KS.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof VS.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};mo.Impersonated=Ql});var ed=K(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.OAuthClientAuthHandler=void 0;hs.getErrorFromOAuthErrorResponse=XS;var go=Qe(),YS=rs(),QS=["PUT","POST","PATCH"],Zl=class{#e=(0,YS.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new go.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new go.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=go.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=go.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=go.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);go.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!QS.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};hs.OAuthClientAuthHandler=Zl;function XS(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let a=new Error(s);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(a,l,{value:e[l],writable:!1,enumerable:!0})})}return a}});var Ca=K(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.StsCredentials=void 0;var ZS=Qe(),ek=bt(),o0=ed(),tk=Gt(),td=class t extends o0.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,tk.removeUndefinedValuesInObject)(o))};ek.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),c=a.data;return c.res=a,c}catch(a){throw a instanceof ZS.GaxiosError&&a.response?(0,o0.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};ba.StsCredentials=td});var er=K(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.BaseExternalAccountClient=Pt.CLOUD_RESOURCE_MANAGER=Pt.EXTERNAL_ACCOUNT_TYPE=Pt.EXPIRATION_TIME_OFFSET=void 0;var nk=Qe(),rk=require("stream"),nd=bt(),ok=Ca(),s0=Gt(),sk=yl(),ik="urn:ietf:params:oauth:grant-type:token-exchange",ak="urn:ietf:params:oauth:token-type:access_token",rd="https://www.googleapis.com/auth/cloud-platform",uk=3600;Pt.EXPIRATION_TIME_OFFSET=300*1e3;Pt.EXTERNAL_ACCOUNT_TYPE="external_account";Pt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var ck="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",lk="https://sts.{universeDomain}/v1/token",od=class t extends nd.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,s0.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Pt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Pt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??lk.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),c=n.get("workforce_pool_user_project"),l=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,s0.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new ok.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[rd],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let p=new RegExp(ck);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=uk),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`};nd.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=nk.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof rk.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:ik,audience:this.audience,requestedTokenType:ak,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[rd]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};nd.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[rd]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${sk.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Pt.BaseExternalAccountClient=od});var i0=K(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.FileSubjectTokenSupplier=void 0;var id=require("util"),ad=require("fs"),dk=(0,id.promisify)(ad.readFile??(()=>{})),fk=(0,id.promisify)(ad.realpath??(()=>{})),hk=(0,id.promisify)(ad.lstat??(()=>{})),sd=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await fk(e),!(await hk(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await dk(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};wa.FileSubjectTokenSupplier=sd});var a0=K(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.UrlSubjectTokenSupplier=void 0;var pk=bt(),ud=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};pk.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};Ea.UrlSubjectTokenSupplier=ud});var u0=K(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.CertificateSubjectTokenSupplier=At.InvalidConfigurationError=At.CertificateSourceUnavailableError=At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Aa=Gt(),Sa=require("fs"),ka=require("crypto"),mk=require("https");At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var un=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};At.CertificateSourceUnavailableError=un;var Ft=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};At.InvalidConfigurationError=Ft;var cd=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ft("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ft("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ft("Cannot create mTLS Agent with missing certificate or key");return new mk.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Aa.isValidFile)(e))return e;throw new un(`Provided certificate config path is invalid: ${e}`)}let n=process.env[At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Aa.isValidFile)(n))return n;throw new un(`Path from environment variable "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Aa.getWellKnownCertificateConfigFileLocation)();if(await(0,Aa.isValidFile)(r))return r;throw new un(`Could not find certificate configuration file. Searched override path, the "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Sa.promises.readFile(e,"utf8")}catch{throw new un(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Ft(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Ft?r:new Ft(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Sa.promises.readFile(e),new ka.X509Certificate(r)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read certificate file at ${e}: ${a}`)}try{o=await Sa.promises.readFile(n),(0,ka.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:o}}async#r(e){let n=new ka.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Sa.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,d)=>{try{return new ka.X509Certificate(l)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Ft(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>n.raw.equals(l.raw)),c;if(a===-1)c=[n,...s];else if(a===0)c=s;else throw new Ft(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(r){if(r instanceof Ft)throw r;let o=r instanceof Error?r.message:String(r);throw new un(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};At.CertificateSubjectTokenSupplier=cd});var fd=K(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.IdentityPoolClient=void 0;var gk=er(),ld=Gt(),yk=i0(),_k=a0(),c0=u0(),bk=Ca(),l0=Qe(),dd=class t extends gk.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,ld.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,ld.originalOrCamelOptions)(r),a=(0,ld.originalOrCamelOptions)(s.get("format")),c=a.get("type")||"text",l=a.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=s.get("file"),f=s.get("url"),p=s.get("certificate"),g=s.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new yk.FileSubjectTokenSupplier({filePath:d,formatType:c,subjectTokenFieldName:l});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new _k.UrlSubjectTokenSupplier({url:f,formatType:c,subjectTokenFieldName:l,headers:g,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let _=new c0.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=_}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof c0.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new bk.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new l0.Gaxios({agent:n})}),this.transporter=new l0.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};va.IdentityPoolClient=dd});var pd=K(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.AwsRequestSigner=void 0;var Ta=Qe(),f0=rs(),d0="AWS4-HMAC-SHA256",Ck="aws4_request",hd=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,f0.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,a=e.headers,c=await this.getCredentials(),l=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let d=await Ek({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:c,requestPayload:s,additionalAmzHeaders:a}),f=Ta.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:l.host},a||{});c.token&&Ta.Gaxios.mergeHeaders(f,{"x-amz-security-token":c.token});let p={url:r,method:o,headers:f};return s!==void 0&&(p.body=s),p}};Da.AwsRequestSigner=hd;async function ps(t,e,n){return await t.signWithHmacSha256(e,n)}async function wk(t,e,n,r,o){let s=await ps(t,`AWS4${e}`,n),a=await ps(t,s,r),c=await ps(t,a,o);return await ps(t,c,"aws4_request")}async function Ek(t){let e=Ta.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=Ta.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",d=[...c.keys()].sort();d.forEach(k=>{l+=`${k}:${c.get(k)}
53
- `});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),g=`${t.method.toUpperCase()}
52
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,as="secret must be a string or buffer",co="key must be a string or a buffer",eS="key must be a string, a buffer or an object",Fl=typeof Ot.createPublicKey=="function";Fl&&(co+=" or a KeyObject",as+="or a KeyObject");function my(t){if(!lo.isBuffer(t)&&typeof t!="string"&&(!Fl||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Vt(co)}function gy(t){if(!lo.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Vt(eS)}function tS(t){if(!lo.isBuffer(t)){if(typeof t=="string")return t;if(!Fl||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Vt(as)}}function Il(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function yy(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Vt(t){var e=[].slice.call(arguments,1),n=hy.format.bind(hy,t).apply(null,e);return new TypeError(n)}function nS(t){return lo.isBuffer(t)||typeof t=="string"}function us(t){return nS(t)||(t=JSON.stringify(t)),t}function _y(t){return function(n,r){tS(r),n=us(n);var o=Ot.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Il(s)}}var Pl,rS="timingSafeEqual"in Ot?function(e,n){return e.byteLength!==n.byteLength?!1:Ot.timingSafeEqual(e,n)}:function(e,n){return Pl||(Pl=fy()),Pl(e,n)};function oS(t){return function(n,r,o){var s=_y(t)(n,o);return rS(lo.from(r),lo.from(s))}}function by(t){return function(n,r){gy(r),n=us(n);var o=Ot.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Il(s)}}function Cy(t){return function(n,r,o){my(o),n=us(n),r=yy(r);var s=Ot.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function sS(t){return function(n,r){gy(r),n=us(n);var o=Ot.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Ot.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ot.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Il(s)}}function iS(t){return function(n,r,o){my(o),n=us(n),r=yy(r);var s=Ot.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Ot.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ot.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function aS(t){var e=by(t);return function(){var r=e.apply(null,arguments);return r=py.derToJose(r,"ES"+t),r}}function uS(t){var e=Cy(t);return function(r,o,s){o=py.joseToDer(o,"ES"+t).toString("base64");var a=e(r,o,s);return a}}function cS(){return function(){return""}}function lS(){return function(e,n){return n===""}}wy.exports=function(e){var n={hs:_y,rs:by,ps:sS,es:aS,none:cS},r={hs:oS,rs:Cy,ps:iS,es:uS,none:lS},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Vt(ZA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:n[s](a),verify:r[s](a)}}});var Bl=K((K1,Ey)=>{var dS=require("buffer").Buffer;Ey.exports=function(e){return typeof e=="string"?e:typeof e=="number"||dS.isBuffer(e)?e.toString():JSON.stringify(e)}});var Dy=K((Y1,Ty)=>{var fS=io().Buffer,Ay=xl(),hS=Nl(),pS=require("stream"),Sy=Bl(),Ml=require("util");function ky(t,e){return fS.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function mS(t,e,n){n=n||"utf8";var r=ky(Sy(t),"binary"),o=ky(Sy(e),n);return Ml.format("%s.%s",r,o)}function vy(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=hS(e.alg),a=mS(e,n,o),c=s.sign(a,r);return Ml.format("%s.%s",a,c)}function fa(t){var e=t.secret||t.privateKey||t.key,n=new Ay(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new Ay(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Ml.inherits(fa,pS);fa.prototype.sign=function(){try{var e=vy({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};fa.sign=vy;Ty.exports=fa});var Ly=K((Q1,My)=>{var xy=io().Buffer,Ry=xl(),gS=Nl(),yS=require("stream"),Oy=Bl(),_S=require("util"),bS=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function CS(t){return Object.prototype.toString.call(t)==="[object Object]"}function wS(t){if(CS(t))return t;try{return JSON.parse(t)}catch{return}}function Py(t){var e=t.split(".",1)[0];return wS(xy.from(e,"base64").toString("binary"))}function ES(t){return t.split(".",2).join(".")}function Fy(t){return t.split(".")[2]}function AS(t,e){e=e||"utf8";var n=t.split(".")[1];return xy.from(n,"base64").toString(e)}function Iy(t){return bS.test(t)&&!!Py(t)}function Ny(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Oy(t);var o=Fy(t),s=ES(t),a=gS(e);return a.verify(s,o,n)}function By(t,e){if(e=e||{},t=Oy(t),!Iy(t))return null;var n=Py(t);if(!n)return null;var r=AS(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Fy(t)}}function fo(t){t=t||{};var e=t.secret||t.publicKey||t.key,n=new Ry(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Ry(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}_S.inherits(fo,yS);fo.prototype.verify=function(){try{var e=Ny(this.signature.buffer,this.algorithm,this.key.buffer),n=By(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};fo.decode=By;fo.isValid=Iy;fo.verify=Ny;My.exports=fo});var Ll=K(Zn=>{var jy=Dy(),ha=Ly(),SS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Zn.ALGORITHMS=SS;Zn.sign=jy.sign;Zn.verify=ha.verify;Zn.decode=ha.decode;Zn.isValid=ha.isValid;Zn.createSign=function(e){return new jy(e)};Zn.createVerify=function(e){return new ha(e)}});var e0=K(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.GoogleToken=void 0;var $y=pa(require("fs")),kS=Qe(),vS=pa(Ll()),TS=pa(require("path")),DS=require("util");function pa(t,e){if(typeof WeakMap=="function")var n=new WeakMap,r=new WeakMap;return(pa=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,d={__proto__:null,default:s};if(s===null||xn(s)!="object"&&typeof s!="function")return d;if(c=a?r:n){if(c.has(s))return c.get(s);c.set(s,d)}for(var f in s)f!=="default"&&{}.hasOwnProperty.call(s,f)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,f))&&(l.get||l.set)?c(d,f,l):d[f]=s[f]);return d})(t,e)}function xn(t){"@babel/helpers - typeof";return xn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},xn(t)}function RS(t,e){Ky(t,e),e.add(t)}function xS(t,e,n){Ky(t,e),e.set(t,n)}function Ky(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Uy(t,e,n){return t.set(Kt(t,e),n),n}function qy(t,e){return t.get(Kt(t,e))}function Kt(t,e,n){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:n;throw new TypeError("Private element is not present on this object")}function Hy(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,Xy(r.key),r)}}function Yy(t,e,n){return e&&Hy(t.prototype,e),n&&Hy(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function Qy(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function OS(t,e,n){return e=fs(e),PS(t,zl()?Reflect.construct(e,n||[],fs(t).constructor):e.apply(t,n))}function PS(t,e){if(e&&(xn(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return FS(t)}function FS(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function IS(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&ds(t,e)}function jl(t){var e=typeof Map=="function"?new Map:void 0;return jl=function(r){if(r===null||!BS(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return NS(r,arguments,fs(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),ds(o,r)},jl(t)}function NS(t,e,n){if(zl())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&ds(o,n.prototype),o}function zl(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(zl=function(){return!!t})()}function BS(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function ds(t,e){return ds=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},ds(t,e)}function fs(t){return fs=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},fs(t)}function Ct(t,e,n){return(e=Xy(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Xy(t){var e=MS(t,"string");return xn(e)=="symbol"?e:e+""}function MS(t,e){if(xn(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(xn(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Et(){var t,e,n=typeof Symbol=="function"?Symbol:{},r=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(b,C,y,_){var g=C&&C.prototype instanceof c?C:c,S=Object.create(g.prototype);return wt(S,"_invoke",(function(w,E,T){var R,U,J,F=0,V=T||[],Y=!1,X={p:0,n:0,v:t,a:ee,f:ee.bind(t,4),d:function(Ae,ae){return R=Ae,U=0,J=t,X.n=ae,a}};function ee(de,Ae){for(U=de,J=Ae,e=0;!Y&&F&&!ae&&e<V.length;e++){var ae,pe=V[e],W=X.p,Q=pe[2];de>3?(ae=Q===Ae)&&(J=pe[(U=pe[4])?5:(U=3,3)],pe[4]=pe[5]=t):pe[0]<=W&&((ae=de<2&&W<pe[1])?(U=0,X.v=Ae,X.n=pe[1]):W<Q&&(ae=de<3||pe[0]>Ae||Ae>Q)&&(pe[4]=de,pe[5]=Ae,X.n=Q,U=0))}if(ae||de>1)return a;throw Y=!0,Ae}return function(de,Ae,ae){if(F>1)throw TypeError("Generator is already running");for(Y&&Ae===1&&ee(Ae,ae),U=Ae,J=ae;(e=U<2?t:J)||!Y;){R||(U?U<3?(U>1&&(X.n=-1),ee(U,J)):X.n=J:X.v=J);try{if(F=2,R){if(U||(de="next"),e=R[de]){if(!(e=e.call(R,J)))throw TypeError("iterator result is not an object");if(!e.done)return e;J=e.value,U<2&&(U=0)}else U===1&&(e=R.return)&&e.call(R),U<2&&(J=TypeError("The iterator does not provide a '"+de+"' method"),U=1);R=t}else if((e=(Y=X.n<0)?J:w.call(E,X))!==a)break}catch(pe){R=t,U=1,J=pe}finally{F=1}}return{value:e,done:Y}}})(b,y,_),!0),S}var a={};function c(){}function l(){}function d(){}e=Object.getPrototypeOf;var f=[][r]?e(e([][r]())):(wt(e={},r,function(){return this}),e),p=d.prototype=c.prototype=Object.create(f);function m(b){return Object.setPrototypeOf?Object.setPrototypeOf(b,d):(b.__proto__=d,wt(b,o,"GeneratorFunction")),b.prototype=Object.create(p),b}return l.prototype=d,wt(p,"constructor",d),wt(d,"constructor",l),l.displayName="GeneratorFunction",wt(d,o,"GeneratorFunction"),wt(p),wt(p,o,"Generator"),wt(p,r,function(){return this}),wt(p,"toString",function(){return"[object Generator]"}),(Et=function(){return{w:s,m}})()}function wt(t,e,n,r){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}wt=function(a,c,l,d){if(c)o?o(a,c,{value:l,enumerable:!d,configurable:!d,writable:!d}):a[c]=l;else{var f=function(m,b){wt(a,m,function(C){return this._invoke(m,b,C)})};f("next",0),f("throw",1),f("return",2)}},wt(t,e,n,r)}function zy(t,e,n,r,o,s,a){try{var c=t[s](a),l=c.value}catch(d){return void n(d)}c.done?e(l):Promise.resolve(l).then(r,o)}function ho(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var s=t.apply(e,n);function a(l){zy(s,r,o,a,c,"next",l)}function c(l){zy(s,r,o,a,c,"throw",l)}a(void 0)})}}var Wy=$y.readFile?(0,DS.promisify)($y.readFile):ho(Et().m(function t(){return Et().w(function(e){for(;;)switch(e.n){case 0:throw new ls("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Gy="https://oauth2.googleapis.com/token",LS="https://oauth2.googleapis.com/revoke?token=",ls=(function(t){function e(n,r){var o;return Qy(this,e),o=OS(this,e,[n]),Ct(o,"code",void 0),o.code=r,o}return IS(e,t),Yy(e)})(jl(Error)),cs=new WeakMap,an=new WeakSet,Z1=ma.GoogleToken=(function(){function t(e){Qy(this,t),RS(this,an),Ct(this,"expiresAt",void 0),Ct(this,"key",void 0),Ct(this,"keyFile",void 0),Ct(this,"iss",void 0),Ct(this,"sub",void 0),Ct(this,"scope",void 0),Ct(this,"rawToken",void 0),Ct(this,"tokenExpires",void 0),Ct(this,"email",void 0),Ct(this,"additionalClaims",void 0),Ct(this,"eagerRefreshThresholdMillis",void 0),Ct(this,"transporter",{request:function(r){return(0,kS.request)(r)}}),xS(this,cs,void 0),Kt(an,this,Zy).call(this,e)}return Yy(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var n=new Date().getTime();return this.rawToken&&this.expiresAt?n>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var n,r=new Date().getTime(),o=(n=this.eagerRefreshThresholdMillis)!==null&&n!==void 0?n:0;return this.rawToken&&this.expiresAt?this.expiresAt<=r+o:!0}},{key:"getToken",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(xn(n)==="object"&&(r=n,n=void 0),r=Object.assign({forceRefresh:!1},r),n){var o=n;Kt(an,this,Jy).call(this,r).then(function(s){return o(null,s)},n);return}return Kt(an,this,Jy).call(this,r)}},{key:"getCredentials",value:(function(){var e=ho(Et().m(function r(o){var s,a,c,l,d,f,p;return Et().w(function(m){for(;;)switch(m.n){case 0:s=TS.extname(o),p=s,m.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return m.n=2,Wy(o,"utf8");case 2:if(a=m.v,c=JSON.parse(a),l=c.private_key,d=c.client_email,!(!l||!d)){m.n=3;break}throw new ls("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return m.a(2,{privateKey:l,clientEmail:d});case 4:return m.n=5,Wy(o,"utf8");case 5:return f=m.v,m.a(2,{privateKey:f});case 6:throw new ls("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new ls("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return m.a(2)}},r)}));function n(r){return e.apply(this,arguments)}return n})()},{key:"revokeToken",value:function(n){if(n){Kt(an,this,Vy).call(this).then(function(){return n()},n);return}return Kt(an,this,Vy).call(this)}}])})();function Jy(t){return $l.apply(this,arguments)}function $l(){return $l=ho(Et().m(function t(e){return Et().w(function(n){for(;;)switch(n.n){case 0:if(!(qy(cs,this)&&!e.forceRefresh)){n.n=1;break}return n.a(2,qy(cs,this));case 1:return n.p=1,n.n=2,Uy(cs,this,Kt(an,this,jS).call(this,e));case 2:return n.a(2,n.v);case 3:return n.p=3,Uy(cs,this,void 0),n.f(3);case 4:return n.a(2)}},t,this,[[1,,3,4]])})),$l.apply(this,arguments)}function jS(t){return Ul.apply(this,arguments)}function Ul(){return Ul=ho(Et().m(function t(e){var n;return Et().w(function(r){for(;;)switch(r.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){r.n=1;break}return r.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){r.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){r.n=4;break}return r.n=3,this.getCredentials(this.keyFile);case 3:n=r.v,this.key=n.privateKey,this.iss=n.clientEmail||this.iss,n.clientEmail||Kt(an,this,$S).call(this);case 4:return r.a(2,Kt(an,this,US).call(this))}},t,this)})),Ul.apply(this,arguments)}function $S(){if(!this.iss)throw new ls("email is required.","MISSING_CREDENTIALS")}function Vy(){return ql.apply(this,arguments)}function ql(){return ql=ho(Et().m(function t(){var e;return Et().w(function(n){for(;;)switch(n.n){case 0:if(this.accessToken){n.n=1;break}throw new Error("No token to revoke.");case 1:return e=LS+this.accessToken,n.n=2,this.transporter.request({url:e,retry:!0});case 2:Kt(an,this,Zy).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return n.a(2)}},t,this)})),ql.apply(this,arguments)}function Zy(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,xn(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function US(){return Hl.apply(this,arguments)}function Hl(){return Hl=ho(Et().m(function t(){var e,n,r,o,s,a,c,l,d,f;return Et().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),n=this.additionalClaims||{},r=Object.assign({iss:this.iss,scope:this.scope,aud:Gy,exp:e+3600,iat:e,sub:this.sub},n),o=vS.sign({header:{alg:"RS256"},payload:r,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:Gy,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=p.v,this.rawToken=s.data,this.expiresAt=s.data.expires_in===null||s.data.expires_in===void 0?void 0:(e+s.data.expires_in)*1e3,p.a(2,this.rawToken);case 3:throw p.p=3,f=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=f.response&&(a=f.response)!==null&&a!==void 0&&a.data?(c=f.response)===null||c===void 0?void 0:c.data:{},l.error&&(d=l.error_description?": ".concat(l.error_description):"",f.message="".concat(l.error).concat(d)),f;case 4:return p.a(2)}},t,this,[[1,3]])})),Hl.apply(this,arguments)}});var Gl=K(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.JWTAccess=void 0;var qS=Ll(),HS=Gt(),t0={alg:"RS256",typ:"JWT"},Wl=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new HS.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:l,iat:c}:d={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},n){for(let C in d)if(n[C])throw new Error(`The '${C}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...t0,kid:this.keyId}:t0,p=Object.assign(d,n),m=qS.sign({header:f,payload:p,secret:this.key}),b=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:l*1e3,headers:b}),b}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};ga.JWTAccess=Wl});var Vl=K(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.JWT=void 0;var n0=e0(),zS=Gl(),WS=vr(),ya=bt(),Jl=class t extends WS.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==ya.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ya.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ya.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new zS.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==ya.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new n0.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new n0.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let n=await this.createGToken().getCredentials(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};_a.JWT=Jl});var Yl=K(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.UserRefreshClient=po.USER_REFRESH_ACCOUNT_TYPE=void 0;var GS=vr(),JS=bt();po.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Kl=class t extends GS.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return JS.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};po.UserRefreshClient=Kl});var Xl=K(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.Impersonated=mo.IMPERSONATED_ACCOUNT_TYPE=void 0;var r0=vr(),VS=Qe(),KS=Gt();mo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Ql=class t extends r0.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new r0.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,KS.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof VS.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};mo.Impersonated=Ql});var ed=K(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.OAuthClientAuthHandler=void 0;hs.getErrorFromOAuthErrorResponse=XS;var go=Qe(),YS=rs(),QS=["PUT","POST","PATCH"],Zl=class{#e=(0,YS.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new go.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new go.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=go.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=go.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=go.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);go.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!QS.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};hs.OAuthClientAuthHandler=Zl;function XS(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let a=new Error(s);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(a,l,{value:e[l],writable:!1,enumerable:!0})})}return a}});var Ca=K(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.StsCredentials=void 0;var ZS=Qe(),ek=bt(),o0=ed(),tk=Gt(),td=class t extends o0.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,tk.removeUndefinedValuesInObject)(o))};ek.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),c=a.data;return c.res=a,c}catch(a){throw a instanceof ZS.GaxiosError&&a.response?(0,o0.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};ba.StsCredentials=td});var er=K(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.BaseExternalAccountClient=Pt.CLOUD_RESOURCE_MANAGER=Pt.EXTERNAL_ACCOUNT_TYPE=Pt.EXPIRATION_TIME_OFFSET=void 0;var nk=Qe(),rk=require("stream"),nd=bt(),ok=Ca(),s0=Gt(),sk=yl(),ik="urn:ietf:params:oauth:grant-type:token-exchange",ak="urn:ietf:params:oauth:token-type:access_token",rd="https://www.googleapis.com/auth/cloud-platform",uk=3600;Pt.EXPIRATION_TIME_OFFSET=300*1e3;Pt.EXTERNAL_ACCOUNT_TYPE="external_account";Pt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var ck="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",lk="https://sts.{universeDomain}/v1/token",od=class t extends nd.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,s0.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Pt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Pt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??lk.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),c=n.get("workforce_pool_user_project"),l=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,s0.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new ok.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[rd],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let p=new RegExp(ck);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=uk),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`};nd.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=nk.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof rk.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:ik,audience:this.audience,requestedTokenType:ak,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[rd]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};nd.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[rd]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${sk.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Pt.BaseExternalAccountClient=od});var i0=K(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.FileSubjectTokenSupplier=void 0;var id=require("util"),ad=require("fs"),dk=(0,id.promisify)(ad.readFile??(()=>{})),fk=(0,id.promisify)(ad.realpath??(()=>{})),hk=(0,id.promisify)(ad.lstat??(()=>{})),sd=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await fk(e),!(await hk(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await dk(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};wa.FileSubjectTokenSupplier=sd});var a0=K(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.UrlSubjectTokenSupplier=void 0;var pk=bt(),ud=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};pk.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};Ea.UrlSubjectTokenSupplier=ud});var u0=K(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.CertificateSubjectTokenSupplier=At.InvalidConfigurationError=At.CertificateSourceUnavailableError=At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Aa=Gt(),Sa=require("fs"),ka=require("crypto"),mk=require("https");At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var un=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};At.CertificateSourceUnavailableError=un;var Ft=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};At.InvalidConfigurationError=Ft;var cd=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ft("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ft("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ft("Cannot create mTLS Agent with missing certificate or key");return new mk.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Aa.isValidFile)(e))return e;throw new un(`Provided certificate config path is invalid: ${e}`)}let n=process.env[At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Aa.isValidFile)(n))return n;throw new un(`Path from environment variable "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Aa.getWellKnownCertificateConfigFileLocation)();if(await(0,Aa.isValidFile)(r))return r;throw new un(`Could not find certificate configuration file. Searched override path, the "${At.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Sa.promises.readFile(e,"utf8")}catch{throw new un(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Ft(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Ft?r:new Ft(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Sa.promises.readFile(e),new ka.X509Certificate(r)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read certificate file at ${e}: ${a}`)}try{o=await Sa.promises.readFile(n),(0,ka.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new un(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:o}}async#r(e){let n=new ka.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Sa.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,d)=>{try{return new ka.X509Certificate(l)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Ft(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>n.raw.equals(l.raw)),c;if(a===-1)c=[n,...s];else if(a===0)c=s;else throw new Ft(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(r){if(r instanceof Ft)throw r;let o=r instanceof Error?r.message:String(r);throw new un(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};At.CertificateSubjectTokenSupplier=cd});var fd=K(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.IdentityPoolClient=void 0;var gk=er(),ld=Gt(),yk=i0(),_k=a0(),c0=u0(),bk=Ca(),l0=Qe(),dd=class t extends gk.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,ld.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,ld.originalOrCamelOptions)(r),a=(0,ld.originalOrCamelOptions)(s.get("format")),c=a.get("type")||"text",l=a.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=s.get("file"),f=s.get("url"),p=s.get("certificate"),m=s.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new yk.FileSubjectTokenSupplier({filePath:d,formatType:c,subjectTokenFieldName:l});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new _k.UrlSubjectTokenSupplier({url:f,formatType:c,subjectTokenFieldName:l,headers:m,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let b=new c0.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=b}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof c0.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new bk.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new l0.Gaxios({agent:n})}),this.transporter=new l0.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};va.IdentityPoolClient=dd});var pd=K(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.AwsRequestSigner=void 0;var Ta=Qe(),f0=rs(),d0="AWS4-HMAC-SHA256",Ck="aws4_request",hd=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,f0.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,a=e.headers,c=await this.getCredentials(),l=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let d=await Ek({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:c,requestPayload:s,additionalAmzHeaders:a}),f=Ta.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:l.host},a||{});c.token&&Ta.Gaxios.mergeHeaders(f,{"x-amz-security-token":c.token});let p={url:r,method:o,headers:f};return s!==void 0&&(p.body=s),p}};Da.AwsRequestSigner=hd;async function ps(t,e,n){return await t.signWithHmacSha256(e,n)}async function wk(t,e,n,r,o){let s=await ps(t,`AWS4${e}`,n),a=await ps(t,s,r),c=await ps(t,a,o);return await ps(t,c,"aws4_request")}async function Ek(t){let e=Ta.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=Ta.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",d=[...c.keys()].sort();d.forEach(S=>{l+=`${S}:${c.get(S)}
53
+ `});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),m=`${t.method.toUpperCase()}
54
54
  ${t.canonicalUri}
55
55
  ${t.canonicalQuerystring}
56
56
  ${l}
57
57
  ${f}
58
- ${p}`,_=`${a}/${t.region}/${r}/${Ck}`,C=`${d0}
58
+ ${p}`,b=`${a}/${t.region}/${r}/${Ck}`,C=`${d0}
59
59
  ${s}
60
- ${_}
61
- `+await t.crypto.sha256DigestHex(g),b=await wk(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),y=await ps(t.crypto,b,C),m=`${d0} Credential=${t.securityCredentials.accessKeyId}/${_}, SignedHeaders=${f}, Signature=${(0,f0.fromArrayBufferToHex)(y)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var h0=K(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.DefaultAwsSecurityCredentialsSupplier=void 0;var Ra=bt(),md=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:n};Ra.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Ra.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return Ra.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n};return Ra.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};xa.DefaultAwsSecurityCredentialsSupplier=md});var yd=K(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.AwsClient=void 0;var Ak=pd(),Sk=er(),kk=h0(),p0=Gt(),vk=Qe(),gd=class t extends Sk.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,p0.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,p0.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let a=s.get("region_url"),c=s.get("url"),l=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new kk.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new Ak.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return vk.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Oa.AwsClient=gd});var Ed=K(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.InvalidSubjectTokenError=je.InvalidMessageFieldError=je.InvalidCodeFieldError=je.InvalidTokenTypeFieldError=je.InvalidExpirationTimeFieldError=je.InvalidSuccessFieldError=je.InvalidVersionFieldError=je.ExecutableResponseError=je.ExecutableResponse=void 0;var Pa="urn:ietf:params:oauth:token-type:saml2",_d="urn:ietf:params:oauth:token-type:id_token",bd="urn:ietf:params:oauth:token-type:jwt",Cd=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Fa("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Ia("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==Pa&&this.tokenType!==_d&&this.tokenType!==bd)throw new Na(`Executable response must contain a 'token_type' field when successful and it must be one of ${_d}, ${bd}, or ${Pa}.`);if(this.tokenType===Pa){if(!e.saml_response)throw new ms(`Executable response must contain a 'saml_response' field when token_type=${Pa}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new ms(`Executable response must contain a 'id_token' field when token_type=${_d} or ${bd}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Ba("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Ma("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};je.ExecutableResponse=Cd;var cn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};je.ExecutableResponseError=cn;var Fa=class extends cn{};je.InvalidVersionFieldError=Fa;var Ia=class extends cn{};je.InvalidSuccessFieldError=Ia;var wd=class extends cn{};je.InvalidExpirationTimeFieldError=wd;var Na=class extends cn{};je.InvalidTokenTypeFieldError=Na;var Ba=class extends cn{};je.InvalidCodeFieldError=Ba;var Ma=class extends cn{};je.InvalidMessageFieldError=Ma;var ms=class extends cn{};je.InvalidSubjectTokenError=ms});var kd=K(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.PluggableAuthHandler=yo.ExecutableError=void 0;var Tr=Ed(),Tk=require("child_process"),Ad=require("fs"),La=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};yo.ExecutableError=La;var Sd=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let o=Tk.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",c=>{s+=c}),o.stderr.on("data",c=>{s+=c});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",c=>{if(clearTimeout(a),c===0)try{let l=JSON.parse(s),d=new Tr.ExecutableResponse(l);return n(d)}catch(l){return l instanceof Tr.ExecutableResponseError?r(l):r(new Tr.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new La(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Ad.promises.realpath(this.outputFile)}catch{return}if(!(await Ad.promises.lstat(e)).isFile())return;let n=await Ad.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new Tr.ExecutableResponse(r).isValid()?new Tr.ExecutableResponse(r):void 0}catch(r){throw r instanceof Tr.ExecutableResponseError?r:new Tr.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};yo.PluggableAuthHandler=Sd});var Td=K(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.PluggableAuthClient=_o.ExecutableError=void 0;var Dk=er(),Rk=Ed(),m0=kd(),xk=kd();Object.defineProperty(_o,"ExecutableError",{enumerable:!0,get:function(){return xk.ExecutableError}});var Ok=30*1e3,g0=5*1e3,y0=120*1e3,Pk="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",_0=1,vd=class extends Dk.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=Ok;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<g0||this.timeoutMillis>y0)throw new Error(`Timeout must be between ${g0} and ${y0} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new m0.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Pk]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>_0)throw new Error(`Version of executable is not currently supported, maximum supported version is ${_0}.`);if(!e.success)throw new m0.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Rk.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};_o.PluggableAuthClient=vd});var Rd=K(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.ExternalAccountClient=void 0;var Fk=er(),Ik=fd(),Nk=yd(),Bk=Td(),Dd=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),e&&e.type===Fk.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new Nk.AwsClient(e):e.credential_source?.executable?new Bk.PluggableAuthClient(e):new Ik.IdentityPoolClient(e):null}};ja.ExternalAccountClient=Dd});var E0=K(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.ExternalAccountAuthorizedUserClient=bo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var C0=bt(),b0=ed(),w0=Qe(),Mk=require("stream"),Lk=er();bo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var jk="https://sts.{universeDomain}/v1/oauthtoken",xd=class t extends b0.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};C0.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof w0.GaxiosError&&o.response?(0,b0.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Od=class extends C0.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new xd({tokenRefreshEndpoint:e.token_url??jk.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=Lk.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=w0.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof Mk.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};bo.ExternalAccountAuthorizedUserClient=Od});var v0=K(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.GoogleAuth=Yt.GoogleAuthExceptionMessages=void 0;var $k=require("child_process"),gs=require("fs"),Uk=Qe(),ys=ns(),qk=require("os"),Pd=require("path"),Hk=rs(),zk=vl(),Wk=Dl(),Gk=Rl(),Co=Vl(),A0=Yl(),wo=Xl(),Jk=Rd(),_s=er(),Fd=bt(),S0=E0(),k0=Gt();Yt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
60
+ ${b}
61
+ `+await t.crypto.sha256DigestHex(m),y=await wk(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),_=await ps(t.crypto,y,C),g=`${d0} Credential=${t.securityCredentials.accessKeyId}/${b}, SignedHeaders=${f}, Signature=${(0,f0.fromArrayBufferToHex)(_)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:g,canonicalQuerystring:t.canonicalQuerystring}}});var h0=K(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.DefaultAwsSecurityCredentialsSupplier=void 0;var Ra=bt(),md=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:n};Ra.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Ra.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return Ra.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n};return Ra.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};xa.DefaultAwsSecurityCredentialsSupplier=md});var yd=K(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.AwsClient=void 0;var Ak=pd(),Sk=er(),kk=h0(),p0=Gt(),vk=Qe(),gd=class t extends Sk.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,p0.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,p0.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let a=s.get("region_url"),c=s.get("url"),l=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new kk.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new Ak.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return vk.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Oa.AwsClient=gd});var Ed=K(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.InvalidSubjectTokenError=je.InvalidMessageFieldError=je.InvalidCodeFieldError=je.InvalidTokenTypeFieldError=je.InvalidExpirationTimeFieldError=je.InvalidSuccessFieldError=je.InvalidVersionFieldError=je.ExecutableResponseError=je.ExecutableResponse=void 0;var Pa="urn:ietf:params:oauth:token-type:saml2",_d="urn:ietf:params:oauth:token-type:id_token",bd="urn:ietf:params:oauth:token-type:jwt",Cd=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Fa("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Ia("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==Pa&&this.tokenType!==_d&&this.tokenType!==bd)throw new Na(`Executable response must contain a 'token_type' field when successful and it must be one of ${_d}, ${bd}, or ${Pa}.`);if(this.tokenType===Pa){if(!e.saml_response)throw new ms(`Executable response must contain a 'saml_response' field when token_type=${Pa}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new ms(`Executable response must contain a 'id_token' field when token_type=${_d} or ${bd}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Ba("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Ma("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};je.ExecutableResponse=Cd;var cn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};je.ExecutableResponseError=cn;var Fa=class extends cn{};je.InvalidVersionFieldError=Fa;var Ia=class extends cn{};je.InvalidSuccessFieldError=Ia;var wd=class extends cn{};je.InvalidExpirationTimeFieldError=wd;var Na=class extends cn{};je.InvalidTokenTypeFieldError=Na;var Ba=class extends cn{};je.InvalidCodeFieldError=Ba;var Ma=class extends cn{};je.InvalidMessageFieldError=Ma;var ms=class extends cn{};je.InvalidSubjectTokenError=ms});var kd=K(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.PluggableAuthHandler=yo.ExecutableError=void 0;var Tr=Ed(),Tk=require("child_process"),Ad=require("fs"),La=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};yo.ExecutableError=La;var Sd=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let o=Tk.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",c=>{s+=c}),o.stderr.on("data",c=>{s+=c});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",c=>{if(clearTimeout(a),c===0)try{let l=JSON.parse(s),d=new Tr.ExecutableResponse(l);return n(d)}catch(l){return l instanceof Tr.ExecutableResponseError?r(l):r(new Tr.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new La(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Ad.promises.realpath(this.outputFile)}catch{return}if(!(await Ad.promises.lstat(e)).isFile())return;let n=await Ad.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new Tr.ExecutableResponse(r).isValid()?new Tr.ExecutableResponse(r):void 0}catch(r){throw r instanceof Tr.ExecutableResponseError?r:new Tr.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};yo.PluggableAuthHandler=Sd});var Td=K(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.PluggableAuthClient=_o.ExecutableError=void 0;var Dk=er(),Rk=Ed(),m0=kd(),xk=kd();Object.defineProperty(_o,"ExecutableError",{enumerable:!0,get:function(){return xk.ExecutableError}});var Ok=30*1e3,g0=5*1e3,y0=120*1e3,Pk="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",_0=1,vd=class extends Dk.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=Ok;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<g0||this.timeoutMillis>y0)throw new Error(`Timeout must be between ${g0} and ${y0} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new m0.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Pk]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>_0)throw new Error(`Version of executable is not currently supported, maximum supported version is ${_0}.`);if(!e.success)throw new m0.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Rk.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};_o.PluggableAuthClient=vd});var Rd=K(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.ExternalAccountClient=void 0;var Fk=er(),Ik=fd(),Nk=yd(),Bk=Td(),Dd=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),e&&e.type===Fk.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new Nk.AwsClient(e):e.credential_source?.executable?new Bk.PluggableAuthClient(e):new Ik.IdentityPoolClient(e):null}};ja.ExternalAccountClient=Dd});var E0=K(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.ExternalAccountAuthorizedUserClient=bo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var C0=bt(),b0=ed(),w0=Qe(),Mk=require("stream"),Lk=er();bo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var jk="https://sts.{universeDomain}/v1/oauthtoken",xd=class t extends b0.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};C0.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof w0.GaxiosError&&o.response?(0,b0.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Od=class extends C0.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new xd({tokenRefreshEndpoint:e.token_url??jk.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=Lk.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=w0.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof Mk.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};bo.ExternalAccountAuthorizedUserClient=Od});var v0=K(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.GoogleAuth=Yt.GoogleAuthExceptionMessages=void 0;var $k=require("child_process"),gs=require("fs"),Uk=Qe(),ys=ns(),qk=require("os"),Pd=require("path"),Hk=rs(),zk=vl(),Wk=Dl(),Gk=Rl(),Co=Vl(),A0=Yl(),wo=Xl(),Jk=Rd(),_s=er(),Fd=bt(),S0=E0(),k0=Gt();Yt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
62
62
  To learn more about authentication and Google APIs, visit:
63
63
  https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
64
64
  To learn more about authentication and Google APIs, visit:
@@ -71,82 +71,82 @@ ${this.toMarkdown(o,n+1)}`:`${r}- ${o}`).join(`
71
71
  ${this.toMarkdown(s,n+1)}`:`${r}${o}: ${s}`).join(`
72
72
  `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var xs,vf=Me(()=>{"use strict";xs=class{type="webhook";config;defaultTimeout=3e4;constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{format:r="json",timestamp:o=!0,prefix:s,metadata:a}=n||{},c={data:e};return o&&(c.timestamp=new Date().toISOString()),s&&(c.prefix=s),a&&Object.keys(a).length>0&&(c.metadata=a),c}async sendRequest(e,n,r,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:a.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(c=d,l===a.maxAttempts)break;let f=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw c}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry);return!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return console.error(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var vo,Tf,S_,Os,Df=Me(()=>{"use strict";vo=require("fs"),Tf=require("path"),S_=require("os"),Os=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=(0,S_.tmpdir)();this.baseDir=(0,Tf.join)(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,vo.existsSync)(this.baseDir)||(0,vo.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let n=e.match(/_session_([a-f0-9-]+)/i);return n?n[1]:null}catch{return null}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return(0,Tf.join)(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return(0,vo.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Rf,To,k_=Me(()=>{"use strict";kf();vf();Df();Rf=class{handlers=new Map;defaultOptions={};registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){console.error(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){switch(e.type){case"console":return new Rs(e.config);case"webhook":return new xs(e.config);case"temp-file":return new Os(e.config);default:throw new Error(`Unknown output handler type: ${e.type}`)}}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,r)?o.success.push(a):o.failed.push(a)}catch(l){console.error(`[OutputManager] Handler ${a} failed:`,l),o.failed.push(a)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},a=e.map(async c=>{let l=this.handlers.get(c);if(!l){console.warn(`[OutputManager] Handler ${c} not found`),s.failed.push(c);return}try{await l.output(n,o)?s.success.push(c):s.failed.push(c)}catch(d){console.error(`[OutputManager] Handler ${c} failed:`,d),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},To=new Rf});var lR={};ui(lR,{ActiveProbeService:()=>Ts,ConfigService:()=>pr,ProviderHealthStore:()=>$o,ProviderService:()=>gr,SSEParserTransform:()=>xr,SSESerializerTransform:()=>Ds,TokenizerService:()=>Rr,TransformerService:()=>Dr,calculateTokenCount:()=>uf,default:()=>cR,getActiveProbeService:()=>bf,getAllQuotaResults:()=>d_,getAllRateLimitInfo:()=>yp,getHealthStore:()=>Ge,getQuotaAdapter:()=>Eu,getQuotaResult:()=>mu,getRateLimitInfo:()=>gp,getRuntimeDebugLog:()=>tp,initProviderHealthPersistence:()=>gi,initQuotaStorePersistence:()=>gu,initRateLimitPersistence:()=>yi,pluginManager:()=>wf,resetActiveProbeService:()=>__,rewriteStream:()=>Sf,router:()=>wu,searchProjectBySession:()=>cf,sessionUsageCache:()=>hu,setRuntimeDebugLog:()=>ep,startActiveProbe:()=>Au,stopActiveProbe:()=>Su,storeQuotaResult:()=>pu,tokenSpeedPlugin:()=>Of});module.exports=Bh(lR);var R_=Oe(require("fastify"),1),x_=Oe(require("@fastify/cors"),1);var Lo=require("fs"),uc=require("path"),Jh=require("dotenv"),Vh=Oe(ac(),1),pr=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,uc.join)(process.cwd(),this.options.jsonPath);if((0,Lo.existsSync)(e))try{let n=(0,Lo.readFileSync)(e,"utf-8"),r=Vh.default.parse(n);this.config={...this.config,...r},console.log(`Loaded JSON config from: ${e}`)}catch(n){console.warn(`Failed to load JSON config from ${e}:`,n)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,uc.join)(process.cwd(),this.options.envPath);if((0,Lo.existsSync)(e))try{let n=(0,Jh.config)({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){console.warn(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,n){this.config[e]=n}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function He(t,e=500,n="internal_error",r="api_error"){let o=new Error(t);return o.statusCode=e,o.code=n,o.type=r,o}async function Kh(t,e,n){e.log.error(t);let r=t.statusCode||500;if(t.rawBody)try{let s=JSON.parse(t.rawBody);return n.code(r).send(s)}catch{return n.code(r).send(t.rawBody)}let o={error:{message:t.message+(t.stack||"Internal Server Error"),type:t.type||"api_error",code:t.code||"internal_error"}};return n.code(r).send(o)}var Yh=require("undici");function Qh(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([d,f])=>{f&&s.set(d,f)});let a,c=AbortSignal.timeout(n.TIMEOUT??60*1e3*60);if(n.signal){let d=new AbortController,f=()=>d.abort();n.signal.addEventListener("abort",f),c.addEventListener("abort",f),a=d.signal}else a=c;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return n.httpsProxy&&(l.dispatcher=new Yh.ProxyAgent(new URL(n.httpsProxy).toString())),o?.debug({reqId:r.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:n.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var kC=new Set(["authorization","x-api-key","x-goog-api-key","cookie","set-cookie"]),Wr={maxBodyLength:4096,maxStreamChunks:100},cc=!1;function ep(t){cc=t}function tp(){return cc}function hi(t){return cc||t.get("DEBUG_LOG")===!0}function np(t){let e=t.get("DEBUG_LOG_OPTIONS");return!e||typeof e!="object"?Wr:{maxBodyLength:e.maxBodyLength??Wr.maxBodyLength,maxStreamChunks:e.maxStreamChunks??Wr.maxStreamChunks}}function rp(t){let e={};for(let[n,r]of Object.entries(t))kC.has(n.toLowerCase())?e[n]="***MASKED***":e[n]=r;return e}function pi(t,e){return t.length<=e?t:t.slice(0,e)+`...[truncated, total ${t.length} bytes]`}function op(t,e,n){let r=typeof n.body=="string"?n.body:JSON.stringify(n.body);t.info({debug_log:!0,reqId:e,phase:"provider_request",url:n.url,headers:rp(n.headers),body:pi(r,Wr.maxBodyLength)})}function sp(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_response",status:n.status,headers:rp(n.headers),...n.body!==void 0?{body:pi(n.body,Wr.maxBodyLength)}:{}})}function Xh(t,e,n,r){let o=vC(r);t.info({debug_log:!0,reqId:e,phase:"provider_stream_chunk",chunkIndex:n,...o?{usage_monitor:o}:{},data:pi(r,Wr.maxBodyLength)})}function vC(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!(!r||r==="[DONE]"))try{let o=JSON.parse(r),s=o?.usage||o?.response?.usage;s&&e.push({path:o?.usage?"usage":"response.usage",usage:s,choicesLength:Array.isArray(o?.choices)?o.choices.length:void 0,finishReason:o?.choices?.[0]?.finish_reason})}catch{e.push({parseError:!0,data:pi(r,512)})}}if(e.length)return e.length===1?e[0]:e}function Zh(t,e,n){t.info({debug_log:!0,reqId:e,phase:"provider_stream_end",totalChunks:n})}function ip(t,e,n,r){(async()=>{let o=t.pipeThrough(new TextDecoderStream).getReader(),s=0;try{let a="";for(;;){let{done:c,value:l}=await o.read();if(c)break;a+=l;let d=a.split(`
73
73
 
74
- `);a=d.pop()||"";for(let f of d)f.trim()&&(s<r.maxStreamChunks?Xh(e,n,s,f):s===r.maxStreamChunks&&e.info({debug_log:!0,reqId:n,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${r.maxStreamChunks}]`}),s++)}a.trim()&&(s<r.maxStreamChunks&&Xh(e,n,s,a.trim()),s++),Zh(e,n,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${n}:`,a),Zh(e,n,s)}finally{o.releaseLock()}})()}var ap="2.1.36";Gn();var Sn=require("fs"),_c=require("path"),mp=require("@wengine-ai/claude-code-router-shared"),gc=(0,_c.join)(mp.HOME_DIR,"runtime"),yc=(0,_c.join)(gc,"rate-limit.json"),Gr=new Map,fp=!1,IC=null,NC=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],BC=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],MC=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Uo(t,e,n){let r=c=>{if(n instanceof Headers)return n.get(c);let l=Object.keys(n).find(d=>d.toLowerCase()===c);return l?n[l]:null},o=mc(r,NC),s=mc(r,BC),a=mc(r,MC);(o||s||a)&&Gr.set(t,{provider:t,remaining:hp(o),limit:hp(s),reset:LC(a),capturedAt:Date.now()})}function gp(t){return Gr.get(t)}function yp(){return Array.from(Gr.values())}function mc(t,e){for(let n of e){let r=t(n);if(r)return r}return null}function hp(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function LC(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=Number(e);if(Number.isFinite(n))return n>1e12?Math.floor(n/1e3):n>1e9?Math.floor(n):Math.floor(Date.now()/1e3+n);let r=Date.parse(e);if(Number.isFinite(r))return Math.floor(r/1e3);let o=jC(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function jC(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,n=0,r=!1;for(let o of t.matchAll(e)){r=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":n+=s;break;case"s":n+=s*1e3;break;case"m":n+=s*60*1e3;break;case"h":n+=s*60*60*1e3;break;case"d":n+=s*24*60*60*1e3;break}}return r?n:null}function $C(){try{if(!(0,Sn.existsSync)(yc))return;let t=JSON.parse((0,Sn.readFileSync)(yc,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>3600*1e3)continue;Gr.set(n.provider,n)}}catch{}}function pp(){try{if(Gr.size===0)return;(0,Sn.existsSync)(gc)||(0,Sn.mkdirSync)(gc,{recursive:!0}),(0,Sn.writeFileSync)(yc,JSON.stringify(Array.from(Gr.values()),null,2),"utf-8")}catch{}}function yi(){fp||(fp=!0,$C(),IC=setInterval(pp,6e4),process.on("exit",pp))}mi();var Jr=class{name="openai-responses";endPoint="/v1/responses";async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:"detailed"});let n=[],r=e.messages.filter(o=>o.role==="system");if(r.length>0){let o=r[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),n.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,n.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{n.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}n.push(o)}}),e.input=n,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=new TextDecoder,o=new TextEncoder,s="",a=!1,c=this,l=new ReadableStream({async start(d){let f=e.body.getReader(),p=-1,g="",_=C=>(C!==g&&(p++,g=C),p);try{for(;;){let{done:C,value:b}=await f.read();if(C){a||d.enqueue(o.encode(`data: [DONE]
74
+ `);a=d.pop()||"";for(let f of d)f.trim()&&(s<r.maxStreamChunks?Xh(e,n,s,f):s===r.maxStreamChunks&&e.info({debug_log:!0,reqId:n,phase:"provider_stream_chunk_omitted",message:`[chunks after #${s} omitted, maxStreamChunks=${r.maxStreamChunks}]`}),s++)}a.trim()&&(s<r.maxStreamChunks&&Xh(e,n,s,a.trim()),s++),Zh(e,n,s)}catch(a){console.error(`[debug_log] Error reading debug stream for reqId=${n}:`,a),Zh(e,n,s)}finally{o.releaseLock()}})()}var ap="2.1.37";Gn();var Sn=require("fs"),_c=require("path"),mp=require("@wengine-ai/claude-code-router-shared"),gc=(0,_c.join)(mp.HOME_DIR,"runtime"),yc=(0,_c.join)(gc,"rate-limit.json"),Gr=new Map,fp=!1,IC=null,NC=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],BC=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],MC=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Uo(t,e,n){let r=c=>{if(n instanceof Headers)return n.get(c);let l=Object.keys(n).find(d=>d.toLowerCase()===c);return l?n[l]:null},o=mc(r,NC),s=mc(r,BC),a=mc(r,MC);(o||s||a)&&Gr.set(t,{provider:t,remaining:hp(o),limit:hp(s),reset:LC(a),capturedAt:Date.now()})}function gp(t){return Gr.get(t)}function yp(){return Array.from(Gr.values())}function mc(t,e){for(let n of e){let r=t(n);if(r)return r}return null}function hp(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function LC(t){if(!t)return null;let e=t.trim();if(!e)return null;let n=Number(e);if(Number.isFinite(n))return n>1e12?Math.floor(n/1e3):n>1e9?Math.floor(n):Math.floor(Date.now()/1e3+n);let r=Date.parse(e);if(Number.isFinite(r))return Math.floor(r/1e3);let o=jC(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function jC(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,n=0,r=!1;for(let o of t.matchAll(e)){r=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":n+=s;break;case"s":n+=s*1e3;break;case"m":n+=s*60*1e3;break;case"h":n+=s*60*60*1e3;break;case"d":n+=s*24*60*60*1e3;break}}return r?n:null}function $C(){try{if(!(0,Sn.existsSync)(yc))return;let t=JSON.parse((0,Sn.readFileSync)(yc,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>3600*1e3)continue;Gr.set(n.provider,n)}}catch{}}function pp(){try{if(Gr.size===0)return;(0,Sn.existsSync)(gc)||(0,Sn.mkdirSync)(gc,{recursive:!0}),(0,Sn.writeFileSync)(yc,JSON.stringify(Array.from(Gr.values()),null,2),"utf-8")}catch{}}function yi(){fp||(fp=!0,$C(),IC=setInterval(pp,6e4),process.on("exit",pp))}mi();var Jr=class{name="openai-responses";endPoint="/v1/responses";async transformRequestIn(e){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:"detailed"});let n=[],r=e.messages.filter(o=>o.role==="system");if(r.length>0){let o=r[0];Array.isArray(o.content)?o.content.forEach(s=>{let a="";typeof s=="string"?a=s:s&&typeof s=="object"&&"text"in s&&(a=s.text),n.push({role:"system",content:a})}):e.instructions=o.content}if(e.messages.forEach(o=>{if(o.role!=="system"){if(Array.isArray(o.content)){let s=o.content.map(a=>this.normalizeRequestContent(a,o.role)).filter(a=>a!==null);s.length>0?o.content=s:delete o.content}if(o.role==="tool"){let s={...o};s.type="function_call_output",s.call_id=o.tool_call_id,s.output=o.content,delete s.cache_control,delete s.role,delete s.tool_call_id,delete s.content,n.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{n.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}n.push(o)}}),e.input=n,delete e.messages,Array.isArray(e.tools)){let o=e.tools.find(s=>s.function.name==="web_search");e.tools=e.tools.filter(s=>s.function.name!=="web_search").map(s=>(s.function.name==="WebSearch"&&delete s.function.parameters.properties.allowed_domains,s.function.name==="Edit"?{type:s.type,name:s.function.name,description:s.function.description,parameters:{...s.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:s.type,name:s.function.name,description:s.function.description,parameters:s.function.parameters})),o&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=new TextDecoder,o=new TextEncoder,s="",a=!1,c=this,l=new ReadableStream({async start(d){let f=e.body.getReader(),p=-1,m="",b=C=>(C!==m&&(p++,m=C),p);try{for(;;){let{done:C,value:y}=await f.read();if(C){a||d.enqueue(o.encode(`data: [DONE]
75
75
 
76
- `));break}let y=r.decode(b,{stream:!0});s+=y;let m=s.split(/\r?\n/);s=m.pop()||"";for(let k of m)if(k.trim())try{if(k.startsWith("event: "))continue;if(k.startsWith("data: ")){let w=k.slice(5).trim();if(w==="[DONE]"){a=!0,d.enqueue(o.encode(`data: [DONE]
76
+ `));break}let _=r.decode(y,{stream:!0});s+=_;let g=s.split(/\r?\n/);s=g.pop()||"";for(let S of g)if(S.trim())try{if(S.startsWith("event: "))continue;if(S.startsWith("data: ")){let w=S.slice(5).trim();if(w==="[DONE]"){a=!0,d.enqueue(o.encode(`data: [DONE]
77
77
 
78
- `));continue}try{let A=JSON.parse(w);if(A.type==="response.output_text.delta"){let T={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:_(A.type),delta:{content:A.delta||""},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
78
+ `));continue}try{let E=JSON.parse(w);if(E.type==="response.output_text.delta"){let T={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:b(E.type),delta:{content:E.delta||""},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
79
79
 
80
- `))}else if(A.type==="response.output_item.added"&&A.item?.type==="function_call"){let T={id:A.item.call_id||A.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex-",choices:[{index:_(A.type),delta:{role:"assistant",tool_calls:[{index:0,id:A.item.call_id||A.item.id,function:{name:A.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
80
+ `))}else if(E.type==="response.output_item.added"&&E.item?.type==="function_call"){let T={id:E.item.call_id||E.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex-",choices:[{index:b(E.type),delta:{role:"assistant",tool_calls:[{index:0,id:E.item.call_id||E.item.id,function:{name:E.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
81
81
 
82
- `))}else if(A.type==="response.output_item.added"&&A.item?.type==="message"){let T=[];(A.item.content||[]).forEach(U=>{U.type==="output_text"&&T.push({type:"text",text:U.text||""})});let R={role:"assistant"};if(T.length===1&&T[0].type==="text"?R.content=T[0].text:T.length>0&&(R.content=T),R.content){let U={id:A.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:_(A.type),delta:R,finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(U)}
82
+ `))}else if(E.type==="response.output_item.added"&&E.item?.type==="message"){let T=[];(E.item.content||[]).forEach(U=>{U.type==="output_text"&&T.push({type:"text",text:U.text||""})});let R={role:"assistant"};if(T.length===1&&T[0].type==="text"?R.content=T[0].text:T.length>0&&(R.content=T),R.content){let U={id:E.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:b(E.type),delta:R,finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(U)}
83
83
 
84
- `))}}else if(A.type==="response.output_text.annotation.added"){let T={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex",choices:[{index:_(A.type),delta:{annotations:[{type:"url_citation",url_citation:{url:A.annotation?.url||"",title:A.annotation?.title||"",content:"",start_index:A.annotation?.start_index||0,end_index:A.annotation?.end_index||0}}]},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
84
+ `))}}else if(E.type==="response.output_text.annotation.added"){let T={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex",choices:[{index:b(E.type),delta:{annotations:[{type:"url_citation",url_citation:{url:E.annotation?.url||"",title:E.annotation?.title||"",content:"",start_index:E.annotation?.start_index||0,end_index:E.annotation?.end_index||0}}]},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
85
85
 
86
- `))}else if(A.type==="response.function_call_arguments.delta"){let T={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex-",choices:[{index:_(A.type),delta:{tool_calls:[{index:0,function:{arguments:A.delta||""}}]},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
86
+ `))}else if(E.type==="response.function_call_arguments.delta"){let T={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex-",choices:[{index:b(E.type),delta:{tool_calls:[{index:0,function:{arguments:E.delta||""}}]},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
87
87
 
88
- `))}else if(A.type==="response.completed"){let T=A.response?.output?.some(U=>U.type==="function_call")?"tool_calls":"stop",R={id:A.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:T}]};d.enqueue(o.encode(`data: ${JSON.stringify(R)}
88
+ `))}else if(E.type==="response.completed"){let T=E.response?.output?.some(U=>U.type==="function_call")?"tool_calls":"stop",R={id:E.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:T}]};d.enqueue(o.encode(`data: ${JSON.stringify(R)}
89
89
 
90
- `)),a=!0}else if(A.type==="response.reasoning_summary_text.delta"){let T={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:_(A.type),delta:{thinking:{content:A.delta||""}},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
90
+ `)),a=!0}else if(E.type==="response.reasoning_summary_text.delta"){let T={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:b(E.type),delta:{thinking:{content:E.delta||""}},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
91
91
 
92
- `))}else if(A.type==="response.reasoning_summary_part.done"&&A.part){let T={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:p,delta:{thinking:{signature:A.item_id}},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
92
+ `))}else if(E.type==="response.reasoning_summary_part.done"&&E.part){let T={id:E.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:E.response?.model,choices:[{index:p,delta:{thinking:{signature:E.item_id}},finish_reason:null}]};d.enqueue(o.encode(`data: ${JSON.stringify(T)}
93
93
 
94
- `))}}catch{d.enqueue(o.encode(k+`
95
- `))}}else d.enqueue(o.encode(k+`
96
- `))}catch(w){console.error("Error processing line:",k,w),d.enqueue(o.encode(k+`
94
+ `))}}catch{d.enqueue(o.encode(S+`
95
+ `))}}else d.enqueue(o.encode(S+`
96
+ `))}catch(w){console.error("Error processing line:",S,w),d.enqueue(o.encode(S+`
97
97
  `))}}s.trim()&&d.enqueue(o.encode(s+`
98
98
  `)),a||d.enqueue(o.encode(`data: [DONE]
99
99
 
100
- `))}catch(C){console.error("Stream error:",C),d.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}d.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,n){let r={...e};if(delete r.cache_control,e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[o,s]=e.body.tee(),a=o.getReader(),c="";try{let{value:g,done:_}=await a.read();!_&&g&&(c=new TextDecoder().decode(g))}finally{a.releaseLock()}o.cancel().catch(()=>{});let l=c.includes("message_start")||c.includes("content_block_start");if(c.includes("chat.completion.chunk")&&!l){let g=this.prependToStream(c,s),_=this.convertOpenAIChatStreamToResponsesAPI(g,n);return new Response(_,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let f=this.prependToStream(c,s),p=this.convertAnthropicStreamToResponsesAPI(f,n);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let o=await e.json();return new Response(JSON.stringify(this.wrapChatInResponses(o)),{headers:{"Content-Type":"application/json"}})}catch{return e}}prependToStream(e,n){let o=new TextEncoder().encode(e),s=n.getReader(),a=!1;return new ReadableStream({async pull(c){a||(a=!0,c.enqueue(o));try{let{done:l,value:d}=await s.read();l?c.close():c.enqueue(d)}catch(l){c.error(l)}},cancel(){s.cancel().catch(()=>{})}})}convertOpenAIChatStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,c=0,l=!1,d=!1,f="",p=-1,g=[];return new ReadableStream({async start(_){try{let C=e.getReader(),b="";for(;;){let{done:y,value:m}=await C.read();if(y)break;b+=r.decode(m,{stream:!0});let k=b.split(`
101
- `);b=k.pop()||"";for(let w of k){let A=w.trim();if(!A||A.startsWith("event:")||!A.startsWith("data:"))continue;let T=A.slice(5).trim();if(T==="[DONE]"){_.enqueue(o.encode(`data: [DONE]
100
+ `))}catch(C){console.error("Stream error:",C),d.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}d.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}})}return e}normalizeRequestContent(e,n){let r={...e};if(delete r.cache_control,e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")&&e.body){let[o,s]=e.body.tee(),a=o.getReader(),c="";try{let{value:m,done:b}=await a.read();!b&&m&&(c=new TextDecoder().decode(m))}finally{a.releaseLock()}o.cancel().catch(()=>{});let l=c.includes("message_start")||c.includes("content_block_start");if(c.includes("chat.completion.chunk")&&!l){let m=this.prependToStream(c,s),b=this.convertOpenAIChatStreamToResponsesAPI(m,n);return new Response(b,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}let f=this.prependToStream(c,s),p=this.convertAnthropicStreamToResponsesAPI(f,n);return new Response(p,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}try{let o=await e.json();return new Response(JSON.stringify(this.wrapChatInResponses(o)),{headers:{"Content-Type":"application/json"}})}catch{return e}}prependToStream(e,n){let o=new TextEncoder().encode(e),s=n.getReader(),a=!1;return new ReadableStream({async pull(c){a||(a=!0,c.enqueue(o));try{let{done:l,value:d}=await s.read();l?c.close():c.enqueue(d)}catch(l){c.error(l)}},cancel(){s.cancel().catch(()=>{})}})}convertOpenAIChatStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,c=0,l=!1,d=!1,f="",p=-1,m=[];return new ReadableStream({async start(b){try{let C=e.getReader(),y="";for(;;){let{done:_,value:g}=await C.read();if(_)break;y+=r.decode(g,{stream:!0});let S=y.split(`
101
+ `);y=S.pop()||"";for(let w of S){let E=w.trim();if(!E||E.startsWith("event:")||!E.startsWith("data:"))continue;let T=E.slice(5).trim();if(T==="[DONE]"){b.enqueue(o.encode(`data: [DONE]
102
102
 
103
- `));continue}let R;try{R=JSON.parse(T)}catch{continue}l||(l=!0,_.enqueue(o.encode(`data: ${JSON.stringify({type:"response.created",response:{id:a,model:s}})}
103
+ `));continue}let R;try{R=JSON.parse(T)}catch{continue}l||(l=!0,b.enqueue(o.encode(`data: ${JSON.stringify({type:"response.created",response:{id:a,model:s}})}
104
104
 
105
- `)),_.enqueue(o.encode(`data: ${JSON.stringify({type:"response.in_progress",response:{id:a,model:s}})}
105
+ `)),b.enqueue(o.encode(`data: ${JSON.stringify({type:"response.in_progress",response:{id:a,model:s}})}
106
106
 
107
- `)));let U=R.choices?.[0];if(!U)continue;let J=U.delta;if(J?.content){if(!d){d=!0;let F=c++,V={id:`${a}-text`,type:"message",role:"assistant",content:[]};g.push(V),_.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:F,item:V})}
107
+ `)));let U=R.choices?.[0];if(!U)continue;let J=U.delta;if(J?.content){if(!d){d=!0;let F=c++,V={id:`${a}-text`,type:"message",role:"assistant",content:[]};m.push(V),b.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:F,item:V})}
108
108
 
109
- `))}_.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_text.delta",item_id:`${a}-text`,output_index:c-1,content_index:0,delta:J.content})}
109
+ `))}b.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_text.delta",item_id:`${a}-text`,output_index:c-1,content_index:0,delta:J.content})}
110
110
 
111
- `))}if(Array.isArray(J?.tool_calls))for(let F of J.tool_calls){if(F.id){f=F.id,p=c++;let V={id:F.id,type:"function_call",call_id:F.id,name:F.function?.name||"",arguments:""};g.push(V),_.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:p,item:V})}
111
+ `))}if(Array.isArray(J?.tool_calls))for(let F of J.tool_calls){if(F.id){f=F.id,p=c++;let V={id:F.id,type:"function_call",call_id:F.id,name:F.function?.name||"",arguments:""};m.push(V),b.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:p,item:V})}
112
112
 
113
- `))}if(F.function?.arguments){_.enqueue(o.encode(`data: ${JSON.stringify({type:"response.function_call_arguments.delta",item_id:f,output_index:p,delta:F.function.arguments})}
113
+ `))}if(F.function?.arguments){b.enqueue(o.encode(`data: ${JSON.stringify({type:"response.function_call_arguments.delta",item_id:f,output_index:p,delta:F.function.arguments})}
114
114
 
115
- `));let V=g.find(Y=>Y.call_id===f);V&&(V.arguments+=F.function.arguments)}}if(U.finish_reason){let F=g.map(V=>V);_.enqueue(o.encode(`data: ${JSON.stringify({type:"response.completed",response:{id:a,model:R.model||s,output:F,usage:R.usage?{input_tokens:R.usage.prompt_tokens||0,output_tokens:R.usage.completion_tokens||0,total_tokens:R.usage.total_tokens||0}:void 0}})}
115
+ `));let V=m.find(Y=>Y.call_id===f);V&&(V.arguments+=F.function.arguments)}}if(U.finish_reason){let F=m.map(V=>V);b.enqueue(o.encode(`data: ${JSON.stringify({type:"response.completed",response:{id:a,model:R.model||s,output:F,usage:R.usage?{input_tokens:R.usage.prompt_tokens||0,output_tokens:R.usage.completion_tokens||0,total_tokens:R.usage.total_tokens||0}:void 0}})}
116
116
 
117
- `))}}}_.close()}catch(C){_.error(C)}}})}convertAnthropicStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,c="",l="",d="",f="",p="",g=0,_=!1,C=!1,b=null,y=[];return new ReadableStream({async start(m){try{let k=e.getReader(),w="";for(;;){let{done:A,value:T}=await k.read();if(A)break;w+=r.decode(T,{stream:!0});let R=w.split(`
118
- `);w=R.pop()||"";for(let U of R){let J=U.trim();if(!J||J.startsWith("event:")||!J.startsWith("data:"))continue;let F=J.slice(5).trim();if(F==="[DONE]")continue;let V;try{V=JSON.parse(F)}catch{continue}if(V.type==="message_start"&&(a=V.message?.id||a,m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.created",response:{id:a,model:s}})}
117
+ `))}}}b.close()}catch(C){b.error(C)}}})}convertAnthropicStreamToResponsesAPI(e,n){let r=new TextDecoder,o=new TextEncoder,s=n?.provider?.models?.[0]||"gpt-5.4",a=`resp_${Date.now()}`,c="",l="",d="",f="",p="",m=0,b=!1,C=!1,y=null,_=[];return new ReadableStream({async start(g){try{let S=e.getReader(),w="";for(;;){let{done:E,value:T}=await S.read();if(E)break;w+=r.decode(T,{stream:!0});let R=w.split(`
118
+ `);w=R.pop()||"";for(let U of R){let J=U.trim();if(!J||J.startsWith("event:")||!J.startsWith("data:"))continue;let F=J.slice(5).trim();if(F==="[DONE]")continue;let V;try{V=JSON.parse(F)}catch{continue}if(V.type==="message_start"&&(a=V.message?.id||a,g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.created",response:{id:a,model:s}})}
119
119
 
120
- `)),m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.in_progress",response:{id:a,model:s}})}
120
+ `)),g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.in_progress",response:{id:a,model:s}})}
121
121
 
122
- `))),V.type==="content_block_start"){let Y=V.content_block;if(b=Y?.type||null,Y?.type==="tool_use"){l=Y.id||"",d=Y.name||"",f="";let X=g++,ee={id:l,type:"function_call",call_id:l,name:d,arguments:""};y.push(ee),m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
122
+ `))),V.type==="content_block_start"){let Y=V.content_block;if(y=Y?.type||null,Y?.type==="tool_use"){l=Y.id||"",d=Y.name||"",f="";let X=m++,ee={id:l,type:"function_call",call_id:l,name:d,arguments:""};_.push(ee),g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
123
123
 
124
- `))}if(Y?.type==="thinking"&&(p=Y.thinking||"",!C)){C=!0;let X=g++,ee={id:`${a}-reasoning`,type:"reasoning_summary",summary:p};y.push(ee),m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
124
+ `))}if(Y?.type==="thinking"&&(p=Y.thinking||"",!C)){C=!0;let X=m++,ee={id:`${a}-reasoning`,type:"reasoning_summary",summary:p};_.push(ee),g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
125
125
 
126
- `))}if(Y?.type==="text"&&(c=Y?.text||"",!_&&Y?.text!==void 0)){_=!0;let X=g++,ee={id:`${a}-text`,type:"message",role:"assistant",content:[]};y.push(ee),m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
126
+ `))}if(Y?.type==="text"&&(c=Y?.text||"",!b&&Y?.text!==void 0)){b=!0;let X=m++,ee={id:`${a}-text`,type:"message",role:"assistant",content:[]};_.push(ee),g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
127
127
 
128
- `))}}if(V.type==="content_block_delta"){let Y=V.delta;if(Y?.type==="text_delta"){if(c+=Y.text||"",!_){_=!0;let X=g++,ee={id:`${a}-text`,type:"message",role:"assistant",content:[]};y.push(ee),m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
128
+ `))}}if(V.type==="content_block_delta"){let Y=V.delta;if(Y?.type==="text_delta"){if(c+=Y.text||"",!b){b=!0;let X=m++,ee={id:`${a}-text`,type:"message",role:"assistant",content:[]};_.push(ee),g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_item.added",response_id:a,output_index:X,item:ee})}
129
129
 
130
- `))}m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_text.delta",item_id:`${a}-text`,output_index:g-1,content_index:0,delta:Y.text||""})}
130
+ `))}g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.output_text.delta",item_id:`${a}-text`,output_index:m-1,content_index:0,delta:Y.text||""})}
131
131
 
132
- `))}Y?.type==="thinking_delta"&&(p+=Y.thinking||"",m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.reasoning_summary_text.delta",item_id:`${a}-reasoning`,output_index:g-1,content_index:0,delta:Y.thinking||""})}
132
+ `))}Y?.type==="thinking_delta"&&(p+=Y.thinking||"",g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.reasoning_summary_text.delta",item_id:`${a}-reasoning`,output_index:m-1,content_index:0,delta:Y.thinking||""})}
133
133
 
134
- `))),Y?.type==="input_json_delta"&&(f+=Y.partial_json||"",m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.function_call_arguments.delta",item_id:l||`${a}-tool`,output_index:g-1,delta:Y.partial_json||""})}
134
+ `))),Y?.type==="input_json_delta"&&(f+=Y.partial_json||"",g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.function_call_arguments.delta",item_id:l||`${a}-tool`,output_index:m-1,delta:Y.partial_json||""})}
135
135
 
136
- `)))}if(V.type==="content_block_stop"){if(b==="tool_use"&&l){m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.function_call_arguments.done",item_id:l,output_index:g-1,delta:f})}
136
+ `)))}if(V.type==="content_block_stop"){if(y==="tool_use"&&l){g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.function_call_arguments.done",item_id:l,output_index:m-1,delta:f})}
137
137
 
138
- `));let Y=y.find(X=>X.call_id===l);Y&&(Y.arguments=f)}b=null}if(V.type==="message_delta"){let Y=V.usage,X=y.map(ee=>ee.type==="message"&&ee.role==="assistant"?{...ee,content:[{type:"output_text",text:c}]}:ee);m.enqueue(o.encode(`data: ${JSON.stringify({type:"response.completed",response:{id:a,model:s,output:X,usage:Y?{input_tokens:Y.input_tokens||0,output_tokens:Y.output_tokens||0,total_tokens:(Y.input_tokens||0)+(Y.output_tokens||0)}:void 0}})}
138
+ `));let Y=_.find(X=>X.call_id===l);Y&&(Y.arguments=f)}y=null}if(V.type==="message_delta"){let Y=V.usage,X=_.map(ee=>ee.type==="message"&&ee.role==="assistant"?{...ee,content:[{type:"output_text",text:c}]}:ee);g.enqueue(o.encode(`data: ${JSON.stringify({type:"response.completed",response:{id:a,model:s,output:X,usage:Y?{input_tokens:Y.input_tokens||0,output_tokens:Y.output_tokens||0,total_tokens:(Y.input_tokens||0)+(Y.output_tokens||0)}:void 0}})}
139
139
 
140
- `))}V.type==="message_stop"&&m.enqueue(o.encode(`data: [DONE]
140
+ `))}V.type==="message_stop"&&g.enqueue(o.encode(`data: [DONE]
141
141
 
142
- `))}}w="",m.close()}catch(k){m.error(k)}}})}wrapChatInResponses(e){let n=e?.choices?.[0],r=[],o=[];if(n?.message?.content&&o.push({type:"output_text",text:n.message.content}),r.push({type:"message",role:"assistant",content:o}),Array.isArray(n?.message?.tool_calls))for(let s of n.message.tool_calls)r.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:r,usage:e.usage?{input_tokens:e.usage.prompt_tokens||0,output_tokens:e.usage.completion_tokens||0,total_tokens:e.usage.total_tokens||0}:void 0}}convertResponseToChat(e){let n=e.output?.find(d=>d.type==="message"),r=e.output?.find(d=>d.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(d=>({type:"url_citation",url_citation:{url:d.url||"",title:d.title||"",content:"",start_index:d.start_index||0,end_index:d.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let g=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});g&&f.push(g)}else if(p.type==="output_image_base64"){let g=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});g&&f.push(g)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),s=p}else s=d.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:a,thinking:c,annotations:o},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};async function UC(t,e,n,r){let o=t.body,s=t.provider;if(!s&&o?.model){let d=o.model.split(",");d.length>1&&(s=d[0],o.model=d.slice(1).join(","))}let a=s?n.providerService.getProvider(s):void 0;if(!a&&o?.model){let d=n.providerService.resolveModelRoute(o.model);d&&(a=d.provider,o.model=d.targetModel)}if(!a&&o?.model){let f=n.configService.get("Router")?.default;if(f&&f.includes(",")){let[p,...g]=f.split(","),_=n.providerService.getProvider(p);_&&(a=_,o.model=g.join(","))}}if(t.originalModel||(t.originalModel=o?.model),!a)throw He(`Provider '${s}' not found`,404,"provider_not_found");t.provider=a.name||s;let c=zC(t),l=r.endPoint==="/v1/messages"&&c;c&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true");try{if(r.endPoint==="/v1/responses"&&o.input&&!o.messages){let b=[],y=Array.isArray(o.input)?o.input:[o.input];for(let m of y)if(m.type==="function_call")b.push({role:"assistant",tool_calls:[{id:m.call_id,type:"function",function:{name:m.name,arguments:m.arguments||"{}"}}]});else if(m.type==="function_call_output")b.push({role:"tool",tool_call_id:m.call_id,content:typeof m.output=="string"?m.output:JSON.stringify(m.output)});else if(m.role){let k=m.content;Array.isArray(k)&&(k=k.map(w=>w.type==="input_text"?{type:"text",text:w.text}:w.type==="output_text"?{type:"text",text:w.text}:w.type==="input_image"?{type:"image_url",image_url:{url:w.image_url},media_type:w.mime_type}:w)),b.push({role:m.role,content:k})}o.messages=b,delete o.input,o.instructions&&typeof o.instructions=="string"&&(o.system=o.instructions,delete o.instructions),Array.isArray(o.tools)&&(o.tools=o.tools.filter(m=>m&&typeof m=="object").map(m=>m.type==="function"&&m.name&&!m.function?{type:"function",function:{name:m.name,description:m.description||"",parameters:m.parameters||{type:"object",properties:{}}}}:m.function?.name?m:m.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),o.reasoning&&typeof o.reasoning=="object"&&(o.reasoning={enabled:!0,effort:o.reasoning.effort})}let{requestBody:d,config:f,bypass:p}=await _p(o,a,r,t.headers,{req:t});if(d?.messages&&!p&&!t.isTargetAnthropic){let b=d.messages,y=new Set,m=[],k=[];for(let w of b){if(w?.role!=="system"){k.push(w);continue}let A=JSON.stringify(w.content??"");y.has(A)||(y.add(A),m.push(w))}m.length>0&&k.length>0&&(d.messages=[...k,...m])}let g=await bp(d,f,a,n,p,r,{req:t});try{a?.baseUrl&&g?.headers&&Uo(s,a.baseUrl,g.headers)}catch{}let _=await Cp(d,g,a,r,p,{req:t,isCodexOnMessagesEndpoint:l});if(o.stream&&_?.body){let b=_.body.getReader(),y=await b.read();if(y.done)throw b.releaseLock(),He(`Provider returned empty streaming response from ${s}`,400,"provider_response_error");let m=new TextDecoder().decode(y.value);if(m.includes("event: error")){b.releaseLock();let A=m.length<500?m:m.slice(0,500);throw He(`Provider ${s} returned error in SSE stream: ${A}`,400,"provider_response_error")}if(m.split(`
143
- `).filter(A=>A.startsWith("data:")&&A.trim().length>5).length===0){b.releaseLock();let A=m.length<500?m:m.slice(0,500);throw He(`Provider ${s} returned streaming response with no SSE data lines: ${A}`,400,"provider_response_error")}let w=new ReadableStream({start:A=>{A.enqueue(y.value);let T=()=>{b.read().then(({done:R,value:U})=>{R?A.close():(A.enqueue(U),T())}).catch(R=>A.error(R))};T()},cancel:()=>{b.cancel()}});_=new Response(w,{headers:_.headers,status:_.status,statusText:_.statusText})}let C=wp(_,e,o,n);try{let b=o.model||t.originalModel;s&&b&&Ge().recordSuccess(s,b)}catch{}return C}catch(d){let f=await qC(t,e,n,r,d);if(f)return f;throw d}}async function qC(t,e,n,r,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=n.configService.get("fallback"),d=Ge(),f=t.provider||"",p=t.body.model||"",g=new Set,_=o?.statusCode===429||o?.isRateLimit===!0||o?.rawBody&&_i(o.rawBody)||o?.message&&_i(o.message);if(f&&p&&(_?(d.markRateLimited(f,p,120,o?.message),t.log.warn(`Primary model ${f},${p} rate-limited, will try fallbacks`)):d.recordFailure(f,p,o?.message),g.add(`${f},${p}`),n.recordUsage?.({provider:f,model:p,originalModel:t.originalModel||p,scenarioType:s,modelFamily:t.modelFamily,errorMessage:o?.message||String(o),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})),!n.configService.get("Router")?.enableFallback)return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let b=k=>{let[w,...A]=k.split(","),T=w?.trim(),R=A.join(",").trim();return!T||!R?null:{provider:T,model:R,key:`${T},${R}`}},y=[];if(c){let k=a?.[s];Array.isArray(k)&&k.length>0?y.push({name:`${c}/${s}`,models:k}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&y.push({name:`global/${s}`,models:l[s]}),y.length===0&&s!=="image"&&t.body?.messages?.some(A=>A.role==="user"&&Array.isArray(A.content)&&A.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(R=>R.type==="image"||R.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(t.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),y.push({name:"global/image (auto-detected)",models:l.image})),y.length===0)return null;let m=y.reduce((k,w)=>k+w.models.length,0);t.log.warn(`Request failed for ${s}, trying ${m} fallback models across ${y.length} fallback stage(s)`);for(let k of y){t.log.info(`Trying ${k.name} fallback stage with ${k.models.length} models`);for(let w of k.models){let A=b(w);if(!A){t.log.warn(`Fallback model '${w}' is invalid, skipping`);continue}if(g.has(A.key))continue;g.add(A.key);let T=A.provider,R=A.model;try{if(!d.isAvailable(T,R)){t.log.warn(`Fallback model ${w} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${w}`);let U={...t.body};U.model=R;let J={...t,provider:T,body:U},F=n.providerService.getProvider(T);if(!F){t.log.warn(`Fallback provider '${T}' not found, skipping`);continue}if(F.enabled===!1){t.log.warn(`Fallback provider '${T}' is disabled, skipping`);continue}let{requestBody:V,config:Y,bypass:X}=await _p(U,F,r,t.headers,{req:J}),ee=await bp(V,Y,F,n,X,r,{req:J});try{F?.baseUrl&&ee?.headers&&Uo(T,F.baseUrl,ee.headers)}catch{}let de=await Cp(V,ee,F,r,X,{req:J});return t.log.info(`Fallback model ${w} succeeded`),d.recordSuccess(T,R),f&&p&&(jo().promote(f,p,s,T,R),t.log.info(`Promoted fallback model ${T},${R} for ${f},${p}:${s}`),_?t.log.info(`Rate-limited original model ${f},${p} already marked unavailable with cooldown`):(d.forceOpen(f,p,o?.message),t.log.info(`Marked original model ${f},${p} as unavailable`))),t.provider=T,t.body=U,wp(de,e,U,n)}catch(U){d.recordFailure(T,R,U.message),t.log.warn(`Fallback model ${A.key} failed: ${U.message}`),n.recordUsage?.({provider:T,model:R,originalModel:t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:U.message,sessionId:t.usageSessionId||t.id,stream:t.body.stream,req:t});continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function _p(t,e,n,r,o){let s=JSON.parse(JSON.stringify(t)),a=s?.system;if(typeof a=="string"&&a.includes("cch="))s.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let d=0;d<a.length;d++){let f=a[d],p=typeof f=="string"?f:f?.text??"";if(p.includes("cch=")){let g=p.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof f=="string"?a[d]=g:typeof f?.text=="string"&&(f.text=g)}}let c={},l=!1;if(l=HC(e,n,t),l&&(r instanceof Headers?r.delete("content-length"):delete r["content-length"],c.headers=r),!l&&typeof n.transformRequestOut=="function"){let d=await n.transformRequestOut(s);d.body?(s=d.body,c=d.config||{}):s=d}if(!l&&e.transformer?.use?.length)for(let d of e.transformer.use){if(!d||typeof d.transformRequestIn!="function")continue;let f=await d.transformRequestIn(s,e,o);f.body?(s=f.body,c={...c,...f.config}):s=f}if(!l&&e.transformer?.[t.model]?.use?.length)for(let d of e.transformer[t.model].use)!d||typeof d.transformRequestIn!="function"||(s=await d.transformRequestIn(s,e,o));return{requestBody:s,config:c,bypass:l}}function HC(t,e,n){return e.endPoint==="/v1/chat/completions"&&Array.isArray(n?.system)?!1:t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[n.model]?.use.length||t.transformer?.[n.model]?.use.length===1&&t.transformer?.[n.model]?.use[0].name===e.name)}function zC(t){let n=(t.headers||{})["user-agent"]||"";if(typeof n=="string"&&/codex/i.test(n))return!0;let r=t.body?.model||"";return!!(typeof r=="string"&&/gpt-5\.\d+-(xhigh|mini|fast|codex)/i.test(r))}async function bp(t,e,n,r,o,s,a){let c=e.url||new URL(n.baseUrl);if(!e.TIMEOUT){let f=r.configService.get("API_TIMEOUT_MS");f&&(e.TIMEOUT=typeof f=="string"?parseInt(f,10):f)}if(o&&typeof s.auth=="function"){let f=await s.auth(t,n);if(f.body){t=f.body;let p=e.headers||{};f.config?.headers&&(p={...p,...f.config.headers},delete p.host,delete f.config.headers),e={...e,...f.config,headers:p}}else t=f}let l={Authorization:`Bearer ${n.apiKey}`,...e?.headers||{}};for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];hi(r.configService)&&op(r.log,a.req.id,{url:String(c),headers:l,body:t});let d=await Qh(c,t,{httpsProxy:r.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,r.log);if(!d.ok){let f=await d.text();r.log.error(`[provider_response_error] Error from provider(${n.name},${t.model}: ${d.status}): ${f}`);let p=He(`Error from provider(${n.name},${t.model}: ${d.status}): ${f}`,d.status,"provider_response_error");throw p.isRateLimit=d.status===429||_i(f),p.rawBody=f,p}if(d.ok){let f=d.headers.get("content-type")||"",p=t.stream===!0;if(r.log.info(`[hidden-error-check] provider=${n.name} model=${t.model} stream=${t.stream} isStreamRequest=${p} contentType=${f} ok=${d.ok} status=${d.status} hasBody=${!!d.body}`),!p||f.includes("application/json")){let g=d.clone(),_="";try{if(_=await g.text(),!_||_.trim()==="")throw new SyntaxError("Empty JSON body");let C=JSON.parse(_);if(C&&typeof C=="object"&&C.error&&(typeof C.error=="string"||typeof C.error=="object"&&Object.keys(C.error).length>0)){r.log.error(`[provider_response_error] Hidden error from provider(${n.name},${t.model}: ${d.status}): ${_}`);let y=_i(_),m=He(`Error from provider(${n.name},${t.model}: ${d.status}): ${_}`,400,"provider_response_error");throw m.isRateLimit=y,m.rawBody=_,m}}catch(C){if(C instanceof SyntaxError){r.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${n.name},${t.model}: 200): "${_}"`);let b=He(`API returned an empty or malformed response (HTTP 200) from ${n.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw b.rawBody=_,b}throw C}}}if(!t.stream&&hi(r.configService)){let p=await d.clone().text();sp(r.log,a.req.id,{status:d.status,headers:Object.fromEntries(d.headers.entries()),body:p})}return d}async function Cp(t,e,n,r,o,s){let a=e;if(!o&&n.transformer?.use?.length)for(let c of Array.from(n.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&n.transformer?.[t.model]?.use?.length)for(let c of Array.from(n.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformResponseIn&&(s.provider||(s.provider=n),a=await r.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Jr().transformResponseIn(a,{...s,provider:n})}catch(c){console.error("Failed to apply Responses API conversion for codex client:",c)}return a}function wp(t,e,n,r){if(t.ok||e.code(t.status),n.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&hi(r.configService)){let[s,a]=t.body.tee(),c=np(r.configService);return ip(s,r.log,e.request.id,c),e.send(a)}return e.send(t.body)}else return t.json()}var bc=async t=>{t.get("/",async()=>({message:"LLMs API",version:ap})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:Ge().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:n}of e)n.endPoint&&t.post(n.endPoint,async(r,o)=>UC(r,o,t,n));t.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(n,r)=>{let{name:o,baseUrl:s,apiKey:a,models:c}=n.body;if(!o?.trim())throw He("Provider name is required",400,"invalid_request");if(!s||!WC(s))throw He("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw He("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw He("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(n.body.name))throw He(`Provider with name '${n.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(n.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{let r=t.providerService.getProvider(n.params.id);if(!r)throw He("Provider not found",404,"provider_not_found");return r}),t.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(n,r)=>{let o=t.providerService.updateProvider(n.params.id,n.body);if(!o)throw He("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{if(!t.providerService.deleteProvider(n.params.id))throw He("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(n,r)=>{if(!t.providerService.toggleProvider(n.params.id,n.body.enabled))throw He("Provider not found",404,"provider_not_found");return{message:`Provider ${n.body.enabled?"enabled":"disabled"} successfully`}})};function _i(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function WC(t){try{return new URL(t),!0}catch{return!1}}var gr=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")):Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],quotaToken:n.quota_token,transformer:n.transformer?r:void 0,cacheMode:n.cache_mode||"exclusive",enabled:n.enabled!==!1,wakeupEnabled:n.wakeup_enabled===!0,wakeupTime:n.wakeup_time||"06:00",wakeupModel:n.wakeup_model||""}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}registerProvider(e){let n={...e,enabled:e.enabled!==!1,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let a=`${r.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let a=`${r.name},${s}`,c={provider:r.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){let r=this.providers.get(e);if(!r)return!1;r.enabled=n;let o=this.configService.get("providers");if(o&&Array.isArray(o)){let s=o.find(a=>a.name===e);s&&(s.enabled=n)}return!0}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var Ye=[];for(let t=0;t<256;++t)Ye.push((t+256).toString(16).slice(1));function Ep(t,e=0){return(Ye[t[e+0]]+Ye[t[e+1]]+Ye[t[e+2]]+Ye[t[e+3]]+"-"+Ye[t[e+4]]+Ye[t[e+5]]+"-"+Ye[t[e+6]]+Ye[t[e+7]]+"-"+Ye[t[e+8]]+Ye[t[e+9]]+"-"+Ye[t[e+10]]+Ye[t[e+11]]+Ye[t[e+12]]+Ye[t[e+13]]+Ye[t[e+14]]+Ye[t[e+15]]).toLowerCase()}var Ap=require("crypto"),Ci=new Uint8Array(256),bi=Ci.length;function Cc(){return bi>Ci.length-16&&((0,Ap.randomFillSync)(Ci),bi=0),Ci.slice(bi,bi+=16)}var Sp=require("crypto"),wc={randomUUID:Sp.randomUUID};function GC(t,e,n){if(wc.randomUUID&&!e&&!t)return wc.randomUUID();t=t||{};let r=t.random??t.rng?.()??Cc();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return Ep(r)}var Ut=GC;var kp=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var vp=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);function JC(t){return t.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Tp(t){let e=[],n=[],r=g=>{if(typeof g=="string"){n.push({type:"text",text:g});return}Array.isArray(g)&&g.forEach(_=>{if(typeof _=="string"){n.push({type:"text",text:_});return}_&&typeof _=="object"&&_.type==="text"&&_.text&&n.push({..._})})},o=()=>{let g=new Map;for(let _=0;_<n.length;_++){let C=n[_],b=C?.text??JSON.stringify(C),y=g.get(b);if(y===void 0){g.set(b,_);continue}!n[y]?.cache_control&&C?.cache_control&&(n[y]=C),n.splice(_,1),_--}};t.messages.forEach(g=>{g.role==="system"?r(g.content):e.push(g)}),o();let s=[];for(let g=0;g<e.length;g++){let _=e[g];if(_.role==="tool"){let C=_.content;try{typeof _.content=="string"&&(C=JSON.parse(_.content))}catch{}C!=null&&typeof C!="object"&&typeof C!="string"&&(C=String(C));let b={type:"tool_result",tool_use_id:_.tool_call_id,content:C};_.cache_control&&(b.cache_control=_.cache_control);let y=s[s.length-1];y&&y.role==="user"&&Array.isArray(y.content)?y.content.push(b):s.push({role:"user",content:[b]})}else if(_.role==="user"){let C=[];typeof _.content=="string"?C.push({type:"text",text:_.content}):Array.isArray(_.content)&&_.content.forEach(y=>{y&&typeof y=="object"&&y.type==="image_url"&&y.image_url?.url?C.push({type:"image",source:{type:"base64",media_type:y.media_type||"image/jpeg",data:y.image_url.url.split(",")[1]||y.image_url.url}}):C.push(y)});let b=s[s.length-1];b&&b.role==="user"&&Array.isArray(b.content)?b.content.push(...C):s.push({role:"user",content:C.length>0?C:[{type:"text",text:" "}]})}else if(_.role==="assistant"){let C=[];_.content&&(typeof _.content=="string"?C.push({type:"text",text:_.content}):Array.isArray(_.content)&&C.push(..._.content)),_.tool_calls&&_.tool_calls.length>0&&_.tool_calls.forEach(y=>{let m={};try{m=JSON.parse(y.function.arguments)}catch{m=y.function.arguments}C.push({type:"tool_use",id:y.id,name:y.function.name,input:m})}),_.thinking&&C.unshift({type:"thinking",thinking:_.thinking.content,signature:_.thinking.signature});let b=s[s.length-1];b&&b.role==="assistant"&&Array.isArray(b.content)?b.content.push(...C):s.push({role:"assistant",content:C.length>0?C:[{type:"text",text:" "}]})}}let a=()=>{let g=n.filter(_=>_?.cache_control).length;for(let _ of s)Array.isArray(_.content)&&(g+=_.content.filter(C=>C?.cache_control).length);return g},c=g=>g&&typeof g=="object"?{...g}:{type:"ephemeral"},l=()=>{for(let g=s.length-1;g>=0;g--){let _=s[g]?.content;if(!Array.isArray(_))continue;let C=_.find(b=>b?.cache_control);if(C?.cache_control)return C.cache_control}for(let g=n.length-1;g>=0;g--)if(n[g]?.cache_control)return n[g].cache_control;return{type:"ephemeral"}},d=(g,_)=>{if(!Array.isArray(g?.content)||g.content.some(b=>b?.cache_control))return!1;let C=g.content.find(b=>b&&typeof b=="object"&&!b.cache_control);return C?(C.cache_control=c(_),!0):!1};(()=>{let g=4-a();if(g<=0||s.length===0)return;let _=s,C=l(),b=[];for(let y=_.length-1;y>=0;y--)_[y]?.role!=="user"||!Array.isArray(_[y].content)||b.push(y);for(let y of b){if(g<=0)break;d(_[y],C)&&g--}})();let p={messages:s,model:t.model,max_tokens:t.max_tokens||4096,temperature:t.temperature,stream:t.stream};if(n.length>0){let g=n.some(_=>_?.cache_control);p.system=g?n:n.map(_=>_.text||"").join(`
142
+ `))}}w="",g.close()}catch(S){g.error(S)}}})}wrapChatInResponses(e){let n=e?.choices?.[0],r=[],o=[];if(n?.message?.content&&o.push({type:"output_text",text:n.message.content}),r.push({type:"message",role:"assistant",content:o}),Array.isArray(n?.message?.tool_calls))for(let s of n.message.tool_calls)r.push({type:"function_call",id:s.id,call_id:s.id,name:s.function?.name||"",arguments:s.function?.arguments||"{}"});return{id:e.id||`resp_${Date.now()}`,object:"response",model:e.model,output:r,usage:e.usage?{input_tokens:e.usage.prompt_tokens||0,output_tokens:e.usage.completion_tokens||0,total_tokens:e.usage.total_tokens||0}:void 0}}convertResponseToChat(e){let n=e.output?.find(d=>d.type==="message"),r=e.output?.find(d=>d.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(d=>({type:"url_citation",url_citation:{url:d.url||"",title:d.title||"",content:"",start_index:d.start_index||0,end_index:d.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let m=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});m&&f.push(m)}else if(p.type==="output_image_base64"){let m=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});m&&f.push(m)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),s=p}else s=d.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:a,thinking:c,annotations:o},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};async function UC(t,e,n,r){let o=t.body,s=t.provider;if(!s&&o?.model){let d=o.model.split(",");d.length>1&&(s=d[0],o.model=d.slice(1).join(","))}let a=s?n.providerService.getProvider(s):void 0;if(!a&&o?.model){let d=n.providerService.resolveModelRoute(o.model);d&&(a=d.provider,o.model=d.targetModel)}if(!a&&o?.model){let f=n.configService.get("Router")?.default;if(f&&f.includes(",")){let[p,...m]=f.split(","),b=n.providerService.getProvider(p);b&&(a=b,o.model=m.join(","))}}if(t.originalModel||(t.originalModel=o?.model),!a)throw He(`Provider '${s}' not found`,404,"provider_not_found");t.provider=a.name||s;let c=zC(t),l=r.endPoint==="/v1/messages"&&c;c&&e.header("X-Codex-Detected","true"),l&&e.header("X-Codex-On-Messages","true");try{if(r.endPoint==="/v1/responses"&&o.input&&!o.messages){let y=[],_=Array.isArray(o.input)?o.input:[o.input];for(let g of _)if(g.type==="function_call")y.push({role:"assistant",tool_calls:[{id:g.call_id,type:"function",function:{name:g.name,arguments:g.arguments||"{}"}}]});else if(g.type==="function_call_output")y.push({role:"tool",tool_call_id:g.call_id,content:typeof g.output=="string"?g.output:JSON.stringify(g.output)});else if(g.role){let S=g.content;Array.isArray(S)&&(S=S.map(w=>w.type==="input_text"?{type:"text",text:w.text}:w.type==="output_text"?{type:"text",text:w.text}:w.type==="input_image"?{type:"image_url",image_url:{url:w.image_url},media_type:w.mime_type}:w)),y.push({role:g.role,content:S})}o.messages=y,delete o.input,o.instructions&&typeof o.instructions=="string"&&(o.system=o.instructions,delete o.instructions),Array.isArray(o.tools)&&(o.tools=o.tools.filter(g=>g&&typeof g=="object").map(g=>g.type==="function"&&g.name&&!g.function?{type:"function",function:{name:g.name,description:g.description||"",parameters:g.parameters||{type:"object",properties:{}}}}:g.function?.name?g:g.type==="web_search"?{type:"function",function:{name:"web_search",description:"Search the web",parameters:{type:"object",properties:{query:{type:"string"}}}}}:null).filter(Boolean)),o.reasoning&&typeof o.reasoning=="object"&&(o.reasoning={enabled:!0,effort:o.reasoning.effort})}let{requestBody:d,config:f,bypass:p}=await _p(o,a,r,t.headers,{req:t});if(d?.messages&&!p&&!t.isTargetAnthropic){let y=d.messages,_=new Set,g=[],S=[];for(let w of y){if(w?.role!=="system"){S.push(w);continue}let E=JSON.stringify(w.content??"");_.has(E)||(_.add(E),g.push(w))}g.length>0&&S.length>0&&(d.messages=[...S,...g])}let m=await bp(d,f,a,n,p,r,{req:t});try{a?.baseUrl&&m?.headers&&Uo(s,a.baseUrl,m.headers)}catch{}let b=await Cp(d,m,a,r,p,{req:t,isCodexOnMessagesEndpoint:l});if(o.stream&&b?.body){let y=b.body.getReader(),_=await y.read();if(_.done)throw y.releaseLock(),He(`Provider returned empty streaming response from ${s}`,400,"provider_response_error");let g=new TextDecoder().decode(_.value);if(g.includes("event: error")){y.releaseLock();let E=g.length<500?g:g.slice(0,500);throw He(`Provider ${s} returned error in SSE stream: ${E}`,400,"provider_response_error")}if(g.split(`
143
+ `).filter(E=>E.startsWith("data:")&&E.trim().length>5).length===0){y.releaseLock();let E=g.length<500?g:g.slice(0,500);throw He(`Provider ${s} returned streaming response with no SSE data lines: ${E}`,400,"provider_response_error")}let w=new ReadableStream({start:E=>{E.enqueue(_.value);let T=()=>{y.read().then(({done:R,value:U})=>{R?E.close():(E.enqueue(U),T())}).catch(R=>E.error(R))};T()},cancel:()=>{y.cancel()}});b=new Response(w,{headers:b.headers,status:b.status,statusText:b.statusText})}let C=wp(b,e,o,n);try{let y=o.model||t.originalModel;s&&y&&Ge().recordSuccess(s,y)}catch{}return C}catch(d){let f=await qC(t,e,n,r,d);if(f)return f;throw d}}async function qC(t,e,n,r,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=n.configService.get("fallback"),d=Ge(),f=t.provider||"",p=t.body.model||"",m=new Set,b=o?.statusCode===429||o?.isRateLimit===!0||o?.rawBody&&_i(o.rawBody)||o?.message&&_i(o.message);if(f&&p&&(b?(d.markRateLimited(f,p,120,o?.message),t.log.warn(`Primary model ${f},${p} rate-limited, will try fallbacks`)):d.recordFailure(f,p,o?.message),m.add(`${f},${p}`),n.recordUsage?.({provider:f,model:p,originalModel:t.originalModel||p,scenarioType:s,modelFamily:t.modelFamily,errorMessage:o?.message||String(o),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0,req:t})),!n.configService.get("Router")?.enableFallback)return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let y=S=>{let[w,...E]=S.split(","),T=w?.trim(),R=E.join(",").trim();return!T||!R?null:{provider:T,model:R,key:`${T},${R}`}},_=[];if(c){let S=a?.[s];Array.isArray(S)&&S.length>0?_.push({name:`${c}/${s}`,models:S}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&_.push({name:`global/${s}`,models:l[s]}),_.length===0&&s!=="image"&&t.body?.messages?.some(E=>E.role==="user"&&Array.isArray(E.content)&&E.content.some(T=>T.type==="image"||T.type==="image_url"||Array.isArray(T?.content)&&T.content.some(R=>R.type==="image"||R.type==="image_url")))&&Array.isArray(l?.image)&&l.image.length>0&&(t.log.info(`No fallback for scenario '${s}', but request has images \u2014 trying fallback.image`),_.push({name:"global/image (auto-detected)",models:l.image})),_.length===0)return null;let g=_.reduce((S,w)=>S+w.models.length,0);t.log.warn(`Request failed for ${s}, trying ${g} fallback models across ${_.length} fallback stage(s)`);for(let S of _){t.log.info(`Trying ${S.name} fallback stage with ${S.models.length} models`);for(let w of S.models){let E=y(w);if(!E){t.log.warn(`Fallback model '${w}' is invalid, skipping`);continue}if(m.has(E.key))continue;m.add(E.key);let T=E.provider,R=E.model;try{if(!d.isAvailable(T,R)){t.log.warn(`Fallback model ${w} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${w}`);let U={...t.body};U.model=R;let J={...t,provider:T,body:U},F=n.providerService.getProvider(T);if(!F){t.log.warn(`Fallback provider '${T}' not found, skipping`);continue}if(F.enabled===!1){t.log.warn(`Fallback provider '${T}' is disabled, skipping`);continue}let{requestBody:V,config:Y,bypass:X}=await _p(U,F,r,t.headers,{req:J}),ee=await bp(V,Y,F,n,X,r,{req:J});try{F?.baseUrl&&ee?.headers&&Uo(T,F.baseUrl,ee.headers)}catch{}let de=await Cp(V,ee,F,r,X,{req:J});return t.log.info(`Fallback model ${w} succeeded`),d.recordSuccess(T,R),f&&p&&(jo().promote(f,p,s,T,R),t.log.info(`Promoted fallback model ${T},${R} for ${f},${p}:${s}`),b?t.log.info(`Rate-limited original model ${f},${p} already marked unavailable with cooldown`):(d.forceOpen(f,p,o?.message),t.log.info(`Marked original model ${f},${p} as unavailable`))),t.provider=T,t.body=U,wp(de,e,U,n)}catch(U){d.recordFailure(T,R,U.message),t.log.warn(`Fallback model ${E.key} failed: ${U.message}`),n.recordUsage?.({provider:T,model:R,originalModel:t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:U.message,sessionId:t.usageSessionId||t.id,stream:t.body.stream,req:t});continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function _p(t,e,n,r,o){let s=JSON.parse(JSON.stringify(t)),a=s?.system;if(typeof a=="string"&&a.includes("cch="))s.system=a.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");else if(Array.isArray(a))for(let d=0;d<a.length;d++){let f=a[d],p=typeof f=="string"?f:f?.text??"";if(p.includes("cch=")){let m=p.replace(/cch=[^;]+;?/g,"cch=ccr-stable;");typeof f=="string"?a[d]=m:typeof f?.text=="string"&&(f.text=m)}}let c={},l=!1;if(l=HC(e,n,t),l&&(r instanceof Headers?r.delete("content-length"):delete r["content-length"],c.headers=r),!l&&typeof n.transformRequestOut=="function"){let d=await n.transformRequestOut(s);d.body?(s=d.body,c=d.config||{}):s=d}if(!l&&e.transformer?.use?.length)for(let d of e.transformer.use){if(!d||typeof d.transformRequestIn!="function")continue;let f=await d.transformRequestIn(s,e,o);f.body?(s=f.body,c={...c,...f.config}):s=f}if(!l&&e.transformer?.[t.model]?.use?.length)for(let d of e.transformer[t.model].use)!d||typeof d.transformRequestIn!="function"||(s=await d.transformRequestIn(s,e,o));return{requestBody:s,config:c,bypass:l}}function HC(t,e,n){return e.endPoint==="/v1/chat/completions"&&Array.isArray(n?.system)?!1:t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[n.model]?.use.length||t.transformer?.[n.model]?.use.length===1&&t.transformer?.[n.model]?.use[0].name===e.name)}function zC(t){let e=t.headers||{},n=e["x-anthropic-billing-header"]||"";if(typeof n=="string"&&n.includes("cc_version="))return!1;let r=e["user-agent"]||"";if(typeof r=="string"&&/codex/i.test(r))return!0;let o=t.pathname||t.url||"";if(typeof o=="string"&&o.split("?",1)[0].endsWith("/v1/responses"))return!0;let s=t.originalModel||"";return typeof s=="string"&&s.toLowerCase()==="ccr-codex"}async function bp(t,e,n,r,o,s,a){let c=e.url||new URL(n.baseUrl);if(!e.TIMEOUT){let f=r.configService.get("API_TIMEOUT_MS");f&&(e.TIMEOUT=typeof f=="string"?parseInt(f,10):f)}if(o&&typeof s.auth=="function"){let f=await s.auth(t,n);if(f.body){t=f.body;let p=e.headers||{};f.config?.headers&&(p={...p,...f.config.headers},delete p.host,delete f.config.headers),e={...e,...f.config,headers:p}}else t=f}let l={Authorization:`Bearer ${n.apiKey}`,...e?.headers||{}};for(let f in l)(l[f]==="undefined"||["authorization","Authorization"].includes(f)&&l[f]?.includes("undefined"))&&delete l[f];hi(r.configService)&&op(r.log,a.req.id,{url:String(c),headers:l,body:t});let d=await Qh(c,t,{httpsProxy:r.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,r.log);if(!d.ok){let f=await d.text();r.log.error(`[provider_response_error] Error from provider(${n.name},${t.model}: ${d.status}): ${f}`);let p=He(`Error from provider(${n.name},${t.model}: ${d.status}): ${f}`,d.status,"provider_response_error");throw p.isRateLimit=d.status===429||_i(f),p.rawBody=f,p}if(d.ok){let f=d.headers.get("content-type")||"",p=t.stream===!0;if(r.log.info(`[hidden-error-check] provider=${n.name} model=${t.model} stream=${t.stream} isStreamRequest=${p} contentType=${f} ok=${d.ok} status=${d.status} hasBody=${!!d.body}`),!p||f.includes("application/json")){let m=d.clone(),b="";try{if(b=await m.text(),!b||b.trim()==="")throw new SyntaxError("Empty JSON body");let C=JSON.parse(b);if(C&&typeof C=="object"&&C.error&&(typeof C.error=="string"||typeof C.error=="object"&&Object.keys(C.error).length>0)){r.log.error(`[provider_response_error] Hidden error from provider(${n.name},${t.model}: ${d.status}): ${b}`);let _=_i(b),g=He(`Error from provider(${n.name},${t.model}: ${d.status}): ${b}`,400,"provider_response_error");throw g.isRateLimit=_,g.rawBody=b,g}}catch(C){if(C instanceof SyntaxError){r.log.warn(`[provider_response_error] Empty or malformed JSON response from provider(${n.name},${t.model}: 200): "${b}"`);let y=He(`API returned an empty or malformed response (HTTP 200) from ${n.name} \u2014 check for a proxy or gateway intercepting the request`,400,"provider_response_error");throw y.rawBody=b,y}throw C}}}if(!t.stream&&hi(r.configService)){let p=await d.clone().text();sp(r.log,a.req.id,{status:d.status,headers:Object.fromEntries(d.headers.entries()),body:p})}return d}async function Cp(t,e,n,r,o,s){let a=e;if(!o&&n.transformer?.use?.length)for(let c of Array.from(n.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&n.transformer?.[t.model]?.use?.length)for(let c of Array.from(n.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformResponseIn&&(s.provider||(s.provider=n),a=await r.transformResponseIn(a,s)),s?.isCodexOnMessagesEndpoint)try{a=await new Jr().transformResponseIn(a,{...s,provider:n})}catch(c){console.error("Failed to apply Responses API conversion for codex client:",c)}return a}function wp(t,e,n,r){if(t.ok||e.code(t.status),n.stream===!0){if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&hi(r.configService)){let[s,a]=t.body.tee(),c=np(r.configService);return ip(s,r.log,e.request.id,c),e.send(a)}return e.send(t.body)}else return t.json()}var bc=async t=>{t.get("/",async()=>({message:"LLMs API",version:ap})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:Ge().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError,rateLimitUntil:o.rateLimitUntil??null})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:n}of e)n.endPoint&&t.post(n.endPoint,async(r,o)=>UC(r,o,t,n));t.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(n,r)=>{let{name:o,baseUrl:s,apiKey:a,models:c}=n.body;if(!o?.trim())throw He("Provider name is required",400,"invalid_request");if(!s||!WC(s))throw He("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw He("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw He("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(n.body.name))throw He(`Provider with name '${n.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(n.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{let r=t.providerService.getProvider(n.params.id);if(!r)throw He("Provider not found",404,"provider_not_found");return r}),t.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(n,r)=>{let o=t.providerService.updateProvider(n.params.id,n.body);if(!o)throw He("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{if(!t.providerService.deleteProvider(n.params.id))throw He("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(n,r)=>{if(!t.providerService.toggleProvider(n.params.id,n.body.enabled))throw He("Provider not found",404,"provider_not_found");return{message:`Provider ${n.body.enabled?"enabled":"disabled"} successfully`}})};function _i(t){let e=t.toLowerCase();return e.includes("rate limit")||e.includes("rate_limit")||e.includes("rate_limit_error")||e.includes("too many requests")||e.includes("too many")||e.includes("quota exhausted")||e.includes("qps_limit")||e.includes("token_limit")||e.includes("\u9650\u6D41")||e.includes("\u9891\u7387\u9650\u5236")}function WC(t){try{return new URL(t),!0}catch{return!1}}var gr=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")):Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return new a(s[1])}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?new a:a}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],quotaToken:n.quota_token,transformer:n.transformer?r:void 0,cacheMode:n.cache_mode||"exclusive",enabled:n.enabled!==!1,wakeupEnabled:n.wakeup_enabled===!0,wakeupTime:n.wakeup_time||"06:00",wakeupModel:n.wakeup_model||""}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}registerProvider(e){let n={...e,enabled:e.enabled!==!1,wakeupEnabled:e.wakeupEnabled===!0,wakeupTime:e.wakeupTime||"06:00",wakeupModel:e.wakeupModel||""};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let a=`${r.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let a=`${r.name},${s}`,c={provider:r.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){let r=this.providers.get(e);if(!r)return!1;r.enabled=n;let o=this.configService.get("providers");if(o&&Array.isArray(o)){let s=o.find(a=>a.name===e);s&&(s.enabled=n)}return!0}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.enabled!==!1&&n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var Ye=[];for(let t=0;t<256;++t)Ye.push((t+256).toString(16).slice(1));function Ep(t,e=0){return(Ye[t[e+0]]+Ye[t[e+1]]+Ye[t[e+2]]+Ye[t[e+3]]+"-"+Ye[t[e+4]]+Ye[t[e+5]]+"-"+Ye[t[e+6]]+Ye[t[e+7]]+"-"+Ye[t[e+8]]+Ye[t[e+9]]+"-"+Ye[t[e+10]]+Ye[t[e+11]]+Ye[t[e+12]]+Ye[t[e+13]]+Ye[t[e+14]]+Ye[t[e+15]]).toLowerCase()}var Ap=require("crypto"),Ci=new Uint8Array(256),bi=Ci.length;function Cc(){return bi>Ci.length-16&&((0,Ap.randomFillSync)(Ci),bi=0),Ci.slice(bi,bi+=16)}var Sp=require("crypto"),wc={randomUUID:Sp.randomUUID};function GC(t,e,n){if(wc.randomUUID&&!e&&!t)return wc.randomUUID();t=t||{};let r=t.random??t.rng?.()??Cc();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return Ep(r)}var Ut=GC;var kp=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var vp=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);function JC(t){return t.filter(e=>!!e?.function?.name).map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function Tp(t){let e=[],n=[],r=m=>{if(typeof m=="string"){n.push({type:"text",text:m});return}Array.isArray(m)&&m.forEach(b=>{if(typeof b=="string"){n.push({type:"text",text:b});return}b&&typeof b=="object"&&b.type==="text"&&b.text&&n.push({...b})})},o=()=>{let m=new Map;for(let b=0;b<n.length;b++){let C=n[b],y=C?.text??JSON.stringify(C),_=m.get(y);if(_===void 0){m.set(y,b);continue}!n[_]?.cache_control&&C?.cache_control&&(n[_]=C),n.splice(b,1),b--}};t.messages.forEach(m=>{m.role==="system"?r(m.content):e.push(m)}),o();let s=[];for(let m=0;m<e.length;m++){let b=e[m];if(b.role==="tool"){let C=b.content;try{typeof b.content=="string"&&(C=JSON.parse(b.content))}catch{}C!=null&&typeof C!="object"&&typeof C!="string"&&(C=String(C));let y={type:"tool_result",tool_use_id:b.tool_call_id,content:C};b.cache_control&&(y.cache_control=b.cache_control);let _=s[s.length-1];_&&_.role==="user"&&Array.isArray(_.content)?_.content.push(y):s.push({role:"user",content:[y]})}else if(b.role==="user"){let C=[];typeof b.content=="string"?C.push({type:"text",text:b.content}):Array.isArray(b.content)&&b.content.forEach(_=>{_&&typeof _=="object"&&_.type==="image_url"&&_.image_url?.url?C.push({type:"image",source:{type:"base64",media_type:_.media_type||"image/jpeg",data:_.image_url.url.split(",")[1]||_.image_url.url}}):C.push(_)});let y=s[s.length-1];y&&y.role==="user"&&Array.isArray(y.content)?y.content.push(...C):s.push({role:"user",content:C.length>0?C:[{type:"text",text:" "}]})}else if(b.role==="assistant"){let C=[];b.content&&(typeof b.content=="string"?C.push({type:"text",text:b.content}):Array.isArray(b.content)&&C.push(...b.content)),b.tool_calls&&b.tool_calls.length>0&&b.tool_calls.forEach(_=>{let g={};try{g=JSON.parse(_.function.arguments)}catch{g=_.function.arguments}C.push({type:"tool_use",id:_.id,name:_.function.name,input:g})}),b.thinking&&C.unshift({type:"thinking",thinking:b.thinking.content,signature:b.thinking.signature});let y=s[s.length-1];y&&y.role==="assistant"&&Array.isArray(y.content)?y.content.push(...C):s.push({role:"assistant",content:C.length>0?C:[{type:"text",text:" "}]})}}let a=()=>{let m=n.filter(b=>b?.cache_control).length;for(let b of s)Array.isArray(b.content)&&(m+=b.content.filter(C=>C?.cache_control).length);return m},c=m=>m&&typeof m=="object"?{...m}:{type:"ephemeral"},l=()=>{for(let m=s.length-1;m>=0;m--){let b=s[m]?.content;if(!Array.isArray(b))continue;let C=b.find(y=>y?.cache_control);if(C?.cache_control)return C.cache_control}for(let m=n.length-1;m>=0;m--)if(n[m]?.cache_control)return n[m].cache_control;return{type:"ephemeral"}},d=(m,b)=>{if(!Array.isArray(m?.content)||m.content.some(y=>y?.cache_control))return!1;let C=m.content.find(y=>y&&typeof y=="object"&&!y.cache_control);return C?(C.cache_control=c(b),!0):!1};(()=>{let m=4-a();if(m<=0||s.length===0)return;let b=s,C=l(),y=[];for(let _=b.length-1;_>=0;_--)b[_]?.role!=="user"||!Array.isArray(b[_].content)||y.push(_);for(let _ of y){if(m<=0)break;d(b[_],C)&&m--}})();let p={messages:s,model:t.model,max_tokens:t.max_tokens||4096,temperature:t.temperature,stream:t.stream};if(n.length>0){let m=n.some(b=>b?.cache_control);p.system=m?n:n.map(b=>b.text||"").join(`
144
144
 
145
145
  `)}return t.tools&&t.tools.length>0&&(p.tools=JC(t.tools),t.tool_choice&&(t.tool_choice==="auto"?p.tool_choice={type:"auto"}:t.tool_choice==="any"||t.tool_choice==="required"?p.tool_choice={type:"any"}:typeof t.tool_choice=="string"?p.tool_choice={type:"tool",name:t.tool_choice}:typeof t.tool_choice=="object"&&t.tool_choice.type==="function"&&(p.tool_choice={type:"tool",name:t.tool_choice.function.name}))),p}var wi=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n){let r={};return this.useBearer?(r.authorization=`Bearer ${n.apiKey}`,r["x-api-key"]=void 0):(r["x-api-key"]=n.apiKey,r.authorization=void 0),{body:e,config:{headers:r}}}async transformRequestOut(e){let n=[];if(e.system){if(typeof e.system=="string")n.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let s=e.system.filter(a=>a.type==="text"&&a.text).map(a=>({type:"text",text:a.text,cache_control:a.cache_control}));n.push({role:"system",content:s})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(s=>{if(s.role==="system"){n.push({role:"system",content:s.content});return}if(s.role==="user"||s.role==="assistant"){if(typeof s.content=="string"){n.push({role:s.role,content:s.content});return}if(Array.isArray(s.content)){if(s.role==="user"){let a=s.content.filter(l=>l.type==="tool_result"&&l.tool_use_id);a.length&&a.forEach(l=>{let d={role:"tool",content:typeof l.content=="string"?l.content:JSON.stringify(l.content),tool_call_id:l.tool_use_id,cache_control:l.cache_control};n.push(d)});let c=s.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&n.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?vp(l.source.data,l.source.media_type):l.source.url},media_type:l.source.media_type}:l)})}else if(s.role==="assistant"){let a={role:"assistant",content:""},c=s.content.filter(f=>f.type==="text"&&f.text);c.length&&(a.content=c.map(f=>f.text).join(`
146
- `));let l=s.content.filter(f=>f.type==="tool_use"&&f.id);l.length&&(a.tool_calls=l.map(f=>({id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.input||{})}})));let d=s.content.find(f=>f.type==="thinking");d&&(a.thinking={content:d.thinking,signature:d.signature}),n.push(a)}return}}});let o={messages:n,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(o.reasoning={effort:kp(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}async transformRequestIn(e,n,r){if(!this.isAnthropicMessagesEndpoint(n.baseUrl))return e;r&&r.req&&(r.req.isTargetAnthropic=!0);let o=Tp(e),s={};return this.useBearer?(s.authorization=`Bearer ${n.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=n.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:o,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,n){if(n?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema}}))}async convertOpenAIStreamToAnthropic(e,n){return new ReadableStream({start:async o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,c=null,l="unknown",d=!1,f=!1,p=!1,g=new Map,_=new Map,C=0,b=0,y=0,m=!1,k=!1,w=0,A=-1,T=()=>{let F=w;return w++,F},R=F=>{if(!m)try{o.enqueue(F);let V=new TextDecoder().decode(F);this.logger.debug({reqId:n.req.id,data:V,type:"send data"})}catch(V){if(V instanceof TypeError&&V.message.includes("Controller is already closed"))m=!0;else throw this.logger.debug({reqId:n.req.id,error:V instanceof Error?V.message:String(V),type:"send data error"}),V}},U=()=>{if(!m)try{if(!d){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),o.close(),m=!0;return}if(A>=0){let V={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
146
+ `));let l=s.content.filter(f=>f.type==="tool_use"&&f.id);l.length&&(a.tool_calls=l.map(f=>({id:f.id,type:"function",function:{name:f.name,arguments:JSON.stringify(f.input||{})}})));let d=s.content.find(f=>f.type==="thinking");d&&(a.thinking={content:d.thinking,signature:d.signature}),n.push(a)}return}}});let o={messages:n,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(o.reasoning={effort:kp(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}async transformRequestIn(e,n,r){if(!this.isAnthropicMessagesEndpoint(n.baseUrl))return e;r&&r.req&&(r.req.isTargetAnthropic=!0);let o=Tp(e),s={};return this.useBearer?(s.authorization=`Bearer ${n.apiKey}`,s["x-api-key"]=void 0):(s["x-api-key"]=n.apiKey,s.authorization=void 0),s["anthropic-version"]="2023-06-01",s["content-type"]="application/json",{body:o,config:{headers:s}}}isAnthropicMessagesEndpoint(e){try{return new URL(e.trim()).pathname.replace(/\/+$/,"").endsWith("/messages")}catch{return!1}}async transformResponseIn(e,n){if(n?.req?.isTargetAnthropic)return e;if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema}}))}async convertOpenAIStreamToAnthropic(e,n){return new ReadableStream({start:async o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,c=null,l="unknown",d=!1,f=!1,p=!1,m=new Map,b=new Map,C=0,y=0,_=0,g=!1,S=!1,w=0,E=-1,T=()=>{let F=w;return w++,F},R=F=>{if(!g)try{o.enqueue(F);let V=new TextDecoder().decode(F);this.logger.debug({reqId:n.req.id,data:V,type:"send data"})}catch(V){if(V instanceof TypeError&&V.message.includes("Controller is already closed"))g=!0;else throw this.logger.debug({reqId:n.req.id,error:V instanceof Error?V.message:String(V),type:"send data error"}),V}},U=()=>{if(!g)try{if(!d){this.logger?.warn("[empty_stream] Upstream produced no data, closing silently"),o.close(),g=!0;return}if(E>=0){let V={type:"content_block_stop",index:E};R(s.encode(`event: content_block_stop
147
147
  data: ${JSON.stringify(V)}
148
148
 
149
- `)),A=-1}if(c)R(s.encode(`event: message_delta
149
+ `)),E=-1}if(c)R(s.encode(`event: message_delta
150
150
  data: ${JSON.stringify(c)}
151
151
 
152
152
  `)),c=null;else{let V=n?.req?.tokenCount||0;R(s.encode(`event: message_delta
@@ -155,170 +155,170 @@ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_
155
155
  `))}let F={type:"message_stop"};R(s.encode(`event: message_stop
156
156
  data: ${JSON.stringify(F)}
157
157
 
158
- `)),o.close(),m=!0}catch(F){if(F instanceof TypeError&&F.message.includes("Controller is already closed"))m=!0;else throw F}},J=null;try{J=e.getReader();let F=new TextDecoder,V="";for(;!m;){let{done:Y,value:X}=await J.read();if(Y)break;V+=F.decode(X,{stream:!0});let ee=V.split(`
159
- `);V=ee.pop()||"";for(let de of ee){if(m||p)break;if(!de.startsWith("data:"))continue;let Ae=de.slice(5).trim();if(this.logger.debug({reqId:n.req.id,type:"recieved data",data:Ae}),Ae!=="[DONE]")try{let ae=JSON.parse(Ae);if(C++,this.logger.debug({reqId:n.req.id,response:ae,tppe:"Original Response"}),ae.error){n?.req&&(n.req.sseError=ae.error);let W={type:"error",message:{type:"api_error",message:JSON.stringify(ae.error)}};R(s.encode(`event: error
158
+ `)),o.close(),g=!0}catch(F){if(F instanceof TypeError&&F.message.includes("Controller is already closed"))g=!0;else throw F}},J=null;try{J=e.getReader();let F=new TextDecoder,V="";for(;!g;){let{done:Y,value:X}=await J.read();if(Y)break;V+=F.decode(X,{stream:!0});let ee=V.split(`
159
+ `);V=ee.pop()||"";for(let de of ee){if(g||p)break;if(!de.startsWith("data:"))continue;let Ae=de.slice(5).trim();if(this.logger.debug({reqId:n.req.id,type:"recieved data",data:Ae}),Ae!=="[DONE]")try{let ae=JSON.parse(Ae);if(C++,this.logger.debug({reqId:n.req.id,response:ae,tppe:"Original Response"}),ae.error){n?.req&&(n.req.sseError=ae.error);let W={type:"error",message:{type:"api_error",message:JSON.stringify(ae.error)}};R(s.encode(`event: error
160
160
  data: ${JSON.stringify(W)}
161
161
 
162
- `));continue}if(l=ae.model||l,!d&&!m&&!p){d=!0;let W=n?.req?.tokenCount||0,Q={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:W,output_tokens:0}}};R(s.encode(`event: message_start
162
+ `));continue}if(l=ae.model||l,!d&&!g&&!p){d=!0;let W=n?.req?.tokenCount||0,Q={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:W,output_tokens:0}}};R(s.encode(`event: message_start
163
163
  data: ${JSON.stringify(Q)}
164
164
 
165
- `))}let pe=ae.choices?.[0];if(ae.usage){let W=ae.usage?.prompt_tokens_details?.cached_tokens||0,re=(ae.usage?.prompt_tokens||0)-W;this.logger?.info({debug_log:!0,reqId:n.req.id,phase:"anthropic_transformer_usage",providerUsage:ae.usage,mappedUsage:{input_tokens:re,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:W},choicesLength:Array.isArray(ae.choices)?ae.choices.length:void 0,finishReason:pe?.finish_reason}),c?c.usage={input_tokens:re,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:W}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:re,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:W}}}if(!pe)continue;if(pe?.delta?.thinking&&!m&&!p&&!f){if(!k){let W=T(),Q={type:"content_block_start",index:W,content_block:{type:"thinking",thinking:""}};R(s.encode(`event: content_block_start
165
+ `))}let pe=ae.choices?.[0];if(ae.usage){let W=ae.usage?.prompt_tokens_details?.cached_tokens||0,re=(ae.usage?.prompt_tokens||0)-W;this.logger?.info({debug_log:!0,reqId:n.req.id,phase:"anthropic_transformer_usage",providerUsage:ae.usage,mappedUsage:{input_tokens:re,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:W},choicesLength:Array.isArray(ae.choices)?ae.choices.length:void 0,finishReason:pe?.finish_reason}),c?c.usage={input_tokens:re,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:W}:c={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:re,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:W}}}if(!pe)continue;if(pe?.delta?.thinking&&!g&&!p&&!f){if(!S){let W=T(),Q={type:"content_block_start",index:W,content_block:{type:"thinking",thinking:""}};R(s.encode(`event: content_block_start
166
166
  data: ${JSON.stringify(Q)}
167
167
 
168
- `)),A=W,k=!0}if(pe.delta.thinking.signature){let W={type:"content_block_delta",index:A,delta:{type:"signature_delta",signature:pe.delta.thinking.signature}};R(s.encode(`event: content_block_delta
168
+ `)),E=W,S=!0}if(pe.delta.thinking.signature){let W={type:"content_block_delta",index:E,delta:{type:"signature_delta",signature:pe.delta.thinking.signature}};R(s.encode(`event: content_block_delta
169
169
  data: ${JSON.stringify(W)}
170
170
 
171
- `));let Q={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
171
+ `));let Q={type:"content_block_stop",index:E};R(s.encode(`event: content_block_stop
172
172
  data: ${JSON.stringify(Q)}
173
173
 
174
- `)),A=-1}else if(pe.delta.thinking.content){let W={type:"content_block_delta",index:A,delta:{type:"thinking_delta",thinking:pe.delta.thinking.content||""}};R(s.encode(`event: content_block_delta
174
+ `)),E=-1}else if(pe.delta.thinking.content){let W={type:"content_block_delta",index:E,delta:{type:"thinking_delta",thinking:pe.delta.thinking.content||""}};R(s.encode(`event: content_block_delta
175
175
  data: ${JSON.stringify(W)}
176
176
 
177
- `))}}if(pe?.delta?.content&&!m&&!p){if(b++,A>=0&&!f){let Q={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
177
+ `))}}if(pe?.delta?.content&&!g&&!p){if(y++,E>=0&&!f){let Q={type:"content_block_stop",index:E};R(s.encode(`event: content_block_stop
178
178
  data: ${JSON.stringify(Q)}
179
179
 
180
- `)),A=-1}if(!f&&!p){f=!0;let W=T(),Q={type:"content_block_start",index:W,content_block:{type:"text",text:""}};R(s.encode(`event: content_block_start
180
+ `)),E=-1}if(!f&&!p){f=!0;let W=T(),Q={type:"content_block_start",index:W,content_block:{type:"text",text:""}};R(s.encode(`event: content_block_start
181
181
  data: ${JSON.stringify(Q)}
182
182
 
183
- `)),A=W}if(!m&&!p){let W={type:"content_block_delta",index:A,delta:{type:"text_delta",text:pe.delta.content}};R(s.encode(`event: content_block_delta
183
+ `)),E=W}if(!g&&!p){let W={type:"content_block_delta",index:E,delta:{type:"text_delta",text:pe.delta.content}};R(s.encode(`event: content_block_delta
184
184
  data: ${JSON.stringify(W)}
185
185
 
186
- `))}}if(pe?.delta?.annotations?.length&&!m&&!p){if(A>=0&&f){let W={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
186
+ `))}}if(pe?.delta?.annotations?.length&&!g&&!p){if(E>=0&&f){let W={type:"content_block_stop",index:E};R(s.encode(`event: content_block_stop
187
187
  data: ${JSON.stringify(W)}
188
188
 
189
- `)),A=-1,f=!1}pe?.delta?.annotations.forEach(W=>{let Q=T(),re={type:"content_block_start",index:Q,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Ut()}`,content:[{type:"web_search_result",title:W.url_citation.title,url:W.url_citation.url}]}};R(s.encode(`event: content_block_start
189
+ `)),E=-1,f=!1}pe?.delta?.annotations.forEach(W=>{let Q=T(),re={type:"content_block_start",index:Q,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Ut()}`,content:[{type:"web_search_result",title:W.url_citation.title,url:W.url_citation.url}]}};R(s.encode(`event: content_block_start
190
190
  data: ${JSON.stringify(re)}
191
191
 
192
192
  `));let $e={type:"content_block_stop",index:Q};R(s.encode(`event: content_block_stop
193
193
  data: ${JSON.stringify($e)}
194
194
 
195
- `)),A=-1})}if(pe?.delta?.tool_calls&&!m&&!p){y++;let W=new Set;for(let Q of pe.delta.tool_calls){if(m)break;let re=Q.index??0;if(W.has(re))continue;if(W.add(re),!_.has(re)){if(A>=0){let Re={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
195
+ `)),E=-1})}if(pe?.delta?.tool_calls&&!g&&!p){_++;let W=new Set;for(let Q of pe.delta.tool_calls){if(g)break;let re=Q.index??0;if(W.has(re))continue;if(W.add(re),!b.has(re)){if(E>=0){let Re={type:"content_block_stop",index:E};R(s.encode(`event: content_block_stop
196
196
  data: ${JSON.stringify(Re)}
197
197
 
198
- `)),A=-1}let ke=T();_.set(re,ke);let G=Q.id||`call_ccr_${re}`,le=Q.function?.name||`tool_${re}`,_e={type:"content_block_start",index:ke,content_block:{type:"tool_use",id:G,name:le,input:{}}};R(s.encode(`event: content_block_start
198
+ `)),E=-1}let ke=T();b.set(re,ke);let G=Q.id||`call_ccr_${re}`,le=Q.function?.name||`tool_${re}`,_e={type:"content_block_start",index:ke,content_block:{type:"tool_use",id:G,name:le,input:{}}};R(s.encode(`event: content_block_start
199
199
  data: ${JSON.stringify(_e)}
200
200
 
201
- `)),A=ke;let Bt={id:G,name:le,arguments:"",contentBlockIndex:ke};g.set(re,Bt)}else if(Q.id&&Q.function?.name){let ke=g.get(re);ke.id.startsWith("call_")&&ke.name.startsWith("tool_")&&(ke.id=Q.id,ke.name=Q.function.name)}if(Q.function?.arguments&&!m&&!p){let ke=_.get(re);if(ke===void 0)continue;let G=g.get(re);G&&(G.arguments+=Q.function.arguments);try{let le={type:"content_block_delta",index:ke,delta:{type:"input_json_delta",partial_json:Q.function.arguments}};R(s.encode(`event: content_block_delta
201
+ `)),E=ke;let Bt={id:G,name:le,arguments:"",contentBlockIndex:ke};m.set(re,Bt)}else if(Q.id&&Q.function?.name){let ke=m.get(re);ke.id.startsWith("call_")&&ke.name.startsWith("tool_")&&(ke.id=Q.id,ke.name=Q.function.name)}if(Q.function?.arguments&&!g&&!p){let ke=b.get(re);if(ke===void 0)continue;let G=m.get(re);G&&(G.arguments+=Q.function.arguments);try{let le={type:"content_block_delta",index:ke,delta:{type:"input_json_delta",partial_json:Q.function.arguments}};R(s.encode(`event: content_block_delta
202
202
  data: ${JSON.stringify(le)}
203
203
 
204
204
  `))}catch{try{let le=Q.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),_e={type:"content_block_delta",index:ke,delta:{type:"input_json_delta",partial_json:le}};R(s.encode(`event: content_block_delta
205
205
  data: ${JSON.stringify(_e)}
206
206
 
207
- `))}catch(le){console.error(le)}}}}}if(pe?.finish_reason&&!m&&!p){if(b===0&&y===0&&console.error("Warning: No content in the stream response!"),A>=0){let W={type:"content_block_stop",index:A};R(s.encode(`event: content_block_stop
207
+ `))}catch(le){console.error(le)}}}}}if(pe?.finish_reason&&!g&&!p){if(y===0&&_===0&&console.error("Warning: No content in the stream response!"),E>=0){let W={type:"content_block_stop",index:E};R(s.encode(`event: content_block_stop
208
208
  data: ${JSON.stringify(W)}
209
209
 
210
- `)),A=-1}if(!m){let Q={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[pe.finish_reason]||"end_turn",re=ae.usage?.prompt_tokens_details?.cached_tokens||0,ke=(ae.usage?.prompt_tokens||0)-re;c={type:"message_delta",delta:{stop_reason:Q,stop_sequence:null},usage:{input_tokens:ke,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:re}}}break}}catch(ae){this.logger?.error(`parseError: ${ae.name} message: ${ae.message} stack: ${ae.stack} data: ${Ae}`)}}}U()}catch(F){if(!m)try{o.error(F)}catch(V){console.error(V)}}finally{if(J)try{J.releaseLock()}catch(F){console.error(F)}}},cancel:o=>{this.logger.debug({reqId:n.req.id},`cancle stream: ${o}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[];if(r.message.annotations){let l=`srvtoolu_${Ut()}`;o.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:l,content:r.message.annotations.map(d=>({type:"web_search_result",url:d.url_citation.url,title:d.url_citation.title}))})}r.message.content&&o.push({type:"text",text:r.message.content}),r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(l=>{let d={};try{let f=l.function.arguments||"{}";typeof f=="object"?d=f:typeof f=="string"&&(d=JSON.parse(f))}catch{d={text:l.function.arguments||""}}o.push({type:"tool_use",id:l.id,name:l.function.name,input:d})}),r.message?.thinking?.content&&o.push({type:"thinking",thinking:r.message.thinking.content,signature:r.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens||0,a=(e.usage?.prompt_tokens||0)-s,c={id:e.id?.startsWith("msg_")?e.id:`msg_${Ut().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":r.finish_reason==="length"?"max_tokens":r.finish_reason==="tool_calls"?"tool_use":r.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:n.req.id,result:c},"Conversion complete, final Anthropic response"),c}catch{throw He(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Vr={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function VC(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(Vr).includes(r)?r:Vr.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(Vr).includes(o)?o:Vr.TYPE_UNSPECIFIED})}}}function qo(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&VC(t.type,e);for(let[a,c]of Object.entries(t))if(c!=null)if(a=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=c.toUpperCase();e.type=Object.values(Vr).includes(l)?l:Vr.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=qo(c);else if(r.includes(a)){let l=[];for(let d of c){if(d.type=="null"){e.nullable=!0;continue}l.push(qo(d))}e[a]=l}else if(o.includes(a)){let l={};for(let[d,f]of Object.entries(c))l[d]=qo(f);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}return e}function KC(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=qo(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=qo(e.response));return t}function Ei(t){let e=[],n=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));n?.length&&e.push(KC({functionDeclarations:n})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let o=[],s=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let d;l.role==="assistant"?d="model":(["user","system"].includes(l.role),d="user");let f=[];if(typeof l.content=="string"){let p={text:l.content};l.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),f.push(p)}else Array.isArray(l.content)?f.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?f.push({text:l.content.text}):f.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&f.push(...l.tool_calls.map(p=>{let g={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return l.thinking?.signature&&(g.thoughtSignature=l.thinking.signature),g})),f.length===0&&f.push({text:""}),o.push({role:d,parts:f}),d==="model"&&l.tool_calls){let p=l.tool_calls.map(g=>{let _=s.find(C=>C.tool_call_id===g.id);return{functionResponse:{name:g?.function?.name,response:{result:_?.content}}}});o.push({role:"user",parts:p})}});let a={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],d,f=t.reasoning.max_tokens;typeof f<"u"&&(f>=l[0]&&f<=l[1]?d=f:f<l[0]?d=l[0]:f>l[1]&&(d=l[1]),a.thinkingConfig.thinkingBudget=d)}let c={contents:o,tools:e.length?e:void 0,generationConfig:a};if(t.tool_choice){let l={functionCallingConfig:{}};t.tool_choice==="auto"?l.functionCallingConfig.mode="auto":t.tool_choice==="none"?l.functionCallingConfig.mode="none":t.tool_choice==="required"?l.functionCallingConfig.mode="any":t.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[t.tool_choice?.function?.name]),c.toolConfig=l}return c}function Ai(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,c=t.tool_choice,l={messages:[],model:r,max_tokens:o,temperature:s,stream:a,tool_choice:c};return Array.isArray(e)&&e.forEach(d=>{typeof d=="string"?l.messages.push({role:"user",content:d}):typeof d.text=="string"?l.messages.push({role:"user",content:d.text||null}):d.role==="user"?l.messages.push({role:"user",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]}):d.role==="model"&&l.messages.push({role:"assistant",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]})}),Array.isArray(n)&&(l.tools=[],n.forEach(d=>{Array.isArray(d.functionDeclarations)&&d.functionDeclarations.forEach(f=>{l.tools.push({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}})})})),l}async function Si(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json();n?.debug({response:r},`${e} response:`);let o="",s="",a=r.candidates[0]?.content?.parts||[],c=[];for(let p of a)p.text&&p.thought===!0?o+=p.text:c.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let l=c?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],d=c?.filter(p=>p.text)?.map(p=>p.text)?.join(`
211
- `)||"",f={id:r.responseId,choices:[{finish_reason:r.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:d,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:o||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.modelVersion,object:"chat.completion",usage:{completion_tokens:r.usageMetadata?.candidatesTokenCount||0,prompt_tokens:r.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:r.usageMetadata?.cachedContentTokenCount||0},total_tokens:r.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:r.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(f),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=!1,a=!1,c=!1,l="",d=0,f=-1,p=new ReadableStream({async start(g){let _=async(y,m)=>{if(y.startsWith("data: ")){let k=y.slice(6).trim();if(k){n?.debug({chunkStr:k},`${e} chunk:`);try{let w=JSON.parse(k);if(!w.candidates||!w.candidates[0]){n?.debug({chunkStr:k},"Invalid chunk structure");return}let A=w.candidates[0],T=A.content?.parts||[];T.filter(F=>F.text&&F.thought===!0).forEach(F=>{c||(c=!0);let V={choices:[{delta:{role:"assistant",content:null,thinking:{content:F.text}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(V)}
210
+ `)),E=-1}if(!g){let Q={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[pe.finish_reason]||"end_turn",re=ae.usage?.prompt_tokens_details?.cached_tokens||0,ke=(ae.usage?.prompt_tokens||0)-re;c={type:"message_delta",delta:{stop_reason:Q,stop_sequence:null},usage:{input_tokens:ke,output_tokens:ae.usage?.completion_tokens||0,cache_read_input_tokens:re}}}break}}catch(ae){this.logger?.error(`parseError: ${ae.name} message: ${ae.message} stack: ${ae.stack} data: ${Ae}`)}}}U()}catch(F){if(!g)try{o.error(F)}catch(V){console.error(V)}}finally{if(J)try{J.releaseLock()}catch(F){console.error(F)}}},cancel:o=>{this.logger.debug({reqId:n.req.id},`cancle stream: ${o}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[];if(r.message.annotations){let l=`srvtoolu_${Ut()}`;o.push({type:"server_tool_use",id:l,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:l,content:r.message.annotations.map(d=>({type:"web_search_result",url:d.url_citation.url,title:d.url_citation.title}))})}r.message.content&&o.push({type:"text",text:r.message.content}),r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(l=>{let d={};try{let f=l.function.arguments||"{}";typeof f=="object"?d=f:typeof f=="string"&&(d=JSON.parse(f))}catch{d={text:l.function.arguments||""}}o.push({type:"tool_use",id:l.id,name:l.function.name,input:d})}),r.message?.thinking?.content&&o.push({type:"thinking",thinking:r.message.thinking.content,signature:r.message.thinking.signature});let s=e.usage?.prompt_tokens_details?.cached_tokens||0,a=(e.usage?.prompt_tokens||0)-s,c={id:e.id?.startsWith("msg_")?e.id:`msg_${Ut().replace(/-/g,"")}`,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":r.finish_reason==="length"?"max_tokens":r.finish_reason==="tool_calls"?"tool_use":r.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:a,cache_creation_input_tokens:0,cache_read_input_tokens:s,output_tokens:e.usage?.completion_tokens||0,server_tool_use:{web_search_requests:0,web_fetch_requests:0},service_tier:"standard",cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},inference_geo:"",iterations:[],speed:"standard"},stop_details:null,context_management:null};return this.logger.debug({reqId:n.req.id,result:c},"Conversion complete, final Anthropic response"),c}catch{throw He(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Vr={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function VC(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(Vr).includes(r)?r:Vr.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(Vr).includes(o)?o:Vr.TYPE_UNSPECIFIED})}}}function qo(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&VC(t.type,e);for(let[a,c]of Object.entries(t))if(c!=null)if(a=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=c.toUpperCase();e.type=Object.values(Vr).includes(l)?l:Vr.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=qo(c);else if(r.includes(a)){let l=[];for(let d of c){if(d.type=="null"){e.nullable=!0;continue}l.push(qo(d))}e[a]=l}else if(o.includes(a)){let l={};for(let[d,f]of Object.entries(c))l[d]=qo(f);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}return e}function KC(t){if(t.functionDeclarations)for(let e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=qo(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=qo(e.response));return t}function Ei(t){let e=[],n=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));n?.length&&e.push(KC({functionDeclarations:n})),t.tools?.find(l=>l.function.name==="web_search")&&e.push({googleSearch:{}});let o=[],s=t.messages.filter(l=>l.role==="tool");t.messages.filter(l=>l.role!=="tool").forEach(l=>{let d;l.role==="assistant"?d="model":(["user","system"].includes(l.role),d="user");let f=[];if(typeof l.content=="string"){let p={text:l.content};l.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),f.push(p)}else Array.isArray(l.content)?f.push(...l.content.map(p=>{if(p.type==="text")return{text:p.text||""};if(p.type==="image_url")return p.image_url.url.startsWith("http")?{file_data:{mime_type:p.media_type,file_uri:p.image_url.url}}:{inlineData:{mime_type:p.media_type,data:p.image_url.url?.split(",")?.pop()||p.image_url.url}}})):l.content&&typeof l.content=="object"&&(l.content.text?f.push({text:l.content.text}):f.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&f.push(...l.tool_calls.map(p=>{let m={functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")}};return l.thinking?.signature&&(m.thoughtSignature=l.thinking.signature),m})),f.length===0&&f.push({text:""}),o.push({role:d,parts:f}),d==="model"&&l.tool_calls){let p=l.tool_calls.map(m=>{let b=s.find(C=>C.tool_call_id===m.id);return{functionResponse:{name:m?.function?.name,response:{result:b?.content}}}});o.push({role:"user",parts:p})}});let a={};if(t.reasoning&&t.reasoning.effort&&t.reasoning.effort!=="none")if(a.thinkingConfig={includeThoughts:!0},t.model.includes("gemini-3"))a.thinkingConfig.thinkingLevel=t.reasoning.effort;else{let l=t.model.includes("pro")?[128,32768]:[0,24576],d,f=t.reasoning.max_tokens;typeof f<"u"&&(f>=l[0]&&f<=l[1]?d=f:f<l[0]?d=l[0]:f>l[1]&&(d=l[1]),a.thinkingConfig.thinkingBudget=d)}let c={contents:o,tools:e.length?e:void 0,generationConfig:a};if(t.tool_choice){let l={functionCallingConfig:{}};t.tool_choice==="auto"?l.functionCallingConfig.mode="auto":t.tool_choice==="none"?l.functionCallingConfig.mode="none":t.tool_choice==="required"?l.functionCallingConfig.mode="any":t.tool_choice?.function?.name&&(l.functionCallingConfig.mode="any",l.functionCallingConfig.allowedFunctionNames=[t.tool_choice?.function?.name]),c.toolConfig=l}return c}function Ai(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,c=t.tool_choice,l={messages:[],model:r,max_tokens:o,temperature:s,stream:a,tool_choice:c};return Array.isArray(e)&&e.forEach(d=>{typeof d=="string"?l.messages.push({role:"user",content:d}):typeof d.text=="string"?l.messages.push({role:"user",content:d.text||null}):d.role==="user"?l.messages.push({role:"user",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]}):d.role==="model"&&l.messages.push({role:"assistant",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]})}),Array.isArray(n)&&(l.tools=[],n.forEach(d=>{Array.isArray(d.functionDeclarations)&&d.functionDeclarations.forEach(f=>{l.tools.push({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}})})})),l}async function Si(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json();n?.debug({response:r},`${e} response:`);let o="",s="",a=r.candidates[0]?.content?.parts||[],c=[];for(let p of a)p.text&&p.thought===!0?o+=p.text:c.push(p);s=a.find(p=>p.thoughtSignature)?.thoughtSignature;let l=c?.filter(p=>p.functionCall)?.map(p=>({id:p.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:p.functionCall?.name,arguments:JSON.stringify(p.functionCall?.args||{})}}))||[],d=c?.filter(p=>p.text)?.map(p=>p.text)?.join(`
211
+ `)||"",f={id:r.responseId,choices:[{finish_reason:r.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:d,role:"assistant",tool_calls:l.length>0?l:void 0,...s&&{thinking:{content:o||"(no content)",signature:s}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.modelVersion,object:"chat.completion",usage:{completion_tokens:r.usageMetadata?.candidatesTokenCount||0,prompt_tokens:r.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:r.usageMetadata?.cachedContentTokenCount||0},total_tokens:r.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:r.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(f),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=!1,a=!1,c=!1,l="",d=0,f=-1,p=new ReadableStream({async start(m){let b=async(_,g)=>{if(_.startsWith("data: ")){let S=_.slice(6).trim();if(S){n?.debug({chunkStr:S},`${e} chunk:`);try{let w=JSON.parse(S);if(!w.candidates||!w.candidates[0]){n?.debug({chunkStr:S},"Invalid chunk structure");return}let E=w.candidates[0],T=E.content?.parts||[];T.filter(F=>F.text&&F.thought===!0).forEach(F=>{c||(c=!0);let V={choices:[{delta:{role:"assistant",content:null,thinking:{content:F.text}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(V)}
212
212
 
213
- `))});let R=T.find(F=>F.thoughtSignature)?.thoughtSignature;if(R&&!s){if(!c){let V={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(V)}
213
+ `))});let R=T.find(F=>F.thoughtSignature)?.thoughtSignature;if(R&&!s){if(!c){let V={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(V)}
214
214
 
215
- `))}let F={choices:[{delta:{role:"assistant",content:null,thinking:{signature:R}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(m.enqueue(o.encode(`data: ${JSON.stringify(F)}
215
+ `))}let F={choices:[{delta:{role:"assistant",content:null,thinking:{signature:R}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(g.enqueue(o.encode(`data: ${JSON.stringify(F)}
216
216
 
217
- `)),s=!0,d++,l){let V={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(V)}
217
+ `)),s=!0,d++,l){let V={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(V)}
218
218
 
219
219
  `)),l="",a||(a=!0)}}let U=T.filter(F=>F.functionCall).map(F=>({id:F.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:F.functionCall?.name,arguments:JSON.stringify(F.functionCall?.args||{})}})),J=T.filter(F=>F.text&&F.thought!==!0).map(F=>F.text).join(`
220
- `);if(!J&&s&&!a){let F={choices:[{delta:{role:"assistant",content:"(no content)"},index:d,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(F)}
220
+ `);if(!J&&s&&!a){let F={choices:[{delta:{role:"assistant",content:"(no content)"},index:d,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(F)}
221
221
 
222
- `)),a||(a=!0)}if(c&&J&&!s)if(w.modelVersion.includes("3")){l+=J;return}else{let F={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(F)}
222
+ `)),a||(a=!0)}if(c&&J&&!s)if(w.modelVersion.includes("3")){l+=J;return}else{let F={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};g.enqueue(o.encode(`data: ${JSON.stringify(F)}
223
223
 
224
- `)),s=!0}if(J){l||d++;let F={choices:[{delta:{role:"assistant",content:J},finish_reason:A.finishReason?.toLowerCase()||null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:w.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w.usageMetadata?.cachedContentTokenCount||0},total_tokens:w.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(F.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((V,Y)=>{let X=A?.groundingMetadata?.groundingSupports?.filter(ee=>ee.groundingChunkIndices?.includes(Y));return{type:"url_citation",url_citation:{url:V?.web?.uri||"",title:V?.web?.title||"",content:X?.[0]?.segment?.text||"",start_index:X?.[0]?.segment?.startIndex||0,end_index:X?.[0]?.segment?.endIndex||0}}})),m.enqueue(o.encode(`data: ${JSON.stringify(F)}
224
+ `)),s=!0}if(J){l||d++;let F={choices:[{delta:{role:"assistant",content:J},finish_reason:E.finishReason?.toLowerCase()||null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:w.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w.usageMetadata?.cachedContentTokenCount||0},total_tokens:w.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(F.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((V,Y)=>{let X=E?.groundingMetadata?.groundingSupports?.filter(ee=>ee.groundingChunkIndices?.includes(Y));return{type:"url_citation",url_citation:{url:V?.web?.uri||"",title:V?.web?.title||"",content:X?.[0]?.segment?.text||"",start_index:X?.[0]?.segment?.startIndex||0,end_index:X?.[0]?.segment?.endIndex||0}}})),g.enqueue(o.encode(`data: ${JSON.stringify(F)}
225
225
 
226
- `)),!a&&J&&(a=!0)}U.length>0&&(U.forEach(F=>{d++,f++;let V={choices:[{delta:{role:"assistant",tool_calls:[{...F,index:f}]},finish_reason:A.finishReason?.toLowerCase()||null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:w.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w.usageMetadata?.cachedContentTokenCount||0},total_tokens:w.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(V.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((Y,X)=>{let ee=A?.groundingMetadata?.groundingSupports?.filter(de=>de.groundingChunkIndices?.includes(X));return{type:"url_citation",url_citation:{url:Y?.web?.uri||"",title:Y?.web?.title||"",content:ee?.[0]?.segment?.text||"",start_index:ee?.[0]?.segment?.startIndex||0,end_index:ee?.[0]?.segment?.endIndex||0}}})),m.enqueue(o.encode(`data: ${JSON.stringify(V)}
226
+ `)),!a&&J&&(a=!0)}U.length>0&&(U.forEach(F=>{d++,f++;let V={choices:[{delta:{role:"assistant",tool_calls:[{...F,index:f}]},finish_reason:E.finishReason?.toLowerCase()||null,index:d,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:w.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w.usageMetadata?.cachedContentTokenCount||0},total_tokens:w.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w.usageMetadata?.thoughtsTokenCount||0}}};E?.groundingMetadata?.groundingChunks?.length&&(V.choices[0].delta.annotations=E.groundingMetadata.groundingChunks.map((Y,X)=>{let ee=E?.groundingMetadata?.groundingSupports?.filter(de=>de.groundingChunkIndices?.includes(X));return{type:"url_citation",url_citation:{url:Y?.web?.uri||"",title:Y?.web?.title||"",content:ee?.[0]?.segment?.text||"",start_index:ee?.[0]?.segment?.startIndex||0,end_index:ee?.[0]?.segment?.endIndex||0}}})),g.enqueue(o.encode(`data: ${JSON.stringify(V)}
227
227
 
228
- `))}),!a&&J&&(a=!0))}catch(w){n?.error(`Error parsing ${e} stream chunk`,k,w.message)}}}},C=t.body.getReader(),b="";try{for(;;){let{done:y,value:m}=await C.read();if(y){b&&await _(b,g);break}b+=r.decode(m,{stream:!0});let k=b.split(`
229
- `);b=k.pop()||"";for(let w of k)await _(w,g)}}catch(y){g.error(y)}finally{g.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var ki=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,n){return{body:Ei(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}transformRequestOut=Ai;async transformResponseOut(e){return Si(e,this.name,this.logger)}};async function _v(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Oe($d(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
228
+ `))}),!a&&J&&(a=!0))}catch(w){n?.error(`Error parsing ${e} stream chunk`,S,w.message)}}}},C=t.body.getReader(),y="";try{for(;;){let{done:_,value:g}=await C.read();if(_){y&&await b(y,m);break}y+=r.decode(g,{stream:!0});let S=y.split(`
229
+ `);y=S.pop()||"";for(let w of S)await b(w,m)}}catch(_){m.error(_)}finally{m.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var ki=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,n){return{body:Ei(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}transformRequestOut=Ai;async transformResponseOut(e){return Si(e,this.name,this.logger)}};async function _v(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Oe($d(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
230
230
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
231
231
  2. Run "gcloud auth application-default login"
232
- 3. Use Google Cloud environment with default service account`)}}var qa=class{name="vertex-gemini";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await _v();return{body:Ei(e),config:{url:new URL(`./v1beta1/projects/${r}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Ai(e)}async transformResponseOut(e){return Si(e,this.name)}};var Ha=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let n=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),r=e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content)||n;return r&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(o=>{if(o.role==="assistant"){let s=o.thinking?.content,a=o.thinking?.signature,c="";if(typeof o.content=="string"){let d=/<thinking>([\s\S]*?)<\/thinking>/g.exec(o.content);d&&(c=d[1].trim(),o.content=o.content.replace(d[0],"").trim())}s&&typeof s=="string"&&s.trim()?(o.reasoning_content=s,a&&(o.reasoning_content_signature=a)):c&&(o.reasoning_content=c),r&&!o.reasoning_content&&(o.reasoning_content=" "),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(g,_,C)=>{let b=g.split(`
233
- `);for(let y of b)y.trim()&&_.enqueue(C.encode(y+`
234
- `))},p=(g,_)=>{let{controller:C,encoder:b}=_;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let y=JSON.parse(g.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){_.appendReasoningContent(y.choices[0].delta.reasoning_content);let m={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(m)}
232
+ 3. Use Google Cloud environment with default service account`)}}var qa=class{name="vertex-gemini";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await _v();return{body:Ei(e),config:{url:new URL(`./v1beta1/projects/${r}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Ai(e)}async transformResponseOut(e){return Si(e,this.name)}};var Ha=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let n=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),r=e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content)||n;return r&&e.tool_choice&&delete e.tool_choice,e.messages.forEach(o=>{if(o.role==="assistant"){let s=o.thinking?.content,a=o.thinking?.signature,c="";if(typeof o.content=="string"){let d=/<thinking>([\s\S]*?)<\/thinking>/g.exec(o.content);d&&(c=d[1].trim(),o.content=o.content.replace(d[0],"").trim())}s&&typeof s=="string"&&s.trim()?(o.reasoning_content=s,a&&(o.reasoning_content_signature=a)):c&&(o.reasoning_content=c),r&&!o.reasoning_content&&(o.reasoning_content=" "),o.thinking&&delete o.thinking}}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(m,b,C)=>{let y=m.split(`
233
+ `);for(let _ of y)_.trim()&&b.enqueue(C.encode(_+`
234
+ `))},p=(m,b)=>{let{controller:C,encoder:y}=b;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let _=JSON.parse(m.slice(6));if(_.choices?.[0]?.delta?.reasoning_content){b.appendReasoningContent(_.choices[0].delta.reasoning_content);let g={..._,choices:[{..._.choices[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(g)}
235
235
 
236
- `;C.enqueue(b.encode(k));return}if(y.choices?.[0]?.delta?.content&&_.reasoningContent()&&!_.isReasoningComplete()){_.setReasoningComplete(!0);let m="ccr_think_signature",k=y.choices[0].delta.content,w={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:_.reasoningContent(),signature:m}}}]};delete w.choices[0].delta.reasoning_content;let A=`data: ${JSON.stringify(w)}
236
+ `;C.enqueue(y.encode(S));return}if(_.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let g="ccr_think_signature",S=_.choices[0].delta.content,w={..._,choices:[{..._.choices[0],delta:{..._.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:g}}}]};delete w.choices[0].delta.reasoning_content;let E=`data: ${JSON.stringify(w)}
237
237
 
238
- `;C.enqueue(b.encode(A));let T={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:k}}]};delete T.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(T)}
238
+ `;C.enqueue(y.encode(E));let T={..._,choices:[{..._.choices[0],delta:{..._.choices[0].delta,content:S}}]};delete T.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(T)}
239
239
 
240
- `;C.enqueue(b.encode(R));return}if(y.choices[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){let m=`data: ${JSON.stringify(y)}
240
+ `;C.enqueue(y.encode(R));return}if(_.choices[0]?.delta?.reasoning_content&&delete _.choices[0].delta.reasoning_content,_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){let g=`data: ${JSON.stringify(_)}
241
241
 
242
- `;C.enqueue(b.encode(m))}}catch{C.enqueue(b.encode(g+`
243
- `))}else C.enqueue(b.encode(g+`
244
- `))};try{for(;;){let{done:g,value:_}=await d.read();if(g){a.trim()&&f(a,l,r);break}let C=n.decode(_,{stream:!0});a+=C;let b=a.split(`
245
- `);a=b.pop()||"";for(let y of b)if(y.trim())try{p(y,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:m=>o+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",y,m),l.enqueue(r.encode(y+`
246
- `))}}}catch(g){console.error("Stream error:",g),l.error(g)}finally{try{d.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var za=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
242
+ `;C.enqueue(y.encode(g))}}catch{C.enqueue(y.encode(m+`
243
+ `))}else C.enqueue(y.encode(m+`
244
+ `))};try{for(;;){let{done:m,value:b}=await d.read();if(m){a.trim()&&f(a,l,r);break}let C=n.decode(b,{stream:!0});a+=C;let y=a.split(`
245
+ `);a=y.pop()||"";for(let _ of y)if(_.trim())try{p(_,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:g=>o+=g,isReasoningComplete:()=>s,setReasoningComplete:g=>s=g})}catch(g){console.error("Error processing line:",_,g),l.enqueue(r.encode(_+`
246
+ `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var za=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
247
247
  IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
248
248
  Examples:
249
249
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
250
- 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message.tool_calls?.length&&n?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let r=n?.choices[0]?.message.tool_calls[0],o=JSON.parse(r.function.arguments||"{}");n.choices[0].message.content=o.response||"",delete n.choices[0].message.tool_calls}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=-1,s="",a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(g,_,C)=>{let b=g.split(`
251
- `);for(let y of b)y.trim()&&_.enqueue(C.encode(y+`
252
- `))},p=(g,_)=>{let{controller:C,encoder:b,exitToolIndex:y,setExitToolIndex:m,appendExitToolResponse:k}=_;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let w=JSON.parse(g.slice(6));if(w.choices[0]?.delta?.tool_calls?.length){let A=w.choices[0].delta.tool_calls[0];if(A.function?.name==="ExitTool"){m(A.index);return}else if(y()>-1&&A.index===y()&&A.function.arguments){k(A.function.arguments);try{let T=JSON.parse(_.exitToolResponse());w.choices=[{delta:{role:"assistant",content:T.response||""}}];let R=`data: ${JSON.stringify(w)}
253
-
254
- `;C.enqueue(b.encode(R))}catch{}return}}if(w.choices?.[0]?.delta&&Object.keys(w.choices[0].delta).length>0){let A=`data: ${JSON.stringify(w)}
255
-
256
- `;C.enqueue(b.encode(A))}}catch{C.enqueue(b.encode(g+`
257
- `))}else C.enqueue(b.encode(g+`
258
- `))};try{for(;;){let{done:g,value:_}=await d.read();if(g){a.trim()&&f(a,l,r);break}let C=n.decode(_,{stream:!0});a+=C;let b=a.split(`
259
- `);a=b.pop()||"";for(let y of b)if(y.trim())try{p(y,{controller:l,encoder:r,exitToolIndex:()=>o,setExitToolIndex:m=>o=m,exitToolResponse:()=>s,appendExitToolResponse:m=>s+=m})}catch(m){console.error("Error processing line:",y,m),l.enqueue(r.encode(y+`
260
- `))}}}catch(g){console.error("Stream error:",g),l.error(g)}finally{try{d.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Wa=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",d=new ReadableStream({async start(f){let p=e.body.getReader(),g=(C,b,y)=>{let m=C.split(`
261
- `);for(let k of m)k.trim()&&b.enqueue(y.encode(k+`
262
- `))},_=(C,b)=>{let{controller:y,encoder:m}=b;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let k=C.slice(6);try{let w=JSON.parse(k);if(w.usage&&(this.logger?.debug({usage:w.usage,hasToolCall:c},"usage"),w.choices[0].finish_reason=c?"tool_calls":"stop"),w.choices?.[0]?.finish_reason==="error"){y.enqueue(m.encode(`data: ${JSON.stringify({error:w.choices?.[0].error})}
263
-
264
- `));return}w.choices?.[0]?.delta?.content&&!b.hasTextContent()&&b.setHasTextContent(!0);let A=w.choices?.[0]?.delta?.reasoning||w.choices?.[0]?.delta?.reasoning_content;if(A){b.appendReasoningContent(A);let F={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,thinking:{content:A}}}]};F.choices?.[0]?.delta&&(delete F.choices[0].delta.reasoning,delete F.choices[0].delta.reasoning_content);let V=`data: ${JSON.stringify(F)}
265
-
266
- `;y.enqueue(m.encode(V));return}if(w.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let F="ccr_think_signature",V=w.choices[0].delta.content,Y={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:F}}}]};Y.choices?.[0]?.delta&&delete Y.choices[0].delta.reasoning;let X=`data: ${JSON.stringify(Y)}
267
-
268
- `;y.enqueue(m.encode(X));let ee={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:V}}]};ee.choices?.[0]?.delta&&(delete ee.choices[0].delta.reasoning,delete ee.choices[0].delta.reasoning_content);let de=`data: ${JSON.stringify(ee)}
269
-
270
- `;y.enqueue(m.encode(de));return}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.reasoning_content&&delete w.choices[0].delta.reasoning_content,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(F=>{F.id=`call_${Ut()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0);let T=w.choices?.[0]?.delta,R=T&&Object.keys(T).length>0,U=w.choices?.[0]?.finish_reason,J=w.usage;if(R||U||J){let F=`data: ${JSON.stringify(w)}
271
-
272
- `;y.enqueue(m.encode(F))}}catch{y.enqueue(m.encode(C+`
273
- `))}}else y.enqueue(m.encode(C+`
274
- `))};try{for(;;){let{done:C,value:b}=await p.read();if(C){l.trim()&&g(l,f,r);break}if(!b||b.length===0)continue;let y;try{y=n.decode(b,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(y.length===0)continue;if(l+=y,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
275
- `);l=k.pop()||"";for(let w of k)if(w.trim())try{_(w,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:A=>o=A,reasoningContent:()=>s,appendReasoningContent:A=>s+=A,isReasoningComplete:()=>a,setReasoningComplete:A=>a=A})}catch(A){console.error("Error processing line:",w,A),f.enqueue(r.encode(w+`
276
- `))}continue}let m=l.split(`
277
- `);l=m.pop()||"";for(let k of m)if(k.trim())try{_(k,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",k,w),f.enqueue(r.encode(k+`
278
- `))}}}catch(C){console.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}f.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ga=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var Ja=class{name="groq";async transformRequestIn(e){return e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{delete n.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c="",l=new ReadableStream({async start(d){let f=e.body.getReader(),p=(_,C,b)=>{let y=_.split(`
279
- `);for(let m of y)m.trim()&&C.enqueue(b.encode(m+`
280
- `))},g=(_,C)=>{let{controller:b,encoder:y}=C;if(_.startsWith("data: ")&&_.trim()!=="data: [DONE]"){let m=_.slice(6);try{let k=JSON.parse(m);if(k.error)throw new Error(JSON.stringify(k));k.choices?.[0]?.delta?.content&&!C.hasTextContent()&&C.setHasTextContent(!0),k.choices?.[0]?.delta?.tool_calls?.length&&k.choices?.[0]?.delta?.tool_calls.forEach(A=>{A.id=`call_${Ut()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&C.hasTextContent()&&(typeof k.choices[0].index=="number"?k.choices[0].index+=1:k.choices[0].index=1);let w=`data: ${JSON.stringify(k)}
281
-
282
- `;b.enqueue(y.encode(w))}catch{b.enqueue(y.encode(_+`
283
- `))}}else b.enqueue(y.encode(_+`
284
- `))};try{for(;;){let{done:_,value:C}=await f.read();if(_){c.trim()&&p(c,d,r);break}if(!C||C.length===0)continue;let b;try{b=n.decode(C,{stream:!0})}catch(m){console.warn("Failed to decode chunk",m);continue}if(b.length===0)continue;if(c+=b,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let m=c.split(`
285
- `);c=m.pop()||"";for(let k of m)if(k.trim())try{g(k,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",k,w),d.enqueue(r.encode(k+`
286
- `))}continue}let y=c.split(`
287
- `);c=y.pop()||"";for(let m of y)if(m.trim())try{g(m,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:k=>o=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){console.error("Error processing line:",m,k),d.enqueue(r.encode(m+`
288
- `))}}}catch(_){console.error("Stream error:",_),d.error(_)}finally{try{f.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}d.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Va=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),e}};var $0=Oe(ac());var On=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function F0(t){return/^[0-9A-Fa-f]$/.test(t)}function nr(t){return t>="0"&&t<="9"}function I0(t){return t>=" "}function bs(t){return`,:[]/{}()
250
+ 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message.tool_calls?.length&&n?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let r=n?.choices[0]?.message.tool_calls[0],o=JSON.parse(r.function.arguments||"{}");n.choices[0].message.content=o.response||"",delete n.choices[0].message.tool_calls}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=-1,s="",a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(m,b,C)=>{let y=m.split(`
251
+ `);for(let _ of y)_.trim()&&b.enqueue(C.encode(_+`
252
+ `))},p=(m,b)=>{let{controller:C,encoder:y,exitToolIndex:_,setExitToolIndex:g,appendExitToolResponse:S}=b;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let w=JSON.parse(m.slice(6));if(w.choices[0]?.delta?.tool_calls?.length){let E=w.choices[0].delta.tool_calls[0];if(E.function?.name==="ExitTool"){g(E.index);return}else if(_()>-1&&E.index===_()&&E.function.arguments){S(E.function.arguments);try{let T=JSON.parse(b.exitToolResponse());w.choices=[{delta:{role:"assistant",content:T.response||""}}];let R=`data: ${JSON.stringify(w)}
253
+
254
+ `;C.enqueue(y.encode(R))}catch{}return}}if(w.choices?.[0]?.delta&&Object.keys(w.choices[0].delta).length>0){let E=`data: ${JSON.stringify(w)}
255
+
256
+ `;C.enqueue(y.encode(E))}}catch{C.enqueue(y.encode(m+`
257
+ `))}else C.enqueue(y.encode(m+`
258
+ `))};try{for(;;){let{done:m,value:b}=await d.read();if(m){a.trim()&&f(a,l,r);break}let C=n.decode(b,{stream:!0});a+=C;let y=a.split(`
259
+ `);a=y.pop()||"";for(let _ of y)if(_.trim())try{p(_,{controller:l,encoder:r,exitToolIndex:()=>o,setExitToolIndex:g=>o=g,exitToolResponse:()=>s,appendExitToolResponse:g=>s+=g})}catch(g){console.error("Error processing line:",_,g),l.enqueue(r.encode(_+`
260
+ `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Wa=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",d=new ReadableStream({async start(f){let p=e.body.getReader(),m=(C,y,_)=>{let g=C.split(`
261
+ `);for(let S of g)S.trim()&&y.enqueue(_.encode(S+`
262
+ `))},b=(C,y)=>{let{controller:_,encoder:g}=y;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let S=C.slice(6);try{let w=JSON.parse(S);if(w.usage&&(this.logger?.debug({usage:w.usage,hasToolCall:c},"usage"),w.choices[0].finish_reason=c?"tool_calls":"stop"),w.choices?.[0]?.finish_reason==="error"){_.enqueue(g.encode(`data: ${JSON.stringify({error:w.choices?.[0].error})}
263
+
264
+ `));return}w.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0);let E=w.choices?.[0]?.delta?.reasoning||w.choices?.[0]?.delta?.reasoning_content;if(E){y.appendReasoningContent(E);let F={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,thinking:{content:E}}}]};F.choices?.[0]?.delta&&(delete F.choices[0].delta.reasoning,delete F.choices[0].delta.reasoning_content);let V=`data: ${JSON.stringify(F)}
265
+
266
+ `;_.enqueue(g.encode(V));return}if(w.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let F="ccr_think_signature",V=w.choices[0].delta.content,Y={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:F}}}]};Y.choices?.[0]?.delta&&delete Y.choices[0].delta.reasoning;let X=`data: ${JSON.stringify(Y)}
267
+
268
+ `;_.enqueue(g.encode(X));let ee={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:V}}]};ee.choices?.[0]?.delta&&(delete ee.choices[0].delta.reasoning,delete ee.choices[0].delta.reasoning_content);let de=`data: ${JSON.stringify(ee)}
269
+
270
+ `;_.enqueue(g.encode(de));return}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.reasoning_content&&delete w.choices[0].delta.reasoning_content,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(F=>{F.id=`call_${Ut()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0);let T=w.choices?.[0]?.delta,R=T&&Object.keys(T).length>0,U=w.choices?.[0]?.finish_reason,J=w.usage;if(R||U||J){let F=`data: ${JSON.stringify(w)}
271
+
272
+ `;_.enqueue(g.encode(F))}}catch{_.enqueue(g.encode(C+`
273
+ `))}}else _.enqueue(g.encode(C+`
274
+ `))};try{for(;;){let{done:C,value:y}=await p.read();if(C){l.trim()&&m(l,f,r);break}if(!y||y.length===0)continue;let _;try{_=n.decode(y,{stream:!0})}catch(S){console.warn("Failed to decode chunk",S);continue}if(_.length===0)continue;if(l+=_,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let S=l.split(`
275
+ `);l=S.pop()||"";for(let w of S)if(w.trim())try{b(w,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){console.error("Error processing line:",w,E),f.enqueue(r.encode(w+`
276
+ `))}continue}let g=l.split(`
277
+ `);l=g.pop()||"";for(let S of g)if(S.trim())try{b(S,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",S,w),f.enqueue(r.encode(S+`
278
+ `))}}}catch(C){console.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}f.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ga=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var Ja=class{name="groq";async transformRequestIn(e){return e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{delete n.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c="",l=new ReadableStream({async start(d){let f=e.body.getReader(),p=(b,C,y)=>{let _=b.split(`
279
+ `);for(let g of _)g.trim()&&C.enqueue(y.encode(g+`
280
+ `))},m=(b,C)=>{let{controller:y,encoder:_}=C;if(b.startsWith("data: ")&&b.trim()!=="data: [DONE]"){let g=b.slice(6);try{let S=JSON.parse(g);if(S.error)throw new Error(JSON.stringify(S));S.choices?.[0]?.delta?.content&&!C.hasTextContent()&&C.setHasTextContent(!0),S.choices?.[0]?.delta?.tool_calls?.length&&S.choices?.[0]?.delta?.tool_calls.forEach(E=>{E.id=`call_${Ut()}`}),S.choices?.[0]?.delta?.tool_calls?.length&&C.hasTextContent()&&(typeof S.choices[0].index=="number"?S.choices[0].index+=1:S.choices[0].index=1);let w=`data: ${JSON.stringify(S)}
281
+
282
+ `;y.enqueue(_.encode(w))}catch{y.enqueue(_.encode(b+`
283
+ `))}}else y.enqueue(_.encode(b+`
284
+ `))};try{for(;;){let{done:b,value:C}=await f.read();if(b){c.trim()&&p(c,d,r);break}if(!C||C.length===0)continue;let y;try{y=n.decode(C,{stream:!0})}catch(g){console.warn("Failed to decode chunk",g);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let g=c.split(`
285
+ `);c=g.pop()||"";for(let S of g)if(S.trim())try{m(S,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",S,w),d.enqueue(r.encode(S+`
286
+ `))}continue}let _=c.split(`
287
+ `);c=_.pop()||"";for(let g of _)if(g.trim())try{m(g,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>s,appendReasoningContent:S=>s+=S,isReasoningComplete:()=>a,setReasoningComplete:S=>a=S})}catch(S){console.error("Error processing line:",g,S),d.enqueue(r.encode(g+`
288
+ `))}}}catch(b){console.error("Stream error:",b),d.error(b)}finally{try{f.releaseLock()}catch(b){console.error("Error releasing reader lock:",b)}d.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Va=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),e}};var $0=Oe(ac());var On=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function F0(t){return/^[0-9A-Fa-f]$/.test(t)}function nr(t){return t>="0"&&t<="9"}function I0(t){return t>=" "}function bs(t){return`,:[]/{}()
289
289
  +`.includes(t)}function Ud(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function qd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var Hd=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,zd=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Wd(t){return`,[]/{}
290
290
  +`.includes(t)}function Gd(t){return Cs(t)||bv.test(t)}var bv=/^[[{\w-]$/;function N0(t){return t===`
291
291
  `||t==="\r"||t===" "||t==="\b"||t==="\f"}function tr(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function B0(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function M0(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function Cs(t){return Jd(t)||Ka(t)}function Jd(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Vd(t){return t==='"'}function Ka(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function Kd(t){return t==="'"}function Eo(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function It(t,e){let n=t.length;if(!tr(t,n-1))return t+e;for(;tr(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function L0(t,e,n){return t.substring(0,e)+t.substring(e+n)}function j0(t){return/[,\n][ \t\r]*$/.test(t)}var Cv={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},wv={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
292
- `,r:"\r",t:" "};function Yd(t){let e=0,n="";d(["```","[```","{```"]),s()||de(),d(["```","```]","```}"]);let o=p(",");for(o&&a(),Gd(t[e])&&j0(n)?(o||(n=It(n,",")),m()):o&&(n=Eo(n,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return n;ee();function s(){a();let W=b()||y()||k()||A()||T()||U(!1)||J();return a(),W}function a(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Q=e,re=c(W);do re=l(),re&&(re=c(W));while(re);return e>Q}function c(W){let Q=W?tr:B0,re="";for(;;)if(Q(t,e))re+=t[e],e++;else if(M0(t,e))re+=" ",e++;else break;return re.length>0?(n+=re,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!Ev(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
293
- `;)e++;return!0}return!1}function d(W){if(f(W)){if(Ud(t[e]))for(;e<t.length&&qd(t[e]);)e++;return a(),!0}return!1}function f(W){c(!0);for(let Q of W){let re=e+Q.length;if(t.slice(e,re)===Q)return e=re,!0}return!1}function p(W){return t[e]===W?(n+=t[e],e++,!0):!1}function g(W){return t[e]===W?(e++,!0):!1}function _(){return g("\\")}function C(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),g(","),!0):!1}function b(){if(t[e]==="{"){n+="{",e++,a(),g(",")&&a();let W=!0;for(;e<t.length&&t[e]!=="}";){let Q;if(W?(Q=!0,W=!1):(Q=p(","),Q||(n=It(n,",")),a()),C(),!(k()||U(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=Eo(n,","):Ae();break}a();let $e=p(":"),ke=e>=t.length;$e||(Gd(t[e])||ke?n=It(n,":"):ae()),s()||($e||ke?n+="null":ae())}return t[e]==="}"?(n+="}",e++):n=It(n,"}"),!0}return!1}function y(){if(t[e]==="["){n+="[",e++,a(),g(",")&&a();let W=!0;for(;e<t.length&&t[e]!=="]";)if(W?W=!1:p(",")||(n=It(n,",")),C(),!s()){n=Eo(n,",");break}return t[e]==="]"?(n+="]",e++):n=It(n,"]"),!0}return!1}function m(){let W=!0,Q=!0;for(;Q;)W?W=!1:p(",")||(n=It(n,",")),Q=s();Q||(n=Eo(n,",")),n=`[
292
+ `,r:"\r",t:" "};function Yd(t){let e=0,n="";d(["```","[```","{```"]),s()||de(),d(["```","```]","```}"]);let o=p(",");for(o&&a(),Gd(t[e])&&j0(n)?(o||(n=It(n,",")),g()):o&&(n=Eo(n,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return n;ee();function s(){a();let W=y()||_()||S()||E()||T()||U(!1)||J();return a(),W}function a(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Q=e,re=c(W);do re=l(),re&&(re=c(W));while(re);return e>Q}function c(W){let Q=W?tr:B0,re="";for(;;)if(Q(t,e))re+=t[e],e++;else if(M0(t,e))re+=" ",e++;else break;return re.length>0?(n+=re,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!Ev(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
293
+ `;)e++;return!0}return!1}function d(W){if(f(W)){if(Ud(t[e]))for(;e<t.length&&qd(t[e]);)e++;return a(),!0}return!1}function f(W){c(!0);for(let Q of W){let re=e+Q.length;if(t.slice(e,re)===Q)return e=re,!0}return!1}function p(W){return t[e]===W?(n+=t[e],e++,!0):!1}function m(W){return t[e]===W?(e++,!0):!1}function b(){return m("\\")}function C(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),m(","),!0):!1}function y(){if(t[e]==="{"){n+="{",e++,a(),m(",")&&a();let W=!0;for(;e<t.length&&t[e]!=="}";){let Q;if(W?(Q=!0,W=!1):(Q=p(","),Q||(n=It(n,",")),a()),C(),!(S()||U(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=Eo(n,","):Ae();break}a();let $e=p(":"),ke=e>=t.length;$e||(Gd(t[e])||ke?n=It(n,":"):ae()),s()||($e||ke?n+="null":ae())}return t[e]==="}"?(n+="}",e++):n=It(n,"}"),!0}return!1}function _(){if(t[e]==="["){n+="[",e++,a(),m(",")&&a();let W=!0;for(;e<t.length&&t[e]!=="]";)if(W?W=!1:p(",")||(n=It(n,",")),C(),!s()){n=Eo(n,",");break}return t[e]==="]"?(n+="]",e++):n=It(n,"]"),!0}return!1}function g(){let W=!0,Q=!0;for(;Q;)W?W=!1:p(",")||(n=It(n,",")),Q=s();Q||(n=Eo(n,",")),n=`[
294
294
  ${n}
295
- ]`}function k(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,re=t[e]==="\\";if(re&&(e++,re=!0),Cs(t[e])){let $e=Vd(t[e])?Vd:Kd(t[e])?Kd:Ka(t[e])?Ka:Jd,ke=e,G=n.length,le='"';for(e++;;){if(e>=t.length){let _e=F(e-1);return!W&&bs(t.charAt(_e))?(e=ke,n=n.substring(0,G),k(!0)):(le=It(le,'"'),n+=le,!0)}if(e===Q)return le=It(le,'"'),n+=le,!0;if($e(t[e])){let _e=e,Bt=le.length;if(le+='"',e++,n+=le,a(!1),W||e>=t.length||bs(t[e])||Cs(t[e])||nr(t[e]))return w(),!0;let Re=F(_e-1),Le=t.charAt(Re);if(Le===",")return e=ke,n=n.substring(0,G),k(!1,Re);if(bs(Le))return e=ke,n=n.substring(0,G),k(!0);n=n.substring(0,G),e=_e+1,le=`${le.substring(0,Bt)}\\${le.substring(Bt)}`}else if(W&&Wd(t[e])){if(t[e-1]===":"&&Hd.test(t.substring(ke+1,e+2)))for(;e<t.length&&zd.test(t[e]);)le+=t[e],e++;return le=It(le,'"'),n+=le,w(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(wv[_e]!==void 0)le+=t.slice(e,e+2),e+=2;else if(_e==="u"){let Re=2;for(;Re<6&&F0(t[e+Re]);)Re++;Re===6?(le+=t.slice(e,e+6),e+=6):e+Re>=t.length?e=t.length:pe()}else le+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(le+=`\\${_e}`,e++):N0(_e)?(le+=Cv[_e],e++):(I0(_e)||X(_e),le+=_e,e++)}re&&_()}}return!1}function w(){let W=!1;for(a();t[e]==="+";){W=!0,e++,a(),n=Eo(n,'"',!0);let Q=n.length;k()?n=L0(n,Q,1):n=It(n,'"')}return W}function A(){let W=e;if(t[e]==="-"){if(e++,V())return Y(W),!0;if(!nr(t[e]))return e=W,!1}for(;nr(t[e]);)e++;if(t[e]==="."){if(e++,V())return Y(W),!0;if(!nr(t[e]))return e=W,!1;for(;nr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,V())return Y(W),!0;if(!nr(t[e]))return e=W,!1;for(;nr(t[e]);)e++}if(!V())return e=W,!1;if(e>W){let Q=t.slice(W,e),re=/^0\d/.test(Q);return n+=re?`"${Q}"`:Q,!0}return!1}function T(){return R("true","true")||R("false","false")||R("null","null")||R("True","true")||R("False","false")||R("None","null")}function R(W,Q){return t.slice(e,e+W.length)===W?(n+=Q,e+=W.length,!0):!1}function U(W){let Q=e;if(Ud(t[e])){for(;e<t.length&&qd(t[e]);)e++;let re=e;for(;tr(t,re);)re++;if(t[re]==="(")return e=re+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Wd(t[e])&&!Cs(t[e])&&(!W||t[e]!==":");)e++;if(t[e-1]===":"&&Hd.test(t.substring(Q,e+2)))for(;e<t.length&&zd.test(t[e]);)e++;if(e>Q){for(;tr(t,e-1)&&e>0;)e--;let re=t.slice(Q,e);return n+=re==="undefined"?"null":JSON.stringify(re),t[e]==='"'&&e++,!0}}function J(){if(t[e]==="/"){let W=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(W,e)}"`,!0}}function F(W){let Q=W;for(;Q>0&&tr(t,Q);)Q--;return Q}function V(){return e>=t.length||bs(t[e])||tr(t,e)}function Y(W){n+=`${t.slice(W,e)}0`}function X(W){throw new On(`Invalid character ${JSON.stringify(W)}`,e)}function ee(){throw new On(`Unexpected character ${JSON.stringify(t[e])}`,e)}function de(){throw new On("Unexpected end of json string",t.length)}function Ae(){throw new On("Object key expected",e)}function ae(){throw new On("Colon expected",e)}function pe(){let W=t.slice(e,e+6);throw new On(`Invalid unicode character "${W}"`,e)}}function Ev(t,e){return t[e]==="*"&&t[e+1]==="/"}function Qd(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),t}catch(n){try{let r=$0.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=Yd(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Ya=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=Qd(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,a="",c=!1,l=!1,d="",f=new ReadableStream({async start(p){let g=e.body.getReader(),_=(y,m,k)=>{let w=y.split(`
296
- `);for(let A of w)A.trim()&&m.enqueue(k.encode(A+`
297
- `))},C=(y,m,k)=>{let w="";try{w=Qd(o.arguments||"",this.logger)}catch(U){console.error(`${U.message} ${U.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),w=o.arguments||""}let A={role:"assistant",tool_calls:[{function:{name:o.name,arguments:w},id:o.id,index:o.index,type:"function"}]},T={...y,choices:[{...y.choices[0],delta:A}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let R=`data: ${JSON.stringify(T)}
295
+ ]`}function S(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,re=t[e]==="\\";if(re&&(e++,re=!0),Cs(t[e])){let $e=Vd(t[e])?Vd:Kd(t[e])?Kd:Ka(t[e])?Ka:Jd,ke=e,G=n.length,le='"';for(e++;;){if(e>=t.length){let _e=F(e-1);return!W&&bs(t.charAt(_e))?(e=ke,n=n.substring(0,G),S(!0)):(le=It(le,'"'),n+=le,!0)}if(e===Q)return le=It(le,'"'),n+=le,!0;if($e(t[e])){let _e=e,Bt=le.length;if(le+='"',e++,n+=le,a(!1),W||e>=t.length||bs(t[e])||Cs(t[e])||nr(t[e]))return w(),!0;let Re=F(_e-1),Le=t.charAt(Re);if(Le===",")return e=ke,n=n.substring(0,G),S(!1,Re);if(bs(Le))return e=ke,n=n.substring(0,G),S(!0);n=n.substring(0,G),e=_e+1,le=`${le.substring(0,Bt)}\\${le.substring(Bt)}`}else if(W&&Wd(t[e])){if(t[e-1]===":"&&Hd.test(t.substring(ke+1,e+2)))for(;e<t.length&&zd.test(t[e]);)le+=t[e],e++;return le=It(le,'"'),n+=le,w(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(wv[_e]!==void 0)le+=t.slice(e,e+2),e+=2;else if(_e==="u"){let Re=2;for(;Re<6&&F0(t[e+Re]);)Re++;Re===6?(le+=t.slice(e,e+6),e+=6):e+Re>=t.length?e=t.length:pe()}else le+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(le+=`\\${_e}`,e++):N0(_e)?(le+=Cv[_e],e++):(I0(_e)||X(_e),le+=_e,e++)}re&&b()}}return!1}function w(){let W=!1;for(a();t[e]==="+";){W=!0,e++,a(),n=Eo(n,'"',!0);let Q=n.length;S()?n=L0(n,Q,1):n=It(n,'"')}return W}function E(){let W=e;if(t[e]==="-"){if(e++,V())return Y(W),!0;if(!nr(t[e]))return e=W,!1}for(;nr(t[e]);)e++;if(t[e]==="."){if(e++,V())return Y(W),!0;if(!nr(t[e]))return e=W,!1;for(;nr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,V())return Y(W),!0;if(!nr(t[e]))return e=W,!1;for(;nr(t[e]);)e++}if(!V())return e=W,!1;if(e>W){let Q=t.slice(W,e),re=/^0\d/.test(Q);return n+=re?`"${Q}"`:Q,!0}return!1}function T(){return R("true","true")||R("false","false")||R("null","null")||R("True","true")||R("False","false")||R("None","null")}function R(W,Q){return t.slice(e,e+W.length)===W?(n+=Q,e+=W.length,!0):!1}function U(W){let Q=e;if(Ud(t[e])){for(;e<t.length&&qd(t[e]);)e++;let re=e;for(;tr(t,re);)re++;if(t[re]==="(")return e=re+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Wd(t[e])&&!Cs(t[e])&&(!W||t[e]!==":");)e++;if(t[e-1]===":"&&Hd.test(t.substring(Q,e+2)))for(;e<t.length&&zd.test(t[e]);)e++;if(e>Q){for(;tr(t,e-1)&&e>0;)e--;let re=t.slice(Q,e);return n+=re==="undefined"?"null":JSON.stringify(re),t[e]==='"'&&e++,!0}}function J(){if(t[e]==="/"){let W=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(W,e)}"`,!0}}function F(W){let Q=W;for(;Q>0&&tr(t,Q);)Q--;return Q}function V(){return e>=t.length||bs(t[e])||tr(t,e)}function Y(W){n+=`${t.slice(W,e)}0`}function X(W){throw new On(`Invalid character ${JSON.stringify(W)}`,e)}function ee(){throw new On(`Unexpected character ${JSON.stringify(t[e])}`,e)}function de(){throw new On("Unexpected end of json string",t.length)}function Ae(){throw new On("Object key expected",e)}function ae(){throw new On("Colon expected",e)}function pe(){let W=t.slice(e,e+6);throw new On(`Invalid unicode character "${W}"`,e)}}function Ev(t,e){return t[e]==="*"&&t[e+1]==="/"}function Qd(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),t}catch(n){try{let r=$0.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=Yd(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Ya=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=Qd(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,a="",c=!1,l=!1,d="",f=new ReadableStream({async start(p){let m=e.body.getReader(),b=(_,g,S)=>{let w=_.split(`
296
+ `);for(let E of w)E.trim()&&g.enqueue(S.encode(E+`
297
+ `))},C=(_,g,S)=>{let w="";try{w=Qd(o.arguments||"",this.logger)}catch(U){console.error(`${U.message} ${U.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),w=o.arguments||""}let E={role:"assistant",tool_calls:[{function:{name:o.name,arguments:w},id:o.id,index:o.index,type:"function"}]},T={..._,choices:[{..._.choices[0],delta:E}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let R=`data: ${JSON.stringify(T)}
298
298
 
299
- `;m.enqueue(k.encode(R))},b=(y,m)=>{let{controller:k,encoder:w}=m;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let A=y.slice(6);try{let T=JSON.parse(A);if(T.choices?.[0]?.delta?.tool_calls?.length){let U=T.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:U.index,name:U.function?.name||"",id:U.id||"",arguments:U.function?.arguments||""},U.function?.arguments&&(U.function.arguments="");let J=`data: ${JSON.stringify(T)}
299
+ `;g.enqueue(S.encode(R))},y=(_,g)=>{let{controller:S,encoder:w}=g;if(_.startsWith("data: ")&&_.trim()!=="data: [DONE]"){let E=_.slice(6);try{let T=JSON.parse(E);if(T.choices?.[0]?.delta?.tool_calls?.length){let U=T.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:U.index,name:U.function?.name||"",id:U.id||"",arguments:U.function?.arguments||""},U.function?.arguments&&(U.function.arguments="");let J=`data: ${JSON.stringify(T)}
300
300
 
301
- `;k.enqueue(w.encode(J));return}else if(o.index===U.index){U.function?.arguments&&(o.arguments+=U.function.arguments);return}else{C(T,k,w),o={index:U.index,name:U.function?.name||"",id:U.id||"",arguments:U.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){C(T,k,w),o={};return}T.choices?.[0]?.delta?.tool_calls?.length&&m.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let R=`data: ${JSON.stringify(T)}
301
+ `;S.enqueue(w.encode(J));return}else if(o.index===U.index){U.function?.arguments&&(o.arguments+=U.function.arguments);return}else{C(T,S,w),o={index:U.index,name:U.function?.name||"",id:U.id||"",arguments:U.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){C(T,S,w),o={};return}T.choices?.[0]?.delta?.tool_calls?.length&&g.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let R=`data: ${JSON.stringify(T)}
302
302
 
303
- `;k.enqueue(w.encode(R))}catch{k.enqueue(w.encode(y+`
304
- `))}}else k.enqueue(w.encode(y+`
305
- `))};try{for(;;){let{done:y,value:m}=await g.read();if(y){d.trim()&&_(d,p,r);break}if(!m||m.length===0)continue;let k;try{k=n.decode(m,{stream:!0})}catch(A){console.warn("Failed to decode chunk",A);continue}if(k.length===0)continue;if(d+=k,d.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let A=d.split(`
306
- `);d=A.pop()||"";for(let T of A)if(T.trim())try{b(T,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:R=>s=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>c,setReasoningComplete:R=>c=R})}catch(R){console.error("Error processing line:",T,R),p.enqueue(r.encode(T+`
303
+ `;S.enqueue(w.encode(R))}catch{S.enqueue(w.encode(_+`
304
+ `))}}else S.enqueue(w.encode(_+`
305
+ `))};try{for(;;){let{done:_,value:g}=await m.read();if(_){d.trim()&&b(d,p,r);break}if(!g||g.length===0)continue;let S;try{S=n.decode(g,{stream:!0})}catch(E){console.warn("Failed to decode chunk",E);continue}if(S.length===0)continue;if(d+=S,d.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let E=d.split(`
306
+ `);d=E.pop()||"";for(let T of E)if(T.trim())try{y(T,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:R=>s=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>c,setReasoningComplete:R=>c=R})}catch(R){console.error("Error processing line:",T,R),p.enqueue(r.encode(T+`
307
307
  `))}continue}let w=d.split(`
308
- `);d=w.pop()||"";for(let A of w)if(A.trim())try{b(A,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>c,setReasoningComplete:T=>c=T})}catch(T){console.error("Error processing line:",A,T),p.enqueue(r.encode(A+`
309
- `))}}}catch(y){console.error("Stream error:",y),p.error(y)}finally{try{g.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}p.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Qa=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return n.choices[0]?.message.reasoning_content&&(n.thinking={content:n.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(g,_,C)=>{let b=g.split(`
310
- `);for(let y of b)y.trim()&&_.enqueue(C.encode(y+`
311
- `))},p=(g,_)=>{let{controller:C,encoder:b}=_;if(this.logger?.debug({line:g},"Processing reason line"),g.startsWith("data: ")&&g.trim()!=="data: [DONE]")try{let y=JSON.parse(g.slice(6));if(console.log(JSON.stringify(y)),y.choices?.[0]?.delta?.reasoning_content){_.appendReasoningContent(y.choices[0].delta.reasoning_content);let m={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(m)}
308
+ `);d=w.pop()||"";for(let E of w)if(E.trim())try{y(E,{controller:p,encoder:r,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>a,appendReasoningContent:T=>a+=T,isReasoningComplete:()=>c,setReasoningComplete:T=>c=T})}catch(T){console.error("Error processing line:",E,T),p.enqueue(r.encode(E+`
309
+ `))}}}catch(_){console.error("Stream error:",_),p.error(_)}finally{try{m.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}p.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Qa=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return n.choices[0]?.message.reasoning_content&&(n.thinking={content:n.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let d=e.body.getReader(),f=(m,b,C)=>{let y=m.split(`
310
+ `);for(let _ of y)_.trim()&&b.enqueue(C.encode(_+`
311
+ `))},p=(m,b)=>{let{controller:C,encoder:y}=b;if(this.logger?.debug({line:m},"Processing reason line"),m.startsWith("data: ")&&m.trim()!=="data: [DONE]")try{let _=JSON.parse(m.slice(6));if(console.log(JSON.stringify(_)),_.choices?.[0]?.delta?.reasoning_content){b.appendReasoningContent(_.choices[0].delta.reasoning_content);let g={..._,choices:[{..._.choices[0],delta:{..._.choices[0].delta,thinking:{content:_.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(g)}
312
312
 
313
- `;C.enqueue(b.encode(k));return}if(y.choices?.[0]?.delta?.content&&_.reasoningContent()&&!_.isReasoningComplete()){_.setReasoningComplete(!0);let m="ccr_think_signature",k=y.choices[0].delta.content,w={...y,choices:[{...y.choices[0],delta:{...y.choices[0].delta,content:null,thinking:{content:_.reasoningContent(),signature:m}}}]};delete w.choices[0].delta.reasoning_content;let A=`data: ${JSON.stringify(w)}
313
+ `;C.enqueue(y.encode(S));return}if(_.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let g="ccr_think_signature",S=_.choices[0].delta.content,w={..._,choices:[{..._.choices[0],delta:{..._.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:g}}}]};delete w.choices[0].delta.reasoning_content;let E=`data: ${JSON.stringify(w)}
314
314
 
315
- `;C.enqueue(b.encode(A))}if(y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0){_.isReasoningComplete()&&y.choices[0].index++;let m=`data: ${JSON.stringify(y)}
315
+ `;C.enqueue(y.encode(E))}if(_.choices?.[0]?.delta?.reasoning_content&&delete _.choices[0].delta.reasoning_content,_.choices?.[0]?.delta&&Object.keys(_.choices[0].delta).length>0){b.isReasoningComplete()&&_.choices[0].index++;let g=`data: ${JSON.stringify(_)}
316
316
 
317
- `;C.enqueue(b.encode(m))}}catch{C.enqueue(b.encode(g+`
318
- `))}else C.enqueue(b.encode(g+`
319
- `))};try{for(;;){let{done:g,value:_}=await d.read();if(g){a.trim()&&f(a,l,r);break}let C=n.decode(_,{stream:!0});a+=C;let b=a.split(`
320
- `);a=b.pop()||"";for(let y of b)if(y.trim())try{p(y,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:m=>o+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",y,m),l.enqueue(r.encode(y+`
321
- `))}}}catch(g){console.error("Stream error:",g),l.error(g)}finally{try{d.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Xa=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var Za=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function U0(t){let e=[];for(let r=0;r<t.messages.length;r++){let o=t.messages[r],s=r===t.messages.length-1,a=o.role==="assistant",c=[];typeof o.content=="string"?c.push({type:"text",text:o.content}):Array.isArray(o.content)&&o.content.forEach(l=>{l.type==="text"?c.push({type:"text",text:l.text||""}):l.type==="image_url"&&c.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&c.length===0&&!o.tool_calls&&!o.content)&&(s&&a&&c.length===0&&o.tool_calls&&c.push({type:"text",text:""}),e.push({role:o.role==="assistant"?"assistant":"user",content:c}))}let n={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(n.tools=t.tools.map(r=>({name:r.function.name,description:r.function.description,input_schema:r.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?n.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(n.tool_choice={type:"tool",name:t.tool_choice})),n}function q0(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function H0(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o;r.tool_use&&r.tool_use.length>0&&(o=r.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:r.id,choices:[{finish_reason:r.stop_reason||null,index:0,message:{content:r.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:{completion_tokens:r.usage.output_tokens,prompt_tokens:r.usage.input_tokens,total_tokens:r.usage.input_tokens+r.usage.output_tokens}};return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=(c,l)=>{if(c.startsWith("data: ")){let d=c.slice(6).trim();if(d){n?.debug({chunkStr:d},`${e} chunk:`);try{let f=JSON.parse(d);if(f.type==="content_block_delta"&&f.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:f.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
317
+ `;C.enqueue(y.encode(g))}}catch{C.enqueue(y.encode(m+`
318
+ `))}else C.enqueue(y.encode(m+`
319
+ `))};try{for(;;){let{done:m,value:b}=await d.read();if(m){a.trim()&&f(a,l,r);break}let C=n.decode(b,{stream:!0});a+=C;let y=a.split(`
320
+ `);a=y.pop()||"";for(let _ of y)if(_.trim())try{p(_,{controller:l,encoder:r,reasoningContent:()=>o,appendReasoningContent:g=>o+=g,isReasoningComplete:()=>s,setReasoningComplete:g=>s=g})}catch(g){console.error("Error processing line:",_,g),l.enqueue(r.encode(_+`
321
+ `))}}}catch(m){console.error("Stream error:",m),l.error(m)}finally{try{d.releaseLock()}catch(m){console.error("Error releasing reader lock:",m)}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Xa=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var Za=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function U0(t){let e=[];for(let r=0;r<t.messages.length;r++){let o=t.messages[r],s=r===t.messages.length-1,a=o.role==="assistant",c=[];typeof o.content=="string"?c.push({type:"text",text:o.content}):Array.isArray(o.content)&&o.content.forEach(l=>{l.type==="text"?c.push({type:"text",text:l.text||""}):l.type==="image_url"&&c.push({type:"image",source:{type:"base64",media_type:l.media_type||"image/jpeg",data:l.image_url.url}})}),!(!s&&c.length===0&&!o.tool_calls&&!o.content)&&(s&&a&&c.length===0&&o.tool_calls&&c.push({type:"text",text:""}),e.push({role:o.role==="assistant"?"assistant":"user",content:c}))}let n={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(n.tools=t.tools.map(r=>({name:r.function.name,description:r.function.description,input_schema:r.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?n.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(n.tool_choice={type:"tool",name:t.tool_choice})),n}function q0(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function H0(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o;r.tool_use&&r.tool_use.length>0&&(o=r.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:r.id,choices:[{finish_reason:r.stop_reason||null,index:0,message:{content:r.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:{completion_tokens:r.usage.output_tokens,prompt_tokens:r.usage.input_tokens,total_tokens:r.usage.input_tokens+r.usage.output_tokens}};return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r=new TextDecoder,o=new TextEncoder,s=(c,l)=>{if(c.startsWith("data: ")){let d=c.slice(6).trim();if(d){n?.debug({chunkStr:d},`${e} chunk:`);try{let f=JSON.parse(d);if(f.type==="content_block_delta"&&f.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:f.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
322
322
 
323
323
  `))}else if(f.type==="content_block_delta"&&f.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:f.index||0,function:{arguments:f.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
324
324
 
@@ -330,26 +330,26 @@ ${n}
330
330
 
331
331
  `));else{let p={choices:[{delta:{role:"assistant",content:f.content?.[0]?.text||""},finish_reason:f.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:f.id||"",model:f.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:f.usage?.output_tokens||0,prompt_tokens:f.usage?.input_tokens||0,total_tokens:(f.usage?.input_tokens||0)+(f.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
332
332
 
333
- `))}}catch(f){n?.error(`Error parsing ${e} stream chunk`,d,f.message)}}}},a=new ReadableStream({async start(c){let l=t.body.getReader(),d="";try{for(;;){let{done:f,value:p}=await l.read();if(f){d&&s(d,c);break}d+=r.decode(p,{stream:!0});let g=d.split(`
334
- `);d=g.pop()||"";for(let _ of g)s(_,c)}}catch(f){c.error(f)}finally{c.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function Av(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Oe($d(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
333
+ `))}}catch(f){n?.error(`Error parsing ${e} stream chunk`,d,f.message)}}}},a=new ReadableStream({async start(c){let l=t.body.getReader(),d="";try{for(;;){let{done:f,value:p}=await l.read();if(f){d&&s(d,c);break}d+=r.decode(p,{stream:!0});let m=d.split(`
334
+ `);d=m.pop()||"";for(let b of m)s(b,c)}}catch(f){c.error(f)}finally{c.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function Av(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>Oe($d(),1));return(await(await new t({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(t){throw console.error("Error getting access token:",t),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
335
335
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
336
336
  2. Run "gcloud auth application-default login"
337
- 3. Use Google Cloud environment with default service account`)}}var eu=class{name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Av();return{body:U0(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return q0(e)}async transformResponseOut(e){return H0(e,this.name,this.logger)}};var tu=class{name="cerebras";async transformRequestIn(e,n){let r=JSON.parse(JSON.stringify(e));return r.reasoning?delete r.reasoning:r.disable_reasoning=!1,{body:r,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var nu=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var ru=class{name="OpenAI";endPoint="/v1/chat/completions"};var ou=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var su=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",d=new ReadableStream({async start(f){let p=e.body.getReader(),g=(C,b,y)=>{let m=C.split(`
338
- `);for(let k of m)k.trim()&&b.enqueue(y.encode(k+`
339
- `))},_=(C,b)=>{let{controller:y,encoder:m}=b;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let k=C.slice(6);try{let w=JSON.parse(k);if(w.usage&&(this.logger?.debug({usage:w.usage,hasToolCall:c},"usage"),w.choices[0].finish_reason=c?"tool_calls":"stop"),w.choices?.[0]?.finish_reason==="error"&&y.enqueue(m.encode(`data: ${JSON.stringify({error:w.choices?.[0].error})}
337
+ 3. Use Google Cloud environment with default service account`)}}var eu=class{name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(r=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Av();return{body:U0(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return q0(e)}async transformResponseOut(e){return H0(e,this.name,this.logger)}};var tu=class{name="cerebras";async transformRequestIn(e,n){let r=JSON.parse(JSON.stringify(e));return r.reasoning?delete r.reasoning:r.disable_reasoning=!1,{body:r,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var nu=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var ru=class{name="OpenAI";endPoint="/v1/chat/completions"};var ou=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var su=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(n=>{Array.isArray(n.content)&&n.content.forEach(r=>{r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)})}):e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control,r.type==="image_url"&&(r.image_url.url.startsWith("http")||(r.image_url.url=`data:${r.media_type};base64,${r.image_url.url}`),delete r.media_type)}):n.cache_control&&delete n.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",d=new ReadableStream({async start(f){let p=e.body.getReader(),m=(C,y,_)=>{let g=C.split(`
338
+ `);for(let S of g)S.trim()&&y.enqueue(_.encode(S+`
339
+ `))},b=(C,y)=>{let{controller:_,encoder:g}=y;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let S=C.slice(6);try{let w=JSON.parse(S);if(w.usage&&(this.logger?.debug({usage:w.usage,hasToolCall:c},"usage"),w.choices[0].finish_reason=c?"tool_calls":"stop"),w.choices?.[0]?.finish_reason==="error"&&_.enqueue(g.encode(`data: ${JSON.stringify({error:w.choices?.[0].error})}
340
340
 
341
- `)),w.choices?.[0]?.delta?.content&&!b.hasTextContent()&&b.setHasTextContent(!0),w.choices?.[0]?.delta?.reasoning){b.appendReasoningContent(w.choices[0].delta.reasoning);let T={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,thinking:{content:w.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let R=`data: ${JSON.stringify(T)}
341
+ `)),w.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),w.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(w.choices[0].delta.reasoning);let T={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,thinking:{content:w.choices[0].delta.reasoning}}}]};T.choices?.[0]?.delta&&delete T.choices[0].delta.reasoning;let R=`data: ${JSON.stringify(T)}
342
342
 
343
- `;y.enqueue(m.encode(R));return}if(w.choices?.[0]?.delta?.content&&b.reasoningContent()&&!b.isReasoningComplete()){b.setReasoningComplete(!0);let R={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:null,thinking:{content:b.reasoningContent(),signature:"ccr_think_signature"}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let U=`data: ${JSON.stringify(R)}
343
+ `;_.enqueue(g.encode(R));return}if(w.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let R={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:"ccr_think_signature"}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let U=`data: ${JSON.stringify(R)}
344
344
 
345
- `;y.enqueue(m.encode(U))}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${Ut()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),w.choices?.[0]?.delta?.tool_calls?.length&&b.hasTextContent()&&(typeof w.choices[0].index=="number"?w.choices[0].index+=1:w.choices[0].index=1);let A=`data: ${JSON.stringify(w)}
345
+ `;_.enqueue(g.encode(U))}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(T=>{T.id=`call_${Ut()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),w.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof w.choices[0].index=="number"?w.choices[0].index+=1:w.choices[0].index=1);let E=`data: ${JSON.stringify(w)}
346
346
 
347
- `;y.enqueue(m.encode(A))}catch{y.enqueue(m.encode(C+`
348
- `))}}else y.enqueue(m.encode(C+`
349
- `))};try{for(;;){let{done:C,value:b}=await p.read();if(C){l.trim()&&g(l,f,r);break}if(!b||b.length===0)continue;let y;try{y=n.decode(b,{stream:!0})}catch(k){console.warn("Failed to decode chunk",k);continue}if(y.length===0)continue;if(l+=y,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let k=l.split(`
350
- `);l=k.pop()||"";for(let w of k)if(w.trim())try{_(w,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:A=>o=A,reasoningContent:()=>s,appendReasoningContent:A=>s+=A,isReasoningComplete:()=>a,setReasoningComplete:A=>a=A})}catch(A){console.error("Error processing line:",w,A),f.enqueue(r.encode(w+`
351
- `))}continue}let m=l.split(`
352
- `);l=m.pop()||"";for(let k of m)if(k.trim())try{_(k,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",k,w),f.enqueue(r.encode(k+`
347
+ `;_.enqueue(g.encode(E))}catch{_.enqueue(g.encode(C+`
348
+ `))}}else _.enqueue(g.encode(C+`
349
+ `))};try{for(;;){let{done:C,value:y}=await p.read();if(C){l.trim()&&m(l,f,r);break}if(!y||y.length===0)continue;let _;try{_=n.decode(y,{stream:!0})}catch(S){console.warn("Failed to decode chunk",S);continue}if(_.length===0)continue;if(l+=_,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let S=l.split(`
350
+ `);l=S.pop()||"";for(let w of S)if(w.trim())try{b(w,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){console.error("Error processing line:",w,E),f.enqueue(r.encode(w+`
351
+ `))}continue}let g=l.split(`
352
+ `);l=g.pop()||"";for(let S of g)if(S.trim())try{b(S,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>a,setReasoningComplete:w=>a=w})}catch(w){console.error("Error processing line:",S,w),f.enqueue(r.encode(S+`
353
353
  `))}}}catch(C){console.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}f.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Xd=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
354
354
 
355
355
  Output format:
@@ -357,30 +357,30 @@ Output format:
357
357
  Your detailed thinking process goes here
358
358
  </reasoning_content>
359
359
  Your final answer must follow after the closing tag above.`,Sv=10,iu=class{name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<Sv)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
360
- ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:Xd}):r.content=[{type:"text",text:Xd},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Xd}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=o.choices[0]?.message.content.match(s);a&&a[1]&&(o.thinking={content:a[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,a=new TextEncoder,c=new ReadableStream({async start(l){let d=e.body.getReader(),f="",p="SEARCHING",g="",_="",C=(b,y)=>{if(typeof y!="string"){b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0&&!b.choices[0].delta.content&&(b.choices[0].index=o,l.enqueue(a.encode(`data: ${JSON.stringify(b)}
360
+ ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:Xd}):r.content=[{type:"text",text:Xd},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Xd}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=o.choices[0]?.message.content.match(s);a&&a[1]&&(o.thinking={content:a[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,a=new TextEncoder,c=new ReadableStream({async start(l){let d=e.body.getReader(),f="",p="SEARCHING",m="",b="",C=(y,_)=>{if(typeof _!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=o,l.enqueue(a.encode(`data: ${JSON.stringify(y)}
361
361
 
362
- `)));return}let m=g+y;for(g="";m.length>0;)if(p==="SEARCHING"){let k=m.indexOf(n);if(k!==-1)m=m.substring(k+n.length),p="REASONING";else{for(let w=n.length-1;w>0;w--)if(m.endsWith(n.substring(0,w))){g=m.substring(m.length-w);break}m=""}}else if(p==="REASONING"){let k=m.indexOf(r);if(k!==-1){let w=m.substring(0,k);if(w.length>0){let R={...b.choices[0].delta,thinking:{content:w}};delete R.content;let U={...b,choices:[{...b.choices[0],delta:R,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(U)}
362
+ `)));return}let g=m+_;for(m="";g.length>0;)if(p==="SEARCHING"){let S=g.indexOf(n);if(S!==-1)g=g.substring(S+n.length),p="REASONING";else{for(let w=n.length-1;w>0;w--)if(g.endsWith(n.substring(0,w))){m=g.substring(g.length-w);break}g=""}}else if(p==="REASONING"){let S=g.indexOf(r);if(S!==-1){let w=g.substring(0,S);if(w.length>0){let R={...y.choices[0].delta,thinking:{content:w}};delete R.content;let U={...y,choices:[{...y.choices[0],delta:R,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(U)}
363
363
 
364
- `))}let A={...b.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete A.content;let T={...b,choices:[{...b.choices[0],delta:A,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
364
+ `))}let E={...y.choices[0].delta,thinking:{signature:"ccr_think_signature"}};delete E.content;let T={...y,choices:[{...y.choices[0],delta:E,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
365
365
 
366
- `)),o++,m=m.substring(k+r.length),p="FINAL"}else{let w=m;for(let A=r.length-1;A>0;A--)if(m.endsWith(r.substring(0,A))){g=m.substring(m.length-A),w=m.substring(0,m.length-A);break}if(w.length>0){let A={...b.choices[0].delta,thinking:{content:w}};delete A.content;let T={...b,choices:[{...b.choices[0],delta:A,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
366
+ `)),o++,g=g.substring(S+r.length),p="FINAL"}else{let w=g;for(let E=r.length-1;E>0;E--)if(g.endsWith(r.substring(0,E))){m=g.substring(g.length-E),w=g.substring(0,g.length-E);break}if(w.length>0){let E={...y.choices[0].delta,thinking:{content:w}};delete E.content;let T={...y,choices:[{...y.choices[0],delta:E,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
367
367
 
368
- `))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))_+=m;else{let w=_+m,A={...b.choices[0].delta,content:w};A.thinking&&delete A.thinking;let T={...b,choices:[{...b.choices[0],delta:A}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
368
+ `))}g=""}}else if(p==="FINAL"){if(g.length>0)if(/^\s*$/.test(g))b+=g;else{let w=b+g,E={...y.choices[0].delta,content:w};E.thinking&&delete E.thinking;let T={...y,choices:[{...y.choices[0],delta:E}]};l.enqueue(a.encode(`data: ${JSON.stringify(T)}
369
369
 
370
- `)),_=""}o++,m=""}};try{for(;;){let{done:b,value:y}=await d.read();if(b)break;let m=s.decode(y,{stream:!0});f+=m;let k=f.split(`
371
- `);f=k.pop()||"";for(let w of k)if(w.trim()){if(w.trim()==="data: [DONE]"){l.enqueue(a.encode(w+`
370
+ `)),b=""}o++,g=""}};try{for(;;){let{done:y,value:_}=await d.read();if(y)break;let g=s.decode(_,{stream:!0});f+=g;let S=f.split(`
371
+ `);f=S.pop()||"";for(let w of S)if(w.trim()){if(w.trim()==="data: [DONE]"){l.enqueue(a.encode(w+`
372
372
 
373
- `));break}if(w.startsWith("data:"))try{let A=JSON.parse(w.slice(5));C(A,A.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(w+`
373
+ `));break}if(w.startsWith("data:"))try{let E=JSON.parse(w.slice(5));C(E,E.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(w+`
374
374
  `))}else l.enqueue(a.encode(w+`
375
- `))}}}catch(b){console.error("Stream error:",b),l.error(b)}finally{try{d.releaseLock()}catch(b){console.error("Error releasing reader lock:",b)}if(p==="REASONING"){let y={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(y)}
375
+ `))}}}catch(y){console.error("Stream error:",y),l.error(y)}finally{try{d.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}if(p==="REASONING"){let _={choices:[{delta:{thinking:{signature:"ccr_think_signature"}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(_)}
376
376
 
377
377
  `))}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var au=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(r=>r.thinking?.content))&&e.messages.forEach(r=>{if(r.role==="assistant"){let o=r.thinking?.content,s=r.thinking?.signature;o&&typeof o=="string"&&o.trim()&&(r.reasoning_content=o,s&&(r.reasoning_content_signature=s)),r.tool_calls&&r.tool_calls.length>0&&(r.reasoning_content||(r.reasoning_content="")),r.thinking&&delete r.thinking}}),e}async transformResponseOut(e){let n=e.headers.get("Content-Type");if(n?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,o=new TextEncoder,s="",a="",c=new ReadableStream({async start(l){let d=e.body.getReader();try{for(;;){let{done:f,value:p}=await d.read();if(f){a.trim()&&l.enqueue(o.encode(a+`
378
- `));break}let g=r.decode(p,{stream:!0});a+=g;let _=a.split(`
379
- `);a=_.pop()||"";for(let C of _)if(C.trim())if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let b=JSON.parse(C.slice(6));if(b.choices?.[0]?.delta?.reasoning_content){s+=b.choices[0].delta.reasoning_content;let y={...b,choices:[{...b.choices[0],delta:{thinking:{content:b.choices[0].delta.reasoning_content}}}]};delete y.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(y)}
378
+ `));break}let m=r.decode(p,{stream:!0});a+=m;let b=a.split(`
379
+ `);a=b.pop()||"";for(let C of b)if(C.trim())if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let y=JSON.parse(C.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){s+=y.choices[0].delta.reasoning_content;let _={...y,choices:[{...y.choices[0],delta:{thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete _.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(_)}
380
380
 
381
- `));continue}if(b.choices?.[0]?.delta?.content&&s&&!b.choices[0]?.delta?.reasoning_content){let y=Date.now().toString(),m={...b,choices:[{...b.choices[0],delta:{content:null,thinking:{content:s,signature:y}}}]};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
381
+ `));continue}if(y.choices?.[0]?.delta?.content&&s&&!y.choices[0]?.delta?.reasoning_content){let _=Date.now().toString(),g={...y,choices:[{...y.choices[0],delta:{content:null,thinking:{content:s,signature:_}}}]};l.enqueue(o.encode(`data: ${JSON.stringify(g)}
382
382
 
383
- `)),s=""}b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0&&l.enqueue(o.encode(`data: ${JSON.stringify(b)}
383
+ `)),s=""}y.choices?.[0]?.delta?.reasoning_content&&delete y.choices[0].delta.reasoning_content,y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&l.enqueue(o.encode(`data: ${JSON.stringify(y)}
384
384
 
385
385
  `))}catch{l.enqueue(o.encode(C+`
386
386
  `))}else l.enqueue(o.encode(C+`
@@ -388,14 +388,14 @@ ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return
388
388
  error: ${n.message}
389
389
  stack: ${n.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
390
390
  Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(z0).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};var W0=require("tiktoken"),ws=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,W0.get_encoding)(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");let r=0,{messages:o,system:s,tools:a}=e;return Array.isArray(o)&&o.forEach(c=>{typeof c.content=="string"?r+=n.encode(c.content).length:Array.isArray(c.content)&&c.content.forEach(l=>{if(l.type==="text")r+=n.encode(l.text).length;else if(l.type==="tool_use")r+=n.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let d=typeof l.content=="string"?l.content:JSON.stringify(l.content);r+=n.encode(d).length}})}),typeof s=="string"?r+=n.encode(s).length:Array.isArray(s)&&s.forEach(c=>{c.type==="text"&&(typeof c.text=="string"?r+=n.encode(c.text).length:Array.isArray(c.text)&&c.text.forEach(l=>{r+=n.encode(l||"").length}))}),a&&a.forEach(c=>{c.description&&(r+=n.encode(c.name+c.description).length),c.input_schema&&(r+=n.encode(JSON.stringify(c.input_schema)).length)}),r}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};var ks=require("path"),a_=require("os"),Ao=require("fs"),vs=require("fs");var kv=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,a=null,c=o;for(;c<n&&(s=s[t[c]]);)s.end&&(a=s.end),++c;a?(o>r&&e.push(t.slice(r,o)),e.push(a),o+=a.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},vv=kv,Tv=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??null}},Dv=Tv,X0=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),Rv=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),xv=Rv(X0),G0=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",Ov=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${G0}])]+`,` ?[^\\s${G0}]+`]]),Es="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",IP=new RegExp(`^[${Es}]+$`,"gu"),ef=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),uu=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");for(let[r,o]of Ov)n=n.replaceAll(r,o);return new RegExp(n,"gu")}else if(t.String!==void 0){let n=Pv(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},Pv=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Fv=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},Iv=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,Nv=t=>Number.isInteger(t)||typeof t=="bigint",Bv=t=>{let e=0;for(let n of t)++e;return e},Mv=t=>Z0(t.toLowerCase()),Nt=(...t)=>Array.prototype.concat.apply([],t),tf=t=>new Map(Object.entries(t)),Lv=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},Z0=t=>t.replace(new RegExp("\\p{M}","gu"),""),J0=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},jv=t=>t.match(/\S+/g)||[],$v=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},As=$v,Uv=class extends As{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Pn=Uv,qv=class extends Pn{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);Iv(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
391
- `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},Hv=qv,zv=class extends Pn{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(e=>e.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},Wv=zv,Gv=class extends Pn{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>e_(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},Jv=Gv,Vv=class extends Pn{normalize(t){let e=uu(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},Kv=Vv,Yv=class extends Pn{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},cu=Yv,Qv=class extends cu{constructor(){super(...arguments),this.form="NFC"}},Xv=Qv,Zv=class extends cu{constructor(){super(...arguments),this.form="NFD"}},eT=Zv,tT=class extends cu{constructor(){super(...arguments),this.form="NFKC"}},nT=tT,rT=class extends cu{constructor(){super(...arguments),this.form="NFKD"}},oT=rT,sT=class extends Pn{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},iT=sT,aT=class extends Pn{normalize(t){return Z0(t)}},uT=aT,cT=class extends Pn{normalize(t){return t.toLowerCase()}},lT=cT,dT=class extends Pn{normalize(t){return t=this.config.prepend+t,t}},fT=dT;function hT(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new Hv(t);case"Precompiled":return new Wv(t);case"Sequence":return new Jv(t);case"Replace":return new Kv(t);case"NFC":return new Xv(t);case"NFD":return new eT(t);case"NFKC":return new nT(t);case"NFKD":return new oT(t);case"Strip":return new iT(t);case"StripAccents":return new uT(t);case"Lowercase":return new lT(t);case"Prepend":return new fT(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var e_=hT,pT=class extends As{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},dn=pT,mT=class extends dn{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=X0,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(n=>Array.from(this.text_encoder.encode(n),r=>this.byte_encoder[r]).join(""))}},gT=mT,yT=class extends dn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},_T=yT,bT=class extends dn{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},CT=bT,wT=class extends dn{constructor(t){super(),this.config=t,this.pattern=uu(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):Lv(t,this.pattern)}},ET=wT,AT=class extends dn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Es}]+|[${Es}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},ST=AT,kT=class extends dn{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},vT=kT,TT=class extends dn{constructor(){super(),this.pattern=new RegExp(`[^\\s${Es}]+|[${Es}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},DT=TT,RT=class extends dn{constructor(t){super(),this.config=t,this.pattern=uu(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},xT=RT,OT=class extends dn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>t_(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},PT=OT,FT=class extends dn{pre_tokenize_text(t){return jv(t)}},IT=FT;function NT(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new DT;case"Sequence":return new PT(t);case"Whitespace":return new _T;case"WhitespaceSplit":return new IT;case"Metaspace":return new CT(t);case"ByteLevel":return new gT(t);case"Split":return new ET(t);case"Punctuation":return new ST(t);case"Digits":return new vT(t);case"Replace":return new xT(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var t_=NT,BT=class extends As{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=Fv(e,this.tokens_to_ids,this.unk_token_id)),e}convert_tokens_to_ids(t){return t.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(e=>this.vocab[Number(e)]??this.unk_token)}},lu=BT,MT=class extends lu{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=tf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<r.length;){let c=r.length,l=null;for(;s<c;){let d=r.slice(s,c).join("");if(s>0&&(d=this.config.continuing_subword_prefix+d),this.tokens_to_ids.has(d)){l=d;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},V0=MT,K0=class n_{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new n_(!1,new Map)}},LT=class{constructor(){this.root=K0.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=K0.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},jT=LT,Zd=class r_{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new r_(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},$T=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Zd(this.bos_token_id??0,0,0,0,0),o=new Zd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new Zd(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let s of this.begin_nodes[e]){s.prev=null;let a=0,c=null;for(let l of this.end_nodes[e]){let d=l.backtrace_score+s.score;(c===null||d>a)&&(c=l.clone(),a=d)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let n=[],r=this.begin_nodes[t][0].prev;if(r===null)return[];let o=r.clone();for(;o.prev!==null;)n.push(o.clone()),o=o.clone().prev.clone();return n.reverse(),n}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},UT=$T;function qT(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var HT=class extends lu{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=qT(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new jT,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],a=e.slice(r).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let d=this.tokens_to_ids.get(l),f=this.scores[d],p=Bv(l);t.insert(r,p,f,d),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new UT(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},Y0=HT,zT=class{constructor(t=(n,r)=>n>r,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},WT=zT,GT=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},JT=GT,VT=class extends lu{constructor(t){super(t),this.tokens_to_ids=tf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new JT(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new WT((c,l)=>c.score<l.score),s={token:n[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<n.length;++c){let l={bias:c/n.length,token:n[c],prev:a,next:null};a.next=l,this.add_node(o,a),a=l}for(;!o.is_empty();){let c=o.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let d={...c.prev};c.prev.deleted=!0,c.prev=d,d.prev?d.prev.next=d:s=d}let l={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};l.prev?(l.prev.next=l,this.add_node(o,l.prev)):s=l,l.next&&(l.next.prev=l,this.add_node(o,l))}for(let c=s;c!==null;c=c.next)r.push(c.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(a=>this.tokens_to_ids.has(a))?e.push(...s):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},Q0=VT,KT=class extends lu{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=tf(e.target_lang?n[e.target_lang]:n),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},YT=KT;function QT(t,e){switch(t.type){case"WordPiece":return new V0(t);case"Unigram":return new Y0(t,e.eos_token);case"BPE":return new Q0(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Y0(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new Q0(t):new V0(t):new YT(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var XT=QT,ZT=class extends As{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Ss=ZT,eD=class extends Ss{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of r)"SpecialToken"in a?n&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Nt(o,t),s=Nt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Nt(o,e),s=Nt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},tD=eD,nD=class extends Ss{post_process(t,e=null){return{tokens:e?Nt(t,e):t}}},rD=nD,oD=class extends Ss{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=Nt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=Nt(t,o,e,s),r=Nt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},sD=oD,iD=class extends Ss{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=Nt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=Nt(t,o,e,s),r=Nt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},aD=iD,uD=class extends Ss{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>o_(e))}post_process(t,e=null,n=!0){let r={tokens:t};for(let o of this.processors)r=o.post_process(r.tokens,e,n);return r}},cD=uD;function lD(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new tD(t);case"ByteLevel":return new rD(t);case"BertProcessing":return new sD(t);case"RobertaProcessing":return new aD(t);case"Sequence":return new cD(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var o_=lD,dD=class extends As{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},fn=dD,fD=class extends fn{constructor(t){super(t),this.byte_decoder=xv,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},hD=fD,pD=class extends fn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=ef(e)),e})}},mD=pD,gD=class extends fn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},yD=gD,_D=class extends fn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},bD=_D,CD=class extends fn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let r=1;r<t.length;++r)t[r]!==e.at(-1)&&e.push(t[r]);let n=e.filter(r=>r!==this.pad_token).join("");return this.cleanup&&(n=ef(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(t){return[this.convert_tokens_to_string(t)]}},wD=CD,ED=class extends fn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>s_(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},AD=ED,SD=class extends fn{decode_chain(t){let e=uu(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},kD=SD,vD=class extends fn{decode_chain(t){return[t.join("")]}},TD=vD,DD=class extends fn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o)n=o+1;let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},RD=DD,xD=class extends fn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},OD=xD;function PD(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new hD(t);case"WordPiece":return new mD(t);case"Metaspace":return new yD(t);case"BPEDecoder":return new bD(t);case"CTC":return new wD(t);case"Sequence":return new AD(t);case"Replace":return new kD(t);case"Fuse":return new TD(t);case"Strip":return new RD(t);case"ByteFallback":return new OD(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var s_=PD,FD=class{constructor(t,e){let n=J0(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=J0(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=e_(this.tokenizer.normalizer),this.pre_tokenizer=t_(this.tokenizer.pre_tokenizer),this.model=XT(this.tokenizer.model,this.config),this.post_processor=o_(this.tokenizer.post_processor),this.decoder=s_(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new Dv(o);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}),(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new vv(this.added_tokens.map(o=>o.content)),this.added_tokens_map=new Map(this.added_tokens.map(o=>[o.content,o])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return r&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!Nv(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=ef(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=Mv(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(n,{section_index:r}):[n];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:Nt(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}},i_=FD;var du=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||(0,ks.join)((0,a_.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,ks.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,ks.join)(e,"tokenizer.json"),tokenizerConfig:(0,ks.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,Ao.existsSync)(e)||(0,Ao.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,Ao.existsSync)(e.tokenizerJson)||!(0,Ao.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([vs.promises.readFile(e.tokenizerJson,"utf-8"),vs.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[c,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([vs.promises.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),vs.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let n=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new i_(n.tokenizerJson,n.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let a of r)if(typeof a.content=="string")n.push(a.content);else if(Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?n.push(c.text):c.type==="tool_use"&&c.input?n.push(JSON.stringify(c.input)):c.type==="tool_result"&&n.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")n.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&n.push(c)}}if(s)for(let a of s)a.name&&n.push(a.name),a.description&&n.push(a.description),a.input_schema&&n.push(JSON.stringify(a.input_schema));return n.join(" ")}};var fu=class{type="api";name;config;logger;options;constructor(e,n,r={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),a=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let c=await a.json();return this.extractTokenCount(c)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out"):n}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`)}}};var Rr=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new ws("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new ws(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new du(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new fu(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var p_=require("tiktoken");var nf=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},hu=new nf(100);var yu=require("fs/promises"),Cu=require("fs/promises"),_u=require("path"),ko=require("@wengine-ai/claude-code-router-shared");Gn();var Fn=require("fs"),sf=require("path"),l_=require("@wengine-ai/claude-code-router-shared"),rf=(0,sf.join)(l_.HOME_DIR,"runtime"),of=(0,sf.join)(rf,"quota-store.json"),So=new Map,u_=!1,ID=null;function pu(t,e){t&&So.set(t,{...e,provider:t,capturedAt:Date.now()})}function mu(t){let e=So.get(t);return e?{...e}:void 0}function d_(){return Array.from(So.values()).map(t=>({...t}))}function ND(){try{if(!(0,Fn.existsSync)(of))return;let t=JSON.parse((0,Fn.readFileSync)(of,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>1440*60*1e3)continue;So.set(n.provider,n)}}catch{}}function c_(){try{if(So.size===0)return;(0,Fn.existsSync)(rf)||(0,Fn.mkdirSync)(rf,{recursive:!0}),(0,Fn.writeFileSync)(of,JSON.stringify(Array.from(So.values()),null,2),"utf-8")}catch{}}function gu(){u_||(u_=!0,ND(),ID=setInterval(c_,6e4),process.on("exit",c_))}mi();var In=(0,p_.get_encoding)("cl100k_base"),uf=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=In.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=In.encode(s.text).length:s.type==="tool_use"?r+=In.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=In.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=In.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=In.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=In.encode(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=In.encode(o.name+o.description).length),o.input_schema&&(r+=In.encode(JSON.stringify(o.input_schema)).length)}),r},m_=async(t,e)=>{if(t.sessionId){let n=await cf(t.sessionId);if(n){let r=(0,_u.join)(ko.HOME_DIR,n,"config.json"),o=(0,_u.join)(ko.HOME_DIR,n,`${t.sessionId}.json`);try{let s=JSON.parse(await(0,yu.readFile)(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await(0,yu.readFile)(r,"utf8"));if(s&&s.Router)return s.Router}catch{}}}};function bu(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function g_(t){let e=bu(t),n=e.includes("[1m]")||e.endsWith("[1m"),r=e.replace(/\[1m\]|\[1m$/g,""),o=r.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:n};let s=r.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||r.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:n}:{family:null,extended:n}}function BD(t,e){if(!e||!t)return null;let n=bu(t);if(e[t])return e[t];if(e[n])return e[n];let{family:r}=g_(t);if(r&&e[r])return e[r];for(let[o,s]of Object.entries(e)){let a=bu(o);if(a&&n.includes(a))return s}return null}function y_(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function f_(t){if(!t?.includes(","))return null;let[e,...n]=t.split(","),r=e.trim(),o=n.join(",").trim();return!r||!o?null:{providerName:r,routeModel:o}}function st(t,e,n,r){let o=f_(t);if(!o)return t;let{providerName:s,routeModel:a}=o,c=e.find(f=>f.name.toLowerCase()===s.toLowerCase());if(c&&c.enabled===!1)return null;if(r&&!n){let f=jo(),p=f.getPromotion(s,a,r,e);if(p){let g=f_(p);if(g){let _=e.find(b=>b.name.toLowerCase()===g.providerName.toLowerCase()),C=_?.models?.find(b=>String(b).toLowerCase()===g.routeModel.toLowerCase());if(_&&C)return`${_.name},${C}`}f.clear(s,a,r)}}if(!n&&!Ge().isAvailable(s,a))return null;let l=mu(s);if(l){let f=l.limitDaily!==void 0&&l.usedDailyBalance!==void 0&&l.usedDailyBalance>=l.limitDaily,p=l.totalBalance!==void 0&&l.usedBalance!==void 0&&l.usedBalance>=l.totalBalance;if(f||p)return null}let d=c?.models?.find(f=>String(f).toLowerCase()===a.toLowerCase());return c&&d?`${c.name},${d}`:t}function Qt(t,e,n,r,o){let s=Ge(),a=[n?.[t],r?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let d=st(l,e);if(d)return d}return null}function MD(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(n=>n.type==="image"||n.type==="image_url"||Array.isArray(n?.content)&&n.content.some(r=>r.type==="image"||r.type==="image_url")))}function LD(t){let e=bu(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(r=>r.test(e))}function jD(t,e,n,r,o,s,a){let c=n.longContextThreshold||6e4,l=Math.max(e,y_(o)),d=t.modelFamily;if((s||l>2e5)&&n.extendedContext){let _=st(n.extendedContext,r,!1,"extendedContext");if(_)return t.log.info(`Family: using extended context model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:_,scenarioType:"extendedContext",isFallback:!1};let C=Qt("extendedContext",r,n.fallback,a,d);if(C)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:C,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(l>c&&(n.longContext||n.fallback?.longContext?.length||a?.longContext?.length)){let _=n.longContext?st(n.longContext,r,!1,"longContext"):null;if(_)return t.log.info(`Family: using long context model, tokens: ${l}, estimated: ${e}`),{model:_,scenarioType:"longContext",isFallback:!1};let C=Qt("longContext",r,n.fallback,a,d);if(C)return t.log.info(`Family: using long context fallback model, tokens: ${l}, estimated: ${e}`),{model:C,scenarioType:"longContext",isFallback:!0};t.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(t.body.tools)&&t.body.tools.some(_=>_.type?.startsWith("web_search"))&&n.webSearch){let _=st(n.webSearch,r,!1,"webSearch");if(_)return{model:_,scenarioType:"webSearch",isFallback:!1};let C=Qt("webSearch",r,n.fallback,a,d);if(C)return t.log.info("Family: using webSearch fallback model"),{model:C,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&n.think){let _=st(n.think,r,!1,"think");if(_)return{model:_,scenarioType:"think",isFallback:!1};let C=Qt("think",r,n.fallback,a,d);if(C)return t.log.info("Family: using think fallback model"),{model:C,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(n.default){let _=st(n.default,r,!1,"default");if(_)return{model:_,scenarioType:"default",isFallback:!1};let C=Qt("default",r,n.fallback,a,d);if(C)return t.log.info("Family: using default fallback model"),{model:C,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var $D=async(t,e,n,r)=>{let o=await m_(t,n),s=n.get("providers")||[],a=o||n.get("Router"),c=n.get("fallback");if(t.body.model.includes(",")){let m=st(t.body.model,s,!1,"default");if(m)return{model:m,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let k=Qt("default",s,void 0,c);if(k)return t.log.info(`Using fallback for explicit model: ${k}`),{model:k,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:l,extended:d}=g_(t.body.model),f=a?.families?.[l||""];if(f&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${l}${d?" (1M)":""}`),t.modelFamily=l,t.familyFallback=f.fallback;let m=jD(t,e,f,s,r,d,c);if(m)return{model:m.model,scenarioType:m.scenarioType}}let p=BD(t.body.model,a?.models);if(p){let m=st(p,s,!1,"modelMapping");if(m)return t.log.info(`Using mapped model for ${t.body.model}: ${p}`),{model:m,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${p} unavailable (fail pool), skipping`)}let g=Math.max(e,y_(r)),_=a?.extendedContextThreshold||2e5;if(g>_&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${g}, estimated: ${e}, threshold: ${_}`);let m=st(a.extendedContext,s,!1,"extendedContext");if(m)return{model:m,scenarioType:"extendedContext"};t.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let k=Qt("extendedContext",s,void 0,c);if(k)return{model:k,scenarioType:"extendedContext"}}let C=a?.longContextThreshold||6e4;if(g>C&&a?.longContext){t.log.info(`Using long context model due to token count: ${g}, estimated: ${e}, threshold: ${C}`);let m=st(a.longContext,s,!1,"longContext");if(m)return{model:m,scenarioType:"longContext"};t.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let k=Qt("longContext",s,void 0,c);if(k)return{model:k,scenarioType:"longContext"}}if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let m=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(m)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${m[1]}</CCR-SUBAGENT-MODEL>`,""),{model:m[1],scenarioType:"default"}}let y=n.get("Router");if(t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&y?.background){t.log.info(`Using background model for ${t.body.model}`);let m=st(y.background,s,!1,"background");if(m)return{model:m,scenarioType:"background"};t.log.warn(`Background model ${y.background} unavailable (fail pool), falling through`)}if(Array.isArray(t.body.tools)&&t.body.tools.some(m=>m.type?.startsWith("web_search"))&&a?.webSearch){let m=st(a.webSearch,s,!1,"webSearch");if(m)return{model:m,scenarioType:"webSearch"};t.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let k=Qt("webSearch",s,void 0,c);if(k)return{model:k,scenarioType:"webSearch"}}if(t.body.thinking&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let m=st(a.think,s,!1,"think");if(m)return{model:m,scenarioType:"think"};t.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let k=Qt("think",s,void 0,c);if(k)return{model:k,scenarioType:"think"}}if(a?.default){let m=st(a.default,s,!1,"default");if(m)return{model:m,scenarioType:"default"};t.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let k=Qt("default",s,void 0,c);if(k)return{model:k,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},wu=async(t,e,n)=>{let{configService:r,event:o}=n;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let _=t.body.metadata.user_id.split("_session_");_.length>1&&(t.sessionId=_[1])}let a=await m_(t,r)||r.get("Router"),c=r.get("providers")||[],l=hu.get(t.sessionId),{messages:d,system:f=[],tools:p}=t.body,g=r.get("REWRITE_SYSTEM_PROMPT");if(g&&f.length>1&&f[1]?.text?.includes("<env>")){let _=await(0,yu.readFile)(g,"utf-8");f[1].text=`${_}<env>${f[1].text.split("<env>").pop()}`}try{let[_,C]=t.body.model.split(","),b=n.tokenizerService?.getTokenizerConfigForModel(_,C),y;n.tokenizerService?y=(await n.tokenizerService.countTokens({messages:d,system:f,tools:p},b)).tokenCount:y=uf(d,f,p),t.tokenCount=y;let m,k=r.get("CUSTOM_ROUTER_PATH");if(k)try{m=await require(k)(t,r.getAll(),{event:o})}catch(w){t.log.error(`failed to load custom router: ${w.message}`)}if(m)t.scenarioType="default";else{let w=await $D(t,y,r,l);m=w.model,t.scenarioType=w.scenarioType}if(a?.image&&m!==a.image&&MD(t)&&!LD(m)){let w=st(a.image,c,!1,"image");w?(t.log.info(`Using image model fallback for ${m}`),m=w,t.scenarioType="image"):(t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${m}`),t.scenarioType="image")}t.body.model=m}catch(_){t.log.error(`Error in router middleware: ${_.message}`),t.body.model=a?.default,t.scenarioType="default"}},Nn=new Map,h_=1e3;function af(){if(Nn.size<=h_)return;let t=[...Nn.keys()].slice(0,Nn.size-h_);for(let e of t)Nn.delete(e)}var cf=async t=>{if(Nn.has(t)){let e=Nn.get(t);return!e||e===""?null:e}try{let e=await(0,Cu.opendir)(ko.CLAUDE_PROJECTS_DIR),n=[];for await(let s of e)s.isDirectory()&&n.push(s.name);let r=n.map(async s=>{let a=(0,_u.join)(ko.CLAUDE_PROJECTS_DIR,s,`${t}.jsonl`);try{return(await(0,Cu.stat)(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(r);for(let s of o)if(s)return Nn.set(t,s),af(),s;return Nn.set(t,""),af(),null}catch(e){return console.error("Error searching for project by session:",e),Nn.set(t,""),af(),null}};Gn();var Bn=class{async fetchJson(e,n,r,o,s){let a=s||n.apiKey;if(!a)return null;let c={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(r)};if(o)try{let{ProxyAgent:l}=await import("undici");c.dispatcher=new l(new URL(o).toString())}catch{}try{let l=await fetch(e,c);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},lf=class extends Bn{async queryQuota(e,n,r){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,n,r),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>ye(l?.total_balance)!==void 0);if(!a)return null;let c=ye(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},df=class extends Bn{async queryQuota(e,n,r){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,n,r))?.data;if(!s||typeof s!="object")return null;let a={},c=ye(s.limit),l=ye(s.limit_remaining),d=ye(s.usage),f=ye(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),d!==void 0&&(a.usedBalance=d),f!==void 0&&(a.usedDailyBalance=f),this.hasQuotaData(a)?a:null}},ff=class extends Bn{async queryQuota(e,n,r){let o=VD(e.baseUrl),a=(await this.fetchJson(o,e,n,r))?.data;if(!a||typeof a!="object")return null;let c={},l=ye(a.totalBalance),d=ye(a.balance);return l!==void 0&&(c.totalBalance=l),d!==void 0&&(c.remainingBalance=d),l!==void 0&&d!==void 0&&(c.usedBalance=Math.max(0,l-d)),this.hasQuotaData(c)?c:null}},hf=class extends Bn{async queryQuota(e,n,r){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let c=await a.json(),l=Array.isArray(c?.data?.limits)?c.data.limits:[],d=null,f=null,p=null;for(let _ of l)_.type==="TOKENS_LIMIT"?_.unit===3?d=_:_.unit===6?f=_:d||(d=_):_.type==="TIME_LIMIT"&&(p=_);let g={};if(d){let _=ye(d.currentValue),C=ye(d.usage),b=ye(d.remaining),y=ye(d.percentage);_!==void 0?g.usedDailyBalance=_:y!==void 0&&(g.usedDailyBalance=y,g.limitDaily=100),C!==void 0?g.limitDaily=C:_!==void 0&&b!==void 0&&(g.limitDaily=_+b),d.nextResetTime&&(g.resetTime=new Date(d.nextResetTime).toISOString())}if(f){let _=ye(f.currentValue),C=ye(f.usage),b=ye(f.remaining),y=ye(f.percentage);_!==void 0?g.usedBalance=_:y!==void 0&&(g.usedBalance=y,g.totalBalance=100),C!==void 0?g.totalBalance=C:_!==void 0&&b!==void 0&&(g.totalBalance=_+b),f.nextResetTime&&!g.resetTime&&(g.resetTime=new Date(f.nextResetTime).toISOString())}if(p){if(g.usedDailyBalance===void 0){let _=ye(p.currentValue);_!==void 0&&(g.usedDailyBalance=_)}if(g.limitDaily===void 0){let _=ye(p.usage),C=ye(p.currentValue),b=ye(p.remaining);_!==void 0?g.limitDaily=_:C!==void 0&&b!==void 0&&(g.limitDaily=C+b)}p.nextResetTime&&!g.resetTime&&(g.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(g)?g:null}catch{return null}}},pf=class extends Bn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let o={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{let c=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...o,body:a});if(!c.ok)return null;let d=(await c.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(d)||d.length===0)return null;let f=d[0]?.codingPlanQuotaInfo;if(!f)return null;let p={},g=ye(f.per5HourUsedQuota),_=ye(f.per5HourTotalQuota);g!==void 0&&(p.usedDailyBalance=g),_!==void 0&&(p.limitDaily=_);let C=ye(f.perWeekUsedQuota),b=ye(f.perWeekTotalQuota);return C!==void 0&&(p.usedBalance=C),b!==void 0&&(p.totalBalance=b),this.hasQuotaData(p)?p:null}catch{return null}}},mf=class extends Bn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let c=await a.json(),l={},d=Array.isArray(c?.limits)?c.limits:[];if(d.length>0&&d[0]?.detail){let p=d[0].detail,g=ye(p.limit),_=ye(p.remaining),C=p.resetTime;g!==void 0&&_!==void 0&&(l.usedDailyBalance=Math.max(0,g-_),l.limitDaily=g),C&&(l.resetTime=new Date(C).toISOString())}let f=c?.usage;if(f){let p=ye(f.limit),g=ye(f.remaining),_=ye(f.used),C=f.resetTime;p!==void 0&&(l.totalBalance=p,_!==void 0?l.usedBalance=_:g!==void 0&&(l.usedBalance=Math.max(0,p-g),l.remainingBalance=g)),C&&(l.resetTime7d=new Date(C).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},gf=class extends Bn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=yf(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let c=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let A of c)if(l=await this.fetchJson(A,e,n,r,o.trim()),l)break;if(!l)return null;if(l?.base_resp){let A=l.base_resp.status_code;if(A!==void 0&&A!==0)return null}let d=Array.isArray(l?.model_remains)?l.model_remains:[];if(d.length===0)return null;let f=d[0],p={},g=ye(f.current_interval_total_count),_=ye(f.current_interval_usage_count),C=ye(f.current_interval_remaining_percent),b=ye(f.end_time);g!==void 0&&_!==void 0&&g>0?(p.usedDailyBalance=Math.max(0,g-_),p.limitDaily=g):C!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-C)),b&&(p.resetTime=new Date(b).toISOString());let y=ye(f.current_weekly_total_count),m=ye(f.current_weekly_usage_count),k=ye(f.current_weekly_remaining_percent),w=ye(f.weekly_end_time);return y!==void 0&&m!==void 0&&y>0?(p.usedBalance=Math.max(0,y-m),p.remainingBalance=m,p.totalBalance=y):k!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-k),p.remainingBalance=k),w&&!p.resetTime&&(p.resetTime=new Date(w).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},UD=new lf,qD=new df,HD=new ff,zD=new hf,WD=new pf,GD=new mf,JD=new gf;function Eu(t){let e=yf(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?GD:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?JD:e==="deepseek.com"||e.endsWith(".deepseek.com")?UD:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?qD:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?HD:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?zD:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?WD:null:null}function VD(t){let e=yf(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function yf(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function ye(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t!="string")return;let e=t.trim().replace(/,/g,"");if(!e)return;let n=Number(e);return Number.isFinite(n)?n:void 0}var KD={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function YD(t){return t===!0||t==="true"||t===1||t==="1"}function QD(t){let e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`}function XD(t){try{let e=new URL(t),n=e.pathname;return n.endsWith("/v1/messages")?n=n.slice(0,-12):n.endsWith("/messages")?n=n.slice(0,-9):n.endsWith("/v1/chat/completions")?n=n.slice(0,-20):n.endsWith("/chat/completions")&&(n=n.slice(0,-17)),n.endsWith("/v1")||(n=n.endsWith("/")?`${n}v1`:`${n}/v1`),e.pathname=`${n}/models`,e.toString()}catch{return null}}function ZD(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function _f(t,e,n){let r=XD(t.baseUrl);if(!r)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let o={method:"GET",headers:{Authorization:`Bearer ${t.apiKey}`},signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(n).toString())}catch{}let s=await fetch(r,o);if(s.headers&&Uo(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===429)return{success:!1,error:`HTTP 429: ${(await s.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:s.headers};if(s.status>=400&&s.status<500)return{success:!0,headers:s.headers};let a=await s.text().catch(()=>"");return{success:!1,error:`HTTP ${s.status}: ${a.slice(0,100)}`,headers:s.headers}}catch(o){return{success:!1,error:o?.message||o?.toString()||"Unknown probe error"}}}async function eR(t,e,n,r){let o=t.wakeupModel||(Array.isArray(t.models)?t.models[0]:void 0);if(!o)return{success:!1,error:"No models configured for provider"};let s=t.baseUrl.includes("anthropic")||o.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:o,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(n).toString())}catch{}r?.info(`Sending scheduled wake-up call to provider ${t.name} using model ${o}...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown wake-up error"}}}async function tR(t,e,n,r,o){let s=t.baseUrl.includes("anthropic")||e.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:e,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(r).toString())}catch{}o?.debug?.(`Sending independent ping to rate-limited model ${t.name} (${e})...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown ping error"}}}var Ts=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,n,r,o,s){this.config={...KD,...n},this.getProviders=e,this.getHttpsProxy=r,this.logger=o,this.getConfig=s}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&!this.config.excludeProviders.includes(a.name)),n=this.getHttpsProxy?.(),r=Ge();if(e.length===0)return;let o=[];for(let a of e){let c=Eu(a.baseUrl),l=Array.isArray(a.models)?a.models:[];c&&o.push({provider:a.name,models:l,type:"quota-adapter",promise:c.queryQuota(a,this.config.probeTimeoutMs,n).then(d=>{if(d){pu(a.name,d),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let f=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,p=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(f||p){let g=f?`Quota exhausted: 5h limit reached (${d.usedDailyBalance}/${d.limitDaily})`:`Quota exhausted: 7d balance depleted (${d.usedBalance}/${d.totalBalance})`;for(let _ of l){if(r.getState(a.name,_)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${a.name} (${_}): already rate-limited with active cooldown`);continue}r.forceOpen(a.name,_,g)}this.logger?.warn?.(`${g} for ${a.name}, marked as unhealthy`)}else for(let g of l){let _=r.getState(a.name,g);_&&_.status==="open"&&_.lastError?.includes("Quota exhausted")&&(r.recover(a.name,g),this.logger?.info?.(`Quota recovered for ${a.name} (${g}), marked as healthy`))}}})}),ZD(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:_f(a,this.config.probeTimeoutMs,n).then(()=>{})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let s=await Promise.allSettled(o.map(a=>a.promise));for(let a=0;a<o.length;a++){let c=s[a];if(c.status==="rejected"){let l=o[a];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${c.reason}`)}}}async runHealthProbe(){let e=Ge(),n=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(n.length===0)return;this.logger?.debug?.(`Running health probe for ${n.length} providers`);let o=await Promise.allSettled(n.map(s=>_f(s,this.config.probeTimeoutMs,r)));for(let s=0;s<n.length;s++){let a=n[s],c=o[s],l=Array.isArray(a.models)?a.models:[];if(c.status==="fulfilled"){let d=c.value;if(d.success){let f=0;for(let p of l){let g=e.getState(a.name,p);if(g&&g.status==="open"){let _=g.lastError?.includes("Quota exhausted"),C=g.rateLimitUntil||g.lastError&&(g.lastError.includes("429")||g.lastError.toLowerCase().includes("rate limit")||g.lastError.toLowerCase().includes("rate_limit")||g.lastError.toLowerCase().includes("too many requests")||g.lastError.toLowerCase().includes("\u9650\u6D41"));if(_){this.logger?.debug?.(`Skipping health probe recovery for ${a.name} (${p}) because quota is exhausted`);continue}if(C||g.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${a.name} (${p})`);continue}}e.recordSuccess(a.name,p),f++}f>0&&this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let f of l)e.recordFailure(a.name,f,d.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${d.error}`)}}else{for(let d of l)e.recordFailure(a.name,d,c.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${c.reason}`)}}}async runRateLimitProbe(){let e=Ge(),n=e.getRateLimitedModels();if(n.length===0)return;let r=this.getProviders(),o=this.getHttpsProxy?.(),s=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${n.length} model(s)`);for(let a of n){let[c,...l]=a.split(","),d=l.join(",");if(!c||!d)continue;let f=e.getState(c,d);if(!f||!f.rateLimitUntil)continue;if(Date.now()>=f.rateLimitUntil){e.recover(c,d),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${a}`);continue}let p=r.find(g=>g?.name===c&&g.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${c} not found or disabled for rate-limit probe`);continue}try{let g=await tR(p,d,s,o,this.logger);if(g.success)this.logger?.info?.(`Rate-limit probe succeeded for ${a}, recovering model`),e.recover(c,d);else if(g.error&&(g.error.includes("429")||g.error.toLowerCase().includes("rate limit")||g.error.toLowerCase().includes("rate_limit")||g.error.toLowerCase().includes("too many requests")||g.error.toLowerCase().includes("\u9650\u6D41"))){let _=Date.now();f.rateLimitUntil&&f.rateLimitUntil>_?f.rateLimitUntil+=120*1e3:f.rateLimitUntil=_+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${a} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${a} returned non-rate-limit error: ${g.error?.slice(0,100)}`)}catch(g){this.logger?.warn?.(`Rate-limit probe exception for ${a}: ${g?.message||g}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let n=new Date,r=n.getHours(),o=n.getMinutes(),s=QD(n),a=this.getHttpsProxy?.(),c=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let d=l.wakeupTime||c,[f,p]=d.split(":"),g=parseInt(f,10),_=parseInt(p,10);if(isNaN(g)||isNaN(_))continue;let C=r>g||r===g&&o>=_,b=(g*60+_)*6e4-(r*60+o)*6e4,y=b>0&&b<=300*1e3;(C||y)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${d}`),eR(l,3e4,a,this.logger).then(m=>{m.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${m.error}`)}).catch(m=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${m}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?YD(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,n){return this.lastWakeupDate.get(e)===n?!0:(this.lastWakeupDate.set(e,n),!1)}async probeProviderManually(e){let r=this.getProviders().find(c=>c.name===e);if(!r)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(r.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let o=this.getHttpsProxy?.(),s=await _f(r,this.config.probeTimeoutMs,o),a=Array.isArray(r.models)?r.models:[];if(s.success)for(let c of a)Ge().recordSuccess(r.name,c);else for(let c of a)Ge().recordFailure(r.name,c,s.error);return s.success}},rr=null;function bf(t,e,n,r,o){return rr||(rr=new Ts(t,e,n,r,o)),rr}function Au(t,e,n,r,o){let s=bf(t,e,n,r,o);return s.start(),s}function Su(){rr&&rr.stop()}function __(){rr&&(rr.stop(),rr=null)}Gn();var Cf=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},wf=new Cf;var D_=Oe(A_(),1);var xr=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
391
+ `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},Hv=qv,zv=class extends Pn{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(e=>e.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},Wv=zv,Gv=class extends Pn{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>e_(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},Jv=Gv,Vv=class extends Pn{normalize(t){let e=uu(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},Kv=Vv,Yv=class extends Pn{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},cu=Yv,Qv=class extends cu{constructor(){super(...arguments),this.form="NFC"}},Xv=Qv,Zv=class extends cu{constructor(){super(...arguments),this.form="NFD"}},eT=Zv,tT=class extends cu{constructor(){super(...arguments),this.form="NFKC"}},nT=tT,rT=class extends cu{constructor(){super(...arguments),this.form="NFKD"}},oT=rT,sT=class extends Pn{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},iT=sT,aT=class extends Pn{normalize(t){return Z0(t)}},uT=aT,cT=class extends Pn{normalize(t){return t.toLowerCase()}},lT=cT,dT=class extends Pn{normalize(t){return t=this.config.prepend+t,t}},fT=dT;function hT(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new Hv(t);case"Precompiled":return new Wv(t);case"Sequence":return new Jv(t);case"Replace":return new Kv(t);case"NFC":return new Xv(t);case"NFD":return new eT(t);case"NFKC":return new nT(t);case"NFKD":return new oT(t);case"Strip":return new iT(t);case"StripAccents":return new uT(t);case"Lowercase":return new lT(t);case"Prepend":return new fT(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var e_=hT,pT=class extends As{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},dn=pT,mT=class extends dn{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=X0,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(n=>Array.from(this.text_encoder.encode(n),r=>this.byte_encoder[r]).join(""))}},gT=mT,yT=class extends dn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},_T=yT,bT=class extends dn{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},CT=bT,wT=class extends dn{constructor(t){super(),this.config=t,this.pattern=uu(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):Lv(t,this.pattern)}},ET=wT,AT=class extends dn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Es}]+|[${Es}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},ST=AT,kT=class extends dn{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},vT=kT,TT=class extends dn{constructor(){super(),this.pattern=new RegExp(`[^\\s${Es}]+|[${Es}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},DT=TT,RT=class extends dn{constructor(t){super(),this.config=t,this.pattern=uu(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},xT=RT,OT=class extends dn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>t_(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},PT=OT,FT=class extends dn{pre_tokenize_text(t){return jv(t)}},IT=FT;function NT(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new DT;case"Sequence":return new PT(t);case"Whitespace":return new _T;case"WhitespaceSplit":return new IT;case"Metaspace":return new CT(t);case"ByteLevel":return new gT(t);case"Split":return new ET(t);case"Punctuation":return new ST(t);case"Digits":return new vT(t);case"Replace":return new xT(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var t_=NT,BT=class extends As{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=Fv(e,this.tokens_to_ids,this.unk_token_id)),e}convert_tokens_to_ids(t){return t.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(e=>this.vocab[Number(e)]??this.unk_token)}},lu=BT,MT=class extends lu{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=tf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<r.length;){let c=r.length,l=null;for(;s<c;){let d=r.slice(s,c).join("");if(s>0&&(d=this.config.continuing_subword_prefix+d),this.tokens_to_ids.has(d)){l=d;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},V0=MT,K0=class n_{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new n_(!1,new Map)}},LT=class{constructor(){this.root=K0.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=K0.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},jT=LT,Zd=class r_{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new r_(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},$T=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Zd(this.bos_token_id??0,0,0,0,0),o=new Zd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new Zd(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let s of this.begin_nodes[e]){s.prev=null;let a=0,c=null;for(let l of this.end_nodes[e]){let d=l.backtrace_score+s.score;(c===null||d>a)&&(c=l.clone(),a=d)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let n=[],r=this.begin_nodes[t][0].prev;if(r===null)return[];let o=r.clone();for(;o.prev!==null;)n.push(o.clone()),o=o.clone().prev.clone();return n.reverse(),n}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},UT=$T;function qT(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var HT=class extends lu{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=qT(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new jT,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],a=e.slice(r).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let d=this.tokens_to_ids.get(l),f=this.scores[d],p=Bv(l);t.insert(r,p,f,d),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new UT(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},Y0=HT,zT=class{constructor(t=(n,r)=>n>r,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},WT=zT,GT=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},JT=GT,VT=class extends lu{constructor(t){super(t),this.tokens_to_ids=tf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new JT(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new WT((c,l)=>c.score<l.score),s={token:n[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<n.length;++c){let l={bias:c/n.length,token:n[c],prev:a,next:null};a.next=l,this.add_node(o,a),a=l}for(;!o.is_empty();){let c=o.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let d={...c.prev};c.prev.deleted=!0,c.prev=d,d.prev?d.prev.next=d:s=d}let l={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};l.prev?(l.prev.next=l,this.add_node(o,l.prev)):s=l,l.next&&(l.next.prev=l,this.add_node(o,l))}for(let c=s;c!==null;c=c.next)r.push(c.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(a=>this.tokens_to_ids.has(a))?e.push(...s):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},Q0=VT,KT=class extends lu{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=tf(e.target_lang?n[e.target_lang]:n),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},YT=KT;function QT(t,e){switch(t.type){case"WordPiece":return new V0(t);case"Unigram":return new Y0(t,e.eos_token);case"BPE":return new Q0(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Y0(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new Q0(t):new V0(t):new YT(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var XT=QT,ZT=class extends As{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Ss=ZT,eD=class extends Ss{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of r)"SpecialToken"in a?n&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Nt(o,t),s=Nt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Nt(o,e),s=Nt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},tD=eD,nD=class extends Ss{post_process(t,e=null){return{tokens:e?Nt(t,e):t}}},rD=nD,oD=class extends Ss{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=Nt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=Nt(t,o,e,s),r=Nt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},sD=oD,iD=class extends Ss{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=Nt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=Nt(t,o,e,s),r=Nt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},aD=iD,uD=class extends Ss{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>o_(e))}post_process(t,e=null,n=!0){let r={tokens:t};for(let o of this.processors)r=o.post_process(r.tokens,e,n);return r}},cD=uD;function lD(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new tD(t);case"ByteLevel":return new rD(t);case"BertProcessing":return new sD(t);case"RobertaProcessing":return new aD(t);case"Sequence":return new cD(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var o_=lD,dD=class extends As{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},fn=dD,fD=class extends fn{constructor(t){super(t),this.byte_decoder=xv,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},hD=fD,pD=class extends fn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=ef(e)),e})}},mD=pD,gD=class extends fn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},yD=gD,_D=class extends fn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},bD=_D,CD=class extends fn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let r=1;r<t.length;++r)t[r]!==e.at(-1)&&e.push(t[r]);let n=e.filter(r=>r!==this.pad_token).join("");return this.cleanup&&(n=ef(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(t){return[this.convert_tokens_to_string(t)]}},wD=CD,ED=class extends fn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>s_(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},AD=ED,SD=class extends fn{decode_chain(t){let e=uu(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},kD=SD,vD=class extends fn{decode_chain(t){return[t.join("")]}},TD=vD,DD=class extends fn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o)n=o+1;let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},RD=DD,xD=class extends fn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},OD=xD;function PD(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new hD(t);case"WordPiece":return new mD(t);case"Metaspace":return new yD(t);case"BPEDecoder":return new bD(t);case"CTC":return new wD(t);case"Sequence":return new AD(t);case"Replace":return new kD(t);case"Fuse":return new TD(t);case"Strip":return new RD(t);case"ByteFallback":return new OD(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var s_=PD,FD=class{constructor(t,e){let n=J0(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=J0(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=e_(this.tokenizer.normalizer),this.pre_tokenizer=t_(this.tokenizer.pre_tokenizer),this.model=XT(this.tokenizer.model,this.config),this.post_processor=o_(this.tokenizer.post_processor),this.decoder=s_(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new Dv(o);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}),(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new vv(this.added_tokens.map(o=>o.content)),this.added_tokens_map=new Map(this.added_tokens.map(o=>[o.content,o])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return r&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!Nv(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=ef(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=Mv(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(n,{section_index:r}):[n];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:Nt(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}},i_=FD;var du=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||(0,ks.join)((0,a_.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,ks.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,ks.join)(e,"tokenizer.json"),tokenizerConfig:(0,ks.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,Ao.existsSync)(e)||(0,Ao.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,Ao.existsSync)(e.tokenizerJson)||!(0,Ao.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([vs.promises.readFile(e.tokenizerJson,"utf-8"),vs.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[c,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([vs.promises.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),vs.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let n=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new i_(n.tokenizerJson,n.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let a of r)if(typeof a.content=="string")n.push(a.content);else if(Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?n.push(c.text):c.type==="tool_use"&&c.input?n.push(JSON.stringify(c.input)):c.type==="tool_result"&&n.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")n.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&n.push(c)}}if(s)for(let a of s)a.name&&n.push(a.name),a.description&&n.push(a.description),a.input_schema&&n.push(JSON.stringify(a.input_schema));return n.join(" ")}};var fu=class{type="api";name;config;logger;options;constructor(e,n,r={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),a=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let c=await a.json();return this.extractTokenCount(c)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out"):n}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`)}}};var Rr=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new ws("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new ws(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new du(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new fu(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var p_=require("tiktoken");var nf=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},hu=new nf(100);var yu=require("fs/promises"),Cu=require("fs/promises"),_u=require("path"),ko=require("@wengine-ai/claude-code-router-shared");Gn();var Fn=require("fs"),sf=require("path"),l_=require("@wengine-ai/claude-code-router-shared"),rf=(0,sf.join)(l_.HOME_DIR,"runtime"),of=(0,sf.join)(rf,"quota-store.json"),So=new Map,u_=!1,ID=null;function pu(t,e){t&&So.set(t,{...e,provider:t,capturedAt:Date.now()})}function mu(t){let e=So.get(t);return e?{...e}:void 0}function d_(){return Array.from(So.values()).map(t=>({...t}))}function ND(){try{if(!(0,Fn.existsSync)(of))return;let t=JSON.parse((0,Fn.readFileSync)(of,"utf-8"));if(!Array.isArray(t))return;let e=Date.now();for(let n of t)if(n&&n.provider){if(n.capturedAt&&e-n.capturedAt>1440*60*1e3)continue;So.set(n.provider,n)}}catch{}}function c_(){try{if(So.size===0)return;(0,Fn.existsSync)(rf)||(0,Fn.mkdirSync)(rf,{recursive:!0}),(0,Fn.writeFileSync)(of,JSON.stringify(Array.from(So.values()),null,2),"utf-8")}catch{}}function gu(){u_||(u_=!0,ND(),ID=setInterval(c_,6e4),process.on("exit",c_))}mi();var In=(0,p_.get_encoding)("cl100k_base"),uf=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=In.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=In.encode(s.text).length:s.type==="tool_use"?r+=In.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=In.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=In.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=In.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=In.encode(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=In.encode(o.name+o.description).length),o.input_schema&&(r+=In.encode(JSON.stringify(o.input_schema)).length)}),r},m_=async(t,e)=>{if(t.sessionId){let n=await cf(t.sessionId);if(n){let r=(0,_u.join)(ko.HOME_DIR,n,"config.json"),o=(0,_u.join)(ko.HOME_DIR,n,`${t.sessionId}.json`);try{let s=JSON.parse(await(0,yu.readFile)(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await(0,yu.readFile)(r,"utf8"));if(s&&s.Router)return s.Router}catch{}}}};function bu(t){let e=t||"";return e.includes(",")&&(e=e.split(",").pop()||e),e.includes("/")&&(e=e.split("/").pop()||e),e.includes(":")&&(e=e.split(":")[0]),e.trim().toLowerCase()}function g_(t){let e=bu(t),n=e.includes("[1m]")||e.endsWith("[1m"),r=e.replace(/\[1m\]|\[1m$/g,""),o=r.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:n};let s=r.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||r.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:n}:{family:null,extended:n}}function BD(t,e){if(!e||!t)return null;let n=bu(t);if(e[t])return e[t];if(e[n])return e[n];let{family:r}=g_(t);if(r&&e[r])return e[r];for(let[o,s]of Object.entries(e)){let a=bu(o);if(a&&n.includes(a))return s}return null}function y_(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function f_(t){if(!t?.includes(","))return null;let[e,...n]=t.split(","),r=e.trim(),o=n.join(",").trim();return!r||!o?null:{providerName:r,routeModel:o}}function st(t,e,n,r,o){let s=f_(t);if(!s)return t;let{providerName:a,routeModel:c}=s,l=e.find(p=>p.name.toLowerCase()===a.toLowerCase());if(l&&l.enabled===!1)return null;if(o===!0&&r&&!n){let p=jo(),m=p.getPromotion(a,c,r,e);if(m){let b=f_(m);if(b){let C=e.find(_=>_.name.toLowerCase()===b.providerName.toLowerCase()),y=C?.models?.find(_=>String(_).toLowerCase()===b.routeModel.toLowerCase());if(C&&y)return`${C.name},${y}`}p.clear(a,c,r)}}if(!n&&!Ge().isAvailable(a,c))return null;let d=mu(a);if(d){let p=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,m=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(p||m)return null}let f=l?.models?.find(p=>String(p).toLowerCase()===c.toLowerCase());return l&&f?`${l.name},${f}`:t}function Qt(t,e,n,r,o){let s=Ge(),a=[n?.[t],r?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let d=st(l,e);if(d)return d}return null}function MD(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(n=>n.type==="image"||n.type==="image_url"||Array.isArray(n?.content)&&n.content.some(r=>r.type==="image"||r.type==="image_url")))}function LD(t){let e=bu(t);return[/claude/i,/gemini/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-vision/i,/qwen.*vl/i,/glm-4v/i,/grok.*vision/i,/pixtral/i,/llava/i].some(r=>r.test(e))}function jD(t,e,n,r,o,s,a,c){let l=n.longContextThreshold||6e4,d=Math.max(e,y_(o)),f=t.modelFamily;if((s||d>2e5)&&n.extendedContext){let C=st(n.extendedContext,r,!1,"extendedContext",c);if(C)return t.log.info(`Family: using extended context model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:C,scenarioType:"extendedContext",isFallback:!1};let y=c?Qt("extendedContext",r,n.fallback,a,f):null;if(y)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${d}, estimated: ${e}, explicit: ${s}`),{model:y,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(d>l&&(n.longContext||n.fallback?.longContext?.length||a?.longContext?.length)){let C=n.longContext?st(n.longContext,r,!1,"longContext",c):null;if(C)return t.log.info(`Family: using long context model, tokens: ${d}, estimated: ${e}`),{model:C,scenarioType:"longContext",isFallback:!1};let y=c?Qt("longContext",r,n.fallback,a,f):null;if(y)return t.log.info(`Family: using long context fallback model, tokens: ${d}, estimated: ${e}`),{model:y,scenarioType:"longContext",isFallback:!0};t.log.warn("Family: no healthy longContext model available, falling through to other scenarios")}if(Array.isArray(t.body.tools)&&t.body.tools.some(C=>C.type?.startsWith("web_search"))&&n.webSearch){let C=st(n.webSearch,r,!1,"webSearch",c);if(C)return{model:C,scenarioType:"webSearch",isFallback:!1};let y=c?Qt("webSearch",r,n.fallback,a,f):null;if(y)return t.log.info("Family: using webSearch fallback model"),{model:y,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&n.think){let C=st(n.think,r,!1,"think",c);if(C)return{model:C,scenarioType:"think",isFallback:!1};let y=c?Qt("think",r,n.fallback,a,f):null;if(y)return t.log.info("Family: using think fallback model"),{model:y,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(n.default){let C=st(n.default,r,!1,"default",c);if(C)return{model:C,scenarioType:"default",isFallback:!1};let y=c?Qt("default",r,n.fallback,a,f):null;if(y)return t.log.info("Family: using default fallback model"),{model:y,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var $D=async(t,e,n,r)=>{let o=await m_(t,n),s=n.get("providers")||[],a=o||n.get("Router"),c=a?.enableFallback===!0,l=c?n.get("fallback"):void 0;if(t.body.model.includes(",")){let S=st(t.body.model,s,!1,"default",c);if(S)return{model:S,scenarioType:"default"};t.log.warn(`Explicit model ${t.body.model} unavailable (fail pool), trying fallback`);let w=c?Qt("default",s,void 0,l):null;if(w)return t.log.info(`Using fallback for explicit model: ${w}`),{model:w,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:d,extended:f}=g_(t.body.model),p=a?.families?.[d||""];if(p&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${d}${f?" (1M)":""}`),t.modelFamily=d,t.familyFallback=p.fallback;let S=jD(t,e,p,s,r,f,l,c);if(S)return{model:S.model,scenarioType:S.scenarioType}}let m=BD(t.body.model,a?.models);if(m){let S=st(m,s,!1,"modelMapping",c);if(S)return t.log.info(`Using mapped model for ${t.body.model}: ${m}`),{model:S,scenarioType:"modelMapping"};t.log.warn(`Mapped model ${m} unavailable (fail pool), skipping`)}let b=Math.max(e,y_(r)),C=a?.extendedContextThreshold||2e5;if(b>C&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${b}, estimated: ${e}, threshold: ${C}`);let S=st(a.extendedContext,s,!1,"extendedContext",c);if(S)return{model:S,scenarioType:"extendedContext"};t.log.warn(`Extended context model ${a.extendedContext} unavailable (fail pool), trying fallback`);let w=c?Qt("extendedContext",s,void 0,l):null;if(w)return{model:w,scenarioType:"extendedContext"}}let y=a?.longContextThreshold||6e4;if(b>y&&a?.longContext){t.log.info(`Using long context model due to token count: ${b}, estimated: ${e}, threshold: ${y}`);let S=st(a.longContext,s,!1,"longContext",c);if(S)return{model:S,scenarioType:"longContext"};t.log.warn(`Long context model ${a.longContext} unavailable (fail pool), trying fallback`);let w=c?Qt("longContext",s,void 0,l):null;if(w)return{model:w,scenarioType:"longContext"}}if(t.body?.system?.length>1&&t.body?.system[1]?.text?.startsWith("<CCR-SUBAGENT-MODEL>")){let S=t.body?.system[1].text.match(/<CCR-SUBAGENT-MODEL>(.*?)<\/CCR-SUBAGENT-MODEL>/s);if(S)return t.body.system[1].text=t.body.system[1].text.replace(`<CCR-SUBAGENT-MODEL>${S[1]}</CCR-SUBAGENT-MODEL>`,""),{model:S[1],scenarioType:"default"}}let g=n.get("Router");if(t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&g?.background){t.log.info(`Using background model for ${t.body.model}`);let S=st(g.background,s,!1,"background",c);if(S)return{model:S,scenarioType:"background"};t.log.warn(`Background model ${g.background} unavailable (fail pool), falling through`)}if(Array.isArray(t.body.tools)&&t.body.tools.some(S=>S.type?.startsWith("web_search"))&&a?.webSearch){let S=st(a.webSearch,s,!1,"webSearch",c);if(S)return{model:S,scenarioType:"webSearch"};t.log.warn(`WebSearch model ${a.webSearch} unavailable (fail pool), trying fallback`);let w=c?Qt("webSearch",s,void 0,l):null;if(w)return{model:w,scenarioType:"webSearch"}}if(t.body.thinking&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let S=st(a.think,s,!1,"think",c);if(S)return{model:S,scenarioType:"think"};t.log.warn(`Think model ${a.think} unavailable (fail pool), trying fallback`);let w=c?Qt("think",s,void 0,l):null;if(w)return{model:w,scenarioType:"think"}}if(a?.default){let S=st(a.default,s,!1,"default",c);if(S)return{model:S,scenarioType:"default"};t.log.warn(`Default model ${a.default} unavailable (fail pool), trying fallback`);let w=c?Qt("default",s,void 0,l):null;if(w)return{model:w,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},wu=async(t,e,n)=>{let{configService:r,event:o}=n;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let C=t.body.metadata.user_id.split("_session_");C.length>1&&(t.sessionId=C[1])}let a=await m_(t,r)||r.get("Router"),c=a?.enableFallback===!0,l=r.get("providers")||[],d=hu.get(t.sessionId),{messages:f,system:p=[],tools:m}=t.body,b=r.get("REWRITE_SYSTEM_PROMPT");if(b&&p.length>1&&p[1]?.text?.includes("<env>")){let C=await(0,yu.readFile)(b,"utf-8");p[1].text=`${C}<env>${p[1].text.split("<env>").pop()}`}try{let[C,y]=t.body.model.split(","),_=n.tokenizerService?.getTokenizerConfigForModel(C,y),g;n.tokenizerService?g=(await n.tokenizerService.countTokens({messages:f,system:p,tools:m},_)).tokenCount:g=uf(f,p,m),t.tokenCount=g;let S,w=r.get("CUSTOM_ROUTER_PATH");if(w)try{S=await require(w)(t,r.getAll(),{event:o})}catch(E){t.log.error(`failed to load custom router: ${E.message}`)}if(S)t.scenarioType="default";else{let E=await $D(t,g,r,d);S=E.model,t.scenarioType=E.scenarioType}if(a?.image&&S!==a.image&&MD(t)&&!LD(S)){let E=st(a.image,l,!1,"image",c);E?(t.log.info(`Using image model fallback for ${S}`),S=E,t.scenarioType="image"):(t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${S}`),t.scenarioType="image")}t.body.model=S}catch(C){t.log.error(`Error in router middleware: ${C.message}`),t.body.model=a?.default,t.scenarioType="default"}},Nn=new Map,h_=1e3;function af(){if(Nn.size<=h_)return;let t=[...Nn.keys()].slice(0,Nn.size-h_);for(let e of t)Nn.delete(e)}var cf=async t=>{if(Nn.has(t)){let e=Nn.get(t);return!e||e===""?null:e}try{let e=await(0,Cu.opendir)(ko.CLAUDE_PROJECTS_DIR),n=[];for await(let s of e)s.isDirectory()&&n.push(s.name);let r=n.map(async s=>{let a=(0,_u.join)(ko.CLAUDE_PROJECTS_DIR,s,`${t}.jsonl`);try{return(await(0,Cu.stat)(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(r);for(let s of o)if(s)return Nn.set(t,s),af(),s;return Nn.set(t,""),af(),null}catch(e){return console.error("Error searching for project by session:",e),Nn.set(t,""),af(),null}};Gn();var Bn=class{async fetchJson(e,n,r,o,s){let a=s||n.apiKey;if(!a)return null;let c={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${a}`},signal:AbortSignal.timeout(r)};if(o)try{let{ProxyAgent:l}=await import("undici");c.dispatcher=new l(new URL(o).toString())}catch{}try{let l=await fetch(e,c);return l.ok?await l.json():null}catch{return null}}hasQuotaData(e){return e.totalBalance!==void 0||e.usedBalance!==void 0||e.remainingBalance!==void 0||e.usedDailyBalance!==void 0||e.limitDaily!==void 0||e.resetTime!==void 0}},lf=class extends Bn{async queryQuota(e,n,r){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,n,r),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>ye(l?.total_balance)!==void 0);if(!a)return null;let c=ye(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},df=class extends Bn{async queryQuota(e,n,r){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,n,r))?.data;if(!s||typeof s!="object")return null;let a={},c=ye(s.limit),l=ye(s.limit_remaining),d=ye(s.usage),f=ye(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),d!==void 0&&(a.usedBalance=d),f!==void 0&&(a.usedDailyBalance=f),this.hasQuotaData(a)?a:null}},ff=class extends Bn{async queryQuota(e,n,r){let o=VD(e.baseUrl),a=(await this.fetchJson(o,e,n,r))?.data;if(!a||typeof a!="object")return null;let c={},l=ye(a.totalBalance),d=ye(a.balance);return l!==void 0&&(c.totalBalance=l),d!==void 0&&(c.remainingBalance=d),l!==void 0&&d!==void 0&&(c.usedBalance=Math.max(0,l-d)),this.hasQuotaData(c)?c:null}},hf=class extends Bn{async queryQuota(e,n,r){if(!e.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:e.apiKey.trim()},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",s);if(!a.ok)return null;let c=await a.json(),l=Array.isArray(c?.data?.limits)?c.data.limits:[],d=null,f=null,p=null;for(let b of l)b.type==="TOKENS_LIMIT"?b.unit===3?d=b:b.unit===6?f=b:d||(d=b):b.type==="TIME_LIMIT"&&(p=b);let m={};if(d){let b=ye(d.currentValue),C=ye(d.usage),y=ye(d.remaining),_=ye(d.percentage);b!==void 0?m.usedDailyBalance=b:_!==void 0&&(m.usedDailyBalance=_,m.limitDaily=100),C!==void 0?m.limitDaily=C:b!==void 0&&y!==void 0&&(m.limitDaily=b+y),d.nextResetTime&&(m.resetTime=new Date(d.nextResetTime).toISOString())}if(f){let b=ye(f.currentValue),C=ye(f.usage),y=ye(f.remaining),_=ye(f.percentage);b!==void 0?m.usedBalance=b:_!==void 0&&(m.usedBalance=_,m.totalBalance=100),C!==void 0?m.totalBalance=C:b!==void 0&&y!==void 0&&(m.totalBalance=b+y),f.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(f.nextResetTime).toISOString())}if(p){if(m.usedDailyBalance===void 0){let b=ye(p.currentValue);b!==void 0&&(m.usedDailyBalance=b)}if(m.limitDaily===void 0){let b=ye(p.usage),C=ye(p.currentValue),y=ye(p.remaining);b!==void 0?m.limitDaily=b:C!==void 0&&y!==void 0&&(m.limitDaily=C+y)}p.nextResetTime&&!m.resetTime&&(m.resetTime=new Date(p.nextResetTime).toISOString())}return this.hasQuotaData(m)?m:null}catch{return null}}},pf=class extends Bn{async queryQuota(e,n,r){if(!e.quotaToken)return null;let o={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",Origin:"https://bailian.console.aliyun.com",Referer:"https://bailian.console.aliyun.com/cn-beijing",Cookie:e.quotaToken},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=JSON.stringify({Api:"zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",V:"1.0",Data:{queryCodingPlanInstanceInfoRequest:{commodityCode:"sfm_codingplan_public_cn",onlyLatestOne:!0},cornerstoneParam:{feTraceId:`ccr-${Date.now()}`,feURL:"https://bailian.console.aliyun.com/cn-beijing",protocol:"V2",console:"ONE_CONSOLE",productCode:"p_efm",switchAgent:10736808,switchUserType:3,domain:"bailian.console.aliyun.com",consoleSite:"BAILIAN_ALIYUN",userNickName:"",userPrincipalName:"",xsp_lang:"zh-CN"}}}),a=new URLSearchParams({params:s,region:"cn-beijing"}).toString();try{let c=await fetch("https://bailian-cs.console.aliyun.com/data/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=zeldaEasy.broadscope-bailian.codingPlan.queryCodingPlanInstanceInfoV2",{...o,body:a});if(!c.ok)return null;let d=(await c.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(d)||d.length===0)return null;let f=d[0]?.codingPlanQuotaInfo;if(!f)return null;let p={},m=ye(f.per5HourUsedQuota),b=ye(f.per5HourTotalQuota);m!==void 0&&(p.usedDailyBalance=m),b!==void 0&&(p.limitDaily=b);let C=ye(f.perWeekUsedQuota),y=ye(f.perWeekTotalQuota);return C!==void 0&&(p.usedBalance=C),y!==void 0&&(p.totalBalance=y),this.hasQuotaData(p)?p:null}catch{return null}}},mf=class extends Bn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(r).toString())}catch{}try{let a=await fetch("https://api.kimi.com/coding/v1/usages",s);if(!a.ok)return null;let c=await a.json(),l={},d=Array.isArray(c?.limits)?c.limits:[];if(d.length>0&&d[0]?.detail){let p=d[0].detail,m=ye(p.limit),b=ye(p.remaining),C=p.resetTime;m!==void 0&&b!==void 0&&(l.usedDailyBalance=Math.max(0,m-b),l.limitDaily=m),C&&(l.resetTime=new Date(C).toISOString())}let f=c?.usage;if(f){let p=ye(f.limit),m=ye(f.remaining),b=ye(f.used),C=f.resetTime;p!==void 0&&(l.totalBalance=p,b!==void 0?l.usedBalance=b:m!==void 0&&(l.usedBalance=Math.max(0,p-m),l.remainingBalance=m)),C&&(l.resetTime7d=new Date(C).toISOString(),l.resetTime||(l.resetTime=l.resetTime7d))}return this.hasQuotaData(l)?l:null}catch{return null}}},gf=class extends Bn{async queryQuota(e,n,r){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=yf(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com";try{let c=[`https://${a}/v1/token_plan/remains`,`https://${a}/v1/api/openplatform/coding_plan/remains`],l=null;for(let E of c)if(l=await this.fetchJson(E,e,n,r,o.trim()),l)break;if(!l)return null;if(l?.base_resp){let E=l.base_resp.status_code;if(E!==void 0&&E!==0)return null}let d=Array.isArray(l?.model_remains)?l.model_remains:[];if(d.length===0)return null;let f=d[0],p={},m=ye(f.current_interval_total_count),b=ye(f.current_interval_usage_count),C=ye(f.current_interval_remaining_percent),y=ye(f.end_time);m!==void 0&&b!==void 0&&m>0?(p.usedDailyBalance=Math.max(0,m-b),p.limitDaily=m):C!==void 0&&(p.limitDaily=100,p.usedDailyBalance=Math.max(0,100-C)),y&&(p.resetTime=new Date(y).toISOString());let _=ye(f.current_weekly_total_count),g=ye(f.current_weekly_usage_count),S=ye(f.current_weekly_remaining_percent),w=ye(f.weekly_end_time);return _!==void 0&&g!==void 0&&_>0?(p.usedBalance=Math.max(0,_-g),p.remainingBalance=g,p.totalBalance=_):S!==void 0&&(p.totalBalance=100,p.usedBalance=Math.max(0,100-S),p.remainingBalance=S),w&&!p.resetTime&&(p.resetTime=new Date(w).toISOString()),this.hasQuotaData(p)?p:null}catch{return null}}},UD=new lf,qD=new df,HD=new ff,zD=new hf,WD=new pf,GD=new mf,JD=new gf;function Eu(t){let e=yf(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?GD:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?JD:e==="deepseek.com"||e.endsWith(".deepseek.com")?UD:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?qD:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?HD:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?zD:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?WD:null:null}function VD(t){let e=yf(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function yf(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function ye(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t!="string")return;let e=t.trim().replace(/,/g,"");if(!e)return;let n=Number(e);return Number.isFinite(n)?n:void 0}var KD={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function YD(t){return t===!0||t==="true"||t===1||t==="1"}function QD(t){let e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`}function XD(t){try{let e=new URL(t),n=e.pathname;return n.endsWith("/v1/messages")?n=n.slice(0,-12):n.endsWith("/messages")?n=n.slice(0,-9):n.endsWith("/v1/chat/completions")?n=n.slice(0,-20):n.endsWith("/chat/completions")&&(n=n.slice(0,-17)),n.endsWith("/v1")||(n=n.endsWith("/")?`${n}v1`:`${n}/v1`),e.pathname=`${n}/models`,e.toString()}catch{return null}}function ZD(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function _f(t,e,n){let r=XD(t.baseUrl);if(!r)return{success:!1,error:"Cannot derive models endpoint from baseUrl"};try{let o={method:"GET",headers:{Authorization:`Bearer ${t.apiKey}`},signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(n).toString())}catch{}let s=await fetch(r,o);if(s.headers&&Uo(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,headers:s.headers};if(s.status===429)return{success:!1,error:`HTTP 429: ${(await s.text().catch(()=>"")).slice(0,100)||"Rate limited"}`,headers:s.headers};if(s.status>=400&&s.status<500)return{success:!0,headers:s.headers};let a=await s.text().catch(()=>"");return{success:!1,error:`HTTP ${s.status}: ${a.slice(0,100)}`,headers:s.headers}}catch(o){return{success:!1,error:o?.message||o?.toString()||"Unknown probe error"}}}async function eR(t,e,n,r){let o=t.wakeupModel||(Array.isArray(t.models)?t.models[0]:void 0);if(!o)return{success:!1,error:"No models configured for provider"};let s=t.baseUrl.includes("anthropic")||o.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:o,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(e)};if(n)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(n).toString())}catch{}r?.info(`Sending scheduled wake-up call to provider ${t.name} using model ${o}...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown wake-up error"}}}async function tR(t,e,n,r,o){let s=t.baseUrl.includes("anthropic")||e.includes("claude"),a=s?t.baseUrl.includes("/messages")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/v1/messages`:t.baseUrl.includes("/chat/completions")?t.baseUrl:`${t.baseUrl.replace(/\/$/,"")}/chat/completions`;try{let c={"Content-Type":"application/json"};s?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.Authorization=`Bearer ${t.apiKey}`;let l={method:"POST",headers:c,body:JSON.stringify({model:e,messages:[{role:"user",content:"ping"}],max_tokens:1}),signal:AbortSignal.timeout(n)};if(r)try{let{ProxyAgent:p}=await import("undici");l.dispatcher=new p(new URL(r).toString())}catch{}o?.debug?.(`Sending independent ping to rate-limited model ${t.name} (${e})...`);let d=await fetch(a,l);if(d.ok)return{success:!0};let f=await d.text().catch(()=>"");return{success:!1,error:`HTTP ${d.status}: ${f.slice(0,200)||"Unknown error"}`}}catch(c){return{success:!1,error:c?.message||c?.toString()||"Unknown ping error"}}}var Ts=class{config;quotaProbeTimer;healthProbeTimer;wakeupTimer;rateLimitProbeTimer;lastWakeupDate=new Map;getProviders;getHttpsProxy;logger;getConfig;running=!1;constructor(e,n,r,o,s){this.config={...KD,...n},this.getProviders=e,this.getHttpsProxy=r,this.logger=o,this.getConfig=s}start(){if(this.running)return;let e=this.isWakeupGloballyEnabled();!this.config.enabled&&!e||(this.running=!0,setTimeout(()=>{this.running&&(this.config.enabled&&(this.runQuotaProbe(),this.runHealthProbe(),this.runRateLimitProbe()),this.runScheduledWakeup())},this.config.initialDelayMs),this.config.enabled&&(this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*1e3),this.rateLimitProbeTimer=setInterval(()=>this.runRateLimitProbe(),120*1e3)),this.wakeupTimer=setInterval(()=>this.runScheduledWakeup(),60*1e3),this.logger?.info("Active probe service started"))}stop(){this.running=!1,this.quotaProbeTimer&&(clearInterval(this.quotaProbeTimer),this.quotaProbeTimer=void 0),this.healthProbeTimer&&(clearInterval(this.healthProbeTimer),this.healthProbeTimer=void 0),this.rateLimitProbeTimer&&(clearInterval(this.rateLimitProbeTimer),this.rateLimitProbeTimer=void 0),this.wakeupTimer&&(clearInterval(this.wakeupTimer),this.wakeupTimer=void 0),this.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&a.enabled!==!1&&!this.config.excludeProviders.includes(a.name)),n=this.getHttpsProxy?.(),r=Ge();if(e.length===0)return;let o=[];for(let a of e){let c=Eu(a.baseUrl),l=Array.isArray(a.models)?a.models:[];c&&o.push({provider:a.name,models:l,type:"quota-adapter",promise:c.queryQuota(a,this.config.probeTimeoutMs,n).then(d=>{if(d){pu(a.name,d),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let f=d.limitDaily!==void 0&&d.usedDailyBalance!==void 0&&d.usedDailyBalance>=d.limitDaily,p=d.totalBalance!==void 0&&d.usedBalance!==void 0&&d.usedBalance>=d.totalBalance;if(f||p){let m=f?`Quota exhausted: 5h limit reached (${d.usedDailyBalance}/${d.limitDaily})`:`Quota exhausted: 7d balance depleted (${d.usedBalance}/${d.totalBalance})`;for(let b of l){if(r.getState(a.name,b)?.rateLimitUntil){this.logger?.debug?.(`Skip forceOpen for ${a.name} (${b}): already rate-limited with active cooldown`);continue}r.forceOpen(a.name,b,m)}this.logger?.warn?.(`${m} for ${a.name}, marked as unhealthy`)}else for(let m of l){let b=r.getState(a.name,m);b&&b.status==="open"&&b.lastError?.includes("Quota exhausted")&&(r.recover(a.name,m),this.logger?.info?.(`Quota recovered for ${a.name} (${m}), marked as healthy`))}}})}),ZD(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:_f(a,this.config.probeTimeoutMs,n).then(()=>{})})}if(o.length===0)return;this.logger?.debug?.(`Running quota probe with ${o.length} tasks for ${e.length} providers`);let s=await Promise.allSettled(o.map(a=>a.promise));for(let a=0;a<o.length;a++){let c=s[a];if(c.status==="rejected"){let l=o[a];this.logger?.warn?.(`Quota probe failed for ${l.provider} (${l.type}): ${c.reason}`)}}}async runHealthProbe(){let e=Ge(),n=this.getProviders().filter(s=>s?.name&&s.enabled!==!1&&!this.config.excludeProviders.includes(s.name)),r=this.getHttpsProxy?.();if(n.length===0)return;this.logger?.debug?.(`Running health probe for ${n.length} providers`);let o=await Promise.allSettled(n.map(s=>_f(s,this.config.probeTimeoutMs,r)));for(let s=0;s<n.length;s++){let a=n[s],c=o[s],l=Array.isArray(a.models)?a.models:[];if(c.status==="fulfilled"){let d=c.value;if(d.success){let f=0;for(let p of l){let m=e.getState(a.name,p);if(m&&m.status==="open"){let b=m.lastError?.includes("Quota exhausted"),C=m.rateLimitUntil||m.lastError&&(m.lastError.includes("429")||m.lastError.toLowerCase().includes("rate limit")||m.lastError.toLowerCase().includes("rate_limit")||m.lastError.toLowerCase().includes("too many requests")||m.lastError.toLowerCase().includes("\u9650\u6D41"));if(b){this.logger?.debug?.(`Skipping health probe recovery for ${a.name} (${p}) because quota is exhausted`);continue}if(C||m.rateLimitUntil){this.logger?.debug?.(`Skipping health probe recovery for rate-limited ${a.name} (${p})`);continue}}e.recordSuccess(a.name,p),f++}f>0&&this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let f of l)e.recordFailure(a.name,f,d.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${d.error}`)}}else{for(let d of l)e.recordFailure(a.name,d,c.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${c.reason}`)}}}async runRateLimitProbe(){let e=Ge(),n=e.getRateLimitedModels();if(n.length===0)return;let r=this.getProviders(),o=this.getHttpsProxy?.(),s=this.config.probeTimeoutMs;this.logger?.debug?.(`Running rate-limit recovery probe for ${n.length} model(s)`);for(let a of n){let[c,...l]=a.split(","),d=l.join(",");if(!c||!d)continue;let f=e.getState(c,d);if(!f||!f.rateLimitUntil)continue;if(Date.now()>=f.rateLimitUntil){e.recover(c,d),this.logger?.info?.(`Rate-limit cooldown expired, auto-recovered ${a}`);continue}let p=r.find(m=>m?.name===c&&m.enabled!==!1);if(!p){this.logger?.warn?.(`Provider ${c} not found or disabled for rate-limit probe`);continue}try{let m=await tR(p,d,s,o,this.logger);if(m.success)this.logger?.info?.(`Rate-limit probe succeeded for ${a}, recovering model`),e.recover(c,d);else if(m.error&&(m.error.includes("429")||m.error.toLowerCase().includes("rate limit")||m.error.toLowerCase().includes("rate_limit")||m.error.toLowerCase().includes("too many requests")||m.error.toLowerCase().includes("\u9650\u6D41"))){let b=Date.now();f.rateLimitUntil&&f.rateLimitUntil>b?f.rateLimitUntil+=120*1e3:f.rateLimitUntil=b+120*1e3,this.logger?.debug?.(`Rate-limit probe for ${a} confirmed still limited, extending cooldown`)}else this.logger?.debug?.(`Rate-limit probe for ${a} returned non-rate-limit error: ${m.error?.slice(0,100)}`)}catch(m){this.logger?.warn?.(`Rate-limit probe exception for ${a}: ${m?.message||m}`)}}}async runScheduledWakeup(){if(!this.isWakeupGloballyEnabled())return;let e=this.getProviders().filter(l=>l?.name&&l.enabled!==!1&&l.wakeupEnabled===!0);if(e.length===0)return;let n=new Date,r=n.getHours(),o=n.getMinutes(),s=QD(n),a=this.getHttpsProxy?.(),c=this.getConfig&&this.getConfig("WAKEUP_TIME")||"06:00";for(let l of e){let d=l.wakeupTime||c,[f,p]=d.split(":"),m=parseInt(f,10),b=parseInt(p,10);if(isNaN(m)||isNaN(b))continue;let C=r>m||r===m&&o>=b,y=(m*60+b)*6e4-(r*60+o)*6e4,_=y>0&&y<=300*1e3;(C||_)&&!this.hasWakeupFiredToday(l.name,s)&&(this.logger?.info?.(`Scheduled wake-up triggered for provider ${l.name} at ${d}`),eR(l,3e4,a,this.logger).then(g=>{g.success?this.logger?.info?.(`Successfully woke up provider ${l.name}`):this.logger?.error?.(`Failed to wake up provider ${l.name}: ${g.error}`)}).catch(g=>{this.logger?.error?.(`Error in wake-up task for ${l.name}: ${g}`)}))}}isWakeupGloballyEnabled(){return this.getConfig?YD(this.getConfig("WAKEUP_ENABLED")):!1}hasWakeupFiredToday(e,n){return this.lastWakeupDate.get(e)===n?!0:(this.lastWakeupDate.set(e,n),!1)}async probeProviderManually(e){let r=this.getProviders().find(c=>c.name===e);if(!r)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;if(r.enabled===!1)return this.logger?.warn?.(`Provider ${e} is disabled, skipping manual probe`),!1;let o=this.getHttpsProxy?.(),s=await _f(r,this.config.probeTimeoutMs,o),a=Array.isArray(r.models)?r.models:[];if(s.success)for(let c of a)Ge().recordSuccess(r.name,c);else for(let c of a)Ge().recordFailure(r.name,c,s.error);return s.success}},rr=null;function bf(t,e,n,r,o){return rr||(rr=new Ts(t,e,n,r,o)),rr}function Au(t,e,n,r,o){let s=bf(t,e,n,r,o);return s.start(),s}function Su(){rr&&rr.stop()}function __(){rr&&(rr.stop(),rr=null)}Gn();var Cf=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},wf=new Cf;var D_=Oe(A_(),1);var xr=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
392
392
  `);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};var Ds=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
393
393
  `),e.id&&(r+=`id: ${e.id}
394
394
  `),e.retry&&(r+=`retry: ${e.retry}
395
395
  `),e.data&&(e.data.type==="done"?r+=`data: [DONE]
396
396
  `:r+=`data: ${JSON.stringify(e.data)}
397
397
  `),r+=`
398
- `,n.enqueue(r)}})}};var Sf=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let a=await e(s,r);a!==void 0&&r.enqueue(a)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};kf();vf();Df();k_();var Ps=new Map,xf=new Map,aR=1,Of={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,D_.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)To.registerHandlers(n.outputHandlers);else{let s=[];for(let a of r)a==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&To.registerHandlers(s)}n.outputOptions&&To.setDefaultOptions(n.outputOptions);let o=async s=>{let a=t.tokenizerService;if(!a)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let c=s.provider,l=s.model,d=`${c}:${l}`;if(xf.has(d))return xf.get(d);let f=a.getTokenizerConfigForModel(c,l);if(!f)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await a.getTokenizer(f);return xf.set(d,p),t.log?.info(`Created tokenizer for ${c}:${l} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${p.message}`),null}};t.addHook("onRequest",async s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,a,c)=>{let l=s.requestStartTime;if(!l)return;let d=s.id||Date.now().toString(),f;try{let b=s.body?.metadata?.user_id;if(b&&typeof b=="string")try{let y=JSON.parse(b);y.session_id&&(f=y.session_id)}catch{let y=b.match(/_session_([a-f0-9-]+)/i);f=y?y[1]:void 0}}catch{}if(!f)return;let p=await o(s);if(c instanceof ReadableStream){Ps.set(d,{requestId:d,sessionId:f,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[b,y]=c.tee();return(async()=>{let k=null,w=async A=>{let T=Ps.get(d);if(!T)return;let R=performance.now();if(A){let U=T.firstTokenTime?T.firstTokenTime-T.startTime:0,J=T.lastTokenTime-T.startTime;T.tokensPerSecond=v_(T.tokenCount,J,U)}else{let U=R-1e3;T.tokenTimestamps=T.tokenTimestamps.filter(J=>J>U),T.tokensPerSecond=T.tokenTimestamps.length}await T_(T,r,n.outputOptions,A).catch(U=>{t.log?.warn(`Failed to output streaming stats: ${U.message}`)})};try{let T=y.pipeThrough(new TextDecoderStream).pipeThrough(new xr).getReader();for(k=setInterval(async()=>{Ps.get(d)&&await w(!1)},1e3);;){let{done:R,value:U}=await T.read();if(R)break;let J=U,F=Ps.get(d);if(!F)continue;let V=performance.now();if(!F.firstTokenTime&&(J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="text_block"||J.event==="content_block")&&(F.firstTokenTime=V,F.timeToFirstToken=Math.round(V-F.startTime)),J.event==="content_block_delta"&&J.data?.delta){let Y=J.data.delta.type,X="";if(Y==="text_delta"?X=J.data.delta.text||"":Y==="input_json_delta"?X=J.data.delta.partial_json||"":Y==="thinking_delta"&&(X=J.data.delta.thinking||""),X){let ee=p&&p.encodeText?p.encodeText(X).length:Fs(X);F.tokenCount+=ee,F.lastTokenTime=V;for(let de=0;de<ee;de++)F.tokenTimestamps.push(V)}}J.event==="message_stop"&&(k&&(clearInterval(k),k=null),await w(!0),Ps.delete(d))}}catch(A){k&&clearInterval(k),A.name!=="AbortError"&&A.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${A.message}`)}})().catch(k=>{console.log(k),t.log?.warn(`Background stats processing failed: ${k.message}`)}),b}let g=performance.now(),_=0,C=!1;if(c&&typeof c=="string")try{let b=JSON.parse(c);if(typeof b.usage?.output_tokens=="number")_=b.usage.output_tokens,C=!0;else{let y=b.content??b.message?.content;if(y!==void 0)if(C=!0,p)Array.isArray(y)?_=y.reduce((m,k)=>{if(k.type==="text"){let w=k.text||"";return m+(p.encodeText?p.encodeText(w).length:Fs(w))}return m},0):typeof y=="string"&&(_=p.encodeText?p.encodeText(y).length:Fs(y));else{let m=Array.isArray(y)?y.map(k=>k.text).join(""):typeof y=="string"?y:"";_=Fs(m)}}}catch{}if(C){let b=Math.round(g-l),y=g-l,m={requestId:d,sessionId:f,startTime:l,lastTokenTime:g,tokenCount:_,tokensPerSecond:v_(_,y),timeToFirstToken:b,stream:!1,tokenTimestamps:[]};await T_(m,r,n.outputOptions,!0)}return c})})};function v_(t,e,n=0){if(t<=0)return 0;let r=Math.max((e-n)/1e3,aR);return Math.round(t/r)}function Fs(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function T_(t,e,n,r=!1){let o=r?"[Token Speed Final]":"[Token Speed]",s={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:o,metadata:{sessionId:t.sessionId},...n};for(let c of e)try{await To.outputToType(c,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}Gn();Gn();function uR(t={}){let e=(0,R_.default)({bodyLimit:52428800,...t});return e.setErrorHandler(Kh),e.register(x_.default),e}var Pf=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:n,...r}=e;this.app=uR({...r,logger:r.logger??!0}),this.configService=new pr(e),this.transformerService=new Dr(this.configService,this.app.log),this.tokenizerService=new Rr(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new gr(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async c=>{c.decorate("configService",this.configService),c.decorate("transformerService",this.transformerService),c.decorate("providerService",this.providerService),c.decorate("tokenizerService",this.tokenizerService),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await wu(l,d,{configService:this.configService,tokenizerService:this.tokenizerService})}),await bc(c)});return}if(!n)throw new Error("options is required");let r=new pr({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new Dr(r,this.app.log);await o.initialize();let s=new gr(r,o,this.app.log),a=new Rr(r,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",r),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await wu(l,d,{configService:r,tokenizerService:a})}),await bc(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let c=r.body;r.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(r,o)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body)try{let a=r.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let c=a.model.split(","),l=a.model;if(c.length>1){let[d,...f]=c;l=f.join(","),a.model=l,r.provider=d}r.model=l;return}catch(a){return r.log.error({error:a},"Error in modelProviderMiddleware:"),o.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{yi()}catch{}try{gu()}catch{}try{gi()}catch{}try{let r={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Au(()=>this.providerService.getProviders(),r,()=>this.configService.getHttpsProxy(),this.app.log,o=>this.configService.get(o))}catch(r){this.app.log.warn?.(`Failed to start active probe service: ${r.message}`)}let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`);try{Su()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},cR=Pf;0&&(module.exports={ActiveProbeService,ConfigService,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getHealthStore,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,pluginManager,resetActiveProbeService,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin});
398
+ `,n.enqueue(r)}})}};var Sf=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let a=await e(s,r);a!==void 0&&r.enqueue(a)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};kf();vf();Df();k_();var Ps=new Map,xf=new Map,aR=1,Of={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,D_.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)To.registerHandlers(n.outputHandlers);else{let s=[];for(let a of r)a==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):a==="webhook"&&console.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&To.registerHandlers(s)}n.outputOptions&&To.setDefaultOptions(n.outputOptions);let o=async s=>{let a=t.tokenizerService;if(!a)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let c=s.provider,l=s.model,d=`${c}:${l}`;if(xf.has(d))return xf.get(d);let f=a.getTokenizerConfigForModel(c,l);if(!f)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await a.getTokenizer(f);return xf.set(d,p),t.log?.info(`Created tokenizer for ${c}:${l} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${p.message}`),null}};t.addHook("onRequest",async s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,a,c)=>{let l=s.requestStartTime;if(!l)return;let d=s.id||Date.now().toString(),f;try{let y=s.body?.metadata?.user_id;if(y&&typeof y=="string")try{let _=JSON.parse(y);_.session_id&&(f=_.session_id)}catch{let _=y.match(/_session_([a-f0-9-]+)/i);f=_?_[1]:void 0}}catch{}if(!f)return;let p=await o(s);if(c instanceof ReadableStream){Ps.set(d,{requestId:d,sessionId:f,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[y,_]=c.tee();return(async()=>{let S=null,w=async E=>{let T=Ps.get(d);if(!T)return;let R=performance.now();if(E){let U=T.firstTokenTime?T.firstTokenTime-T.startTime:0,J=T.lastTokenTime-T.startTime;T.tokensPerSecond=v_(T.tokenCount,J,U)}else{let U=R-1e3;T.tokenTimestamps=T.tokenTimestamps.filter(J=>J>U),T.tokensPerSecond=T.tokenTimestamps.length}await T_(T,r,n.outputOptions,E).catch(U=>{t.log?.warn(`Failed to output streaming stats: ${U.message}`)})};try{let T=_.pipeThrough(new TextDecoderStream).pipeThrough(new xr).getReader();for(S=setInterval(async()=>{Ps.get(d)&&await w(!1)},1e3);;){let{done:R,value:U}=await T.read();if(R)break;let J=U,F=Ps.get(d);if(!F)continue;let V=performance.now();if(!F.firstTokenTime&&(J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="text_block"||J.event==="content_block")&&(F.firstTokenTime=V,F.timeToFirstToken=Math.round(V-F.startTime)),J.event==="content_block_delta"&&J.data?.delta){let Y=J.data.delta.type,X="";if(Y==="text_delta"?X=J.data.delta.text||"":Y==="input_json_delta"?X=J.data.delta.partial_json||"":Y==="thinking_delta"&&(X=J.data.delta.thinking||""),X){let ee=p&&p.encodeText?p.encodeText(X).length:Fs(X);F.tokenCount+=ee,F.lastTokenTime=V;for(let de=0;de<ee;de++)F.tokenTimestamps.push(V)}}J.event==="message_stop"&&(S&&(clearInterval(S),S=null),await w(!0),Ps.delete(d))}}catch(E){S&&clearInterval(S),E.name!=="AbortError"&&E.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${E.message}`)}})().catch(S=>{console.log(S),t.log?.warn(`Background stats processing failed: ${S.message}`)}),y}let m=performance.now(),b=0,C=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")b=y.usage.output_tokens,C=!0;else{let _=y.content??y.message?.content;if(_!==void 0)if(C=!0,p)Array.isArray(_)?b=_.reduce((g,S)=>{if(S.type==="text"){let w=S.text||"";return g+(p.encodeText?p.encodeText(w).length:Fs(w))}return g},0):typeof _=="string"&&(b=p.encodeText?p.encodeText(_).length:Fs(_));else{let g=Array.isArray(_)?_.map(S=>S.text).join(""):typeof _=="string"?_:"";b=Fs(g)}}}catch{}if(C){let y=Math.round(m-l),_=m-l,g={requestId:d,sessionId:f,startTime:l,lastTokenTime:m,tokenCount:b,tokensPerSecond:v_(b,_),timeToFirstToken:y,stream:!1,tokenTimestamps:[]};await T_(g,r,n.outputOptions,!0)}return c})})};function v_(t,e,n=0){if(t<=0)return 0;let r=Math.max((e-n)/1e3,aR);return Math.round(t/r)}function Fs(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function T_(t,e,n,r=!1){let o=r?"[Token Speed Final]":"[Token Speed]",s={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:o,metadata:{sessionId:t.sessionId},...n};for(let c of e)try{await To.outputToType(c,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}Gn();Gn();function uR(t={}){let e=(0,R_.default)({bodyLimit:52428800,...t});return e.setErrorHandler(Kh),e.register(x_.default),e}var Pf=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:n,...r}=e;this.app=uR({...r,logger:r.logger??!0}),this.configService=new pr(e),this.transformerService=new Dr(this.configService,this.app.log),this.tokenizerService=new Rr(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new gr(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async c=>{c.decorate("configService",this.configService),c.decorate("transformerService",this.transformerService),c.decorate("providerService",this.providerService),c.decorate("tokenizerService",this.tokenizerService),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await wu(l,d,{configService:this.configService,tokenizerService:this.tokenizerService})}),await bc(c)});return}if(!n)throw new Error("options is required");let r=new pr({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new Dr(r,this.app.log);await o.initialize();let s=new gr(r,o,this.app.log),a=new Rr(r,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",r),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,d)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await wu(l,d,{configService:r,tokenizerService:a})}),await bc(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let c=r.body;r.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(r,o)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body)try{let a=r.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let c=a.model.split(","),l=a.model;if(c.length>1){let[d,...f]=c;l=f.join(","),a.model=l,r.provider=d}r.model=l;return}catch(a){return r.log.error({error:a},"Error in modelProviderMiddleware:"),o.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);try{yi()}catch{}try{gu()}catch{}try{gi()}catch{}try{let r={enabled:this.configService.get("ACTIVE_PROBE_ENABLED")??!0,quotaProbeIntervalMinutes:this.configService.get("QUOTA_PROBE_INTERVAL_MINUTES")??10,probeTimeoutMs:this.configService.get("PROBE_TIMEOUT_MS")??15e3,initialDelayMs:this.configService.get("PROBE_INITIAL_DELAY_MS")??5e3,excludeProviders:this.configService.get("EXCLUDE_PROBE_PROVIDERS")??[]};this.activeProbeService=Au(()=>this.providerService.getProviders(),r,()=>this.configService.getHttpsProxy(),this.app.log,o=>this.configService.get(o))}catch(r){this.app.log.warn?.(`Failed to start active probe service: ${r.message}`)}let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`);try{Su()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},cR=Pf;0&&(module.exports={ActiveProbeService,ConfigService,ProviderHealthStore,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,getActiveProbeService,getAllQuotaResults,getAllRateLimitInfo,getHealthStore,getQuotaAdapter,getQuotaResult,getRateLimitInfo,getRuntimeDebugLog,initProviderHealthPersistence,initQuotaStorePersistence,initRateLimitPersistence,pluginManager,resetActiveProbeService,rewriteStream,router,searchProjectBySession,sessionUsageCache,setRuntimeDebugLog,startActiveProbe,stopActiveProbe,storeQuotaResult,tokenSpeedPlugin});
399
399
  /*! Bundled license information:
400
400
 
401
401
  web-streams-polyfill/dist/ponyfill.es2018.js: