@wengine-ai/llms 2.0.85 → 2.0.86
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -139
- package/dist/cjs/server.cjs +121 -121
- package/dist/cjs/server.cjs.map +3 -3
- package/dist/esm/server.mjs +121 -121
- package/dist/esm/server.mjs.map +3 -3
- package/package.json +2 -2
package/dist/esm/server.mjs
CHANGED
|
@@ -5,25 +5,25 @@ var lb=Object.create;var qs=Object.defineProperty;var db=Object.getOwnPropertyDe
|
|
|
5
5
|
`:case"\r":throw Be(H());case"\u2028":case"\u2029":Cb(Ce);break;case void 0:throw Be(H())}pe+=H()},start(){switch(Ce){case"{":case"[":return Ie("punctuator",H())}ge="value"},beforePropertyName(){switch(Ce){case"$":case"_":pe=H(),ge="identifierName";return;case"\\":H(),ge="identifierNameStartEscape";return;case"}":return Ie("punctuator",H());case'"':case"'":So=H()==='"',ge="string";return}if(ze.isIdStartChar(Ce)){pe+=H(),ge="identifierName";return}throw Be(H())},afterPropertyName(){if(Ce===":")return Ie("punctuator",H());throw Be(H())},beforePropertyValue(){ge="value"},afterPropertyValue(){switch(Ce){case",":case"}":return Ie("punctuator",H())}throw Be(H())},beforeArrayValue(){if(Ce==="]")return Ie("punctuator",H());ge="value"},afterArrayValue(){switch(Ce){case",":case"]":return Ie("punctuator",H())}throw Be(H())},end(){throw Be(H())}};function Ie(t,e){return{type:t,value:e,line:Lr,column:jt}}function an(t){for(let e of t){if(br()!==e)throw Be(H());H()}}function yb(){switch(br()){case"b":return H(),"\b";case"f":return H(),"\f";case"n":return H(),`
|
|
6
6
|
`;case"r":return H(),"\r";case"t":return H()," ";case"v":return H(),"\v";case"0":if(H(),ze.isDigit(br()))throw Be(H());return"\0";case"x":return H(),_b();case"u":return H(),Ou();case`
|
|
7
7
|
`:case"\u2028":case"\u2029":return H(),"";case"\r":return H(),br()===`
|
|
8
|
-
`&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Be(H());case void 0:throw Be(H())}return H()}function _b(){let t="",e=br();if(!ze.isHexDigit(e)||(t+=H(),e=br(),!ze.isHexDigit(e)))throw Be(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function Ou(){let t="",e=4;for(;e-- >0;){let r=br();if(!ze.isHexDigit(r))throw Be(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var bb={start(){if(He.type==="eof")throw un();Du()},beforePropertyName(){switch(He.type){case"identifier":case"string":Fu=He.value,et="afterPropertyName";return;case"punctuator":Hs();return;case"eof":throw un()}},afterPropertyName(){if(He.type==="eof")throw un();et="beforePropertyValue"},beforePropertyValue(){if(He.type==="eof")throw un();Du()},beforeArrayValue(){if(He.type==="eof")throw un();if(He.type==="punctuator"&&He.value==="]"){Hs();return}Du()},afterPropertyValue(){if(He.type==="eof")throw un();switch(He.value){case",":et="beforePropertyName";return;case"}":Hs()}},afterArrayValue(){if(He.type==="eof")throw un();switch(He.value){case",":et="beforeArrayValue";return;case"]":Hs()}},end(){}};function Du(){let t;switch(He.type){case"punctuator":switch(He.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=He.value;break}if(vo===void 0)vo=t;else{let e=_r[_r.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,Fu,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")_r.push(t),Array.isArray(t)?et="beforeArrayValue":et="beforePropertyName";else{let e=_r[_r.length-1];e==null?et="end":Array.isArray(e)?et="afterArrayValue":et="afterPropertyValue"}}function Hs(){_r.pop();let t=_r[_r.length-1];t==null?et="end":Array.isArray(t)?et="afterArrayValue":et="afterPropertyValue"}function Be(t){return Gs(t===void 0?`JSON5: invalid end of input at ${Lr}:${jt}`:`JSON5: invalid character '${ah(t)}' at ${Lr}:${jt}`)}function un(){return Gs(`JSON5: invalid end of input at ${Lr}:${jt}`)}function sh(){return jt-=5,Gs(`JSON5: invalid identifier character at ${Lr}:${jt}`)}function Cb(t){console.warn(`JSON5: '${ah(t)}' in strings is not valid ECMAScript; consider escaping`)}function ah(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 r=t.charCodeAt(0).toString(16);return"\\x"+("00"+r).substring(r.length)}return t}function Gs(t){let e=new SyntaxError(t);return e.lineNumber=Lr,e.columnNumber=jt,e}});var dh=V((TD,lh)=>{var Pu=Tu();lh.exports=function(e,r,n){let o=[],s="",a,c,l="",f;if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&(n=r.space,f=r.quote,r=r.replacer),typeof r=="function")c=r;else if(Array.isArray(r)){a=[];for(let y of r){let g;typeof y=="string"?g=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(g=String(y)),g!==void 0&&a.indexOf(g)<0&&a.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),d("",{"":e});function d(y,g){let m=g[y];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(y):typeof m.toJSON=="function"&&(m=m.toJSON(y))),c&&(m=c.call(g,y,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)?
|
|
9
|
-
`+s;A=v.join(D),
|
|
8
|
+
`&&H(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Be(H());case void 0:throw Be(H())}return H()}function _b(){let t="",e=br();if(!ze.isHexDigit(e)||(t+=H(),e=br(),!ze.isHexDigit(e)))throw Be(H());return t+=H(),String.fromCodePoint(parseInt(t,16))}function Ou(){let t="",e=4;for(;e-- >0;){let r=br();if(!ze.isHexDigit(r))throw Be(H());t+=H()}return String.fromCodePoint(parseInt(t,16))}var bb={start(){if(He.type==="eof")throw un();Du()},beforePropertyName(){switch(He.type){case"identifier":case"string":Fu=He.value,et="afterPropertyName";return;case"punctuator":Hs();return;case"eof":throw un()}},afterPropertyName(){if(He.type==="eof")throw un();et="beforePropertyValue"},beforePropertyValue(){if(He.type==="eof")throw un();Du()},beforeArrayValue(){if(He.type==="eof")throw un();if(He.type==="punctuator"&&He.value==="]"){Hs();return}Du()},afterPropertyValue(){if(He.type==="eof")throw un();switch(He.value){case",":et="beforePropertyName";return;case"}":Hs()}},afterArrayValue(){if(He.type==="eof")throw un();switch(He.value){case",":et="beforeArrayValue";return;case"]":Hs()}},end(){}};function Du(){let t;switch(He.type){case"punctuator":switch(He.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=He.value;break}if(vo===void 0)vo=t;else{let e=_r[_r.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,Fu,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")_r.push(t),Array.isArray(t)?et="beforeArrayValue":et="beforePropertyName";else{let e=_r[_r.length-1];e==null?et="end":Array.isArray(e)?et="afterArrayValue":et="afterPropertyValue"}}function Hs(){_r.pop();let t=_r[_r.length-1];t==null?et="end":Array.isArray(t)?et="afterArrayValue":et="afterPropertyValue"}function Be(t){return Gs(t===void 0?`JSON5: invalid end of input at ${Lr}:${jt}`:`JSON5: invalid character '${ah(t)}' at ${Lr}:${jt}`)}function un(){return Gs(`JSON5: invalid end of input at ${Lr}:${jt}`)}function sh(){return jt-=5,Gs(`JSON5: invalid identifier character at ${Lr}:${jt}`)}function Cb(t){console.warn(`JSON5: '${ah(t)}' in strings is not valid ECMAScript; consider escaping`)}function ah(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 r=t.charCodeAt(0).toString(16);return"\\x"+("00"+r).substring(r.length)}return t}function Gs(t){let e=new SyntaxError(t);return e.lineNumber=Lr,e.columnNumber=jt,e}});var dh=V((TD,lh)=>{var Pu=Tu();lh.exports=function(e,r,n){let o=[],s="",a,c,l="",f;if(r!=null&&typeof r=="object"&&!Array.isArray(r)&&(n=r.space,f=r.quote,r=r.replacer),typeof r=="function")c=r;else if(Array.isArray(r)){a=[];for(let y of r){let g;typeof y=="string"?g=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(g=String(y)),g!==void 0&&a.indexOf(g)<0&&a.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),d("",{"":e});function d(y,g){let m=g[y];switch(m!=null&&(typeof m.toJSON5=="function"?m=m.toJSON5(y):typeof m.toJSON=="function"&&(m=m.toJSON(y))),c&&(m=c.call(g,y,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)?_(m):C(m)}function p(y){let g={"'":.1,'"':.2},m={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},v="";for(let A=0;A<y.length;A++){let D=y[A];switch(D){case"'":case'"':g[D]++,v+=D;continue;case"\0":if(Pu.isDigit(y[A+1])){v+="\\x00";continue}}if(m[D]){v+=m[D];continue}if(D<" "){let O=D.charCodeAt(0).toString(16);v+="\\x"+("00"+O).substring(O.length);continue}v+=D}let b=f||Object.keys(g).reduce((A,D)=>g[A]<g[D]?A:D);return v=v.replace(new RegExp(b,"g"),m[b]),b+v+b}function C(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let g=s;s=s+l;let m=a||Object.keys(y),v=[];for(let A of m){let D=d(A,y);if(D!==void 0){let O=k(A)+":";l!==""&&(O+=" "),O+=D,v.push(O)}}let b;if(v.length===0)b="{}";else{let A;if(l==="")A=v.join(","),b="{"+A+"}";else{let D=`,
|
|
9
|
+
`+s;A=v.join(D),b=`{
|
|
10
10
|
`+s+A+`,
|
|
11
|
-
`+g+"}"}}return o.pop(),s=g,
|
|
12
|
-
`+s,A=m.join(
|
|
11
|
+
`+g+"}"}}return o.pop(),s=g,b}function k(y){if(y.length===0)return p(y,!0);let g=String.fromCodePoint(y.codePointAt(0));if(!Pu.isIdStartChar(g))return p(y,!0);for(let m=g.length;m<y.length;m++)if(!Pu.isIdContinueChar(String.fromCodePoint(y.codePointAt(m))))return p(y,!0);return y}function _(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let g=s;s=s+l;let m=[];for(let b=0;b<y.length;b++){let A=d(String(b),y);m.push(A!==void 0?A:"null")}let v;if(m.length===0)v="[]";else if(l==="")v="["+m.join(",")+"]";else{let b=`,
|
|
12
|
+
`+s,A=m.join(b);v=`[
|
|
13
13
|
`+s+A+`,
|
|
14
|
-
`+g+"]"}return o.pop(),s=g,v}}});var Iu=V((DD,fh)=>{var wb=ch(),Eb=dh(),Ab={parse:wb,stringify:Eb};fh.exports=Ab});var bh={};Su(bh,{getFallbackPromotionStore:()=>To,resetFallbackPromotionStore:()=>Rb});function To(t){return cn||(cn=new Bu,t&&cn.configure(t)),cn}function Rb(){cn&&(cn.clearAll(),cn=null)}var Db,Bu,cn,Js=Me(()=>{"use strict";In();Db=600*1e3,Bu=class{promotions=new Map;enabled=!0;ttlMs=Db;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,r,n){return`${e},${r}:${n}`}promote(e,r,n,o,s,a){if(!this.enabled)return;let c=this.getKey(e,r,n),l=`${o},${s}`;this.promotions.set(c,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,r,n,o){if(!this.enabled)return null;let s=this.getKey(e,r,n),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...f]=a.promotedModel.split(","),d=f.join(",");if(!it().isAvailable(l,d))return this.promotions.delete(s),null;let
|
|
15
|
-
`)||n,code:s,status:o},e.data.error)}return Object.assign({message:n,code:s,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};kt.GaxiosError=Hu;function Yb(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 $h(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function n(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&&(r(t.config.headers),n(t.config,"data"),o(t.config.data),n(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&&($h({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),o(t.response.data))),t}});var zh=V(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});Gu.getRetryConfig=Qb;async function Qb(t){let e=qh(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 r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||Xb)(t))return{shouldRetry:!1,config:t.config};let o=Zb(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 Xb(t){let e=qh(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 r=!1;for(let[n,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=n&&s<=o){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function qh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Zb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var Vu=V(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.GaxiosInterceptorManager=void 0;var Ju=class extends Set{};ni.GaxiosInterceptorManager=Ju});var Wh=V((wR,Hh)=>{var Mn=1e3,jn=Mn*60,Ln=jn*60,ln=Ln*24,eC=ln*7,tC=ln*365.25;Hh.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return rC(t);if(r==="number"&&isFinite(t))return e.long?oC(t):nC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function rC(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 r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*tC;case"weeks":case"week":case"w":return r*eC;case"days":case"day":case"d":return r*ln;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Ln;case"minutes":case"minute":case"mins":case"min":case"m":return r*jn;case"seconds":case"second":case"secs":case"sec":case"s":return r*Mn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function nC(t){var e=Math.abs(t);return e>=ln?Math.round(t/ln)+"d":e>=Ln?Math.round(t/Ln)+"h":e>=jn?Math.round(t/jn)+"m":e>=Mn?Math.round(t/Mn)+"s":t+"ms"}function oC(t){var e=Math.abs(t);return e>=ln?oi(t,e,ln,"day"):e>=Ln?oi(t,e,Ln,"hour"):e>=jn?oi(t,e,jn,"minute"):e>=Mn?oi(t,e,Mn,"second"):t+" ms"}function oi(t,e,r,n){var o=e>=r*1.5;return Math.round(t/r)+" "+n+(o?"s":"")}});var Ku=V((ER,Gh)=>{function sC(t){r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=o,r.enabled=c,r.humanize=Wh(),r.destroy=f,Object.keys(t).forEach(d=>{r[d]=t[d]}),r.names=[],r.skips=[],r.formatters={};function e(d){let p=0;for(let b=0;b<d.length;b++)p=(p<<5)-p+d.charCodeAt(b),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=e;function r(d){let p,b=null,k,C;function y(...g){if(!y.enabled)return;let m=y,v=Number(new Date),_=v-(p||v);m.diff=_,m.prev=p,m.curr=v,p=v,g[0]=r.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let A=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(O,q)=>{if(O==="%%")return"%";A++;let J=r.formatters[q];if(typeof J=="function"){let B=g[A];O=J.call(m,B),g.splice(A,1),A--}return O}),r.formatArgs.call(m,g),(m.log||r.log).apply(m,g)}return y.namespace=d,y.useColors=r.useColors(),y.color=r.selectColor(d),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(k!==r.namespaces&&(k=r.namespaces,C=r.enabled(d)),C),set:g=>{b=g}}),typeof r.init=="function"&&r.init(y),y}function n(d,p){let b=r(this.namespace+(typeof p>"u"?":":p)+d);return b.log=this.log,b}function o(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];let p=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of p)b[0]==="-"?r.skips.push(b.slice(1)):r.names.push(b)}function s(d,p){let b=0,k=0,C=-1,y=0;for(;b<d.length;)if(k<p.length&&(p[k]===d[b]||p[k]==="*"))p[k]==="*"?(C=k,y=b,k++):(b++,k++);else if(C!==-1)k=C+1,y++,b=y;else return!1;for(;k<p.length&&p[k]==="*";)k++;return k===p.length}function a(){let d=[...r.names,...r.skips.map(p=>"-"+p)].join(",");return r.enable(""),d}function c(d){for(let p of r.skips)if(s(d,p))return!1;for(let p of r.names)if(s(d,p))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function f(){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 r.enable(r.load()),r}Gh.exports=sC});var Jh=V((at,si)=>{at.formatArgs=aC;at.save=uC;at.load=cC;at.useColors=iC;at.storage=lC();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 iC(){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 aC(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+si.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(r++,o==="%c"&&(n=r))}),t.splice(n,0,e)}at.log=console.debug||console.log||(()=>{});function uC(t){try{t?at.storage.setItem("debug",t):at.storage.removeItem("debug")}catch{}}function cC(){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 lC(){try{return localStorage}catch{}}si.exports=Ku()(at);var{formatters:dC}=si.exports;dC.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Kh=V((AR,Vh)=>{"use strict";Vh.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}});var Xh=V((kR,Qh)=>{"use strict";var fC=X("os"),Yh=X("tty"),St=Kh(),{env:We}=process,Ur;St("no-color")||St("no-colors")||St("color=false")||St("color=never")?Ur=0:(St("color")||St("colors")||St("color=true")||St("color=always"))&&(Ur=1);"FORCE_COLOR"in We&&(We.FORCE_COLOR==="true"?Ur=1:We.FORCE_COLOR==="false"?Ur=0:Ur=We.FORCE_COLOR.length===0?1:Math.min(parseInt(We.FORCE_COLOR,10),3));function Yu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Qu(t,e){if(Ur===0)return 0;if(St("color=16m")||St("color=full")||St("color=truecolor"))return 3;if(St("color=256"))return 2;if(t&&!e&&Ur===void 0)return 0;let r=Ur||0;if(We.TERM==="dumb")return r;if(process.platform==="win32"){let n=fC.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in We)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in We)||We.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in We)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(We.TEAMCITY_VERSION)?1:0;if(We.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in We){let n=parseInt((We.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(We.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(We.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(We.TERM)||"COLORTERM"in We?1:r}function hC(t){let e=Qu(t,t&&t.isTTY);return Yu(e)}Qh.exports={supportsColor:hC,stdout:Yu(Qu(!0,Yh.isatty(1))),stderr:Yu(Qu(!0,Yh.isatty(2)))}});var ep=V((Ge,ai)=>{var pC=X("tty"),ii=X("util");Ge.init=wC;Ge.log=_C;Ge.formatArgs=gC;Ge.save=bC;Ge.load=CC;Ge.useColors=mC;Ge.destroy=ii.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ge.colors=[6,2,3,4,5,1];try{let t=Xh();t&&(t.stderr||t).level>=2&&(Ge.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{}Ge.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function mC(){return"colors"in Ge.inspectOpts?!!Ge.inspectOpts.colors:pC.isatty(process.stderr.fd)}function gC(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
|
|
14
|
+
`+g+"]"}return o.pop(),s=g,v}}});var Iu=V((DD,fh)=>{var wb=ch(),Eb=dh(),Ab={parse:wb,stringify:Eb};fh.exports=Ab});var bh={};Su(bh,{getFallbackPromotionStore:()=>To,resetFallbackPromotionStore:()=>Rb});function To(t){return cn||(cn=new Bu,t&&cn.configure(t)),cn}function Rb(){cn&&(cn.clearAll(),cn=null)}var Db,Bu,cn,Js=Me(()=>{"use strict";In();Db=600*1e3,Bu=class{promotions=new Map;enabled=!0;ttlMs=Db;configure(e){e?.enabled!==void 0&&(this.enabled=e.enabled),e?.ttlMinutes!==void 0&&(this.ttlMs=e.ttlMinutes*60*1e3)}getKey(e,r,n){return`${e},${r}:${n}`}promote(e,r,n,o,s,a){if(!this.enabled)return;let c=this.getKey(e,r,n),l=`${o},${s}`;this.promotions.set(c,{promotedModel:l,timestamp:Date.now(),ttlMs:a??this.ttlMs})}getPromotion(e,r,n,o){if(!this.enabled)return null;let s=this.getKey(e,r,n),a=this.promotions.get(s);if(!a)return null;if(Date.now()-a.timestamp>=a.ttlMs)return this.promotions.delete(s),null;let[l,...f]=a.promotedModel.split(","),d=f.join(",");if(!it().isAvailable(l,d))return this.promotions.delete(s),null;let C=o.find(_=>_.name.toLowerCase()===l.toLowerCase()),k=C?.models?.find(_=>String(_).toLowerCase()===d.toLowerCase());return!C||!k?(this.promotions.delete(s),null):`${C.name},${k}`}clear(e,r,n){let o=this.getKey(e,r,n);this.promotions.delete(o)}clearByPrimary(e,r){let n=`${e},${r}:`,o=0;for(let s of this.promotions.keys())s.startsWith(n)&&(this.promotions.delete(s),o++);return o}clearAll(){this.promotions.clear()}clearExpired(){let e=Date.now();for(let[r,n]of this.promotions)e-n.timestamp>=n.ttlMs&&this.promotions.delete(r)}getAllPromotions(){let e=Date.now(),r=[];for(let[n,o]of this.promotions){let s=o.ttlMs-(e-o.timestamp);s>0&&r.push({key:n,promotedModel:o.promotedModel,remainingMs:s})}return r}},cn=null});function it(t){return Nu||(Nu=new Vs(t)),Nu}var xb,Vs,Nu,In=Me(()=>{"use strict";xb={enabled:!0,failureThreshold:3,probeIntervalMinutes:5,halfOpenSuccessThreshold:2},Vs=class{states=new Map;config;probeTimer;constructor(e){this.config={...xb,...e}}getKey(e,r){return`${e},${r}`}recordSuccess(e,r){if(!this.config.enabled)return;let n=this.getKey(e,r),o=this.states.get(n);o&&(o.successCount++,o.status==="half-open"?o.successCount>=this.config.halfOpenSuccessThreshold&&(this.clearPromotionsForPrimary(e,r),this.states.delete(n)):o.status==="open"&&(o.status="half-open",o.successCount=1,o.failureCount=0))}clearPromotionsForPrimary(e,r){try{let{getFallbackPromotionStore:n}=(Js(),mb(bh));n().clearByPrimary(e,r)}catch{}}recordFailure(e,r,n){if(!this.config.enabled)return;let o=this.getKey(e,r),s=this.states.get(o);s||(s={provider:e,model:r,status:"closed",failureCount:0,successCount:0,lastFailureTime:0,lastProbeTime:0},this.states.set(o,s)),s.failureCount++,s.lastFailureTime=Date.now(),s.lastError=n,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,r){return this.states.get(this.getKey(e,r))}isAvailable(e,r){if(!this.config.enabled)return!0;let n=this.getState(e,r);return n?n.status!=="open":!0}getPriority(e,r){if(!this.config.enabled)return 0;let n=this.getState(e,r);if(!n)return 0;switch(n.status){case"closed":return 0;case"half-open":return 1;case"open":return 2}}getHealthyModels(){return[]}getFailPoolModels(){let e=[];for(let[r,n]of this.states)n.status==="open"&&e.push(r);return e}getHalfOpenModels(){let e=[];for(let[r,n]of this.states)n.status==="half-open"&&e.push(r);return e}forceOpen(e,r,n){if(!this.config.enabled)return;let o=this.getKey(e,r),s=this.states.get(o);s?(s.status="open",s.failureCount=Math.max(s.failureCount,this.config.failureThreshold),s.lastFailureTime=Date.now(),s.lastError=n,s.lastProbeTime=0):(s={provider:e,model:r,status:"open",failureCount:this.config.failureThreshold,successCount:0,lastFailureTime:Date.now(),lastProbeTime:0,lastError:n},this.states.set(o,s))}needsProbe(e){return Date.now()-e.lastProbeTime>=this.config.probeIntervalMinutes*60*1e3}markProbeAttempt(e,r){let n=this.getKey(e,r),o=this.states.get(n);o&&o.status==="open"&&(o.lastProbeTime=Date.now())}clear(){this.states.clear()}getAllStates(){return Array.from(this.states.values())}stopProbeTimer(){this.probeTimer&&(clearInterval(this.probeTimer),this.probeTimer=void 0)}},Nu=null});var qu=V((mR,Bh)=>{"use strict";var ri=Object.prototype.hasOwnProperty,Ih=Object.prototype.toString,Dh=Object.defineProperty,Rh=Object.getOwnPropertyDescriptor,xh=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Ih.call(e)==="[object Array]"},Oh=function(e){if(!e||Ih.call(e)!=="[object Object]")return!1;var r=ri.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&ri.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var o;for(o in e);return typeof o>"u"||ri.call(e,o)},Fh=function(e,r){Dh&&r.name==="__proto__"?Dh(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Ph=function(e,r){if(r==="__proto__")if(ri.call(e,r)){if(Rh)return Rh(e,r).value}else return;return e[r]};Bh.exports=function t(){var e,r,n,o,s,a,c=arguments[0],l=1,f=arguments.length,d=!1;for(typeof c=="boolean"&&(d=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<f;++l)if(e=arguments[l],e!=null)for(r in e)n=Ph(c,r),o=Ph(e,r),c!==o&&(d&&o&&(Oh(o)||(s=xh(o)))?(s?(s=!1,a=n&&xh(n)?n:[]):a=n&&Oh(n)?n:{},Fh(c,{name:r,newValue:t(d,a,o)})):typeof o<"u"&&Fh(c,{name:r,newValue:o}));return c}});var Nh=V((gR,Jb)=>{Jb.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 jh=V((yR,Mh)=>{"use strict";var Vb=Nh();Mh.exports={pkg:Vb}});var Wu=V(kt=>{"use strict";var Uh=kt&&kt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(kt,"__esModule",{value:!0});kt.GaxiosError=kt.GAXIOS_ERROR_SYMBOL=void 0;kt.defaultErrorRedactor=$h;var Lh=Uh(qu()),Kb=Uh(jh()),zu=Kb.default.pkg;kt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${zu.name}-gaxios-error`);var Hu=class t extends Error{config;response;code;status;error;[kt.GAXIOS_ERROR_SYMBOL]=zu.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&kt.GAXIOS_ERROR_SYMBOL in e&&e[kt.GAXIOS_ERROR_SYMBOL]===zu.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,o){if(super(e,{cause:o}),this.config=r,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,Lh.default)(!0,{},r),this.response&&(this.response.config=(0,Lh.default)(!0,{},this.response.config)),this.response){try{this.response.data=Yb(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,r="The request failed"){let n=r;if(typeof e.data=="string"&&(n=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"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;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
|
+
`)||n,code:s,status:o},e.data.error)}return Object.assign({message:n,code:s,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};kt.GaxiosError=Hu;function Yb(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 $h(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function n(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&&(r(t.config.headers),n(t.config,"data"),o(t.config.data),n(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&&($h({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),o(t.response.data))),t}});var zh=V(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});Gu.getRetryConfig=Qb;async function Qb(t){let e=qh(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 r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||Xb)(t))return{shouldRetry:!1,config:t.config};let o=Zb(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 Xb(t){let e=qh(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 r=!1;for(let[n,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=n&&s<=o){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function qh(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function Zb(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var Vu=V(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.GaxiosInterceptorManager=void 0;var Ju=class extends Set{};ni.GaxiosInterceptorManager=Ju});var Wh=V((wR,Hh)=>{var Mn=1e3,jn=Mn*60,Ln=jn*60,ln=Ln*24,eC=ln*7,tC=ln*365.25;Hh.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return rC(t);if(r==="number"&&isFinite(t))return e.long?oC(t):nC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function rC(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 r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*tC;case"weeks":case"week":case"w":return r*eC;case"days":case"day":case"d":return r*ln;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Ln;case"minutes":case"minute":case"mins":case"min":case"m":return r*jn;case"seconds":case"second":case"secs":case"sec":case"s":return r*Mn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function nC(t){var e=Math.abs(t);return e>=ln?Math.round(t/ln)+"d":e>=Ln?Math.round(t/Ln)+"h":e>=jn?Math.round(t/jn)+"m":e>=Mn?Math.round(t/Mn)+"s":t+"ms"}function oC(t){var e=Math.abs(t);return e>=ln?oi(t,e,ln,"day"):e>=Ln?oi(t,e,Ln,"hour"):e>=jn?oi(t,e,jn,"minute"):e>=Mn?oi(t,e,Mn,"second"):t+" ms"}function oi(t,e,r,n){var o=e>=r*1.5;return Math.round(t/r)+" "+n+(o?"s":"")}});var Ku=V((ER,Gh)=>{function sC(t){r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=o,r.enabled=c,r.humanize=Wh(),r.destroy=f,Object.keys(t).forEach(d=>{r[d]=t[d]}),r.names=[],r.skips=[],r.formatters={};function e(d){let p=0;for(let C=0;C<d.length;C++)p=(p<<5)-p+d.charCodeAt(C),p|=0;return r.colors[Math.abs(p)%r.colors.length]}r.selectColor=e;function r(d){let p,C=null,k,_;function y(...g){if(!y.enabled)return;let m=y,v=Number(new Date),b=v-(p||v);m.diff=b,m.prev=p,m.curr=v,p=v,g[0]=r.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let A=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(O,q)=>{if(O==="%%")return"%";A++;let J=r.formatters[q];if(typeof J=="function"){let B=g[A];O=J.call(m,B),g.splice(A,1),A--}return O}),r.formatArgs.call(m,g),(m.log||r.log).apply(m,g)}return y.namespace=d,y.useColors=r.useColors(),y.color=r.selectColor(d),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>C!==null?C:(k!==r.namespaces&&(k=r.namespaces,_=r.enabled(d)),_),set:g=>{C=g}}),typeof r.init=="function"&&r.init(y),y}function n(d,p){let C=r(this.namespace+(typeof p>"u"?":":p)+d);return C.log=this.log,C}function o(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];let p=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let C of p)C[0]==="-"?r.skips.push(C.slice(1)):r.names.push(C)}function s(d,p){let C=0,k=0,_=-1,y=0;for(;C<d.length;)if(k<p.length&&(p[k]===d[C]||p[k]==="*"))p[k]==="*"?(_=k,y=C,k++):(C++,k++);else if(_!==-1)k=_+1,y++,C=y;else return!1;for(;k<p.length&&p[k]==="*";)k++;return k===p.length}function a(){let d=[...r.names,...r.skips.map(p=>"-"+p)].join(",");return r.enable(""),d}function c(d){for(let p of r.skips)if(s(d,p))return!1;for(let p of r.names)if(s(d,p))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function f(){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 r.enable(r.load()),r}Gh.exports=sC});var Jh=V((at,si)=>{at.formatArgs=aC;at.save=uC;at.load=cC;at.useColors=iC;at.storage=lC();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 iC(){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 aC(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+si.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(r++,o==="%c"&&(n=r))}),t.splice(n,0,e)}at.log=console.debug||console.log||(()=>{});function uC(t){try{t?at.storage.setItem("debug",t):at.storage.removeItem("debug")}catch{}}function cC(){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 lC(){try{return localStorage}catch{}}si.exports=Ku()(at);var{formatters:dC}=si.exports;dC.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Kh=V((AR,Vh)=>{"use strict";Vh.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),o=e.indexOf("--");return n!==-1&&(o===-1||n<o)}});var Xh=V((kR,Qh)=>{"use strict";var fC=X("os"),Yh=X("tty"),St=Kh(),{env:We}=process,Ur;St("no-color")||St("no-colors")||St("color=false")||St("color=never")?Ur=0:(St("color")||St("colors")||St("color=true")||St("color=always"))&&(Ur=1);"FORCE_COLOR"in We&&(We.FORCE_COLOR==="true"?Ur=1:We.FORCE_COLOR==="false"?Ur=0:Ur=We.FORCE_COLOR.length===0?1:Math.min(parseInt(We.FORCE_COLOR,10),3));function Yu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Qu(t,e){if(Ur===0)return 0;if(St("color=16m")||St("color=full")||St("color=truecolor"))return 3;if(St("color=256"))return 2;if(t&&!e&&Ur===void 0)return 0;let r=Ur||0;if(We.TERM==="dumb")return r;if(process.platform==="win32"){let n=fC.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in We)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in We)||We.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in We)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(We.TEAMCITY_VERSION)?1:0;if(We.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in We){let n=parseInt((We.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(We.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(We.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(We.TERM)||"COLORTERM"in We?1:r}function hC(t){let e=Qu(t,t&&t.isTTY);return Yu(e)}Qh.exports={supportsColor:hC,stdout:Yu(Qu(!0,Yh.isatty(1))),stderr:Yu(Qu(!0,Yh.isatty(2)))}});var ep=V((Ge,ai)=>{var pC=X("tty"),ii=X("util");Ge.init=wC;Ge.log=_C;Ge.formatArgs=gC;Ge.save=bC;Ge.load=CC;Ge.useColors=mC;Ge.destroy=ii.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ge.colors=[6,2,3,4,5,1];try{let t=Xh();t&&(t.stderr||t).level>=2&&(Ge.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{}Ge.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function mC(){return"colors"in Ge.inspectOpts?!!Ge.inspectOpts.colors:pC.isatty(process.stderr.fd)}function gC(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
|
|
16
16
|
`).join(`
|
|
17
17
|
`+s),t.push(o+"m+"+ai.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=yC()+e+" "+t[0]}function yC(){return Ge.inspectOpts.hideDate?"":new Date().toISOString()+" "}function _C(...t){return process.stderr.write(ii.formatWithOptions(Ge.inspectOpts,...t)+`
|
|
18
18
|
`)}function bC(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function CC(){return process.env.DEBUG}function wC(t){t.inspectOpts={};let e=Object.keys(Ge.inspectOpts);for(let r=0;r<e.length;r++)t.inspectOpts[e[r]]=Ge.inspectOpts[e[r]]}ai.exports=Ku()(Ge);var{formatters:Zh}=ai.exports;Zh.o=function(t){return this.inspectOpts.colors=this.useColors,ii.inspect(t,this.inspectOpts).split(`
|
|
19
19
|
`).map(e=>e.trim()).join(" ")};Zh.O=function(t){return this.inspectOpts.colors=this.useColors,ii.inspect(t,this.inspectOpts)}});var Zu=V((SR,Xu)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Xu.exports=Jh():Xu.exports=ep()});var np=V(ut=>{"use strict";var EC=ut&&ut.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),AC=ut&&ut.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tp=ut&&ut.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&EC(e,t,r);return AC(e,t),e};Object.defineProperty(ut,"__esModule",{value:!0});ut.req=ut.json=ut.toBuffer=void 0;var kC=tp(X("http")),SC=tp(X("https"));async function rp(t){let e=0,r=[];for await(let n of t)e+=n.length,r.push(n);return Buffer.concat(r,e)}ut.toBuffer=rp;async function vC(t){let r=(await rp(t)).toString("utf8");try{return JSON.parse(r)}catch(n){let o=n;throw o.message+=` (input: ${r})`,o}}ut.json=vC;function TC(t,e={}){let n=((typeof t=="string"?t:t.href).startsWith("https:")?SC:kC).request(t,e),o=new Promise((s,a)=>{n.once("response",s).once("error",a).end()});return n.then=o.then.bind(o),n}ut.req=TC});var ap=V(ht=>{"use strict";var sp=ht&&ht.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),DC=ht&&ht.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ip=ht&&ht.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sp(e,t,r);return DC(e,t),e},RC=ht&&ht.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&sp(e,t,r)};Object.defineProperty(ht,"__esModule",{value:!0});ht.Agent=void 0;var xC=ip(X("net")),op=ip(X("http")),OC=X("https");RC(np(),ht);var Qt=Symbol("AgentBaseInternalState"),ec=class extends op.Agent{constructor(e){super(e),this[Qt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:r}=new Error;return typeof r!="string"?!1:r.split(`
|
|
20
|
-
`).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let r=new xC.Socket({writable:!1});return this.sockets[e].push(r),this.totalSocketCount++,r}decrementSockets(e,r){if(!this.sockets[e]||r===null)return;let n=this.sockets[e],o=n.indexOf(r);o!==-1&&(n.splice(o,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?OC.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,r,n){let o={...r,secureEndpoint:this.isSecureEndpoint(r)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof op.Agent)try{return c.addRequest(e,o)}catch(l){return n(l)}this[Qt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(s,a),n(c)})}createConnection(){let e=this[Qt].currentSocket;if(this[Qt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Qt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Qt]&&(this[Qt].defaultPort=e)}get protocol(){return this[Qt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Qt]&&(this[Qt].protocol=e)}};ht.Agent=ec});var up=V(Un=>{"use strict";var FC=Un&&Un.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Un,"__esModule",{value:!0});Un.parseProxyResponse=void 0;var PC=FC(Zu()),ui=(0,PC.default)("https-proxy-agent:parse-proxy-response");function IC(t){return new Promise((e,r)=>{let n=0,o=[];function s(){let d=t.read();d?f(d):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),ui("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){a(),ui("onerror %o",d),r(d)}function f(d){o.push(d),n+=d.length;let p=Buffer.concat(o,n),
|
|
20
|
+
`).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let r=new xC.Socket({writable:!1});return this.sockets[e].push(r),this.totalSocketCount++,r}decrementSockets(e,r){if(!this.sockets[e]||r===null)return;let n=this.sockets[e],o=n.indexOf(r);o!==-1&&(n.splice(o,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?OC.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,r,n){let o={...r,secureEndpoint:this.isSecureEndpoint(r)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof op.Agent)try{return c.addRequest(e,o)}catch(l){return n(l)}this[Qt].currentSocket=c,super.createSocket(e,r,n)},c=>{this.decrementSockets(s,a),n(c)})}createConnection(){let e=this[Qt].currentSocket;if(this[Qt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Qt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Qt]&&(this[Qt].defaultPort=e)}get protocol(){return this[Qt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Qt]&&(this[Qt].protocol=e)}};ht.Agent=ec});var up=V(Un=>{"use strict";var FC=Un&&Un.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Un,"__esModule",{value:!0});Un.parseProxyResponse=void 0;var PC=FC(Zu()),ui=(0,PC.default)("https-proxy-agent:parse-proxy-response");function IC(t){return new Promise((e,r)=>{let n=0,o=[];function s(){let d=t.read();d?f(d):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),ui("onend"),r(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){a(),ui("onerror %o",d),r(d)}function f(d){o.push(d),n+=d.length;let p=Buffer.concat(o,n),C=p.indexOf(`\r
|
|
21
21
|
\r
|
|
22
|
-
`);if(
|
|
23
|
-
`),
|
|
24
|
-
`;if(n.username||n.password){let
|
|
22
|
+
`);if(C===-1){ui("have not received end of HTTP headers yet..."),s();return}let k=p.slice(0,C).toString("ascii").split(`\r
|
|
23
|
+
`),_=k.shift();if(!_)return t.destroy(),r(new Error("No header received from proxy CONNECT response"));let y=_.split(" "),g=+y[1],m=y.slice(2).join(" "),v={};for(let b of k){if(!b)continue;let A=b.indexOf(":");if(A===-1)return t.destroy(),r(new Error(`Invalid header from proxy CONNECT response: "${b}"`));let D=b.slice(0,A).toLowerCase(),O=b.slice(A+1).trimStart(),q=v[D];typeof q=="string"?v[D]=[q,O]:Array.isArray(q)?q.push(O):v[D]=O}ui("got proxy server response: %o %o",_,v),a(),e({connect:{statusCode:g,statusText:m,headers:v},buffered:p})}t.on("error",l),t.on("end",c),s()})}Un.parseProxyResponse=IC});var pp=V(vt=>{"use strict";var BC=vt&&vt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),NC=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fp=vt&&vt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&BC(e,t,r);return NC(e,t),e},hp=vt&&vt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vt,"__esModule",{value:!0});vt.HttpsProxyAgent=void 0;var ci=fp(X("net")),cp=fp(X("tls")),MC=hp(X("assert")),jC=hp(Zu()),LC=ap(),UC=X("url"),$C=up(),xo=(0,jC.default)("https-proxy-agent"),lp=t=>t.servername===void 0&&t.host&&!ci.isIP(t.host)?{...t,servername:t.host}:t,li=class extends LC.Agent{constructor(e,r){super(r),this.options={path:void 0},this.proxy=typeof e=="string"?new UC.URL(e):e,this.proxyHeaders=r?.headers??{},xo("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(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"],...r?dp(r,"headers"):null,host:n,port:o}}async connect(e,r){let{proxy:n}=this;if(!r.host)throw new TypeError('No "host" provided');let o;n.protocol==="https:"?(xo("Creating `tls.Socket`: %o",this.connectOpts),o=cp.connect(lp(this.connectOpts))):(xo("Creating `net.Socket`: %o",this.connectOpts),o=ci.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=ci.isIPv6(r.host)?`[${r.host}]`:r.host,c=`CONNECT ${a}:${r.port} HTTP/1.1\r
|
|
24
|
+
`;if(n.username||n.password){let C=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(C).toString("base64")}`}s.Host=`${a}:${r.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let C of Object.keys(s))c+=`${C}: ${s[C]}\r
|
|
25
25
|
`;let l=(0,$C.parseProxyResponse)(o);o.write(`${c}\r
|
|
26
|
-
`);let{connect:f,buffered:d}=await l;if(e.emit("proxyConnect",f),this.emit("proxyConnect",f,e),f.statusCode===200)return e.once("socket",qC),r.secureEndpoint?(xo("Upgrading socket connection to TLS"),cp.connect({...dp(lp(r),"host","path","port"),socket:o})):o;o.destroy();let p=new ci.Socket({writable:!1});return p.readable=!0,e.once("socket",b=>{xo("Replaying proxy buffer for failed request"),(0,MC.default)(b.listenerCount("data")>0),b.push(d),b.push(null)}),p}};li.protocols=["http","https"];vt.HttpsProxyAgent=li;function qC(t){t.resume()}function dp(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function zC(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 r=t.substring(5,e).split(";"),n="",o=!1,s=r[0]||"text/plain",a=s;for(let d=1;d<r.length;d++)r[d]==="base64"?o=!0:r[d]&&(a+=`;${r[d]}`,r[d].indexOf("charset=")===0&&(n=r[d].substring(8)));!r[0]&&!n.length&&(a+=";charset=US-ASCII",n="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),f=Buffer.from(l,c);return f.type=s,f.typeFull=a,f.charset=n,f}var mp,gp=Me(()=>{mp=zC});var _p=V((di,yp)=>{(function(t,e){typeof di=="object"&&typeof yp<"u"?e(di):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(di,(function(t){"use strict";function e(){}function r(i){return typeof i=="object"&&i!==null||typeof i=="function"}let n=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 f(i){return l(u=>u(i))}function d(i){return c(i)}function p(i,u,h){return a.call(i,u,h)}function b(i,u,h){p(p(i,u,h),void 0,n)}function k(i,u){b(i,u)}function C(i,u){b(i,void 0,u)}function y(i,u,h){return p(i,u,h)}function g(i){p(i,void 0,n)}let m=i=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let u=f(void 0);m=h=>p(u,h)}return m(i)};function v(i,u,h){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,h)}function _(i,u,h){try{return f(v(i,u,h))}catch(E){return d(E)}}let A=16384;class D{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,E=h;h._elements.length===A-1&&(E={_elements:[],_next:void 0}),h._elements.push(u),E!==h&&(this._back=E,h._next=E),++this._size}shift(){let u=this._front,h=u,E=this._cursor,R=E+1,L=u._elements,$=L[E];return R===A&&(h=u._next,R=0),--this._size,this._cursor=R,u!==h&&(this._front=h),L[E]=void 0,$}forEach(u){let h=this._cursor,E=this._front,R=E._elements;for(;(h!==R.length||E._next!==void 0)&&!(h===R.length&&(E=E._next,R=E._elements,h=0,R.length===0));)u(R[h]),++h}peek(){let u=this._front,h=this._cursor;return u._elements[h]}}let O=Symbol("[[AbortSteps]]"),q=Symbol("[[ErrorSteps]]"),J=Symbol("[[CancelSteps]]"),B=Symbol("[[PullSteps]]"),Y=Symbol("[[ReleaseSteps]]");function re(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?ke(i):u._state==="closed"?me(i):ie(i,u._storedError)}function ee(i,u){let h=i._ownerReadableStream;return Nt(h,u)}function ue(i){let u=i._ownerReadableStream;u._state==="readable"?G(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[Y](),u._reader=void 0,i._ownerReadableStream=void 0}function fe(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function ke(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h})}function ie(i,u){ke(i),G(i,u)}function me(i){ke(i),ce(i)}function G(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function K(i,u){ie(i,u)}function ce(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let qe=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},De=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function W(i){return typeof i=="object"||typeof i=="function"}function de(i,u){if(i!==void 0&&!W(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 It(i){return typeof i=="object"&&i!==null||typeof i=="function"}function xe(i,u){if(!It(i))throw new TypeError(`${u} is not an object.`)}function je(i,u,h){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${h}'.`)}function w(i,u,h){if(i===void 0)throw new TypeError(`${u} is required in '${h}'.`)}function S(i){return Number(i)}function T(i){return i===0?0:i}function M(i){return T(De(i))}function F(i,u){let E=Number.MAX_SAFE_INTEGER,R=Number(i);if(R=T(R),!qe(R))throw new TypeError(`${u} is not a finite number`);if(R=M(R),R<0||R>E)throw new TypeError(`${u} is outside the accepted range of 0 to ${E}, inclusive`);return!qe(R)||R===0?0:R}function I(i,u){if(!Ir(i))throw new TypeError(`${u} is not a ReadableStream.`)}function U(i){return new z(i)}function x(i,u){i._reader._readRequests.push(u)}function P(i,u,h){let R=i._reader._readRequests.shift();h?R._closeSteps():R._chunkSteps(u)}function j(i){return i._reader._readRequests.length}function N(i){let u=i._reader;return!(u===void 0||!Z(u))}class z{constructor(u){if(je(u,1,"ReadableStreamDefaultReader"),I(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");re(this,u),this._readRequests=new D}get closed(){return Z(this)?this._closedPromise:d(Ne("closed"))}cancel(u=void 0){return Z(this)?this._ownerReadableStream===void 0?d(fe("cancel")):ee(this,u):d(Ne("cancel"))}read(){if(!Z(this))return d(Ne("read"));if(this._ownerReadableStream===void 0)return d(fe("read from"));let u,h,E=l((L,$)=>{u=L,h=$});return te(this,{_chunkSteps:L=>u({value:L,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:L=>h(L)}),E}releaseLock(){if(!Z(this))throw Ne("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(z.prototype.cancel,"cancel"),o(z.prototype.read,"read"),o(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Z(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof z}function te(i,u){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?u._closeSteps():h._state==="errored"?u._errorSteps(h._storedError):h._readableStreamController[B](u)}function Ee(i){ue(i);let u=new TypeError("Reader was released");Pe(i,u)}function Pe(i,u){let h=i._readRequests;i._readRequests=new D,h.forEach(E=>{E._errorSteps(u)})}function Ne(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,E,R=l(($,Q)=>{h=$,E=Q});return te(u,{_chunkSteps:$=>{this._ongoingPromise=void 0,m(()=>h({value:$,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),h({value:void 0,done:!0})},_errorSteps:$=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),E($)}}),R}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let E=ee(h,u);return ue(h),y(E,()=>({value:u,done:!0}))}return ue(h),f({value:u,done:!0})}}let Ue={next(){return Cn(this)?this._asyncIteratorImpl.next():d(wn("next"))},return(i){return Cn(this)?this._asyncIteratorImpl.return(i):d(wn("return"))}};Object.setPrototypeOf(Ue,we);function bn(i,u){let h=U(i),E=new Se(h,u),R=Object.create(Ue);return R._asyncIteratorImpl=E,R}function Cn(i){if(!r(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Se}catch{return!1}}function wn(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let dt=Number.isNaN||function(i){return i!==i};var lr,Ye,$e;function ve(i){return i.slice()}function Zd(i,u,h,E,R){new Uint8Array(i).set(new Uint8Array(h,E,R),u)}let dr=i=>(typeof i.transfer=="function"?dr=u=>u.transfer():typeof structuredClone=="function"?dr=u=>structuredClone(u,{transfer:[u]}):dr=u=>u,dr(i)),xr=i=>(typeof i.detached=="boolean"?xr=u=>u.detached:xr=u=>u.byteLength===0,xr(i));function ef(i,u,h){if(i.slice)return i.slice(u,h);let E=h-u,R=new ArrayBuffer(E);return Zd(R,0,i,u,E),R}function ms(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 R0(i){let u={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*u})(),E=h.next;return{iterator:h,nextMethod:E,done:!1}}let Xa=($e=(lr=Symbol.asyncIterator)!==null&&lr!==void 0?lr:(Ye=Symbol.for)===null||Ye===void 0?void 0:Ye.call(Symbol,"Symbol.asyncIterator"))!==null&&$e!==void 0?$e:"@@asyncIterator";function tf(i,u="sync",h){if(h===void 0)if(u==="async"){if(h=ms(i,Xa),h===void 0){let L=ms(i,Symbol.iterator),$=tf(i,"sync",L);return R0($)}}else h=ms(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let E=v(h,i,[]);if(!r(E))throw new TypeError("The iterator method must return an object");let R=E.next;return{iterator:E,nextMethod:R,done:!1}}function x0(i){let u=v(i.nextMethod,i.iterator,[]);if(!r(u))throw new TypeError("The iterator.next() method must return an object");return u}function O0(i){return!!i.done}function F0(i){return i.value}function P0(i){return!(typeof i!="number"||dt(i)||i<0)}function rf(i){let u=ef(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function Za(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function eu(i,u,h){if(!P0(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 I0(i){return i._queue.peek().value}function Or(i){i._queue=new D,i._queueTotalSize=0}function nf(i){return i===DataView}function B0(i){return nf(i.constructor)}function N0(i){return nf(i)?1:i.BYTES_PER_ELEMENT}class Xr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!tu(this))throw iu("view");return this._view}respond(u){if(!tu(this))throw iu("respond");if(je(u,1,"respond"),u=F(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(xr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");bs(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!tu(this))throw iu("respondWithNewView");if(je(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(xr(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Cs(this._associatedReadableByteStreamController,u)}}Object.defineProperties(Xr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(Xr.prototype.respond,"respond"),o(Xr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Xr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class fr{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Zr(this))throw _o("byobRequest");return su(this)}get desiredSize(){if(!Zr(this))throw _o("desiredSize");return pf(this)}close(){if(!Zr(this))throw _o("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`);yo(this)}enqueue(u){if(!Zr(this))throw _o("enqueue");if(je(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`);_s(this,u)}error(u=void 0){if(!Zr(this))throw _o("error");Et(this,u)}[J](u){of(this),Or(this);let h=this._cancelAlgorithm(u);return ys(this),h}[B](u){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){hf(this,u);return}let E=this._autoAllocateChunkSize;if(E!==void 0){let R;try{R=new ArrayBuffer(E)}catch($){u._errorSteps($);return}let L={buffer:R,bufferByteLength:E,byteOffset:0,byteLength:E,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}x(h,u),en(this)}[Y](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new D,this._pendingPullIntos.push(u)}}}Object.defineProperties(fr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(fr.prototype.close,"close"),o(fr.prototype.enqueue,"enqueue"),o(fr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(fr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Zr(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof fr}function tu(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof Xr}function en(i){if(!$0(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();b(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,en(i)),null),E=>(Et(i,E),null))}function of(i){nu(i),i._pendingPullIntos=new D}function ru(i,u){let h=!1;i._state==="closed"&&(h=!0);let E=sf(u);u.readerType==="default"?P(i,E,h):J0(i,E,h)}function sf(i){let u=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/h)}function gs(i,u,h,E){i._queue.push({buffer:u,byteOffset:h,byteLength:E}),i._queueTotalSize+=E}function af(i,u,h,E){let R;try{R=ef(u,h,h+E)}catch(L){throw Et(i,L),L}gs(i,R,0,E)}function uf(i,u){u.bytesFilled>0&&af(i,u.buffer,u.byteOffset,u.bytesFilled),En(i)}function cf(i,u){let h=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),E=u.bytesFilled+h,R=h,L=!1,$=E%u.elementSize,Q=E-$;Q>=u.minimumFill&&(R=Q-u.bytesFilled,L=!0);let le=i._queue;for(;R>0;){let oe=le.peek(),he=Math.min(R,oe.byteLength),ye=u.byteOffset+u.bytesFilled;Zd(u.buffer,ye,oe.buffer,oe.byteOffset,he),oe.byteLength===he?le.shift():(oe.byteOffset+=he,oe.byteLength-=he),i._queueTotalSize-=he,lf(i,he,u),R-=he}return L}function lf(i,u,h){h.bytesFilled+=u}function df(i){i._queueTotalSize===0&&i._closeRequested?(ys(i),ko(i._controlledReadableByteStream)):en(i)}function nu(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function ou(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();cf(i,u)&&(En(i),ru(i._controlledReadableByteStream,u))}}function M0(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=u._readRequests.shift();hf(i,h)}}function j0(i,u,h,E){let R=i._controlledReadableByteStream,L=u.constructor,$=N0(L),{byteOffset:Q,byteLength:le}=u,oe=h*$,he;try{he=dr(u.buffer)}catch(Re){E._errorSteps(Re);return}let ye={buffer:he,bufferByteLength:he.byteLength,byteOffset:Q,byteLength:le,bytesFilled:0,minimumFill:oe,elementSize:$,viewConstructor:L,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(ye),yf(R,E);return}if(R._state==="closed"){let Re=new L(ye.buffer,ye.byteOffset,0);E._closeSteps(Re);return}if(i._queueTotalSize>0){if(cf(i,ye)){let Re=sf(ye);df(i),E._chunkSteps(Re);return}if(i._closeRequested){let Re=new TypeError("Insufficient bytes to fill elements in the given buffer");Et(i,Re),E._errorSteps(Re);return}}i._pendingPullIntos.push(ye),yf(R,E),en(i)}function L0(i,u){u.readerType==="none"&&En(i);let h=i._controlledReadableByteStream;if(au(h))for(;_f(h)>0;){let E=En(i);ru(h,E)}}function U0(i,u,h){if(lf(i,u,h),h.readerType==="none"){uf(i,h),ou(i);return}if(h.bytesFilled<h.minimumFill)return;En(i);let E=h.bytesFilled%h.elementSize;if(E>0){let R=h.byteOffset+h.bytesFilled;af(i,h.buffer,R-E,E)}h.bytesFilled-=E,ru(i._controlledReadableByteStream,h),ou(i)}function ff(i,u){let h=i._pendingPullIntos.peek();nu(i),i._controlledReadableByteStream._state==="closed"?L0(i,h):U0(i,u,h),en(i)}function En(i){return i._pendingPullIntos.shift()}function $0(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(N(u)&&j(u)>0||au(u)&&_f(u)>0||pf(i)>0)}function ys(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function yo(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 E=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Et(i,E),E}}ys(i),ko(u)}}function _s(i,u){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:E,byteOffset:R,byteLength:L}=u;if(xr(E))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let $=dr(E);if(i._pendingPullIntos.length>0){let Q=i._pendingPullIntos.peek();if(xr(Q.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");nu(i),Q.buffer=dr(Q.buffer),Q.readerType==="none"&&uf(i,Q)}if(N(h))if(M0(i),j(h)===0)gs(i,$,R,L);else{i._pendingPullIntos.length>0&&En(i);let Q=new Uint8Array($,R,L);P(h,Q,!1)}else au(h)?(gs(i,$,R,L),ou(i)):gs(i,$,R,L);en(i)}function Et(i,u){let h=i._controlledReadableByteStream;h._state==="readable"&&(of(i),Or(i),ys(i),qf(h,u))}function hf(i,u){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,df(i);let E=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);u._chunkSteps(E)}function su(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),E=Object.create(Xr.prototype);z0(E,i,h),i._byobRequest=E}return i._byobRequest}function pf(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function bs(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=dr(h.buffer),ff(i,u)}function Cs(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 R=u.byteLength;h.buffer=dr(u.buffer),ff(i,R)}function mf(i,u,h,E,R,L,$){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Or(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=L,u._pullAlgorithm=E,u._cancelAlgorithm=R,u._autoAllocateChunkSize=$,u._pendingPullIntos=new D,i._readableStreamController=u;let Q=h();b(f(Q),()=>(u._started=!0,en(u),null),le=>(Et(u,le),null))}function q0(i,u,h){let E=Object.create(fr.prototype),R,L,$;u.start!==void 0?R=()=>u.start(E):R=()=>{},u.pull!==void 0?L=()=>u.pull(E):L=()=>f(void 0),u.cancel!==void 0?$=le=>u.cancel(le):$=()=>f(void 0);let Q=u.autoAllocateChunkSize;if(Q===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");mf(i,E,R,L,$,h,Q)}function z0(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 _o(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function H0(i,u){de(i,u);let h=i?.mode;return{mode:h===void 0?void 0:W0(h,`${u} has member 'mode' that`)}}function W0(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function G0(i,u){var h;de(i,u);let E=(h=i?.min)!==null&&h!==void 0?h:1;return{min:F(E,`${u} has member 'min' that`)}}function gf(i){return new Fr(i)}function yf(i,u){i._reader._readIntoRequests.push(u)}function J0(i,u,h){let R=i._reader._readIntoRequests.shift();h?R._closeSteps(u):R._chunkSteps(u)}function _f(i){return i._reader._readIntoRequests.length}function au(i){let u=i._reader;return!(u===void 0||!tn(u))}class Fr{constructor(u){if(je(u,1,"ReadableStreamBYOBReader"),I(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Zr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");re(this,u),this._readIntoRequests=new D}get closed(){return tn(this)?this._closedPromise:d(ws("closed"))}cancel(u=void 0){return tn(this)?this._ownerReadableStream===void 0?d(fe("cancel")):ee(this,u):d(ws("cancel"))}read(u,h={}){if(!tn(this))return d(ws("read"));if(!ArrayBuffer.isView(u))return d(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(xr(u.buffer))return d(new TypeError("view's buffer has been detached"));let E;try{E=G0(h,"options")}catch(oe){return d(oe)}let R=E.min;if(R===0)return d(new TypeError("options.min must be greater than 0"));if(B0(u)){if(R>u.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(R>u.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(fe("read from"));let L,$,Q=l((oe,he)=>{L=oe,$=he});return bf(this,u,R,{_chunkSteps:oe=>L({value:oe,done:!1}),_closeSteps:oe=>L({value:oe,done:!0}),_errorSteps:oe=>$(oe)}),Q}releaseLock(){if(!tn(this))throw ws("releaseLock");this._ownerReadableStream!==void 0&&V0(this)}}Object.defineProperties(Fr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Fr.prototype.cancel,"cancel"),o(Fr.prototype.read,"read"),o(Fr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function tn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Fr}function bf(i,u,h,E){let R=i._ownerReadableStream;R._disturbed=!0,R._state==="errored"?E._errorSteps(R._storedError):j0(R._readableStreamController,u,h,E)}function V0(i){ue(i);let u=new TypeError("Reader was released");Cf(i,u)}function Cf(i,u){let h=i._readIntoRequests;i._readIntoRequests=new D,h.forEach(E=>{E._errorSteps(u)})}function ws(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function bo(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 Es(i){let{size:u}=i;return u||(()=>1)}function As(i,u){de(i,u);let h=i?.highWaterMark,E=i?.size;return{highWaterMark:h===void 0?void 0:S(h),size:E===void 0?void 0:K0(E,`${u} has member 'size' that`)}}function K0(i,u){return _e(i,u),h=>S(i(h))}function Y0(i,u){de(i,u);let h=i?.abort,E=i?.close,R=i?.start,L=i?.type,$=i?.write;return{abort:h===void 0?void 0:Q0(h,i,`${u} has member 'abort' that`),close:E===void 0?void 0:X0(E,i,`${u} has member 'close' that`),start:R===void 0?void 0:Z0(R,i,`${u} has member 'start' that`),write:$===void 0?void 0:e_($,i,`${u} has member 'write' that`),type:L}}function Q0(i,u,h){return _e(i,h),E=>_(i,u,[E])}function X0(i,u,h){return _e(i,h),()=>_(i,u,[])}function Z0(i,u,h){return _e(i,h),E=>v(i,u,[E])}function e_(i,u,h){return _e(i,h),(E,R)=>_(i,u,[E,R])}function wf(i,u){if(!An(i))throw new TypeError(`${u} is not a WritableStream.`)}function t_(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let r_=typeof AbortController=="function";function n_(){if(r_)return new AbortController}class Pr{constructor(u={},h={}){u===void 0?u=null:xe(u,"First parameter");let E=As(h,"Second parameter"),R=Y0(u,"First parameter");if(Af(this),R.type!==void 0)throw new RangeError("Invalid type is specified");let $=Es(E),Q=bo(E,1);y_(this,R,Q,$)}get locked(){if(!An(this))throw Ds("locked");return kn(this)}abort(u=void 0){return An(this)?kn(this)?d(new TypeError("Cannot abort a stream that already has a writer")):ks(this,u):d(Ds("abort"))}close(){return An(this)?kn(this)?d(new TypeError("Cannot close a stream that already has a writer")):Kt(this)?d(new TypeError("Cannot close an already-closing stream")):kf(this):d(Ds("close"))}getWriter(){if(!An(this))throw Ds("getWriter");return Ef(this)}}Object.defineProperties(Pr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(Pr.prototype.abort,"abort"),o(Pr.prototype.close,"close"),o(Pr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Pr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Ef(i){return new hr(i)}function o_(i,u,h,E,R=1,L=()=>1){let $=Object.create(Pr.prototype);Af($);let Q=Object.create(Sn.prototype);return xf($,Q,i,u,h,E,R,L),$}function Af(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new D,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function An(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof Pr}function kn(i){return i._writer!==void 0}function ks(i,u){var h;if(i._state==="closed"||i._state==="errored")return f(void 0);i._writableStreamController._abortReason=u,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(u);let E=i._state;if(E==="closed"||E==="errored")return f(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let R=!1;E==="erroring"&&(R=!0,u=void 0);let L=l(($,Q)=>{i._pendingAbortRequest={_promise:void 0,_resolve:$,_reject:Q,_reason:u,_wasAlreadyErroring:R}});return i._pendingAbortRequest._promise=L,R||cu(i,u),L}function kf(i){let u=i._state;if(u==="closed"||u==="errored")return d(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let h=l((R,L)=>{let $={_resolve:R,_reject:L};i._closeRequest=$}),E=i._writer;return E!==void 0&&i._backpressure&&u==="writable"&&yu(E),__(i._writableStreamController),h}function s_(i){return l((h,E)=>{let R={_resolve:h,_reject:E};i._writeRequests.push(R)})}function uu(i,u){if(i._state==="writable"){cu(i,u);return}lu(i)}function cu(i,u){let h=i._writableStreamController;i._state="erroring",i._storedError=u;let E=i._writer;E!==void 0&&vf(E,u),!l_(i)&&h._started&&lu(i)}function lu(i){i._state="errored",i._writableStreamController[q]();let u=i._storedError;if(i._writeRequests.forEach(R=>{R._reject(u)}),i._writeRequests=new D,i._pendingAbortRequest===void 0){Ss(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(u),Ss(i);return}let E=i._writableStreamController[O](h._reason);b(E,()=>(h._resolve(),Ss(i),null),R=>(h._reject(R),Ss(i),null))}function i_(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function a_(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,uu(i,u)}function u_(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&&If(h)}function c_(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),uu(i,u)}function Kt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function l_(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function d_(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function f_(i){i._inFlightWriteRequest=i._writeRequests.shift()}function Ss(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&mu(u,i._storedError)}function du(i,u){let h=i._writer;h!==void 0&&u!==i._backpressure&&(u?S_(h):yu(h)),i._backpressure=u}class hr{constructor(u){if(je(u,1,"WritableStreamDefaultWriter"),wf(u,"First parameter"),kn(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")!Kt(u)&&u._backpressure?xs(this):Bf(this),Rs(this);else if(h==="erroring")gu(this,u._storedError),Rs(this);else if(h==="closed")Bf(this),A_(this);else{let E=u._storedError;gu(this,E),Pf(this,E)}}get closed(){return rn(this)?this._closedPromise:d(nn("closed"))}get desiredSize(){if(!rn(this))throw nn("desiredSize");if(this._ownerWritableStream===void 0)throw wo("desiredSize");return g_(this)}get ready(){return rn(this)?this._readyPromise:d(nn("ready"))}abort(u=void 0){return rn(this)?this._ownerWritableStream===void 0?d(wo("abort")):h_(this,u):d(nn("abort"))}close(){if(!rn(this))return d(nn("close"));let u=this._ownerWritableStream;return u===void 0?d(wo("close")):Kt(u)?d(new TypeError("Cannot close an already-closing stream")):Sf(this)}releaseLock(){if(!rn(this))throw nn("releaseLock");this._ownerWritableStream!==void 0&&Tf(this)}write(u=void 0){return rn(this)?this._ownerWritableStream===void 0?d(wo("write to")):Df(this,u):d(nn("write"))}}Object.defineProperties(hr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(hr.prototype.abort,"abort"),o(hr.prototype.close,"close"),o(hr.prototype.releaseLock,"releaseLock"),o(hr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(hr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function rn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof hr}function h_(i,u){let h=i._ownerWritableStream;return ks(h,u)}function Sf(i){let u=i._ownerWritableStream;return kf(u)}function p_(i){let u=i._ownerWritableStream,h=u._state;return Kt(u)||h==="closed"?f(void 0):h==="errored"?d(u._storedError):Sf(i)}function m_(i,u){i._closedPromiseState==="pending"?mu(i,u):k_(i,u)}function vf(i,u){i._readyPromiseState==="pending"?Nf(i,u):v_(i,u)}function g_(i){let u=i._ownerWritableStream,h=u._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:Of(u._writableStreamController)}function Tf(i){let u=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");vf(i,h),m_(i,h),u._writer=void 0,i._ownerWritableStream=void 0}function Df(i,u){let h=i._ownerWritableStream,E=h._writableStreamController,R=b_(E,u);if(h!==i._ownerWritableStream)return d(wo("write to"));let L=h._state;if(L==="errored")return d(h._storedError);if(Kt(h)||L==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return d(h._storedError);let $=s_(h);return C_(E,u,R),$}let Rf={};class Sn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!fu(this))throw pu("abortReason");return this._abortReason}get signal(){if(!fu(this))throw pu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!fu(this))throw pu("error");this._controlledWritableStream._state==="writable"&&Ff(this,u)}[O](u){let h=this._abortAlgorithm(u);return vs(this),h}[q](){Or(this)}}Object.defineProperties(Sn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Sn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function fu(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Sn}function xf(i,u,h,E,R,L,$,Q){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Or(u),u._abortReason=void 0,u._abortController=n_(),u._started=!1,u._strategySizeAlgorithm=Q,u._strategyHWM=$,u._writeAlgorithm=E,u._closeAlgorithm=R,u._abortAlgorithm=L;let le=hu(u);du(i,le);let oe=h(),he=f(oe);b(he,()=>(u._started=!0,Ts(u),null),ye=>(u._started=!0,uu(i,ye),null))}function y_(i,u,h,E){let R=Object.create(Sn.prototype),L,$,Q,le;u.start!==void 0?L=()=>u.start(R):L=()=>{},u.write!==void 0?$=oe=>u.write(oe,R):$=()=>f(void 0),u.close!==void 0?Q=()=>u.close():Q=()=>f(void 0),u.abort!==void 0?le=oe=>u.abort(oe):le=()=>f(void 0),xf(i,R,L,$,Q,le,h,E)}function vs(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function __(i){eu(i,Rf,0),Ts(i)}function b_(i,u){try{return i._strategySizeAlgorithm(u)}catch(h){return Co(i,h),1}}function Of(i){return i._strategyHWM-i._queueTotalSize}function C_(i,u,h){try{eu(i,u,h)}catch(R){Co(i,R);return}let E=i._controlledWritableStream;if(!Kt(E)&&E._state==="writable"){let R=hu(i);du(E,R)}Ts(i)}function Ts(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 E=I0(i);E===Rf?w_(i):E_(i,E)}function Co(i,u){i._controlledWritableStream._state==="writable"&&Ff(i,u)}function w_(i){let u=i._controlledWritableStream;d_(u),Za(i);let h=i._closeAlgorithm();vs(i),b(h,()=>(u_(u),null),E=>(c_(u,E),null))}function E_(i,u){let h=i._controlledWritableStream;f_(h);let E=i._writeAlgorithm(u);b(E,()=>{i_(h);let R=h._state;if(Za(i),!Kt(h)&&R==="writable"){let L=hu(i);du(h,L)}return Ts(i),null},R=>(h._state==="writable"&&vs(i),a_(h,R),null))}function hu(i){return Of(i)<=0}function Ff(i,u){let h=i._controlledWritableStream;vs(i),cu(h,u)}function Ds(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function pu(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function nn(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function wo(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Rs(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function Pf(i,u){Rs(i),mu(i,u)}function A_(i){Rs(i),If(i)}function mu(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function k_(i,u){Pf(i,u)}function If(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 xs(i){i._readyPromise=l((u,h)=>{i._readyPromise_resolve=u,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function gu(i,u){xs(i),Nf(i,u)}function Bf(i){xs(i),yu(i)}function Nf(i,u){i._readyPromise_reject!==void 0&&(g(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function S_(i){xs(i)}function v_(i,u){gu(i,u)}function yu(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 T_(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let _u=T_();function D_(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function R_(){let i=_u?.DOMException;return D_(i)?i:void 0}function x_(){let i=function(h,E){this.message=h||"",this.name=E||"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 O_=R_()||x_();function Mf(i,u,h,E,R,L){let $=U(i),Q=Ef(u);i._disturbed=!0;let le=!1,oe=f(void 0);return l((he,ye)=>{let Re;if(L!==void 0){if(Re=()=>{let se=L.reason!==void 0?L.reason:new O_("Aborted","AbortError"),be=[];E||be.push(()=>u._state==="writable"?ks(u,se):f(void 0)),R||be.push(()=>i._state==="readable"?Nt(i,se):f(void 0)),ot(()=>Promise.all(be.map(Oe=>Oe())),!0,se)},L.aborted){Re();return}L.addEventListener("abort",Re)}function Mt(){return l((se,be)=>{function Oe(ft){ft?se():p(Rn(),Oe,be)}Oe(!1)})}function Rn(){return le?f(!0):p(Q._readyPromise,()=>l((se,be)=>{te($,{_chunkSteps:Oe=>{oe=p(Df(Q,Oe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(mr(i,$._closedPromise,se=>(E?At(!0,se):ot(()=>ks(u,se),!0,se),null)),mr(u,Q._closedPromise,se=>(R?At(!0,se):ot(()=>Nt(i,se),!0,se),null)),Ze(i,$._closedPromise,()=>(h?At():ot(()=>p_(Q)),null)),Kt(u)||u._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");R?At(!0,se):ot(()=>Nt(i,se),!0,se)}g(Mt());function Mr(){let se=oe;return p(oe,()=>se!==oe?Mr():void 0)}function mr(se,be,Oe){se._state==="errored"?Oe(se._storedError):C(be,Oe)}function Ze(se,be,Oe){se._state==="closed"?Oe():k(be,Oe)}function ot(se,be,Oe){if(le)return;le=!0,u._state==="writable"&&!Kt(u)?k(Mr(),ft):ft();function ft(){return b(se(),()=>gr(be,Oe),xn=>gr(!0,xn)),null}}function At(se,be){le||(le=!0,u._state==="writable"&&!Kt(u)?k(Mr(),()=>gr(se,be)):gr(se,be))}function gr(se,be){return Tf(Q),ue($),L!==void 0&&L.removeEventListener("abort",Re),se?ye(be):he(void 0),null}})}class pr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Os(this))throw Ps("desiredSize");return bu(this)}close(){if(!Os(this))throw Ps("close");if(!Tn(this))throw new TypeError("The stream is not in a state that permits close");on(this)}enqueue(u=void 0){if(!Os(this))throw Ps("enqueue");if(!Tn(this))throw new TypeError("The stream is not in a state that permits enqueue");return vn(this,u)}error(u=void 0){if(!Os(this))throw Ps("error");Bt(this,u)}[J](u){Or(this);let h=this._cancelAlgorithm(u);return Fs(this),h}[B](u){let h=this._controlledReadableStream;if(this._queue.length>0){let E=Za(this);this._closeRequested&&this._queue.length===0?(Fs(this),ko(h)):Eo(this),u._chunkSteps(E)}else x(h,u),Eo(this)}[Y](){}}Object.defineProperties(pr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(pr.prototype.close,"close"),o(pr.prototype.enqueue,"enqueue"),o(pr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Os(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof pr}function Eo(i){if(!jf(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();b(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,Eo(i)),null),E=>(Bt(i,E),null))}function jf(i){let u=i._controlledReadableStream;return!Tn(i)||!i._started?!1:!!(Br(u)&&j(u)>0||bu(i)>0)}function Fs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function on(i){if(!Tn(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Fs(i),ko(u))}function vn(i,u){if(!Tn(i))return;let h=i._controlledReadableStream;if(Br(h)&&j(h)>0)P(h,u,!1);else{let E;try{E=i._strategySizeAlgorithm(u)}catch(R){throw Bt(i,R),R}try{eu(i,u,E)}catch(R){throw Bt(i,R),R}}Eo(i)}function Bt(i,u){let h=i._controlledReadableStream;h._state==="readable"&&(Or(i),Fs(i),qf(h,u))}function bu(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function F_(i){return!jf(i)}function Tn(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function Lf(i,u,h,E,R,L,$){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Or(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=$,u._strategyHWM=L,u._pullAlgorithm=E,u._cancelAlgorithm=R,i._readableStreamController=u;let Q=h();b(f(Q),()=>(u._started=!0,Eo(u),null),le=>(Bt(u,le),null))}function P_(i,u,h,E){let R=Object.create(pr.prototype),L,$,Q;u.start!==void 0?L=()=>u.start(R):L=()=>{},u.pull!==void 0?$=()=>u.pull(R):$=()=>f(void 0),u.cancel!==void 0?Q=le=>u.cancel(le):Q=()=>f(void 0),Lf(i,R,L,$,Q,h,E)}function Ps(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function I_(i,u){return Zr(i._readableStreamController)?N_(i):B_(i)}function B_(i,u){let h=U(i),E=!1,R=!1,L=!1,$=!1,Q,le,oe,he,ye,Re=l(Ze=>{ye=Ze});function Mt(){return E?(R=!0,f(void 0)):(E=!0,te(h,{_chunkSteps:ot=>{m(()=>{R=!1;let At=ot,gr=ot;L||vn(oe._readableStreamController,At),$||vn(he._readableStreamController,gr),E=!1,R&&Mt()})},_closeSteps:()=>{E=!1,L||on(oe._readableStreamController),$||on(he._readableStreamController),(!L||!$)&&ye(void 0)},_errorSteps:()=>{E=!1}}),f(void 0))}function Rn(Ze){if(L=!0,Q=Ze,$){let ot=ve([Q,le]),At=Nt(i,ot);ye(At)}return Re}function Mr(Ze){if($=!0,le=Ze,L){let ot=ve([Q,le]),At=Nt(i,ot);ye(At)}return Re}function mr(){}return oe=Ao(mr,Mt,Rn),he=Ao(mr,Mt,Mr),C(h._closedPromise,Ze=>(Bt(oe._readableStreamController,Ze),Bt(he._readableStreamController,Ze),(!L||!$)&&ye(void 0),null)),[oe,he]}function N_(i){let u=U(i),h=!1,E=!1,R=!1,L=!1,$=!1,Q,le,oe,he,ye,Re=l(se=>{ye=se});function Mt(se){C(se._closedPromise,be=>(se!==u||(Et(oe._readableStreamController,be),Et(he._readableStreamController,be),(!L||!$)&&ye(void 0)),null))}function Rn(){tn(u)&&(ue(u),u=U(i),Mt(u)),te(u,{_chunkSteps:be=>{m(()=>{E=!1,R=!1;let Oe=be,ft=be;if(!L&&!$)try{ft=rf(be)}catch(xn){Et(oe._readableStreamController,xn),Et(he._readableStreamController,xn),ye(Nt(i,xn));return}L||_s(oe._readableStreamController,Oe),$||_s(he._readableStreamController,ft),h=!1,E?mr():R&&Ze()})},_closeSteps:()=>{h=!1,L||yo(oe._readableStreamController),$||yo(he._readableStreamController),oe._readableStreamController._pendingPullIntos.length>0&&bs(oe._readableStreamController,0),he._readableStreamController._pendingPullIntos.length>0&&bs(he._readableStreamController,0),(!L||!$)&&ye(void 0)},_errorSteps:()=>{h=!1}})}function Mr(se,be){Z(u)&&(ue(u),u=gf(i),Mt(u));let Oe=be?he:oe,ft=be?oe:he;bf(u,se,1,{_chunkSteps:On=>{m(()=>{E=!1,R=!1;let Fn=be?$:L;if(be?L:$)Fn||Cs(Oe._readableStreamController,On);else{let th;try{th=rf(On)}catch(ku){Et(Oe._readableStreamController,ku),Et(ft._readableStreamController,ku),ye(Nt(i,ku));return}Fn||Cs(Oe._readableStreamController,On),_s(ft._readableStreamController,th)}h=!1,E?mr():R&&Ze()})},_closeSteps:On=>{h=!1;let Fn=be?$:L,$s=be?L:$;Fn||yo(Oe._readableStreamController),$s||yo(ft._readableStreamController),On!==void 0&&(Fn||Cs(Oe._readableStreamController,On),!$s&&ft._readableStreamController._pendingPullIntos.length>0&&bs(ft._readableStreamController,0)),(!Fn||!$s)&&ye(void 0)},_errorSteps:()=>{h=!1}})}function mr(){if(h)return E=!0,f(void 0);h=!0;let se=su(oe._readableStreamController);return se===null?Rn():Mr(se._view,!1),f(void 0)}function Ze(){if(h)return R=!0,f(void 0);h=!0;let se=su(he._readableStreamController);return se===null?Rn():Mr(se._view,!0),f(void 0)}function ot(se){if(L=!0,Q=se,$){let be=ve([Q,le]),Oe=Nt(i,be);ye(Oe)}return Re}function At(se){if($=!0,le=se,L){let be=ve([Q,le]),Oe=Nt(i,be);ye(Oe)}return Re}function gr(){}return oe=$f(gr,mr,ot),he=$f(gr,Ze,At),Mt(u),[oe,he]}function M_(i){return r(i)&&typeof i.getReader<"u"}function j_(i){return M_(i)?U_(i.getReader()):L_(i)}function L_(i){let u,h=tf(i,"async"),E=e;function R(){let $;try{$=x0(h)}catch(le){return d(le)}let Q=f($);return y(Q,le=>{if(!r(le))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(O0(le))on(u._readableStreamController);else{let he=F0(le);vn(u._readableStreamController,he)}})}function L($){let Q=h.iterator,le;try{le=ms(Q,"return")}catch(ye){return d(ye)}if(le===void 0)return f(void 0);let oe;try{oe=v(le,Q,[$])}catch(ye){return d(ye)}let he=f(oe);return y(he,ye=>{if(!r(ye))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=Ao(E,R,L,0),u}function U_(i){let u,h=e;function E(){let L;try{L=i.read()}catch($){return d($)}return y(L,$=>{if(!r($))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if($.done)on(u._readableStreamController);else{let Q=$.value;vn(u._readableStreamController,Q)}})}function R(L){try{return f(i.cancel(L))}catch($){return d($)}}return u=Ao(h,E,R,0),u}function $_(i,u){de(i,u);let h=i,E=h?.autoAllocateChunkSize,R=h?.cancel,L=h?.pull,$=h?.start,Q=h?.type;return{autoAllocateChunkSize:E===void 0?void 0:F(E,`${u} has member 'autoAllocateChunkSize' that`),cancel:R===void 0?void 0:q_(R,h,`${u} has member 'cancel' that`),pull:L===void 0?void 0:z_(L,h,`${u} has member 'pull' that`),start:$===void 0?void 0:H_($,h,`${u} has member 'start' that`),type:Q===void 0?void 0:W_(Q,`${u} has member 'type' that`)}}function q_(i,u,h){return _e(i,h),E=>_(i,u,[E])}function z_(i,u,h){return _e(i,h),E=>_(i,u,[E])}function H_(i,u,h){return _e(i,h),E=>v(i,u,[E])}function W_(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function G_(i,u){return de(i,u),{preventCancel:!!i?.preventCancel}}function Uf(i,u){de(i,u);let h=i?.preventAbort,E=i?.preventCancel,R=i?.preventClose,L=i?.signal;return L!==void 0&&J_(L,`${u} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!E,preventClose:!!R,signal:L}}function J_(i,u){if(!t_(i))throw new TypeError(`${u} is not an AbortSignal.`)}function V_(i,u){de(i,u);let h=i?.readable;w(h,"readable","ReadableWritablePair"),I(h,`${u} has member 'readable' that`);let E=i?.writable;return w(E,"writable","ReadableWritablePair"),wf(E,`${u} has member 'writable' that`),{readable:h,writable:E}}class Qe{constructor(u={},h={}){u===void 0?u=null:xe(u,"First parameter");let E=As(h,"Second parameter"),R=$_(u,"First parameter");if(Cu(this),R.type==="bytes"){if(E.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=bo(E,0);q0(this,R,L)}else{let L=Es(E),$=bo(E,1);P_(this,R,$,L)}}get locked(){if(!Ir(this))throw sn("locked");return Br(this)}cancel(u=void 0){return Ir(this)?Br(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Nt(this,u):d(sn("cancel"))}getReader(u=void 0){if(!Ir(this))throw sn("getReader");return H0(u,"First parameter").mode===void 0?U(this):gf(this)}pipeThrough(u,h={}){if(!Ir(this))throw sn("pipeThrough");je(u,1,"pipeThrough");let E=V_(u,"First parameter"),R=Uf(h,"Second parameter");if(Br(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(kn(E.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=Mf(this,E.writable,R.preventClose,R.preventAbort,R.preventCancel,R.signal);return g(L),E.readable}pipeTo(u,h={}){if(!Ir(this))return d(sn("pipeTo"));if(u===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!An(u))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let E;try{E=Uf(h,"Second parameter")}catch(R){return d(R)}return Br(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):kn(u)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Mf(this,u,E.preventClose,E.preventAbort,E.preventCancel,E.signal)}tee(){if(!Ir(this))throw sn("tee");let u=I_(this);return ve(u)}values(u=void 0){if(!Ir(this))throw sn("values");let h=G_(u,"First parameter");return bn(this,h.preventCancel)}[Xa](u){return this.values(u)}static from(u){return j_(u)}}Object.defineProperties(Qe,{from:{enumerable:!0}}),Object.defineProperties(Qe.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Qe.from,"from"),o(Qe.prototype.cancel,"cancel"),o(Qe.prototype.getReader,"getReader"),o(Qe.prototype.pipeThrough,"pipeThrough"),o(Qe.prototype.pipeTo,"pipeTo"),o(Qe.prototype.tee,"tee"),o(Qe.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Qe.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Qe.prototype,Xa,{value:Qe.prototype.values,writable:!0,configurable:!0});function Ao(i,u,h,E=1,R=()=>1){let L=Object.create(Qe.prototype);Cu(L);let $=Object.create(pr.prototype);return Lf(L,$,i,u,h,E,R),L}function $f(i,u,h){let E=Object.create(Qe.prototype);Cu(E);let R=Object.create(fr.prototype);return mf(E,R,i,u,h,0,void 0),E}function Cu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Ir(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof Qe}function Br(i){return i._reader!==void 0}function Nt(i,u){if(i._disturbed=!0,i._state==="closed")return f(void 0);if(i._state==="errored")return d(i._storedError);ko(i);let h=i._reader;if(h!==void 0&&tn(h)){let R=h._readIntoRequests;h._readIntoRequests=new D,R.forEach(L=>{L._closeSteps(void 0)})}let E=i._readableStreamController[J](u);return y(E,e)}function ko(i){i._state="closed";let u=i._reader;if(u!==void 0&&(ce(u),Z(u))){let h=u._readRequests;u._readRequests=new D,h.forEach(E=>{E._closeSteps()})}}function qf(i,u){i._state="errored",i._storedError=u;let h=i._reader;h!==void 0&&(G(h,u),Z(h)?Pe(h,u):Cf(h,u))}function sn(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function zf(i,u){de(i,u);let h=i?.highWaterMark;return w(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:S(h)}}let Hf=i=>i.byteLength;o(Hf,"size");class Is{constructor(u){je(u,1,"ByteLengthQueuingStrategy"),u=zf(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Gf(this))throw Wf("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Gf(this))throw Wf("size");return Hf}}Object.defineProperties(Is.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Is.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Wf(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function Gf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof Is}let Jf=()=>1;o(Jf,"size");class Bs{constructor(u){je(u,1,"CountQueuingStrategy"),u=zf(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Kf(this))throw Vf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Kf(this))throw Vf("size");return Jf}}Object.defineProperties(Bs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Bs.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Vf(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function Kf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof Bs}function K_(i,u){de(i,u);let h=i?.cancel,E=i?.flush,R=i?.readableType,L=i?.start,$=i?.transform,Q=i?.writableType;return{cancel:h===void 0?void 0:Z_(h,i,`${u} has member 'cancel' that`),flush:E===void 0?void 0:Y_(E,i,`${u} has member 'flush' that`),readableType:R,start:L===void 0?void 0:Q_(L,i,`${u} has member 'start' that`),transform:$===void 0?void 0:X_($,i,`${u} has member 'transform' that`),writableType:Q}}function Y_(i,u,h){return _e(i,h),E=>_(i,u,[E])}function Q_(i,u,h){return _e(i,h),E=>v(i,u,[E])}function X_(i,u,h){return _e(i,h),(E,R)=>_(i,u,[E,R])}function Z_(i,u,h){return _e(i,h),E=>_(i,u,[E])}class Ns{constructor(u={},h={},E={}){u===void 0&&(u=null);let R=As(h,"Second parameter"),L=As(E,"Third parameter"),$=K_(u,"First parameter");if($.readableType!==void 0)throw new RangeError("Invalid readableType specified");if($.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Q=bo(L,0),le=Es(L),oe=bo(R,1),he=Es(R),ye,Re=l(Mt=>{ye=Mt});eb(this,Re,oe,he,Q,le),rb(this,$),$.start!==void 0?ye($.start(this._transformStreamController)):ye(void 0)}get readable(){if(!Yf(this))throw eh("readable");return this._readable}get writable(){if(!Yf(this))throw eh("writable");return this._writable}}Object.defineProperties(Ns.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ns.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function eb(i,u,h,E,R,L){function $(){return u}function Q(Re){return sb(i,Re)}function le(Re){return ib(i,Re)}function oe(){return ab(i)}i._writable=o_($,Q,oe,le,h,E);function he(){return ub(i)}function ye(Re){return cb(i,Re)}i._readable=Ao($,he,ye,R,L),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,Ms(i,!0),i._transformStreamController=void 0}function Yf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof Ns}function Qf(i,u){Bt(i._readable._readableStreamController,u),wu(i,u)}function wu(i,u){Ls(i._transformStreamController),Co(i._writable._writableStreamController,u),Eu(i)}function Eu(i){i._backpressure&&Ms(i,!1)}function Ms(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=u}class Nr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!js(this))throw Us("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return bu(u)}enqueue(u=void 0){if(!js(this))throw Us("enqueue");Xf(this,u)}error(u=void 0){if(!js(this))throw Us("error");nb(this,u)}terminate(){if(!js(this))throw Us("terminate");ob(this)}}Object.defineProperties(Nr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Nr.prototype.enqueue,"enqueue"),o(Nr.prototype.error,"error"),o(Nr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Nr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function js(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof Nr}function tb(i,u,h,E,R){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=h,u._flushAlgorithm=E,u._cancelAlgorithm=R,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function rb(i,u){let h=Object.create(Nr.prototype),E,R,L;u.transform!==void 0?E=$=>u.transform($,h):E=$=>{try{return Xf(h,$),f(void 0)}catch(Q){return d(Q)}},u.flush!==void 0?R=()=>u.flush(h):R=()=>f(void 0),u.cancel!==void 0?L=$=>u.cancel($):L=()=>f(void 0),tb(i,h,E,R,L)}function Ls(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function Xf(i,u){let h=i._controlledTransformStream,E=h._readable._readableStreamController;if(!Tn(E))throw new TypeError("Readable side is not in a state that permits enqueue");try{vn(E,u)}catch(L){throw wu(h,L),h._readable._storedError}F_(E)!==h._backpressure&&Ms(h,!0)}function nb(i,u){Qf(i._controlledTransformStream,u)}function Zf(i,u){let h=i._transformAlgorithm(u);return y(h,void 0,E=>{throw Qf(i._controlledTransformStream,E),E})}function ob(i){let u=i._controlledTransformStream,h=u._readable._readableStreamController;on(h);let E=new TypeError("TransformStream terminated");wu(u,E)}function sb(i,u){let h=i._transformStreamController;if(i._backpressure){let E=i._backpressureChangePromise;return y(E,()=>{let R=i._writable;if(R._state==="erroring")throw R._storedError;return Zf(h,u)})}return Zf(h,u)}function ib(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let E=i._readable;h._finishPromise=l((L,$)=>{h._finishPromise_resolve=L,h._finishPromise_reject=$});let R=h._cancelAlgorithm(u);return Ls(h),b(R,()=>(E._state==="errored"?Dn(h,E._storedError):(Bt(E._readableStreamController,u),Au(h)),null),L=>(Bt(E._readableStreamController,L),Dn(h,L),null)),h._finishPromise}function ab(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let h=i._readable;u._finishPromise=l((R,L)=>{u._finishPromise_resolve=R,u._finishPromise_reject=L});let E=u._flushAlgorithm();return Ls(u),b(E,()=>(h._state==="errored"?Dn(u,h._storedError):(on(h._readableStreamController),Au(u)),null),R=>(Bt(h._readableStreamController,R),Dn(u,R),null)),u._finishPromise}function ub(i){return Ms(i,!1),i._backpressureChangePromise}function cb(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let E=i._writable;h._finishPromise=l((L,$)=>{h._finishPromise_resolve=L,h._finishPromise_reject=$});let R=h._cancelAlgorithm(u);return Ls(h),b(R,()=>(E._state==="errored"?Dn(h,E._storedError):(Co(E._writableStreamController,u),Eu(i),Au(h)),null),L=>(Co(E._writableStreamController,L),Eu(i),Dn(h,L),null)),h._finishPromise}function Us(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function Au(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Dn(i,u){i._finishPromise_reject!==void 0&&(g(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function eh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=Is,t.CountQueuingStrategy=Bs,t.ReadableByteStreamController=fr,t.ReadableStream=Qe,t.ReadableStreamBYOBReader=Fr,t.ReadableStreamBYOBRequest=Xr,t.ReadableStreamDefaultController=pr,t.ReadableStreamDefaultReader=z,t.TransformStream=Ns,t.TransformStreamDefaultController=Nr,t.WritableStream=Pr,t.WritableStreamDefaultController=Sn,t.WritableStreamDefaultWriter=hr}))});var bp=V(()=>{if(!globalThis.ReadableStream)try{let t=X("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,X("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,_p())}try{let{Blob:t}=X("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();n+=c.byteLength,s.enqueue(new Uint8Array(c)),n===o.size&&s.close()}})})}catch{}});async function*tc(t,e=!0){for(let r of t)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(e){let n=r.byteOffset,o=r.byteOffset+r.byteLength;for(;n!==o;){let s=Math.min(o-n,Cp),a=r.buffer.slice(n,n+s);n+=a.byteLength,yield new Uint8Array(a)}}else yield r;else{let n=0,o=r;for(;n!==o.size;){let a=await o.slice(n,Math.min(o.size,n+Cp)).arrayBuffer();n+=a.byteLength,yield new Uint8Array(a)}}}var PR,Cp,wp,HC,Lt,Oo=Me(()=>{PR=jr(bp(),1);Cp=65536;wp=class rc{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],r={}){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 r!="object"&&typeof r!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");r===null&&(r={});let n=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 rc?a=s:a=n.encode(`${s}`),this.#r+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let o=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of tc(this.#e,!1))r+=e.decode(n,{stream:!0});return r+=e.decode(),r}async arrayBuffer(){let e=new Uint8Array(this.size),r=0;for await(let n of tc(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=tc(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await e.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,r=this.size,n=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=r<0?Math.max(o+r,0):Math.min(r,o),c=Math.max(a-s,0),l=this.#e,f=[],d=0;for(let b of l){if(d>=c)break;let k=ArrayBuffer.isView(b)?b.byteLength:b.size;if(s&&k<=s)s-=k,a-=k;else{let C;ArrayBuffer.isView(b)?(C=b.subarray(s,Math.min(k,a)),d+=C.byteLength):(C=b.slice(s,Math.min(k,a)),d+=C.size),a-=k,f.push(C),s=0}}let p=new rc([],{type:String(n).toLowerCase()});return p.#r=c,p.#e=f,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(wp.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});HC=wp,Lt=HC});var WC,GC,$r,nc=Me(()=>{Oo();WC=class extends Lt{#e=0;#t="";constructor(e,r,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let o=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Lt&&/^(File)$/.test(e[Symbol.toStringTag])}},GC=WC,$r=GC});function kp(t,e=Lt){var r=`${Ep()}${Ep()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${r}\r
|
|
26
|
+
`);let{connect:f,buffered:d}=await l;if(e.emit("proxyConnect",f),this.emit("proxyConnect",f,e),f.statusCode===200)return e.once("socket",qC),r.secureEndpoint?(xo("Upgrading socket connection to TLS"),cp.connect({...dp(lp(r),"host","path","port"),socket:o})):o;o.destroy();let p=new ci.Socket({writable:!1});return p.readable=!0,e.once("socket",C=>{xo("Replaying proxy buffer for failed request"),(0,MC.default)(C.listenerCount("data")>0),C.push(d),C.push(null)}),p}};li.protocols=["http","https"];vt.HttpsProxyAgent=li;function qC(t){t.resume()}function dp(t,...e){let r={},n;for(n in t)e.includes(n)||(r[n]=t[n]);return r}});function zC(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 r=t.substring(5,e).split(";"),n="",o=!1,s=r[0]||"text/plain",a=s;for(let d=1;d<r.length;d++)r[d]==="base64"?o=!0:r[d]&&(a+=`;${r[d]}`,r[d].indexOf("charset=")===0&&(n=r[d].substring(8)));!r[0]&&!n.length&&(a+=";charset=US-ASCII",n="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),f=Buffer.from(l,c);return f.type=s,f.typeFull=a,f.charset=n,f}var mp,gp=Me(()=>{mp=zC});var _p=V((di,yp)=>{(function(t,e){typeof di=="object"&&typeof yp<"u"?e(di):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.WebStreamsPolyfill={}))})(di,(function(t){"use strict";function e(){}function r(i){return typeof i=="object"&&i!==null||typeof i=="function"}let n=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 f(i){return l(u=>u(i))}function d(i){return c(i)}function p(i,u,h){return a.call(i,u,h)}function C(i,u,h){p(p(i,u,h),void 0,n)}function k(i,u){C(i,u)}function _(i,u){C(i,void 0,u)}function y(i,u,h){return p(i,u,h)}function g(i){p(i,void 0,n)}let m=i=>{if(typeof queueMicrotask=="function")m=queueMicrotask;else{let u=f(void 0);m=h=>p(u,h)}return m(i)};function v(i,u,h){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,h)}function b(i,u,h){try{return f(v(i,u,h))}catch(E){return d(E)}}let A=16384;class D{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,E=h;h._elements.length===A-1&&(E={_elements:[],_next:void 0}),h._elements.push(u),E!==h&&(this._back=E,h._next=E),++this._size}shift(){let u=this._front,h=u,E=this._cursor,R=E+1,L=u._elements,$=L[E];return R===A&&(h=u._next,R=0),--this._size,this._cursor=R,u!==h&&(this._front=h),L[E]=void 0,$}forEach(u){let h=this._cursor,E=this._front,R=E._elements;for(;(h!==R.length||E._next!==void 0)&&!(h===R.length&&(E=E._next,R=E._elements,h=0,R.length===0));)u(R[h]),++h}peek(){let u=this._front,h=this._cursor;return u._elements[h]}}let O=Symbol("[[AbortSteps]]"),q=Symbol("[[ErrorSteps]]"),J=Symbol("[[CancelSteps]]"),B=Symbol("[[PullSteps]]"),Y=Symbol("[[ReleaseSteps]]");function re(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?ke(i):u._state==="closed"?me(i):ie(i,u._storedError)}function ee(i,u){let h=i._ownerReadableStream;return Nt(h,u)}function ue(i){let u=i._ownerReadableStream;u._state==="readable"?G(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):K(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[Y](),u._reader=void 0,i._ownerReadableStream=void 0}function fe(i){return new TypeError("Cannot "+i+" a stream using a released reader")}function ke(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h})}function ie(i,u){ke(i),G(i,u)}function me(i){ke(i),ce(i)}function G(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}function K(i,u){ie(i,u)}function ce(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}let qe=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},De=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function W(i){return typeof i=="object"||typeof i=="function"}function de(i,u){if(i!==void 0&&!W(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 It(i){return typeof i=="object"&&i!==null||typeof i=="function"}function xe(i,u){if(!It(i))throw new TypeError(`${u} is not an object.`)}function je(i,u,h){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${h}'.`)}function w(i,u,h){if(i===void 0)throw new TypeError(`${u} is required in '${h}'.`)}function S(i){return Number(i)}function T(i){return i===0?0:i}function M(i){return T(De(i))}function F(i,u){let E=Number.MAX_SAFE_INTEGER,R=Number(i);if(R=T(R),!qe(R))throw new TypeError(`${u} is not a finite number`);if(R=M(R),R<0||R>E)throw new TypeError(`${u} is outside the accepted range of 0 to ${E}, inclusive`);return!qe(R)||R===0?0:R}function I(i,u){if(!Ir(i))throw new TypeError(`${u} is not a ReadableStream.`)}function U(i){return new z(i)}function x(i,u){i._reader._readRequests.push(u)}function P(i,u,h){let R=i._reader._readRequests.shift();h?R._closeSteps():R._chunkSteps(u)}function j(i){return i._reader._readRequests.length}function N(i){let u=i._reader;return!(u===void 0||!Z(u))}class z{constructor(u){if(je(u,1,"ReadableStreamDefaultReader"),I(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");re(this,u),this._readRequests=new D}get closed(){return Z(this)?this._closedPromise:d(Ne("closed"))}cancel(u=void 0){return Z(this)?this._ownerReadableStream===void 0?d(fe("cancel")):ee(this,u):d(Ne("cancel"))}read(){if(!Z(this))return d(Ne("read"));if(this._ownerReadableStream===void 0)return d(fe("read from"));let u,h,E=l((L,$)=>{u=L,h=$});return te(this,{_chunkSteps:L=>u({value:L,done:!1}),_closeSteps:()=>u({value:void 0,done:!0}),_errorSteps:L=>h(L)}),E}releaseLock(){if(!Z(this))throw Ne("releaseLock");this._ownerReadableStream!==void 0&&Ae(this)}}Object.defineProperties(z.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(z.prototype.cancel,"cancel"),o(z.prototype.read,"read"),o(z.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(z.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Z(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof z}function te(i,u){let h=i._ownerReadableStream;h._disturbed=!0,h._state==="closed"?u._closeSteps():h._state==="errored"?u._errorSteps(h._storedError):h._readableStreamController[B](u)}function Ae(i){ue(i);let u=new TypeError("Reader was released");Pe(i,u)}function Pe(i,u){let h=i._readRequests;i._readRequests=new D,h.forEach(E=>{E._errorSteps(u)})}function Ne(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,E,R=l(($,Q)=>{h=$,E=Q});return te(u,{_chunkSteps:$=>{this._ongoingPromise=void 0,m(()=>h({value:$,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),h({value:void 0,done:!0})},_errorSteps:$=>{this._ongoingPromise=void 0,this._isFinished=!0,ue(u),E($)}}),R}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let h=this._reader;if(!this._preventCancel){let E=ee(h,u);return ue(h),y(E,()=>({value:u,done:!0}))}return ue(h),f({value:u,done:!0})}}let Ue={next(){return Cn(this)?this._asyncIteratorImpl.next():d(wn("next"))},return(i){return Cn(this)?this._asyncIteratorImpl.return(i):d(wn("return"))}};Object.setPrototypeOf(Ue,we);function bn(i,u){let h=U(i),E=new Se(h,u),R=Object.create(Ue);return R._asyncIteratorImpl=E,R}function Cn(i){if(!r(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof Se}catch{return!1}}function wn(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}let dt=Number.isNaN||function(i){return i!==i};var lr,Ye,$e;function ve(i){return i.slice()}function Zd(i,u,h,E,R){new Uint8Array(i).set(new Uint8Array(h,E,R),u)}let dr=i=>(typeof i.transfer=="function"?dr=u=>u.transfer():typeof structuredClone=="function"?dr=u=>structuredClone(u,{transfer:[u]}):dr=u=>u,dr(i)),xr=i=>(typeof i.detached=="boolean"?xr=u=>u.detached:xr=u=>u.byteLength===0,xr(i));function ef(i,u,h){if(i.slice)return i.slice(u,h);let E=h-u,R=new ArrayBuffer(E);return Zd(R,0,i,u,E),R}function ms(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 R0(i){let u={[Symbol.iterator]:()=>i.iterator},h=(async function*(){return yield*u})(),E=h.next;return{iterator:h,nextMethod:E,done:!1}}let Xa=($e=(lr=Symbol.asyncIterator)!==null&&lr!==void 0?lr:(Ye=Symbol.for)===null||Ye===void 0?void 0:Ye.call(Symbol,"Symbol.asyncIterator"))!==null&&$e!==void 0?$e:"@@asyncIterator";function tf(i,u="sync",h){if(h===void 0)if(u==="async"){if(h=ms(i,Xa),h===void 0){let L=ms(i,Symbol.iterator),$=tf(i,"sync",L);return R0($)}}else h=ms(i,Symbol.iterator);if(h===void 0)throw new TypeError("The object is not iterable");let E=v(h,i,[]);if(!r(E))throw new TypeError("The iterator method must return an object");let R=E.next;return{iterator:E,nextMethod:R,done:!1}}function x0(i){let u=v(i.nextMethod,i.iterator,[]);if(!r(u))throw new TypeError("The iterator.next() method must return an object");return u}function O0(i){return!!i.done}function F0(i){return i.value}function P0(i){return!(typeof i!="number"||dt(i)||i<0)}function rf(i){let u=ef(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}function Za(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}function eu(i,u,h){if(!P0(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 I0(i){return i._queue.peek().value}function Or(i){i._queue=new D,i._queueTotalSize=0}function nf(i){return i===DataView}function B0(i){return nf(i.constructor)}function N0(i){return nf(i)?1:i.BYTES_PER_ELEMENT}class Xr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!tu(this))throw iu("view");return this._view}respond(u){if(!tu(this))throw iu("respond");if(je(u,1,"respond"),u=F(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(xr(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");bs(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!tu(this))throw iu("respondWithNewView");if(je(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(xr(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Cs(this._associatedReadableByteStreamController,u)}}Object.defineProperties(Xr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(Xr.prototype.respond,"respond"),o(Xr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Xr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class fr{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Zr(this))throw _o("byobRequest");return su(this)}get desiredSize(){if(!Zr(this))throw _o("desiredSize");return pf(this)}close(){if(!Zr(this))throw _o("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`);yo(this)}enqueue(u){if(!Zr(this))throw _o("enqueue");if(je(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`);_s(this,u)}error(u=void 0){if(!Zr(this))throw _o("error");Et(this,u)}[J](u){of(this),Or(this);let h=this._cancelAlgorithm(u);return ys(this),h}[B](u){let h=this._controlledReadableByteStream;if(this._queueTotalSize>0){hf(this,u);return}let E=this._autoAllocateChunkSize;if(E!==void 0){let R;try{R=new ArrayBuffer(E)}catch($){u._errorSteps($);return}let L={buffer:R,bufferByteLength:E,byteOffset:0,byteLength:E,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}x(h,u),en(this)}[Y](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new D,this._pendingPullIntos.push(u)}}}Object.defineProperties(fr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(fr.prototype.close,"close"),o(fr.prototype.enqueue,"enqueue"),o(fr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(fr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Zr(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof fr}function tu(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof Xr}function en(i){if(!$0(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();C(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,en(i)),null),E=>(Et(i,E),null))}function of(i){nu(i),i._pendingPullIntos=new D}function ru(i,u){let h=!1;i._state==="closed"&&(h=!0);let E=sf(u);u.readerType==="default"?P(i,E,h):J0(i,E,h)}function sf(i){let u=i.bytesFilled,h=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/h)}function gs(i,u,h,E){i._queue.push({buffer:u,byteOffset:h,byteLength:E}),i._queueTotalSize+=E}function af(i,u,h,E){let R;try{R=ef(u,h,h+E)}catch(L){throw Et(i,L),L}gs(i,R,0,E)}function uf(i,u){u.bytesFilled>0&&af(i,u.buffer,u.byteOffset,u.bytesFilled),En(i)}function cf(i,u){let h=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),E=u.bytesFilled+h,R=h,L=!1,$=E%u.elementSize,Q=E-$;Q>=u.minimumFill&&(R=Q-u.bytesFilled,L=!0);let le=i._queue;for(;R>0;){let oe=le.peek(),he=Math.min(R,oe.byteLength),ye=u.byteOffset+u.bytesFilled;Zd(u.buffer,ye,oe.buffer,oe.byteOffset,he),oe.byteLength===he?le.shift():(oe.byteOffset+=he,oe.byteLength-=he),i._queueTotalSize-=he,lf(i,he,u),R-=he}return L}function lf(i,u,h){h.bytesFilled+=u}function df(i){i._queueTotalSize===0&&i._closeRequested?(ys(i),ko(i._controlledReadableByteStream)):en(i)}function nu(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}function ou(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();cf(i,u)&&(En(i),ru(i._controlledReadableByteStream,u))}}function M0(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let h=u._readRequests.shift();hf(i,h)}}function j0(i,u,h,E){let R=i._controlledReadableByteStream,L=u.constructor,$=N0(L),{byteOffset:Q,byteLength:le}=u,oe=h*$,he;try{he=dr(u.buffer)}catch(Re){E._errorSteps(Re);return}let ye={buffer:he,bufferByteLength:he.byteLength,byteOffset:Q,byteLength:le,bytesFilled:0,minimumFill:oe,elementSize:$,viewConstructor:L,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(ye),yf(R,E);return}if(R._state==="closed"){let Re=new L(ye.buffer,ye.byteOffset,0);E._closeSteps(Re);return}if(i._queueTotalSize>0){if(cf(i,ye)){let Re=sf(ye);df(i),E._chunkSteps(Re);return}if(i._closeRequested){let Re=new TypeError("Insufficient bytes to fill elements in the given buffer");Et(i,Re),E._errorSteps(Re);return}}i._pendingPullIntos.push(ye),yf(R,E),en(i)}function L0(i,u){u.readerType==="none"&&En(i);let h=i._controlledReadableByteStream;if(au(h))for(;_f(h)>0;){let E=En(i);ru(h,E)}}function U0(i,u,h){if(lf(i,u,h),h.readerType==="none"){uf(i,h),ou(i);return}if(h.bytesFilled<h.minimumFill)return;En(i);let E=h.bytesFilled%h.elementSize;if(E>0){let R=h.byteOffset+h.bytesFilled;af(i,h.buffer,R-E,E)}h.bytesFilled-=E,ru(i._controlledReadableByteStream,h),ou(i)}function ff(i,u){let h=i._pendingPullIntos.peek();nu(i),i._controlledReadableByteStream._state==="closed"?L0(i,h):U0(i,u,h),en(i)}function En(i){return i._pendingPullIntos.shift()}function $0(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(N(u)&&j(u)>0||au(u)&&_f(u)>0||pf(i)>0)}function ys(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}function yo(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 E=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Et(i,E),E}}ys(i),ko(u)}}function _s(i,u){let h=i._controlledReadableByteStream;if(i._closeRequested||h._state!=="readable")return;let{buffer:E,byteOffset:R,byteLength:L}=u;if(xr(E))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let $=dr(E);if(i._pendingPullIntos.length>0){let Q=i._pendingPullIntos.peek();if(xr(Q.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");nu(i),Q.buffer=dr(Q.buffer),Q.readerType==="none"&&uf(i,Q)}if(N(h))if(M0(i),j(h)===0)gs(i,$,R,L);else{i._pendingPullIntos.length>0&&En(i);let Q=new Uint8Array($,R,L);P(h,Q,!1)}else au(h)?(gs(i,$,R,L),ou(i)):gs(i,$,R,L);en(i)}function Et(i,u){let h=i._controlledReadableByteStream;h._state==="readable"&&(of(i),Or(i),ys(i),qf(h,u))}function hf(i,u){let h=i._queue.shift();i._queueTotalSize-=h.byteLength,df(i);let E=new Uint8Array(h.buffer,h.byteOffset,h.byteLength);u._chunkSteps(E)}function su(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),E=Object.create(Xr.prototype);z0(E,i,h),i._byobRequest=E}return i._byobRequest}function pf(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function bs(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=dr(h.buffer),ff(i,u)}function Cs(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 R=u.byteLength;h.buffer=dr(u.buffer),ff(i,R)}function mf(i,u,h,E,R,L,$){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Or(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=L,u._pullAlgorithm=E,u._cancelAlgorithm=R,u._autoAllocateChunkSize=$,u._pendingPullIntos=new D,i._readableStreamController=u;let Q=h();C(f(Q),()=>(u._started=!0,en(u),null),le=>(Et(u,le),null))}function q0(i,u,h){let E=Object.create(fr.prototype),R,L,$;u.start!==void 0?R=()=>u.start(E):R=()=>{},u.pull!==void 0?L=()=>u.pull(E):L=()=>f(void 0),u.cancel!==void 0?$=le=>u.cancel(le):$=()=>f(void 0);let Q=u.autoAllocateChunkSize;if(Q===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");mf(i,E,R,L,$,h,Q)}function z0(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 _o(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}function H0(i,u){de(i,u);let h=i?.mode;return{mode:h===void 0?void 0:W0(h,`${u} has member 'mode' that`)}}function W0(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}function G0(i,u){var h;de(i,u);let E=(h=i?.min)!==null&&h!==void 0?h:1;return{min:F(E,`${u} has member 'min' that`)}}function gf(i){return new Fr(i)}function yf(i,u){i._reader._readIntoRequests.push(u)}function J0(i,u,h){let R=i._reader._readIntoRequests.shift();h?R._closeSteps(u):R._chunkSteps(u)}function _f(i){return i._reader._readIntoRequests.length}function au(i){let u=i._reader;return!(u===void 0||!tn(u))}class Fr{constructor(u){if(je(u,1,"ReadableStreamBYOBReader"),I(u,"First parameter"),Br(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Zr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");re(this,u),this._readIntoRequests=new D}get closed(){return tn(this)?this._closedPromise:d(ws("closed"))}cancel(u=void 0){return tn(this)?this._ownerReadableStream===void 0?d(fe("cancel")):ee(this,u):d(ws("cancel"))}read(u,h={}){if(!tn(this))return d(ws("read"));if(!ArrayBuffer.isView(u))return d(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(xr(u.buffer))return d(new TypeError("view's buffer has been detached"));let E;try{E=G0(h,"options")}catch(oe){return d(oe)}let R=E.min;if(R===0)return d(new TypeError("options.min must be greater than 0"));if(B0(u)){if(R>u.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(R>u.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(fe("read from"));let L,$,Q=l((oe,he)=>{L=oe,$=he});return bf(this,u,R,{_chunkSteps:oe=>L({value:oe,done:!1}),_closeSteps:oe=>L({value:oe,done:!0}),_errorSteps:oe=>$(oe)}),Q}releaseLock(){if(!tn(this))throw ws("releaseLock");this._ownerReadableStream!==void 0&&V0(this)}}Object.defineProperties(Fr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Fr.prototype.cancel,"cancel"),o(Fr.prototype.read,"read"),o(Fr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function tn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof Fr}function bf(i,u,h,E){let R=i._ownerReadableStream;R._disturbed=!0,R._state==="errored"?E._errorSteps(R._storedError):j0(R._readableStreamController,u,h,E)}function V0(i){ue(i);let u=new TypeError("Reader was released");Cf(i,u)}function Cf(i,u){let h=i._readIntoRequests;i._readIntoRequests=new D,h.forEach(E=>{E._errorSteps(u)})}function ws(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}function bo(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 Es(i){let{size:u}=i;return u||(()=>1)}function As(i,u){de(i,u);let h=i?.highWaterMark,E=i?.size;return{highWaterMark:h===void 0?void 0:S(h),size:E===void 0?void 0:K0(E,`${u} has member 'size' that`)}}function K0(i,u){return _e(i,u),h=>S(i(h))}function Y0(i,u){de(i,u);let h=i?.abort,E=i?.close,R=i?.start,L=i?.type,$=i?.write;return{abort:h===void 0?void 0:Q0(h,i,`${u} has member 'abort' that`),close:E===void 0?void 0:X0(E,i,`${u} has member 'close' that`),start:R===void 0?void 0:Z0(R,i,`${u} has member 'start' that`),write:$===void 0?void 0:e_($,i,`${u} has member 'write' that`),type:L}}function Q0(i,u,h){return _e(i,h),E=>b(i,u,[E])}function X0(i,u,h){return _e(i,h),()=>b(i,u,[])}function Z0(i,u,h){return _e(i,h),E=>v(i,u,[E])}function e_(i,u,h){return _e(i,h),(E,R)=>b(i,u,[E,R])}function wf(i,u){if(!An(i))throw new TypeError(`${u} is not a WritableStream.`)}function t_(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}let r_=typeof AbortController=="function";function n_(){if(r_)return new AbortController}class Pr{constructor(u={},h={}){u===void 0?u=null:xe(u,"First parameter");let E=As(h,"Second parameter"),R=Y0(u,"First parameter");if(Af(this),R.type!==void 0)throw new RangeError("Invalid type is specified");let $=Es(E),Q=bo(E,1);y_(this,R,Q,$)}get locked(){if(!An(this))throw Ds("locked");return kn(this)}abort(u=void 0){return An(this)?kn(this)?d(new TypeError("Cannot abort a stream that already has a writer")):ks(this,u):d(Ds("abort"))}close(){return An(this)?kn(this)?d(new TypeError("Cannot close a stream that already has a writer")):Kt(this)?d(new TypeError("Cannot close an already-closing stream")):kf(this):d(Ds("close"))}getWriter(){if(!An(this))throw Ds("getWriter");return Ef(this)}}Object.defineProperties(Pr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(Pr.prototype.abort,"abort"),o(Pr.prototype.close,"close"),o(Pr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Pr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Ef(i){return new hr(i)}function o_(i,u,h,E,R=1,L=()=>1){let $=Object.create(Pr.prototype);Af($);let Q=Object.create(Sn.prototype);return xf($,Q,i,u,h,E,R,L),$}function Af(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new D,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}function An(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof Pr}function kn(i){return i._writer!==void 0}function ks(i,u){var h;if(i._state==="closed"||i._state==="errored")return f(void 0);i._writableStreamController._abortReason=u,(h=i._writableStreamController._abortController)===null||h===void 0||h.abort(u);let E=i._state;if(E==="closed"||E==="errored")return f(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let R=!1;E==="erroring"&&(R=!0,u=void 0);let L=l(($,Q)=>{i._pendingAbortRequest={_promise:void 0,_resolve:$,_reject:Q,_reason:u,_wasAlreadyErroring:R}});return i._pendingAbortRequest._promise=L,R||cu(i,u),L}function kf(i){let u=i._state;if(u==="closed"||u==="errored")return d(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let h=l((R,L)=>{let $={_resolve:R,_reject:L};i._closeRequest=$}),E=i._writer;return E!==void 0&&i._backpressure&&u==="writable"&&yu(E),__(i._writableStreamController),h}function s_(i){return l((h,E)=>{let R={_resolve:h,_reject:E};i._writeRequests.push(R)})}function uu(i,u){if(i._state==="writable"){cu(i,u);return}lu(i)}function cu(i,u){let h=i._writableStreamController;i._state="erroring",i._storedError=u;let E=i._writer;E!==void 0&&vf(E,u),!l_(i)&&h._started&&lu(i)}function lu(i){i._state="errored",i._writableStreamController[q]();let u=i._storedError;if(i._writeRequests.forEach(R=>{R._reject(u)}),i._writeRequests=new D,i._pendingAbortRequest===void 0){Ss(i);return}let h=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,h._wasAlreadyErroring){h._reject(u),Ss(i);return}let E=i._writableStreamController[O](h._reason);C(E,()=>(h._resolve(),Ss(i),null),R=>(h._reject(R),Ss(i),null))}function i_(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}function a_(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,uu(i,u)}function u_(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&&If(h)}function c_(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),uu(i,u)}function Kt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}function l_(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}function d_(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}function f_(i){i._inFlightWriteRequest=i._writeRequests.shift()}function Ss(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&mu(u,i._storedError)}function du(i,u){let h=i._writer;h!==void 0&&u!==i._backpressure&&(u?S_(h):yu(h)),i._backpressure=u}class hr{constructor(u){if(je(u,1,"WritableStreamDefaultWriter"),wf(u,"First parameter"),kn(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")!Kt(u)&&u._backpressure?xs(this):Bf(this),Rs(this);else if(h==="erroring")gu(this,u._storedError),Rs(this);else if(h==="closed")Bf(this),A_(this);else{let E=u._storedError;gu(this,E),Pf(this,E)}}get closed(){return rn(this)?this._closedPromise:d(nn("closed"))}get desiredSize(){if(!rn(this))throw nn("desiredSize");if(this._ownerWritableStream===void 0)throw wo("desiredSize");return g_(this)}get ready(){return rn(this)?this._readyPromise:d(nn("ready"))}abort(u=void 0){return rn(this)?this._ownerWritableStream===void 0?d(wo("abort")):h_(this,u):d(nn("abort"))}close(){if(!rn(this))return d(nn("close"));let u=this._ownerWritableStream;return u===void 0?d(wo("close")):Kt(u)?d(new TypeError("Cannot close an already-closing stream")):Sf(this)}releaseLock(){if(!rn(this))throw nn("releaseLock");this._ownerWritableStream!==void 0&&Tf(this)}write(u=void 0){return rn(this)?this._ownerWritableStream===void 0?d(wo("write to")):Df(this,u):d(nn("write"))}}Object.defineProperties(hr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(hr.prototype.abort,"abort"),o(hr.prototype.close,"close"),o(hr.prototype.releaseLock,"releaseLock"),o(hr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(hr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function rn(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof hr}function h_(i,u){let h=i._ownerWritableStream;return ks(h,u)}function Sf(i){let u=i._ownerWritableStream;return kf(u)}function p_(i){let u=i._ownerWritableStream,h=u._state;return Kt(u)||h==="closed"?f(void 0):h==="errored"?d(u._storedError):Sf(i)}function m_(i,u){i._closedPromiseState==="pending"?mu(i,u):k_(i,u)}function vf(i,u){i._readyPromiseState==="pending"?Nf(i,u):v_(i,u)}function g_(i){let u=i._ownerWritableStream,h=u._state;return h==="errored"||h==="erroring"?null:h==="closed"?0:Of(u._writableStreamController)}function Tf(i){let u=i._ownerWritableStream,h=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");vf(i,h),m_(i,h),u._writer=void 0,i._ownerWritableStream=void 0}function Df(i,u){let h=i._ownerWritableStream,E=h._writableStreamController,R=b_(E,u);if(h!==i._ownerWritableStream)return d(wo("write to"));let L=h._state;if(L==="errored")return d(h._storedError);if(Kt(h)||L==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return d(h._storedError);let $=s_(h);return C_(E,u,R),$}let Rf={};class Sn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!fu(this))throw pu("abortReason");return this._abortReason}get signal(){if(!fu(this))throw pu("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!fu(this))throw pu("error");this._controlledWritableStream._state==="writable"&&Ff(this,u)}[O](u){let h=this._abortAlgorithm(u);return vs(this),h}[q](){Or(this)}}Object.defineProperties(Sn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Sn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function fu(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof Sn}function xf(i,u,h,E,R,L,$,Q){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Or(u),u._abortReason=void 0,u._abortController=n_(),u._started=!1,u._strategySizeAlgorithm=Q,u._strategyHWM=$,u._writeAlgorithm=E,u._closeAlgorithm=R,u._abortAlgorithm=L;let le=hu(u);du(i,le);let oe=h(),he=f(oe);C(he,()=>(u._started=!0,Ts(u),null),ye=>(u._started=!0,uu(i,ye),null))}function y_(i,u,h,E){let R=Object.create(Sn.prototype),L,$,Q,le;u.start!==void 0?L=()=>u.start(R):L=()=>{},u.write!==void 0?$=oe=>u.write(oe,R):$=()=>f(void 0),u.close!==void 0?Q=()=>u.close():Q=()=>f(void 0),u.abort!==void 0?le=oe=>u.abort(oe):le=()=>f(void 0),xf(i,R,L,$,Q,le,h,E)}function vs(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function __(i){eu(i,Rf,0),Ts(i)}function b_(i,u){try{return i._strategySizeAlgorithm(u)}catch(h){return Co(i,h),1}}function Of(i){return i._strategyHWM-i._queueTotalSize}function C_(i,u,h){try{eu(i,u,h)}catch(R){Co(i,R);return}let E=i._controlledWritableStream;if(!Kt(E)&&E._state==="writable"){let R=hu(i);du(E,R)}Ts(i)}function Ts(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 E=I0(i);E===Rf?w_(i):E_(i,E)}function Co(i,u){i._controlledWritableStream._state==="writable"&&Ff(i,u)}function w_(i){let u=i._controlledWritableStream;d_(u),Za(i);let h=i._closeAlgorithm();vs(i),C(h,()=>(u_(u),null),E=>(c_(u,E),null))}function E_(i,u){let h=i._controlledWritableStream;f_(h);let E=i._writeAlgorithm(u);C(E,()=>{i_(h);let R=h._state;if(Za(i),!Kt(h)&&R==="writable"){let L=hu(i);du(h,L)}return Ts(i),null},R=>(h._state==="writable"&&vs(i),a_(h,R),null))}function hu(i){return Of(i)<=0}function Ff(i,u){let h=i._controlledWritableStream;vs(i),cu(h,u)}function Ds(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}function pu(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}function nn(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}function wo(i){return new TypeError("Cannot "+i+" a stream using a released writer")}function Rs(i){i._closedPromise=l((u,h)=>{i._closedPromise_resolve=u,i._closedPromise_reject=h,i._closedPromiseState="pending"})}function Pf(i,u){Rs(i),mu(i,u)}function A_(i){Rs(i),If(i)}function mu(i,u){i._closedPromise_reject!==void 0&&(g(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}function k_(i,u){Pf(i,u)}function If(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 xs(i){i._readyPromise=l((u,h)=>{i._readyPromise_resolve=u,i._readyPromise_reject=h}),i._readyPromiseState="pending"}function gu(i,u){xs(i),Nf(i,u)}function Bf(i){xs(i),yu(i)}function Nf(i,u){i._readyPromise_reject!==void 0&&(g(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}function S_(i){xs(i)}function v_(i,u){gu(i,u)}function yu(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 T_(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let _u=T_();function D_(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}function R_(){let i=_u?.DOMException;return D_(i)?i:void 0}function x_(){let i=function(h,E){this.message=h||"",this.name=E||"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 O_=R_()||x_();function Mf(i,u,h,E,R,L){let $=U(i),Q=Ef(u);i._disturbed=!0;let le=!1,oe=f(void 0);return l((he,ye)=>{let Re;if(L!==void 0){if(Re=()=>{let se=L.reason!==void 0?L.reason:new O_("Aborted","AbortError"),be=[];E||be.push(()=>u._state==="writable"?ks(u,se):f(void 0)),R||be.push(()=>i._state==="readable"?Nt(i,se):f(void 0)),ot(()=>Promise.all(be.map(Oe=>Oe())),!0,se)},L.aborted){Re();return}L.addEventListener("abort",Re)}function Mt(){return l((se,be)=>{function Oe(ft){ft?se():p(Rn(),Oe,be)}Oe(!1)})}function Rn(){return le?f(!0):p(Q._readyPromise,()=>l((se,be)=>{te($,{_chunkSteps:Oe=>{oe=p(Df(Q,Oe),void 0,e),se(!1)},_closeSteps:()=>se(!0),_errorSteps:be})}))}if(mr(i,$._closedPromise,se=>(E?At(!0,se):ot(()=>ks(u,se),!0,se),null)),mr(u,Q._closedPromise,se=>(R?At(!0,se):ot(()=>Nt(i,se),!0,se),null)),Ze(i,$._closedPromise,()=>(h?At():ot(()=>p_(Q)),null)),Kt(u)||u._state==="closed"){let se=new TypeError("the destination writable stream closed before all data could be piped to it");R?At(!0,se):ot(()=>Nt(i,se),!0,se)}g(Mt());function Mr(){let se=oe;return p(oe,()=>se!==oe?Mr():void 0)}function mr(se,be,Oe){se._state==="errored"?Oe(se._storedError):_(be,Oe)}function Ze(se,be,Oe){se._state==="closed"?Oe():k(be,Oe)}function ot(se,be,Oe){if(le)return;le=!0,u._state==="writable"&&!Kt(u)?k(Mr(),ft):ft();function ft(){return C(se(),()=>gr(be,Oe),xn=>gr(!0,xn)),null}}function At(se,be){le||(le=!0,u._state==="writable"&&!Kt(u)?k(Mr(),()=>gr(se,be)):gr(se,be))}function gr(se,be){return Tf(Q),ue($),L!==void 0&&L.removeEventListener("abort",Re),se?ye(be):he(void 0),null}})}class pr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Os(this))throw Ps("desiredSize");return bu(this)}close(){if(!Os(this))throw Ps("close");if(!Tn(this))throw new TypeError("The stream is not in a state that permits close");on(this)}enqueue(u=void 0){if(!Os(this))throw Ps("enqueue");if(!Tn(this))throw new TypeError("The stream is not in a state that permits enqueue");return vn(this,u)}error(u=void 0){if(!Os(this))throw Ps("error");Bt(this,u)}[J](u){Or(this);let h=this._cancelAlgorithm(u);return Fs(this),h}[B](u){let h=this._controlledReadableStream;if(this._queue.length>0){let E=Za(this);this._closeRequested&&this._queue.length===0?(Fs(this),ko(h)):Eo(this),u._chunkSteps(E)}else x(h,u),Eo(this)}[Y](){}}Object.defineProperties(pr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(pr.prototype.close,"close"),o(pr.prototype.enqueue,"enqueue"),o(pr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Os(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof pr}function Eo(i){if(!jf(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let h=i._pullAlgorithm();C(h,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,Eo(i)),null),E=>(Bt(i,E),null))}function jf(i){let u=i._controlledReadableStream;return!Tn(i)||!i._started?!1:!!(Br(u)&&j(u)>0||bu(i)>0)}function Fs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}function on(i){if(!Tn(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Fs(i),ko(u))}function vn(i,u){if(!Tn(i))return;let h=i._controlledReadableStream;if(Br(h)&&j(h)>0)P(h,u,!1);else{let E;try{E=i._strategySizeAlgorithm(u)}catch(R){throw Bt(i,R),R}try{eu(i,u,E)}catch(R){throw Bt(i,R),R}}Eo(i)}function Bt(i,u){let h=i._controlledReadableStream;h._state==="readable"&&(Or(i),Fs(i),qf(h,u))}function bu(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}function F_(i){return!jf(i)}function Tn(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}function Lf(i,u,h,E,R,L,$){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Or(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=$,u._strategyHWM=L,u._pullAlgorithm=E,u._cancelAlgorithm=R,i._readableStreamController=u;let Q=h();C(f(Q),()=>(u._started=!0,Eo(u),null),le=>(Bt(u,le),null))}function P_(i,u,h,E){let R=Object.create(pr.prototype),L,$,Q;u.start!==void 0?L=()=>u.start(R):L=()=>{},u.pull!==void 0?$=()=>u.pull(R):$=()=>f(void 0),u.cancel!==void 0?Q=le=>u.cancel(le):Q=()=>f(void 0),Lf(i,R,L,$,Q,h,E)}function Ps(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}function I_(i,u){return Zr(i._readableStreamController)?N_(i):B_(i)}function B_(i,u){let h=U(i),E=!1,R=!1,L=!1,$=!1,Q,le,oe,he,ye,Re=l(Ze=>{ye=Ze});function Mt(){return E?(R=!0,f(void 0)):(E=!0,te(h,{_chunkSteps:ot=>{m(()=>{R=!1;let At=ot,gr=ot;L||vn(oe._readableStreamController,At),$||vn(he._readableStreamController,gr),E=!1,R&&Mt()})},_closeSteps:()=>{E=!1,L||on(oe._readableStreamController),$||on(he._readableStreamController),(!L||!$)&&ye(void 0)},_errorSteps:()=>{E=!1}}),f(void 0))}function Rn(Ze){if(L=!0,Q=Ze,$){let ot=ve([Q,le]),At=Nt(i,ot);ye(At)}return Re}function Mr(Ze){if($=!0,le=Ze,L){let ot=ve([Q,le]),At=Nt(i,ot);ye(At)}return Re}function mr(){}return oe=Ao(mr,Mt,Rn),he=Ao(mr,Mt,Mr),_(h._closedPromise,Ze=>(Bt(oe._readableStreamController,Ze),Bt(he._readableStreamController,Ze),(!L||!$)&&ye(void 0),null)),[oe,he]}function N_(i){let u=U(i),h=!1,E=!1,R=!1,L=!1,$=!1,Q,le,oe,he,ye,Re=l(se=>{ye=se});function Mt(se){_(se._closedPromise,be=>(se!==u||(Et(oe._readableStreamController,be),Et(he._readableStreamController,be),(!L||!$)&&ye(void 0)),null))}function Rn(){tn(u)&&(ue(u),u=U(i),Mt(u)),te(u,{_chunkSteps:be=>{m(()=>{E=!1,R=!1;let Oe=be,ft=be;if(!L&&!$)try{ft=rf(be)}catch(xn){Et(oe._readableStreamController,xn),Et(he._readableStreamController,xn),ye(Nt(i,xn));return}L||_s(oe._readableStreamController,Oe),$||_s(he._readableStreamController,ft),h=!1,E?mr():R&&Ze()})},_closeSteps:()=>{h=!1,L||yo(oe._readableStreamController),$||yo(he._readableStreamController),oe._readableStreamController._pendingPullIntos.length>0&&bs(oe._readableStreamController,0),he._readableStreamController._pendingPullIntos.length>0&&bs(he._readableStreamController,0),(!L||!$)&&ye(void 0)},_errorSteps:()=>{h=!1}})}function Mr(se,be){Z(u)&&(ue(u),u=gf(i),Mt(u));let Oe=be?he:oe,ft=be?oe:he;bf(u,se,1,{_chunkSteps:On=>{m(()=>{E=!1,R=!1;let Fn=be?$:L;if(be?L:$)Fn||Cs(Oe._readableStreamController,On);else{let th;try{th=rf(On)}catch(ku){Et(Oe._readableStreamController,ku),Et(ft._readableStreamController,ku),ye(Nt(i,ku));return}Fn||Cs(Oe._readableStreamController,On),_s(ft._readableStreamController,th)}h=!1,E?mr():R&&Ze()})},_closeSteps:On=>{h=!1;let Fn=be?$:L,$s=be?L:$;Fn||yo(Oe._readableStreamController),$s||yo(ft._readableStreamController),On!==void 0&&(Fn||Cs(Oe._readableStreamController,On),!$s&&ft._readableStreamController._pendingPullIntos.length>0&&bs(ft._readableStreamController,0)),(!Fn||!$s)&&ye(void 0)},_errorSteps:()=>{h=!1}})}function mr(){if(h)return E=!0,f(void 0);h=!0;let se=su(oe._readableStreamController);return se===null?Rn():Mr(se._view,!1),f(void 0)}function Ze(){if(h)return R=!0,f(void 0);h=!0;let se=su(he._readableStreamController);return se===null?Rn():Mr(se._view,!0),f(void 0)}function ot(se){if(L=!0,Q=se,$){let be=ve([Q,le]),Oe=Nt(i,be);ye(Oe)}return Re}function At(se){if($=!0,le=se,L){let be=ve([Q,le]),Oe=Nt(i,be);ye(Oe)}return Re}function gr(){}return oe=$f(gr,mr,ot),he=$f(gr,Ze,At),Mt(u),[oe,he]}function M_(i){return r(i)&&typeof i.getReader<"u"}function j_(i){return M_(i)?U_(i.getReader()):L_(i)}function L_(i){let u,h=tf(i,"async"),E=e;function R(){let $;try{$=x0(h)}catch(le){return d(le)}let Q=f($);return y(Q,le=>{if(!r(le))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(O0(le))on(u._readableStreamController);else{let he=F0(le);vn(u._readableStreamController,he)}})}function L($){let Q=h.iterator,le;try{le=ms(Q,"return")}catch(ye){return d(ye)}if(le===void 0)return f(void 0);let oe;try{oe=v(le,Q,[$])}catch(ye){return d(ye)}let he=f(oe);return y(he,ye=>{if(!r(ye))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return u=Ao(E,R,L,0),u}function U_(i){let u,h=e;function E(){let L;try{L=i.read()}catch($){return d($)}return y(L,$=>{if(!r($))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if($.done)on(u._readableStreamController);else{let Q=$.value;vn(u._readableStreamController,Q)}})}function R(L){try{return f(i.cancel(L))}catch($){return d($)}}return u=Ao(h,E,R,0),u}function $_(i,u){de(i,u);let h=i,E=h?.autoAllocateChunkSize,R=h?.cancel,L=h?.pull,$=h?.start,Q=h?.type;return{autoAllocateChunkSize:E===void 0?void 0:F(E,`${u} has member 'autoAllocateChunkSize' that`),cancel:R===void 0?void 0:q_(R,h,`${u} has member 'cancel' that`),pull:L===void 0?void 0:z_(L,h,`${u} has member 'pull' that`),start:$===void 0?void 0:H_($,h,`${u} has member 'start' that`),type:Q===void 0?void 0:W_(Q,`${u} has member 'type' that`)}}function q_(i,u,h){return _e(i,h),E=>b(i,u,[E])}function z_(i,u,h){return _e(i,h),E=>b(i,u,[E])}function H_(i,u,h){return _e(i,h),E=>v(i,u,[E])}function W_(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}function G_(i,u){return de(i,u),{preventCancel:!!i?.preventCancel}}function Uf(i,u){de(i,u);let h=i?.preventAbort,E=i?.preventCancel,R=i?.preventClose,L=i?.signal;return L!==void 0&&J_(L,`${u} has member 'signal' that`),{preventAbort:!!h,preventCancel:!!E,preventClose:!!R,signal:L}}function J_(i,u){if(!t_(i))throw new TypeError(`${u} is not an AbortSignal.`)}function V_(i,u){de(i,u);let h=i?.readable;w(h,"readable","ReadableWritablePair"),I(h,`${u} has member 'readable' that`);let E=i?.writable;return w(E,"writable","ReadableWritablePair"),wf(E,`${u} has member 'writable' that`),{readable:h,writable:E}}class Qe{constructor(u={},h={}){u===void 0?u=null:xe(u,"First parameter");let E=As(h,"Second parameter"),R=$_(u,"First parameter");if(Cu(this),R.type==="bytes"){if(E.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=bo(E,0);q0(this,R,L)}else{let L=Es(E),$=bo(E,1);P_(this,R,$,L)}}get locked(){if(!Ir(this))throw sn("locked");return Br(this)}cancel(u=void 0){return Ir(this)?Br(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Nt(this,u):d(sn("cancel"))}getReader(u=void 0){if(!Ir(this))throw sn("getReader");return H0(u,"First parameter").mode===void 0?U(this):gf(this)}pipeThrough(u,h={}){if(!Ir(this))throw sn("pipeThrough");je(u,1,"pipeThrough");let E=V_(u,"First parameter"),R=Uf(h,"Second parameter");if(Br(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(kn(E.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=Mf(this,E.writable,R.preventClose,R.preventAbort,R.preventCancel,R.signal);return g(L),E.readable}pipeTo(u,h={}){if(!Ir(this))return d(sn("pipeTo"));if(u===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!An(u))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let E;try{E=Uf(h,"Second parameter")}catch(R){return d(R)}return Br(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):kn(u)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Mf(this,u,E.preventClose,E.preventAbort,E.preventCancel,E.signal)}tee(){if(!Ir(this))throw sn("tee");let u=I_(this);return ve(u)}values(u=void 0){if(!Ir(this))throw sn("values");let h=G_(u,"First parameter");return bn(this,h.preventCancel)}[Xa](u){return this.values(u)}static from(u){return j_(u)}}Object.defineProperties(Qe,{from:{enumerable:!0}}),Object.defineProperties(Qe.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Qe.from,"from"),o(Qe.prototype.cancel,"cancel"),o(Qe.prototype.getReader,"getReader"),o(Qe.prototype.pipeThrough,"pipeThrough"),o(Qe.prototype.pipeTo,"pipeTo"),o(Qe.prototype.tee,"tee"),o(Qe.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Qe.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Qe.prototype,Xa,{value:Qe.prototype.values,writable:!0,configurable:!0});function Ao(i,u,h,E=1,R=()=>1){let L=Object.create(Qe.prototype);Cu(L);let $=Object.create(pr.prototype);return Lf(L,$,i,u,h,E,R),L}function $f(i,u,h){let E=Object.create(Qe.prototype);Cu(E);let R=Object.create(fr.prototype);return mf(E,R,i,u,h,0,void 0),E}function Cu(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}function Ir(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof Qe}function Br(i){return i._reader!==void 0}function Nt(i,u){if(i._disturbed=!0,i._state==="closed")return f(void 0);if(i._state==="errored")return d(i._storedError);ko(i);let h=i._reader;if(h!==void 0&&tn(h)){let R=h._readIntoRequests;h._readIntoRequests=new D,R.forEach(L=>{L._closeSteps(void 0)})}let E=i._readableStreamController[J](u);return y(E,e)}function ko(i){i._state="closed";let u=i._reader;if(u!==void 0&&(ce(u),Z(u))){let h=u._readRequests;u._readRequests=new D,h.forEach(E=>{E._closeSteps()})}}function qf(i,u){i._state="errored",i._storedError=u;let h=i._reader;h!==void 0&&(G(h,u),Z(h)?Pe(h,u):Cf(h,u))}function sn(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}function zf(i,u){de(i,u);let h=i?.highWaterMark;return w(h,"highWaterMark","QueuingStrategyInit"),{highWaterMark:S(h)}}let Hf=i=>i.byteLength;o(Hf,"size");class Is{constructor(u){je(u,1,"ByteLengthQueuingStrategy"),u=zf(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Gf(this))throw Wf("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Gf(this))throw Wf("size");return Hf}}Object.defineProperties(Is.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Is.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Wf(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}function Gf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof Is}let Jf=()=>1;o(Jf,"size");class Bs{constructor(u){je(u,1,"CountQueuingStrategy"),u=zf(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Kf(this))throw Vf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Kf(this))throw Vf("size");return Jf}}Object.defineProperties(Bs.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Bs.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Vf(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}function Kf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof Bs}function K_(i,u){de(i,u);let h=i?.cancel,E=i?.flush,R=i?.readableType,L=i?.start,$=i?.transform,Q=i?.writableType;return{cancel:h===void 0?void 0:Z_(h,i,`${u} has member 'cancel' that`),flush:E===void 0?void 0:Y_(E,i,`${u} has member 'flush' that`),readableType:R,start:L===void 0?void 0:Q_(L,i,`${u} has member 'start' that`),transform:$===void 0?void 0:X_($,i,`${u} has member 'transform' that`),writableType:Q}}function Y_(i,u,h){return _e(i,h),E=>b(i,u,[E])}function Q_(i,u,h){return _e(i,h),E=>v(i,u,[E])}function X_(i,u,h){return _e(i,h),(E,R)=>b(i,u,[E,R])}function Z_(i,u,h){return _e(i,h),E=>b(i,u,[E])}class Ns{constructor(u={},h={},E={}){u===void 0&&(u=null);let R=As(h,"Second parameter"),L=As(E,"Third parameter"),$=K_(u,"First parameter");if($.readableType!==void 0)throw new RangeError("Invalid readableType specified");if($.writableType!==void 0)throw new RangeError("Invalid writableType specified");let Q=bo(L,0),le=Es(L),oe=bo(R,1),he=Es(R),ye,Re=l(Mt=>{ye=Mt});eb(this,Re,oe,he,Q,le),rb(this,$),$.start!==void 0?ye($.start(this._transformStreamController)):ye(void 0)}get readable(){if(!Yf(this))throw eh("readable");return this._readable}get writable(){if(!Yf(this))throw eh("writable");return this._writable}}Object.defineProperties(Ns.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ns.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function eb(i,u,h,E,R,L){function $(){return u}function Q(Re){return sb(i,Re)}function le(Re){return ib(i,Re)}function oe(){return ab(i)}i._writable=o_($,Q,oe,le,h,E);function he(){return ub(i)}function ye(Re){return cb(i,Re)}i._readable=Ao($,he,ye,R,L),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,Ms(i,!0),i._transformStreamController=void 0}function Yf(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof Ns}function Qf(i,u){Bt(i._readable._readableStreamController,u),wu(i,u)}function wu(i,u){Ls(i._transformStreamController),Co(i._writable._writableStreamController,u),Eu(i)}function Eu(i){i._backpressure&&Ms(i,!1)}function Ms(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=l(h=>{i._backpressureChangePromise_resolve=h}),i._backpressure=u}class Nr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!js(this))throw Us("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return bu(u)}enqueue(u=void 0){if(!js(this))throw Us("enqueue");Xf(this,u)}error(u=void 0){if(!js(this))throw Us("error");nb(this,u)}terminate(){if(!js(this))throw Us("terminate");ob(this)}}Object.defineProperties(Nr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Nr.prototype.enqueue,"enqueue"),o(Nr.prototype.error,"error"),o(Nr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Nr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function js(i){return!r(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof Nr}function tb(i,u,h,E,R){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=h,u._flushAlgorithm=E,u._cancelAlgorithm=R,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}function rb(i,u){let h=Object.create(Nr.prototype),E,R,L;u.transform!==void 0?E=$=>u.transform($,h):E=$=>{try{return Xf(h,$),f(void 0)}catch(Q){return d(Q)}},u.flush!==void 0?R=()=>u.flush(h):R=()=>f(void 0),u.cancel!==void 0?L=$=>u.cancel($):L=()=>f(void 0),tb(i,h,E,R,L)}function Ls(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}function Xf(i,u){let h=i._controlledTransformStream,E=h._readable._readableStreamController;if(!Tn(E))throw new TypeError("Readable side is not in a state that permits enqueue");try{vn(E,u)}catch(L){throw wu(h,L),h._readable._storedError}F_(E)!==h._backpressure&&Ms(h,!0)}function nb(i,u){Qf(i._controlledTransformStream,u)}function Zf(i,u){let h=i._transformAlgorithm(u);return y(h,void 0,E=>{throw Qf(i._controlledTransformStream,E),E})}function ob(i){let u=i._controlledTransformStream,h=u._readable._readableStreamController;on(h);let E=new TypeError("TransformStream terminated");wu(u,E)}function sb(i,u){let h=i._transformStreamController;if(i._backpressure){let E=i._backpressureChangePromise;return y(E,()=>{let R=i._writable;if(R._state==="erroring")throw R._storedError;return Zf(h,u)})}return Zf(h,u)}function ib(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let E=i._readable;h._finishPromise=l((L,$)=>{h._finishPromise_resolve=L,h._finishPromise_reject=$});let R=h._cancelAlgorithm(u);return Ls(h),C(R,()=>(E._state==="errored"?Dn(h,E._storedError):(Bt(E._readableStreamController,u),Au(h)),null),L=>(Bt(E._readableStreamController,L),Dn(h,L),null)),h._finishPromise}function ab(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let h=i._readable;u._finishPromise=l((R,L)=>{u._finishPromise_resolve=R,u._finishPromise_reject=L});let E=u._flushAlgorithm();return Ls(u),C(E,()=>(h._state==="errored"?Dn(u,h._storedError):(on(h._readableStreamController),Au(u)),null),R=>(Bt(h._readableStreamController,R),Dn(u,R),null)),u._finishPromise}function ub(i){return Ms(i,!1),i._backpressureChangePromise}function cb(i,u){let h=i._transformStreamController;if(h._finishPromise!==void 0)return h._finishPromise;let E=i._writable;h._finishPromise=l((L,$)=>{h._finishPromise_resolve=L,h._finishPromise_reject=$});let R=h._cancelAlgorithm(u);return Ls(h),C(R,()=>(E._state==="errored"?Dn(h,E._storedError):(Co(E._writableStreamController,u),Eu(i),Au(h)),null),L=>(Co(E._writableStreamController,L),Eu(i),Dn(h,L),null)),h._finishPromise}function Us(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}function Au(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function Dn(i,u){i._finishPromise_reject!==void 0&&(g(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}function eh(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}t.ByteLengthQueuingStrategy=Is,t.CountQueuingStrategy=Bs,t.ReadableByteStreamController=fr,t.ReadableStream=Qe,t.ReadableStreamBYOBReader=Fr,t.ReadableStreamBYOBRequest=Xr,t.ReadableStreamDefaultController=pr,t.ReadableStreamDefaultReader=z,t.TransformStream=Ns,t.TransformStreamDefaultController=Nr,t.WritableStream=Pr,t.WritableStreamDefaultController=Sn,t.WritableStreamDefaultWriter=hr}))});var bp=V(()=>{if(!globalThis.ReadableStream)try{let t=X("node:process"),{emitWarning:e}=t;try{t.emitWarning=()=>{},Object.assign(globalThis,X("node:stream/web")),t.emitWarning=e}catch(r){throw t.emitWarning=e,r}}catch{Object.assign(globalThis,_p())}try{let{Blob:t}=X("buffer");t&&!t.prototype.stream&&(t.prototype.stream=function(r){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let c=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();n+=c.byteLength,s.enqueue(new Uint8Array(c)),n===o.size&&s.close()}})})}catch{}});async function*tc(t,e=!0){for(let r of t)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(e){let n=r.byteOffset,o=r.byteOffset+r.byteLength;for(;n!==o;){let s=Math.min(o-n,Cp),a=r.buffer.slice(n,n+s);n+=a.byteLength,yield new Uint8Array(a)}}else yield r;else{let n=0,o=r;for(;n!==o.size;){let a=await o.slice(n,Math.min(o.size,n+Cp)).arrayBuffer();n+=a.byteLength,yield new Uint8Array(a)}}}var PR,Cp,wp,HC,Lt,Oo=Me(()=>{PR=jr(bp(),1);Cp=65536;wp=class rc{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],r={}){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 r!="object"&&typeof r!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");r===null&&(r={});let n=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 rc?a=s:a=n.encode(`${s}`),this.#r+=ArrayBuffer.isView(a)?a.byteLength:a.size,this.#e.push(a)}this.#n=`${r.endings===void 0?"transparent":r.endings}`;let o=r.type===void 0?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,r="";for await(let n of tc(this.#e,!1))r+=e.decode(n,{stream:!0});return r+=e.decode(),r}async arrayBuffer(){let e=new Uint8Array(this.size),r=0;for await(let n of tc(this.#e,!1))e.set(n,r),r+=n.length;return e.buffer}stream(){let e=tc(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(r){let n=await e.next();n.done?r.close():r.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,r=this.size,n=""){let{size:o}=this,s=e<0?Math.max(o+e,0):Math.min(e,o),a=r<0?Math.max(o+r,0):Math.min(r,o),c=Math.max(a-s,0),l=this.#e,f=[],d=0;for(let C of l){if(d>=c)break;let k=ArrayBuffer.isView(C)?C.byteLength:C.size;if(s&&k<=s)s-=k,a-=k;else{let _;ArrayBuffer.isView(C)?(_=C.subarray(s,Math.min(k,a)),d+=_.byteLength):(_=C.slice(s,Math.min(k,a)),d+=_.size),a-=k,f.push(_),s=0}}let p=new rc([],{type:String(n).toLowerCase()});return p.#r=c,p.#e=f,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(wp.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});HC=wp,Lt=HC});var WC,GC,$r,nc=Me(()=>{Oo();WC=class extends Lt{#e=0;#t="";constructor(e,r,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let o=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(r)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Lt&&/^(File)$/.test(e[Symbol.toStringTag])}},GC=WC,$r=GC});function kp(t,e=Lt){var r=`${Ep()}${Ep()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${r}\r
|
|
27
27
|
Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?n.push(o+oc(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
|
`)),n.push(`--${r}--`),new e(n,{type:"multipart/form-data; boundary="+r})}var Fo,JC,VC,Ep,KC,Ap,oc,dn,qr,fi=Me(()=>{Oo();nc();({toStringTag:Fo,iterator:JC,hasInstance:VC}=Symbol),Ep=Math.random,KC="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Ap=(t,e,r)=>(t+="",/^(Blob|File)$/.test(e&&e[Fo])?[(r=r!==void 0?r+"":e[Fo]=="File"?e.name:"blob",t),e.name!==r||e[Fo]=="blob"?new $r([e],r,e):e]:[t,e+""]),oc=(t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
|
|
36
|
-
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),dn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},qr=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Fo](){return"FormData"}[JC](){return this.entries()}static[VC](e){return e&&typeof e=="object"&&e[Fo]==="FormData"&&!KC.some(r=>typeof e[r]!="function")}append(...e){dn("append",arguments,2),this.#e.push(Ap(...e))}delete(e){dn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){dn("get",arguments,1),e+="";for(var r=this.#e,n=r.length,o=0;o<n;o++)if(r[o][0]===e)return r[o][1];return null}getAll(e,r){return dn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return dn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){dn("forEach",arguments,1);for(var[n,o]of this)e.call(r,o,n,this)}set(...e){dn("set",arguments,2);var r=[],n=!0;e=Ap(...e),this.#e.forEach(o=>{o[0]===e[0]?n&&(n=!r.push(e)):r.push(o)}),n&&r.push(e),this.#e=r}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Cr,hi=Me(()=>{Cr=class extends Error{constructor(e,r){super(e),Error.captureStackTrace(this,this.constructor),this.type=r}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var tt,sc=Me(()=>{hi();tt=class extends Cr{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var pi,ic,Po,Sp,vp,Tp,mi=Me(()=>{pi=Symbol.toStringTag,ic=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[pi]==="URLSearchParams",Po=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[pi]),Sp=t=>typeof t=="object"&&(t[pi]==="AbortSignal"||t[pi]==="EventTarget"),vp=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},Tp=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var Rp=V((GR,Dp)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=X("worker_threads"),e=new t().port1,r=new ArrayBuffer;e.postMessage(r,[r,r])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Dp.exports=globalThis.DOMException});import{statSync as xp,createReadStream as YC,promises as QC}from"node:fs";import{basename as XC}from"node:path";var Op,ac,Fp,Pp,Ip,Bp,Np,Mp,gi,uc=Me(()=>{Op=jr(Rp(),1);nc();Oo();({stat:ac}=QC),Fp=(t,e)=>Np(xp(t),t,e),Pp=(t,e)=>ac(t).then(r=>Np(r,t,e)),Ip=(t,e)=>ac(t).then(r=>Mp(r,t,e)),Bp=(t,e)=>Mp(xp(t),t,e),Np=(t,e,r="")=>new Lt([new gi({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),Mp=(t,e,r="")=>new $r([new gi({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],XC(e),{type:r,lastModified:t.mtimeMs}),gi=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,r){return new t({path:this.#e,lastModified:this.lastModified,size:r-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await ac(this.#e);if(e>this.lastModified)throw new Op.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*YC(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Lp={};Su(Lp,{toFormData:()=>sw});function ow(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let r=e[2]||e[3]||"",n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),n}async function sw(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new cc(r[1]||r[2]),o,s,a,c,l,f,d=[],p=new qr,
|
|
37
|
-
--`+e;let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n),this.boundaryChars[r[n]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let r=0,n=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:f,flags:d}=this,p=this.boundary.length,b=p-1,k=e.length,C,y,g=A=>{this[A+"Mark"]=r},m=A=>{delete this[A+"Mark"]},v=(A,D,O,q)=>{(D===void 0||D!==O)&&this[A](q&&q.subarray(D,O))},_=(A,D)=>{let O=A+"Mark";O in this&&(D?(v(A,this[O],r,e),delete this[O]):(v(A,this[O],e.length,e),this[O]=0))};for(r=0;r<n;r++)switch(C=e[r],f){case Fe.START_BOUNDARY:if(l===a.length-2){if(C===Io)d|=zr.LAST_BOUNDARY;else if(C!==_i)return;l++;break}else if(l-1===a.length-2){if(d&zr.LAST_BOUNDARY&&C===Io)f=Fe.END,d=0;else if(!(d&zr.LAST_BOUNDARY)&&C===yi)l=0,v("onPartBegin"),f=Fe.HEADER_FIELD_START;else return;break}C!==a[l+2]&&(l=-2),C===a[l+2]&&l++;break;case Fe.HEADER_FIELD_START:f=Fe.HEADER_FIELD,g("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(C===_i){m("onHeaderField"),f=Fe.HEADERS_ALMOST_DONE;break}if(l++,C===Io)break;if(C===ew){if(l===1)return;_("onHeaderField",!0),f=Fe.HEADER_VALUE_START;break}if(y=nw(C),y<tw||y>rw)return;break;case Fe.HEADER_VALUE_START:if(C===ZC)break;g("onHeaderValue"),f=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:C===_i&&(_("onHeaderValue",!0),v("onHeaderEnd"),f=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(C!==yi)return;f=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(C!==yi)return;v("onHeadersEnd"),f=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:f=Fe.PART_DATA,g("onPartData");case Fe.PART_DATA:if(o=l,l===0){for(r+=b;r<k&&!(e[r]in c);)r+=p;r-=b,C=e[r]}if(l<a.length)a[l]===C?(l===0&&_("onPartData",!0),l++):l=0;else if(l===a.length)l++,C===_i?d|=zr.PART_BOUNDARY:C===Io?d|=zr.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(d&zr.PART_BOUNDARY){if(l=0,C===yi){d&=~zr.PART_BOUNDARY,v("onPartEnd"),v("onPartBegin"),f=Fe.HEADER_FIELD_START;break}}else d&zr.LAST_BOUNDARY&&C===Io?(v("onPartEnd"),f=Fe.END,d=0):l=0;if(l>0)s[l-1]=C;else if(o>0){let A=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);v("onPartData",0,o,A),o=0,g("onPartData"),r--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${f}`)}_("onHeaderField"),_("onHeaderValue"),_("onPartData"),this.index=l,this.state=f,this.flags=d}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Hr,{PassThrough as $p}from"node:stream";import{types as qp,deprecate as dc,promisify as iw}from"node:util";import{Buffer as Tt}from"node:buffer";async function lc(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 Tt.alloc(0);if(!(e instanceof Hr))return Tt.alloc(0);let r=[],n=0;try{for await(let o of e){if(t.size>0&&n+o.length>t.size){let s=new tt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}n+=o.length,r.push(o)}}catch(o){throw o instanceof Cr?o:new tt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(o=>typeof o=="string")?Tt.from(r.join("")):Tt.concat(r,n)}catch(o){throw new tt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new tt(`Premature close of server response while trying to fetch ${t.url}`)}var aw,ct,Zt,$n,uw,bi,zp,Hp,Ci=Me(()=>{Oo();fi();sc();hi();mi();aw=iw(Hr.pipeline),ct=Symbol("Body internals"),Zt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:ic(e)?e=Tt.from(e.toString()):Po(e)||Tt.isBuffer(e)||(qp.isAnyArrayBuffer(e)?e=Tt.from(e):ArrayBuffer.isView(e)?e=Tt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Hr||(e instanceof qr?(e=kp(e),n=e.type.split("=")[1]):e=Tt.from(String(e))));let o=e;Tt.isBuffer(e)?o=Hr.Readable.from(e):Po(e)&&(o=Hr.Readable.from(e.stream())),this[ct]={body:e,stream:o,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof Hr&&e.on("error",s=>{let a=s instanceof Cr?s:new tt(`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:r,byteLength:n}=await lc(this);return e.slice(r,r+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new qr,o=new URLSearchParams(await this.text());for(let[s,a]of o)n.append(s,a);return n}let{toFormData:r}=await Promise.resolve().then(()=>(Up(),Lp));return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[ct].body&&this[ct].body.type||"",r=await this.arrayBuffer();return new Lt([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await lc(this);return new TextDecoder().decode(e)}buffer(){return lc(this)}};Zt.prototype.buffer=dc(Zt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Zt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:dc(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});$n=(t,e)=>{let r,n,{body:o}=t[ct];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Hr&&typeof o.getBoundary!="function"&&(r=new $p({highWaterMark:e}),n=new $p({highWaterMark:e}),o.pipe(r),o.pipe(n),t[ct].stream=r,o=n),o},uw=dc(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"),bi=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":ic(t)?"application/x-www-form-urlencoded;charset=UTF-8":Po(t)?t.type||null:Tt.isBuffer(t)||qp.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof qr?`multipart/form-data; boundary=${e[ct].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${uw(t)}`:t instanceof Hr?null:"text/plain;charset=UTF-8",zp=t=>{let{body:e}=t[ct];return e===null?0:Po(e)?e.size:Tt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Hp=async(t,{body:e})=>{e===null?t.end():await aw(e,t)}});import{types as Wp}from"node:util";import Ei from"node:http";function Gp(t=[]){return new lt(t.reduce((e,r,n,o)=>(n%2===0&&e.push(o.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return wi(e),fc(e,String(r)),!0}catch{return!1}}))}var wi,fc,lt,Ai=Me(()=>{wi=typeof Ei.validateHeaderName=="function"?Ei.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}},fc=typeof Ei.validateHeaderValue=="function"?Ei.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let r=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}},lt=class t extends URLSearchParams{constructor(e){let r=[];if(e instanceof t){let n=e.raw();for(let[o,s]of Object.entries(n))r.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!Wp.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)r.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");r=[...e].map(o=>{if(typeof o!="object"||Wp.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 r=r.length>0?r.map(([n,o])=>(wi(n),fc(n,String(o)),[String(n).toLowerCase(),String(o)])):void 0,super(r),new Proxy(this,{get(n,o,s){switch(o){case"append":case"set":return(a,c)=>(wi(a),fc(a,String(c)),URLSearchParams.prototype[o].call(n,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(wi(a),URLSearchParams.prototype[o].call(n,String(a).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let r=this.getAll(e);if(r.length===0)return null;let n=r.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,r=void 0){for(let n of this.keys())Reflect.apply(e,r,[this.get(n),n,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,r)=>(e[r]=this.getAll(r),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,r)=>{let n=this.getAll(r);return r==="host"?e[r]=n[0]:e[r]=n.length>1?n:n[0],e},{})}};Object.defineProperties(lt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var cw,Bo,hc=Me(()=>{cw=new Set([301,302,303,307,308]),Bo=t=>cw.has(t)});var Ut,pt,Jp=Me(()=>{Ai();Ci();hc();Ut=Symbol("Response internals"),pt=class t extends Zt{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,o=new lt(r.headers);if(e!==null&&!o.has("Content-Type")){let s=bi(e,this);s&&o.append("Content-Type",s)}this[Ut]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:o,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[Ut].type}get url(){return this[Ut].url||""}get status(){return this[Ut].status}get ok(){return this[Ut].status>=200&&this[Ut].status<300}get redirected(){return this[Ut].counter>0}get statusText(){return this[Ut].statusText}get headers(){return this[Ut].headers}get highWaterMark(){return this[Ut].highWaterMark}clone(){return new t($n(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,r=302){if(!Bo(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:r})}static error(){let e=new t(null,{status:0,statusText:""});return e[Ut].type="error",e}static json(e=void 0,r={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let o=new lt(r&&r.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(n,{...r,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(pt.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 Vp,Kp=Me(()=>{Vp=t=>{if(t.search)return t.search;let e=t.href.length-1,r=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-r.length]==="?"?"?":""}});import{isIP as lw}from"node:net";function Yp(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 Zp(t){if(!Qp.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function dw(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=lw(e);return r===4&&/^127\./.test(e)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function qn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:dw(t)}function em(t,{referrerURLCallback:e,referrerOriginCallback:r}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let n=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Yp(o),a=Yp(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),r&&(a=r(a));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return qn(s)&&!qn(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:qn(s)&&!qn(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 qn(s)&&!qn(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function tm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&Qp.has(n)&&(r=n);return r}var Qp,Xp,pc=Me(()=>{Qp=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Xp="strict-origin-when-cross-origin"});import{format as fw}from"node:url";import{deprecate as hw}from"node:util";var Je,No,pw,Wr,rm,nm=Me(()=>{Ai();Ci();mi();Kp();pc();Je=Symbol("Request internals"),No=t=>typeof t=="object"&&typeof t[Je]=="object",pw=hw(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Wr=class t extends Zt{constructor(e,r={}){let n;if(No(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let o=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!No(r)&&"data"in r&&pw(),(r.body!=null||No(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=r.body?r.body:No(e)&&e.body!==null?$n(e):null;super(s,{size:r.size||e.size||0});let a=new lt(r.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let f=bi(s,this);f&&a.set("Content-Type",f)}let c=No(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!Sp(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=r.referrer==null?e.referrer:r.referrer;if(l==="")l="no-referrer";else if(l){let f=new URL(l);l=/^about:(\/\/)?client$/.test(f)?"client":f}else l=void 0;this[Je]={method:o,redirect:r.redirect||e.redirect||"follow",headers:a,parsedURL:n,signal:c,referrer:l},this.follow=r.follow===void 0?e.follow===void 0?20:e.follow:r.follow,this.compress=r.compress===void 0?e.compress===void 0?!0:e.compress:r.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent,this.highWaterMark=r.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=r.referrerPolicy||e.referrerPolicy||""}get method(){return this[Je].method}get url(){return fw(this[Je].parsedURL)}get headers(){return this[Je].headers}get redirect(){return this[Je].redirect}get signal(){return this[Je].signal}get referrer(){if(this[Je].referrer==="no-referrer")return"";if(this[Je].referrer==="client")return"about:client";if(this[Je].referrer)return this[Je].referrer.toString()}get referrerPolicy(){return this[Je].referrerPolicy}set referrerPolicy(e){this[Je].referrerPolicy=Zp(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Wr.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}});rm=t=>{let{parsedURL:e}=t[Je],r=new lt(t[Je].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(n="0"),t.body!==null){let c=zp(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=Xp),t.referrer&&t.referrer!=="no-referrer"?t[Je].referrer=em(t):t[Je].referrer="no-referrer",t[Je].referrer instanceof URL&&r.set("Referer",t.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),t.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=Vp(e),a={path:e.pathname+s,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var Mo,om=Me(()=>{hi();Mo=class extends Cr{constructor(e,r="aborted"){super(e,r)}}});var am={};Su(am,{AbortError:()=>Mo,Blob:()=>Lt,FetchError:()=>tt,File:()=>$r,FormData:()=>qr,Headers:()=>lt,Request:()=>Wr,Response:()=>pt,blobFrom:()=>Pp,blobFromSync:()=>Fp,default:()=>mc,fileFrom:()=>Ip,fileFromSync:()=>Bp,isRedirect:()=>Bo});import mw from"node:http";import gw from"node:https";import zn from"node:zlib";import sm,{PassThrough as im,pipeline as Hn}from"node:stream";import{Buffer as ki}from"node:buffer";async function mc(t,e){return new Promise((r,n)=>{let o=new Wr(t,e),{parsedURL:s,options:a}=rm(o);if(!yw.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=mp(o.url),y=new pt(C,{headers:{"Content-Type":C.typeFull}});r(y);return}let c=(s.protocol==="https:"?gw:mw).request,{signal:l}=o,f=null,d=()=>{let C=new Mo("The operation was aborted.");n(C),o.body&&o.body instanceof sm.Readable&&o.body.destroy(C),!(!f||!f.body)&&f.body.emit("error",C)};if(l&&l.aborted){d();return}let p=()=>{d(),k()},b=c(s.toString(),a);l&&l.addEventListener("abort",p);let k=()=>{b.abort(),l&&l.removeEventListener("abort",p)};b.on("error",C=>{n(new tt(`request to ${o.url} failed, reason: ${C.message}`,"system",C)),k()}),_w(b,C=>{f&&f.body&&f.body.destroy(C)}),process.version<"v14"&&b.on("socket",C=>{let y;C.prependListener("end",()=>{y=C._eventsCount}),C.prependListener("close",g=>{if(f&&y<C._eventsCount&&!g){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",f.body.emit("error",m)}})}),b.on("response",C=>{b.setTimeout(0);let y=Gp(C.rawHeaders);if(Bo(C.statusCode)){let A=y.get("Location"),D=null;try{D=A===null?null:new URL(A,o.url)}catch{if(o.redirect!=="manual"){n(new tt(`uri requested responds with an invalid redirect URL: ${A}`,"invalid-redirect")),k();return}}switch(o.redirect){case"error":n(new tt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),k();return;case"manual":break;case"follow":{if(D===null)break;if(o.counter>=o.follow){n(new tt(`maximum redirect reached at: ${o.url}`,"max-redirect")),k();return}let O={headers:new lt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:$n(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!vp(o.url,D)||!Tp(o.url,D))for(let J of["authorization","www-authenticate","cookie","cookie2"])O.headers.delete(J);if(C.statusCode!==303&&o.body&&e.body instanceof sm.Readable){n(new tt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),k();return}(C.statusCode===303||(C.statusCode===301||C.statusCode===302)&&o.method==="POST")&&(O.method="GET",O.body=void 0,O.headers.delete("content-length"));let q=tm(y);q&&(O.referrerPolicy=q),r(mc(new Wr(D,O))),k();return}default:return n(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&C.once("end",()=>{l.removeEventListener("abort",p)});let g=Hn(C,new im,A=>{A&&n(A)});process.version<"v12.10"&&C.on("aborted",p);let m={url:o.url,status:C.statusCode,statusText:C.statusMessage,headers:y,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},v=y.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||v===null||C.statusCode===204||C.statusCode===304){f=new pt(g,m),r(f);return}let _={flush:zn.Z_SYNC_FLUSH,finishFlush:zn.Z_SYNC_FLUSH};if(v==="gzip"||v==="x-gzip"){g=Hn(g,zn.createGunzip(_),A=>{A&&n(A)}),f=new pt(g,m),r(f);return}if(v==="deflate"||v==="x-deflate"){let A=Hn(C,new im,D=>{D&&n(D)});A.once("data",D=>{(D[0]&15)===8?g=Hn(g,zn.createInflate(),O=>{O&&n(O)}):g=Hn(g,zn.createInflateRaw(),O=>{O&&n(O)}),f=new pt(g,m),r(f)}),A.once("end",()=>{f||(f=new pt(g,m),r(f))});return}if(v==="br"){g=Hn(g,zn.createBrotliDecompress(),A=>{A&&n(A)}),f=new pt(g,m),r(f);return}f=new pt(g,m),r(f)}),Hp(b,o).catch(n)})}function _w(t,e){let r=ki.from(`0\r
|
|
36
|
+
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),dn=(t,e,r)=>{if(e.length<r)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${r} arguments required, but only ${e.length} present.`)},qr=class{#e=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Fo](){return"FormData"}[JC](){return this.entries()}static[VC](e){return e&&typeof e=="object"&&e[Fo]==="FormData"&&!KC.some(r=>typeof e[r]!="function")}append(...e){dn("append",arguments,2),this.#e.push(Ap(...e))}delete(e){dn("delete",arguments,1),e+="",this.#e=this.#e.filter(([r])=>r!==e)}get(e){dn("get",arguments,1),e+="";for(var r=this.#e,n=r.length,o=0;o<n;o++)if(r[o][0]===e)return r[o][1];return null}getAll(e,r){return dn("getAll",arguments,1),r=[],e+="",this.#e.forEach(n=>n[0]===e&&r.push(n[1])),r}has(e){return dn("has",arguments,1),e+="",this.#e.some(r=>r[0]===e)}forEach(e,r){dn("forEach",arguments,1);for(var[n,o]of this)e.call(r,o,n,this)}set(...e){dn("set",arguments,2);var r=[],n=!0;e=Ap(...e),this.#e.forEach(o=>{o[0]===e[0]?n&&(n=!r.push(e)):r.push(o)}),n&&r.push(e),this.#e=r}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var Cr,hi=Me(()=>{Cr=class extends Error{constructor(e,r){super(e),Error.captureStackTrace(this,this.constructor),this.type=r}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var tt,sc=Me(()=>{hi();tt=class extends Cr{constructor(e,r,n){super(e,r),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var pi,ic,Po,Sp,vp,Tp,mi=Me(()=>{pi=Symbol.toStringTag,ic=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[pi]==="URLSearchParams",Po=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[pi]),Sp=t=>typeof t=="object"&&(t[pi]==="AbortSignal"||t[pi]==="EventTarget"),vp=(t,e)=>{let r=new URL(e).hostname,n=new URL(t).hostname;return r===n||r.endsWith(`.${n}`)},Tp=(t,e)=>{let r=new URL(e).protocol,n=new URL(t).protocol;return r===n}});var Rp=V((GR,Dp)=>{if(!globalThis.DOMException)try{let{MessageChannel:t}=X("worker_threads"),e=new t().port1,r=new ArrayBuffer;e.postMessage(r,[r,r])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}Dp.exports=globalThis.DOMException});import{statSync as xp,createReadStream as YC,promises as QC}from"node:fs";import{basename as XC}from"node:path";var Op,ac,Fp,Pp,Ip,Bp,Np,Mp,gi,uc=Me(()=>{Op=jr(Rp(),1);nc();Oo();({stat:ac}=QC),Fp=(t,e)=>Np(xp(t),t,e),Pp=(t,e)=>ac(t).then(r=>Np(r,t,e)),Ip=(t,e)=>ac(t).then(r=>Mp(r,t,e)),Bp=(t,e)=>Mp(xp(t),t,e),Np=(t,e,r="")=>new Lt([new gi({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:r}),Mp=(t,e,r="")=>new $r([new gi({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],XC(e),{type:r,lastModified:t.mtimeMs}),gi=class t{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,r){return new t({path:this.#e,lastModified:this.lastModified,size:r-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await ac(this.#e);if(e>this.lastModified)throw new Op.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*YC(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Lp={};Su(Lp,{toFormData:()=>sw});function ow(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let r=e[2]||e[3]||"",n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),n}async function sw(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new cc(r[1]||r[2]),o,s,a,c,l,f,d=[],p=new qr,C=m=>{a+=g.decode(m,{stream:!0})},k=m=>{d.push(m)},_=()=>{let m=new $r(d,f,{type:l});p.append(c,m)},y=()=>{p.append(c,a)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=C,n.onPartEnd=y,o="",s="",a="",c="",l="",f=null,d.length=0},n.onHeaderField=function(m){o+=g.decode(m,{stream:!0})},n.onHeaderValue=function(m){s+=g.decode(m,{stream:!0})},n.onHeaderEnd=function(){if(s+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let m=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);m&&(c=m[2]||m[3]||""),f=ow(s),f&&(n.onPartData=k,n.onPartEnd=_)}else o==="content-type"&&(l=s);s="",o=""};for await(let m of t)n.write(m);return n.end(),p}var Xt,Fe,jp,zr,yi,_i,ZC,Io,ew,tw,rw,nw,fn,cc,Up=Me(()=>{uc();fi();Xt=0,Fe={START_BOUNDARY:Xt++,HEADER_FIELD_START:Xt++,HEADER_FIELD:Xt++,HEADER_VALUE_START:Xt++,HEADER_VALUE:Xt++,HEADER_VALUE_ALMOST_DONE:Xt++,HEADERS_ALMOST_DONE:Xt++,PART_DATA_START:Xt++,PART_DATA:Xt++,END:Xt++},jp=1,zr={PART_BOUNDARY:jp,LAST_BOUNDARY:jp*=2},yi=10,_i=13,ZC=32,Io=45,ew=58,tw=97,rw=122,nw=t=>t|32,fn=()=>{},cc=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=fn,this.onHeaderField=fn,this.onHeadersEnd=fn,this.onHeaderValue=fn,this.onPartBegin=fn,this.onPartData=fn,this.onPartEnd=fn,this.boundaryChars={},e=`\r
|
|
37
|
+
--`+e;let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n),this.boundaryChars[r[n]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Fe.START_BOUNDARY}write(e){let r=0,n=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:f,flags:d}=this,p=this.boundary.length,C=p-1,k=e.length,_,y,g=A=>{this[A+"Mark"]=r},m=A=>{delete this[A+"Mark"]},v=(A,D,O,q)=>{(D===void 0||D!==O)&&this[A](q&&q.subarray(D,O))},b=(A,D)=>{let O=A+"Mark";O in this&&(D?(v(A,this[O],r,e),delete this[O]):(v(A,this[O],e.length,e),this[O]=0))};for(r=0;r<n;r++)switch(_=e[r],f){case Fe.START_BOUNDARY:if(l===a.length-2){if(_===Io)d|=zr.LAST_BOUNDARY;else if(_!==_i)return;l++;break}else if(l-1===a.length-2){if(d&zr.LAST_BOUNDARY&&_===Io)f=Fe.END,d=0;else if(!(d&zr.LAST_BOUNDARY)&&_===yi)l=0,v("onPartBegin"),f=Fe.HEADER_FIELD_START;else return;break}_!==a[l+2]&&(l=-2),_===a[l+2]&&l++;break;case Fe.HEADER_FIELD_START:f=Fe.HEADER_FIELD,g("onHeaderField"),l=0;case Fe.HEADER_FIELD:if(_===_i){m("onHeaderField"),f=Fe.HEADERS_ALMOST_DONE;break}if(l++,_===Io)break;if(_===ew){if(l===1)return;b("onHeaderField",!0),f=Fe.HEADER_VALUE_START;break}if(y=nw(_),y<tw||y>rw)return;break;case Fe.HEADER_VALUE_START:if(_===ZC)break;g("onHeaderValue"),f=Fe.HEADER_VALUE;case Fe.HEADER_VALUE:_===_i&&(b("onHeaderValue",!0),v("onHeaderEnd"),f=Fe.HEADER_VALUE_ALMOST_DONE);break;case Fe.HEADER_VALUE_ALMOST_DONE:if(_!==yi)return;f=Fe.HEADER_FIELD_START;break;case Fe.HEADERS_ALMOST_DONE:if(_!==yi)return;v("onHeadersEnd"),f=Fe.PART_DATA_START;break;case Fe.PART_DATA_START:f=Fe.PART_DATA,g("onPartData");case Fe.PART_DATA:if(o=l,l===0){for(r+=C;r<k&&!(e[r]in c);)r+=p;r-=C,_=e[r]}if(l<a.length)a[l]===_?(l===0&&b("onPartData",!0),l++):l=0;else if(l===a.length)l++,_===_i?d|=zr.PART_BOUNDARY:_===Io?d|=zr.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(d&zr.PART_BOUNDARY){if(l=0,_===yi){d&=~zr.PART_BOUNDARY,v("onPartEnd"),v("onPartBegin"),f=Fe.HEADER_FIELD_START;break}}else d&zr.LAST_BOUNDARY&&_===Io?(v("onPartEnd"),f=Fe.END,d=0):l=0;if(l>0)s[l-1]=_;else if(o>0){let A=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);v("onPartData",0,o,A),o=0,g("onPartData"),r--}break;case Fe.END:break;default:throw new Error(`Unexpected state entered: ${f}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=l,this.state=f,this.flags=d}end(){if(this.state===Fe.HEADER_FIELD_START&&this.index===0||this.state===Fe.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Fe.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Hr,{PassThrough as $p}from"node:stream";import{types as qp,deprecate as dc,promisify as iw}from"node:util";import{Buffer as Tt}from"node:buffer";async function lc(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 Tt.alloc(0);if(!(e instanceof Hr))return Tt.alloc(0);let r=[],n=0;try{for await(let o of e){if(t.size>0&&n+o.length>t.size){let s=new tt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}n+=o.length,r.push(o)}}catch(o){throw o instanceof Cr?o:new tt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return r.every(o=>typeof o=="string")?Tt.from(r.join("")):Tt.concat(r,n)}catch(o){throw new tt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new tt(`Premature close of server response while trying to fetch ${t.url}`)}var aw,ct,Zt,$n,uw,bi,zp,Hp,Ci=Me(()=>{Oo();fi();sc();hi();mi();aw=iw(Hr.pipeline),ct=Symbol("Body internals"),Zt=class{constructor(e,{size:r=0}={}){let n=null;e===null?e=null:ic(e)?e=Tt.from(e.toString()):Po(e)||Tt.isBuffer(e)||(qp.isAnyArrayBuffer(e)?e=Tt.from(e):ArrayBuffer.isView(e)?e=Tt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Hr||(e instanceof qr?(e=kp(e),n=e.type.split("=")[1]):e=Tt.from(String(e))));let o=e;Tt.isBuffer(e)?o=Hr.Readable.from(e):Po(e)&&(o=Hr.Readable.from(e.stream())),this[ct]={body:e,stream:o,boundary:n,disturbed:!1,error:null},this.size=r,e instanceof Hr&&e.on("error",s=>{let a=s instanceof Cr?s:new tt(`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:r,byteLength:n}=await lc(this);return e.slice(r,r+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new qr,o=new URLSearchParams(await this.text());for(let[s,a]of o)n.append(s,a);return n}let{toFormData:r}=await Promise.resolve().then(()=>(Up(),Lp));return r(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[ct].body&&this[ct].body.type||"",r=await this.arrayBuffer();return new Lt([r],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await lc(this);return new TextDecoder().decode(e)}buffer(){return lc(this)}};Zt.prototype.buffer=dc(Zt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Zt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:dc(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});$n=(t,e)=>{let r,n,{body:o}=t[ct];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Hr&&typeof o.getBoundary!="function"&&(r=new $p({highWaterMark:e}),n=new $p({highWaterMark:e}),o.pipe(r),o.pipe(n),t[ct].stream=r,o=n),o},uw=dc(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"),bi=(t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":ic(t)?"application/x-www-form-urlencoded;charset=UTF-8":Po(t)?t.type||null:Tt.isBuffer(t)||qp.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof qr?`multipart/form-data; boundary=${e[ct].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${uw(t)}`:t instanceof Hr?null:"text/plain;charset=UTF-8",zp=t=>{let{body:e}=t[ct];return e===null?0:Po(e)?e.size:Tt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},Hp=async(t,{body:e})=>{e===null?t.end():await aw(e,t)}});import{types as Wp}from"node:util";import Ei from"node:http";function Gp(t=[]){return new lt(t.reduce((e,r,n,o)=>(n%2===0&&e.push(o.slice(n,n+2)),e),[]).filter(([e,r])=>{try{return wi(e),fc(e,String(r)),!0}catch{return!1}}))}var wi,fc,lt,Ai=Me(()=>{wi=typeof Ei.validateHeaderName=="function"?Ei.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}},fc=typeof Ei.validateHeaderValue=="function"?Ei.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let r=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}},lt=class t extends URLSearchParams{constructor(e){let r=[];if(e instanceof t){let n=e.raw();for(let[o,s]of Object.entries(n))r.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!Wp.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)r.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");r=[...e].map(o=>{if(typeof o!="object"||Wp.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 r=r.length>0?r.map(([n,o])=>(wi(n),fc(n,String(o)),[String(n).toLowerCase(),String(o)])):void 0,super(r),new Proxy(this,{get(n,o,s){switch(o){case"append":case"set":return(a,c)=>(wi(a),fc(a,String(c)),URLSearchParams.prototype[o].call(n,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(wi(a),URLSearchParams.prototype[o].call(n,String(a).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let r=this.getAll(e);if(r.length===0)return null;let n=r.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,r=void 0){for(let n of this.keys())Reflect.apply(e,r,[this.get(n),n,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,r)=>(e[r]=this.getAll(r),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,r)=>{let n=this.getAll(r);return r==="host"?e[r]=n[0]:e[r]=n.length>1?n:n[0],e},{})}};Object.defineProperties(lt.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}))});var cw,Bo,hc=Me(()=>{cw=new Set([301,302,303,307,308]),Bo=t=>cw.has(t)});var Ut,pt,Jp=Me(()=>{Ai();Ci();hc();Ut=Symbol("Response internals"),pt=class t extends Zt{constructor(e=null,r={}){super(e,r);let n=r.status!=null?r.status:200,o=new lt(r.headers);if(e!==null&&!o.has("Content-Type")){let s=bi(e,this);s&&o.append("Content-Type",s)}this[Ut]={type:"default",url:r.url,status:n,statusText:r.statusText||"",headers:o,counter:r.counter,highWaterMark:r.highWaterMark}}get type(){return this[Ut].type}get url(){return this[Ut].url||""}get status(){return this[Ut].status}get ok(){return this[Ut].status>=200&&this[Ut].status<300}get redirected(){return this[Ut].counter>0}get statusText(){return this[Ut].statusText}get headers(){return this[Ut].headers}get highWaterMark(){return this[Ut].highWaterMark}clone(){return new t($n(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,r=302){if(!Bo(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new t(null,{headers:{location:new URL(e).toString()},status:r})}static error(){let e=new t(null,{status:0,statusText:""});return e[Ut].type="error",e}static json(e=void 0,r={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let o=new lt(r&&r.headers);return o.has("content-type")||o.set("content-type","application/json"),new t(n,{...r,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(pt.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 Vp,Kp=Me(()=>{Vp=t=>{if(t.search)return t.search;let e=t.href.length-1,r=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-r.length]==="?"?"?":""}});import{isIP as lw}from"node:net";function Yp(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 Zp(t){if(!Qp.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function dw(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),r=lw(e);return r===4&&/^127\./.test(e)||r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function qn(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:dw(t)}function em(t,{referrerURLCallback:e,referrerOriginCallback:r}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let n=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Yp(o),a=Yp(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),r&&(a=r(a));let c=new URL(t.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return qn(s)&&!qn(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:qn(s)&&!qn(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 qn(s)&&!qn(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function tm(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of e)n&&Qp.has(n)&&(r=n);return r}var Qp,Xp,pc=Me(()=>{Qp=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),Xp="strict-origin-when-cross-origin"});import{format as fw}from"node:url";import{deprecate as hw}from"node:util";var Je,No,pw,Wr,rm,nm=Me(()=>{Ai();Ci();mi();Kp();pc();Je=Symbol("Request internals"),No=t=>typeof t=="object"&&typeof t[Je]=="object",pw=hw(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Wr=class t extends Zt{constructor(e,r={}){let n;if(No(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let o=r.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!No(r)&&"data"in r&&pw(),(r.body!=null||No(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=r.body?r.body:No(e)&&e.body!==null?$n(e):null;super(s,{size:r.size||e.size||0});let a=new lt(r.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let f=bi(s,this);f&&a.set("Content-Type",f)}let c=No(e)?e.signal:null;if("signal"in r&&(c=r.signal),c!=null&&!Sp(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=r.referrer==null?e.referrer:r.referrer;if(l==="")l="no-referrer";else if(l){let f=new URL(l);l=/^about:(\/\/)?client$/.test(f)?"client":f}else l=void 0;this[Je]={method:o,redirect:r.redirect||e.redirect||"follow",headers:a,parsedURL:n,signal:c,referrer:l},this.follow=r.follow===void 0?e.follow===void 0?20:e.follow:r.follow,this.compress=r.compress===void 0?e.compress===void 0?!0:e.compress:r.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent,this.highWaterMark=r.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=r.referrerPolicy||e.referrerPolicy||""}get method(){return this[Je].method}get url(){return fw(this[Je].parsedURL)}get headers(){return this[Je].headers}get redirect(){return this[Je].redirect}get signal(){return this[Je].signal}get referrer(){if(this[Je].referrer==="no-referrer")return"";if(this[Je].referrer==="client")return"about:client";if(this[Je].referrer)return this[Je].referrer.toString()}get referrerPolicy(){return this[Je].referrerPolicy}set referrerPolicy(e){this[Je].referrerPolicy=Zp(e)}clone(){return new t(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Wr.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}});rm=t=>{let{parsedURL:e}=t[Je],r=new lt(t[Je].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(n="0"),t.body!==null){let c=zp(t);typeof c=="number"&&!Number.isNaN(c)&&(n=String(c))}n&&r.set("Content-Length",n),t.referrerPolicy===""&&(t.referrerPolicy=Xp),t.referrer&&t.referrer!=="no-referrer"?t[Je].referrer=em(t):t[Je].referrer="no-referrer",t[Je].referrer instanceof URL&&r.set("Referer",t.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),t.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=Vp(e),a={path:e.pathname+s,method:t.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}}});var Mo,om=Me(()=>{hi();Mo=class extends Cr{constructor(e,r="aborted"){super(e,r)}}});var am={};Su(am,{AbortError:()=>Mo,Blob:()=>Lt,FetchError:()=>tt,File:()=>$r,FormData:()=>qr,Headers:()=>lt,Request:()=>Wr,Response:()=>pt,blobFrom:()=>Pp,blobFromSync:()=>Fp,default:()=>mc,fileFrom:()=>Ip,fileFromSync:()=>Bp,isRedirect:()=>Bo});import mw from"node:http";import gw from"node:https";import zn from"node:zlib";import sm,{PassThrough as im,pipeline as Hn}from"node:stream";import{Buffer as ki}from"node:buffer";async function mc(t,e){return new Promise((r,n)=>{let o=new Wr(t,e),{parsedURL:s,options:a}=rm(o);if(!yw.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let _=mp(o.url),y=new pt(_,{headers:{"Content-Type":_.typeFull}});r(y);return}let c=(s.protocol==="https:"?gw:mw).request,{signal:l}=o,f=null,d=()=>{let _=new Mo("The operation was aborted.");n(_),o.body&&o.body instanceof sm.Readable&&o.body.destroy(_),!(!f||!f.body)&&f.body.emit("error",_)};if(l&&l.aborted){d();return}let p=()=>{d(),k()},C=c(s.toString(),a);l&&l.addEventListener("abort",p);let k=()=>{C.abort(),l&&l.removeEventListener("abort",p)};C.on("error",_=>{n(new tt(`request to ${o.url} failed, reason: ${_.message}`,"system",_)),k()}),_w(C,_=>{f&&f.body&&f.body.destroy(_)}),process.version<"v14"&&C.on("socket",_=>{let y;_.prependListener("end",()=>{y=_._eventsCount}),_.prependListener("close",g=>{if(f&&y<_._eventsCount&&!g){let m=new Error("Premature close");m.code="ERR_STREAM_PREMATURE_CLOSE",f.body.emit("error",m)}})}),C.on("response",_=>{C.setTimeout(0);let y=Gp(_.rawHeaders);if(Bo(_.statusCode)){let A=y.get("Location"),D=null;try{D=A===null?null:new URL(A,o.url)}catch{if(o.redirect!=="manual"){n(new tt(`uri requested responds with an invalid redirect URL: ${A}`,"invalid-redirect")),k();return}}switch(o.redirect){case"error":n(new tt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),k();return;case"manual":break;case"follow":{if(D===null)break;if(o.counter>=o.follow){n(new tt(`maximum redirect reached at: ${o.url}`,"max-redirect")),k();return}let O={headers:new lt(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:$n(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!vp(o.url,D)||!Tp(o.url,D))for(let J of["authorization","www-authenticate","cookie","cookie2"])O.headers.delete(J);if(_.statusCode!==303&&o.body&&e.body instanceof sm.Readable){n(new tt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),k();return}(_.statusCode===303||(_.statusCode===301||_.statusCode===302)&&o.method==="POST")&&(O.method="GET",O.body=void 0,O.headers.delete("content-length"));let q=tm(y);q&&(O.referrerPolicy=q),r(mc(new Wr(D,O))),k();return}default:return n(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&_.once("end",()=>{l.removeEventListener("abort",p)});let g=Hn(_,new im,A=>{A&&n(A)});process.version<"v12.10"&&_.on("aborted",p);let m={url:o.url,status:_.statusCode,statusText:_.statusMessage,headers:y,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},v=y.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||v===null||_.statusCode===204||_.statusCode===304){f=new pt(g,m),r(f);return}let b={flush:zn.Z_SYNC_FLUSH,finishFlush:zn.Z_SYNC_FLUSH};if(v==="gzip"||v==="x-gzip"){g=Hn(g,zn.createGunzip(b),A=>{A&&n(A)}),f=new pt(g,m),r(f);return}if(v==="deflate"||v==="x-deflate"){let A=Hn(_,new im,D=>{D&&n(D)});A.once("data",D=>{(D[0]&15)===8?g=Hn(g,zn.createInflate(),O=>{O&&n(O)}):g=Hn(g,zn.createInflateRaw(),O=>{O&&n(O)}),f=new pt(g,m),r(f)}),A.once("end",()=>{f||(f=new pt(g,m),r(f))});return}if(v==="br"){g=Hn(g,zn.createBrotliDecompress(),A=>{A&&n(A)}),f=new pt(g,m),r(f);return}f=new pt(g,m),r(f)}),Hp(C,o).catch(n)})}function _w(t,e){let r=ki.from(`0\r
|
|
38
38
|
\r
|
|
39
39
|
`),n=!1,o=!1,s;t.on("response",a=>{let{headers:c}=a;n=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",a=>{let c=()=>{if(n&&!o){let f=new Error("Premature close");f.code="ERR_STREAM_PREMATURE_CLOSE",e(f)}},l=f=>{o=ki.compare(f.slice(-5),r)===0,!o&&s&&(o=ki.compare(s.slice(-3),r.slice(0,3))===0&&ki.compare(f.slice(-2),r.slice(3))===0),s=f};a.prependListener("close",c),a.on("data",l),t.on("close",()=>{a.removeListener("close",c),a.removeListener("data",l)})})}var yw,um=Me(()=>{gp();Ci();Jp();Ai();nm();sc();om();hc();fi();mi();pc();uc();yw=new Set(["data:","http:","https:"])});var dm=V(Gn=>{"use strict";var bw=Gn&&Gn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Wn;Object.defineProperty(Gn,"__esModule",{value:!0});Gn.Gaxios=void 0;var Cw=bw(qu()),ww=X("https"),hn=Wu(),Ew=zh(),cm=X("stream"),lm=Vu(),Aw=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Si=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new lm.GaxiosInterceptorManager,response:new lm.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],o,s=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Wn.mergeHeaders(s,r.headers),n&&Wn.mergeHeaders(s,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:s,url:o}):this.request({...n,headers:s,url:o})}async request(e={}){let r=await this.#n(e);return r=await this.#t(r),this.#r(this._request(r))}async _defaultAdapter(e){let r=e.fetchImplementation||this.defaults.fetchImplementation||await Wn.#u(),n={...e};delete n.data;let o=await r(e.url,n),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 r;if(e.adapter?r=await e.adapter(e,this._defaultAdapter.bind(this)):r=await this._defaultAdapter(e),!e.validateStatus(r.status)){if(e.responseType==="stream"){let o=[];for await(let s of r.data)o.push(s);r.data=o.toString()}let n=hn.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new hn.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof hn.GaxiosError?n=r:r instanceof Error?n=new hn.GaxiosError(r.message,e,void 0,r):n=new hn.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:o,config:s}=await(0,Ew.getRetryConfig)(n);if(o&&s)return n.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,r){if(e.maxContentLength&&r.headers.has("content-length")&&e.maxContentLength<Number.parseInt(r.headers?.get("content-length")||""))throw new hn.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(r,{config:e}));switch(e.responseType){case"stream":return r.body;case"json":return r.json();case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"text":return r.text();default:return this.getResponseDataFromContentType(r)}}#e(e,r=[]){let n=new URL(e),o=[...r],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(n.toString()))return!1}else if(a instanceof URL){if(a.origin===n.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let c=a.replace(/^\*\./,".");if(n.hostname.endsWith(c))return!1}else if(a===n.origin||a===n.hostname||a===n.href)return!1;return!0}async#t(e){let r=Promise.resolve(e);for(let n of this.interceptors.request.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#r(e){let r=Promise.resolve(e);for(let n of this.interceptors.response.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#n(e){let r=new Headers(this.defaults.headers);Wn.mergeHeaders(r,e.headers);let n=(0,Cw.default)(!0,{},this.defaults,e);if(!n.url)throw new Error("URL is required.");if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let a=n.paramsSerializer(n.params);a.startsWith("?")&&(a=a.slice(1));let c=n.url.toString().includes("?")?"&":"?";n.url=n.url+c+a}else{let a=n.url instanceof URL?n.url:new URL(n.url);for(let[c,l]of new URLSearchParams(n.params))a.searchParams.append(c,l);n.url=a}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let o=typeof n.data=="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof cm.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let a=await Aw();r.set("content-type",`multipart/related; boundary=${a}`),n.body=cm.Readable.from(this.getMultipartRequest(n.multipart,a))}else o?n.body=n.data:typeof n.data=="object"?r.get("Content-Type")==="application/x-www-form-urlencoded"?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(r.has("content-type")||r.set("content-type","application/json"),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!r.has("accept")&&n.responseType==="json"&&r.set("accept","application/json");let s=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(s&&this.#e(n.url,n.noProxy)){let a=await Wn.#a();this.agentCache.has(s)?n.agent=this.agentCache.get(s):(n.agent=new a(s,{cert:n.cert,key:n.key}),this.agentCache.set(s,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new ww.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=hn.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#o(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#o(e){if(e.timeout){let r=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,r]):e.signal=r}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let r=e.headers.get("Content-Type");if(r===null)return e.text();if(r=r.toLowerCase(),r.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return r.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,r){let n=`--${r}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\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 n}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>jr(pp()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(um(),am))).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};Gn.Gaxios=Si;Wn=Si});var Ke=V(rt=>{"use strict";var kw=rt&&rt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Sw=rt&&rt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kw(e,t,r)};Object.defineProperty(rt,"__esModule",{value:!0});rt.instance=rt.Gaxios=rt.GaxiosError=void 0;rt.request=Tw;var fm=dm();Object.defineProperty(rt,"Gaxios",{enumerable:!0,get:function(){return fm.Gaxios}});var vw=Wu();Object.defineProperty(rt,"GaxiosError",{enumerable:!0,get:function(){return vw.GaxiosError}});Sw(Vu(),rt);rt.instance=new fm.Gaxios;async function Tw(t){return rt.instance.request(t)}});var gc=V((hm,vi)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,b=1e9;function k(D){var O,q,J,B=W.prototype={constructor:W,toString:null,valueOf:null},Y=new W(1),re=20,ee=4,ue=-7,fe=21,ke=-1e7,ie=1e7,me=!1,G=1,K=0,ce={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",De=!0;function W(w,S){var T,M,F,I,U,x,P,j,N=this;if(!(N instanceof W))return new W(w,S);if(S==null){if(w&&w._isBigNumber===!0){N.s=w.s,!w.c||w.e>ie?N.c=N.e=null:w.e<ke?N.c=[N.e=0]:(N.e=w.e,N.c=w.c.slice());return}if((x=typeof w=="number")&&w*0==0){if(N.s=1/w<0?(w=-w,-1):1,w===~~w){for(I=0,U=w;U>=10;U/=10,I++);I>ie?N.c=N.e=null:(N.e=I,N.c=[w]);return}j=String(w)}else{if(!r.test(j=String(w)))return J(N,j,x);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(U=j.search(/e/i))>0?(I<0&&(I=U),I+=+j.slice(U+1),j=j.substring(0,U)):I<0&&(I=j.length)}else{if(m(S,2,qe.length,"Base"),S==10&&De)return N=new W(w),xe(N,re+N.e+1,ee);if(j=String(w),x=typeof w=="number"){if(w*0!=0)return J(N,j,x,S);if(N.s=1/w<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(a+w)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(T=qe.slice(0,S),I=U=0,P=j.length;U<P;U++)if(T.indexOf(M=j.charAt(U))<0){if(M=="."){if(U>I){I=P;continue}}else if(!F&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){F=!0,U=-1,I=0;continue}return J(N,String(w),x,S)}x=!1,j=q(j,S,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(U=0;j.charCodeAt(U)===48;U++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(U,++P)){if(P-=U,x&&W.DEBUG&&P>15&&(w>f||w!==o(w)))throw Error(a+N.s*w);if((I=I-U-1)>ie)N.c=N.e=null;else if(I<ke)N.c=[N.e=0];else{if(N.e=I,N.c=[],U=(I+1)%l,I<0&&(U+=l),U<P){for(U&&N.c.push(+j.slice(0,U)),P-=l;U<P;)N.c.push(+j.slice(U,U+=l));U=l-(j=j.slice(U)).length}else U-=P;for(;U--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=k,W.ROUND_UP=0,W.ROUND_DOWN=1,W.ROUND_CEIL=2,W.ROUND_FLOOR=3,W.ROUND_HALF_UP=4,W.ROUND_HALF_DOWN=5,W.ROUND_HALF_EVEN=6,W.ROUND_HALF_CEIL=7,W.ROUND_HALF_FLOOR=8,W.EUCLID=9,W.config=W.set=function(w){var S,T;if(w!=null)if(typeof w=="object"){if(w.hasOwnProperty(S="DECIMAL_PLACES")&&(T=w[S],m(T,0,b,S),re=T),w.hasOwnProperty(S="ROUNDING_MODE")&&(T=w[S],m(T,0,8,S),ee=T),w.hasOwnProperty(S="EXPONENTIAL_AT")&&(T=w[S],T&&T.pop?(m(T[0],-b,0,S),m(T[1],0,b,S),ue=T[0],fe=T[1]):(m(T,-b,b,S),ue=-(fe=T<0?-T:T))),w.hasOwnProperty(S="RANGE"))if(T=w[S],T&&T.pop)m(T[0],-b,-1,S),m(T[1],1,b,S),ke=T[0],ie=T[1];else if(m(T,-b,b,S),T)ke=-(ie=T<0?-T:T);else throw Error(s+S+" cannot be zero: "+T);if(w.hasOwnProperty(S="CRYPTO"))if(T=w[S],T===!!T)if(T)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))me=T;else throw me=!T,Error(s+"crypto unavailable");else me=T;else throw Error(s+S+" not true or false: "+T);if(w.hasOwnProperty(S="MODULO_MODE")&&(T=w[S],m(T,0,9,S),G=T),w.hasOwnProperty(S="POW_PRECISION")&&(T=w[S],m(T,0,b,S),K=T),w.hasOwnProperty(S="FORMAT"))if(T=w[S],typeof T=="object")ce=T;else throw Error(s+S+" not an object: "+T);if(w.hasOwnProperty(S="ALPHABET"))if(T=w[S],typeof T=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(T))De=T.slice(0,10)=="0123456789",qe=T;else throw Error(s+S+" invalid: "+T)}else throw Error(s+"Object expected: "+w);return{DECIMAL_PLACES:re,ROUNDING_MODE:ee,EXPONENTIAL_AT:[ue,fe],RANGE:[ke,ie],CRYPTO:me,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ce,ALPHABET:qe}},W.isBigNumber=function(w){if(!w||w._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var S,T,M=w.c,F=w.e,I=w.s;e:if({}.toString.call(M)=="[object Array]"){if((I===1||I===-1)&&F>=-b&&F<=b&&F===o(F)){if(M[0]===0){if(F===0&&M.length===1)return!0;break e}if(S=(F+1)%l,S<1&&(S+=l),String(M[0]).length==S){for(S=0;S<M.length;S++)if(T=M[S],T<0||T>=c||T!==o(T))break e;if(T!==0)return!0}}}else if(M===null&&F===null&&(I===null||I===1||I===-1))return!0;throw Error(s+"Invalid BigNumber: "+w)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var w=9007199254740992,S=Math.random()*w&2097151?function(){return o(Math.random()*w)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(T){var M,F,I,U,x,P=0,j=[],N=new W(Y);if(T==null?T=re:m(T,0,b),U=n(T/l),me)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(U*=2));P<U;)x=M[P]*131072+(M[P+1]>>>11),x>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),M[P]=F[0],M[P+1]=F[1]):(j.push(x%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(U*=7);P<U;)x=(M[P]&31)*281474976710656+M[P+1]*1099511627776+M[P+2]*4294967296+M[P+3]*16777216+(M[P+4]<<16)+(M[P+5]<<8)+M[P+6],x>=9e15?crypto.randomBytes(7).copy(M,P):(j.push(x%1e14),P+=7);P=U/7}else throw me=!1,Error(s+"crypto unavailable");if(!me)for(;P<U;)x=S(),x<9e15&&(j[P++]=x%1e14);for(U=j[--P],T%=l,U&&T&&(x=d[l-T],j[P]=o(U/x)*x);j[P]===0;j.pop(),P--);if(P<0)j=[I=0];else{for(I=-1;j[0]===0;j.splice(0,1),I-=l);for(P=1,x=j[0];x>=10;x/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=j,N}})(),W.sum=function(){for(var w=1,S=arguments,T=new W(S[0]);w<S.length;)T=T.plus(S[w++]);return T},q=(function(){var w="0123456789";function S(T,M,F,I){for(var U,x=[0],P,j=0,N=T.length;j<N;){for(P=x.length;P--;x[P]*=M);for(x[0]+=I.indexOf(T.charAt(j++)),U=0;U<x.length;U++)x[U]>F-1&&(x[U+1]==null&&(x[U+1]=0),x[U+1]+=x[U]/F|0,x[U]%=F)}return x.reverse()}return function(T,M,F,I,U){var x,P,j,N,z,Z,te,Ee,Pe=T.indexOf("."),Ne=re,we=ee;for(Pe>=0&&(N=K,K=0,T=T.replace(".",""),Ee=new W(M),Z=Ee.pow(T.length-Pe),K=N,Ee.c=S(A(y(Z.c),Z.e,"0"),10,F,w),Ee.e=Ee.c.length),te=S(T,M,F,U?(x=qe,w):(x=w,qe)),j=N=te.length;te[--N]==0;te.pop());if(!te[0])return x.charAt(0);if(Pe<0?--j:(Z.c=te,Z.e=j,Z.s=I,Z=O(Z,Ee,Ne,we,F),te=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,Pe=te[P],N=F/2,z=z||P<0||te[P+1]!=null,z=we<4?(Pe!=null||z)&&(we==0||we==(Z.s<0?3:2)):Pe>N||Pe==N&&(we==4||z||we==6&&te[P-1]&1||we==(Z.s<0?8:7)),P<1||!te[0])T=z?A(x.charAt(1),-Ne,x.charAt(0)):x.charAt(0);else{if(te.length=P,z)for(--F;++te[--P]>F;)te[P]=0,P||(++j,te=[1].concat(te));for(N=te.length;!te[--N];);for(Pe=0,T="";Pe<=N;T+=x.charAt(te[Pe++]));T=A(T,j,x.charAt(0))}return T}})(),O=(function(){function w(M,F,I){var U,x,P,j,N=0,z=M.length,Z=F%p,te=F/p|0;for(M=M.slice();z--;)P=M[z]%p,j=M[z]/p|0,U=te*P+j*Z,x=Z*P+U%p*p+N,N=(x/I|0)+(U/p|0)+te*j,M[z]=x%I;return N&&(M=[N].concat(M)),M}function S(M,F,I,U){var x,P;if(I!=U)P=I>U?1:-1;else for(x=P=0;x<I;x++)if(M[x]!=F[x]){P=M[x]>F[x]?1:-1;break}return P}function T(M,F,I,U){for(var x=0;I--;)M[I]-=x,x=M[I]<F[I]?1:0,M[I]=x*U+M[I]-F[I];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,F,I,U,x){var P,j,N,z,Z,te,Ee,Pe,Ne,we,Se,Ue,bn,Cn,wn,dt,lr,Ye=M.s==F.s?1:-1,$e=M.c,ve=F.c;if(!$e||!$e[0]||!ve||!ve[0])return new W(!M.s||!F.s||($e?ve&&$e[0]==ve[0]:!ve)?NaN:$e&&$e[0]==0||!ve?Ye*0:Ye/0);for(Pe=new W(Ye),Ne=Pe.c=[],j=M.e-F.e,Ye=I+j+1,x||(x=c,j=C(M.e/l)-C(F.e/l),Ye=Ye/l|0),N=0;ve[N]==($e[N]||0);N++);if(ve[N]>($e[N]||0)&&j--,Ye<0)Ne.push(1),z=!0;else{for(Cn=$e.length,dt=ve.length,N=0,Ye+=2,Z=o(x/(ve[0]+1)),Z>1&&(ve=w(ve,Z,x),$e=w($e,Z,x),dt=ve.length,Cn=$e.length),bn=dt,we=$e.slice(0,dt),Se=we.length;Se<dt;we[Se++]=0);lr=ve.slice(),lr=[0].concat(lr),wn=ve[0],ve[1]>=x/2&&wn++;do{if(Z=0,P=S(ve,we,dt,Se),P<0){if(Ue=we[0],dt!=Se&&(Ue=Ue*x+(we[1]||0)),Z=o(Ue/wn),Z>1)for(Z>=x&&(Z=x-1),te=w(ve,Z,x),Ee=te.length,Se=we.length;S(te,we,Ee,Se)==1;)Z--,T(te,dt<Ee?lr:ve,Ee,x),Ee=te.length,P=1;else Z==0&&(P=Z=1),te=ve.slice(),Ee=te.length;if(Ee<Se&&(te=[0].concat(te)),T(we,te,Se,x),Se=we.length,P==-1)for(;S(ve,we,dt,Se)<1;)Z++,T(we,dt<Se?lr:ve,Se,x),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=$e[bn]||0:(we=[$e[bn]],Se=1)}while((bn++<Cn||we[0]!=null)&&Ye--);z=we[0]!=null,Ne[0]||Ne.splice(0,1)}if(x==c){for(N=1,Ye=Ne[0];Ye>=10;Ye/=10,N++);xe(Pe,I+(Pe.e=N+j*l-1)+1,U,z)}else Pe.e=j,Pe.r=+z;return Pe}})();function de(w,S,T,M){var F,I,U,x,P;if(T==null?T=ee:m(T,0,8),!w.c)return w.toString();if(F=w.c[0],U=w.e,S==null)P=y(w.c),P=M==1||M==2&&(U<=ue||U>=fe)?_(P,U):A(P,U,"0");else if(w=xe(new W(w),S,T),I=w.e,P=y(w.c),x=P.length,M==1||M==2&&(S<=I||I<=ue)){for(;x<S;P+="0",x++);P=_(P,I)}else if(S-=U+(M===2&&I>U),P=A(P,I,"0"),I+1>x){if(--S>0)for(P+=".";S--;P+="0");}else if(S+=I-x,S>0)for(I+1==x&&(P+=".");S--;P+="0");return w.s<0&&F?"-"+P:P}function _e(w,S){for(var T,M,F=1,I=new W(w[0]);F<w.length;F++)M=new W(w[F]),(!M.s||(T=g(I,M))===S||T===0&&I.s===S)&&(I=M);return I}function It(w,S,T){for(var M=1,F=S.length;!S[--F];S.pop());for(F=S[0];F>=10;F/=10,M++);return(T=M+T*l-1)>ie?w.c=w.e=null:T<ke?w.c=[w.e=0]:(w.e=T,w.c=S),w}J=(function(){var w=/^(-?)0([xbo])(?=\w[\w.]*$)/i,S=/^([^.]+)\.$/,T=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,U,x,P){var j,N=x?U:U.replace(F,"");if(M.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!x&&(N=N.replace(w,function(z,Z,te){return j=(te=te.toLowerCase())=="x"?16:te=="b"?2:8,!P||P==j?Z:z}),P&&(j=P,N=N.replace(S,"$1").replace(T,"0.$1")),U!=N))return new W(N,j);if(W.DEBUG)throw Error(s+"Not a"+(P?" base "+P:"")+" number: "+U);I.s=null}I.c=I.e=null}})();function xe(w,S,T,M){var F,I,U,x,P,j,N,z=w.c,Z=d;if(z){e:{for(F=1,x=z[0];x>=10;x/=10,F++);if(I=S-F,I<0)I+=l,U=S,P=z[j=0],N=o(P/Z[F-U-1]%10);else if(j=n((I+1)/l),j>=z.length)if(M){for(;z.length<=j;z.push(0));P=N=0,F=1,I%=l,U=I-l+1}else break e;else{for(P=x=z[j],F=1;x>=10;x/=10,F++);I%=l,U=I-l+F,N=U<0?0:o(P/Z[F-U-1]%10)}if(M=M||S<0||z[j+1]!=null||(U<0?P:P%Z[F-U-1]),M=T<4?(N||M)&&(T==0||T==(w.s<0?3:2)):N>5||N==5&&(T==4||M||T==6&&(I>0?U>0?P/Z[F-U]:0:z[j-1])%10&1||T==(w.s<0?8:7)),S<1||!z[0])return z.length=0,M?(S-=w.e+1,z[0]=Z[(l-S%l)%l],w.e=-S||0):z[0]=w.e=0,w;if(I==0?(z.length=j,x=1,j--):(z.length=j+1,x=Z[l-I],z[j]=U>0?o(P/Z[F-U]%Z[U])*x:0),M)for(;;)if(j==0){for(I=1,U=z[0];U>=10;U/=10,I++);for(U=z[0]+=x,x=1;U>=10;U/=10,x++);I!=x&&(w.e++,z[0]==c&&(z[0]=1));break}else{if(z[j]+=x,z[j]!=c)break;z[j--]=0,x=1}for(I=z.length;z[--I]===0;z.pop());}w.e>ie?w.c=w.e=null:w.e<ke&&(w.c=[w.e=0])}return w}function je(w){var S,T=w.e;return T===null?w.toString():(S=y(w.c),S=T<=ue||T>=fe?_(S,T):A(S,T,"0"),w.s<0?"-"+S:S)}return B.absoluteValue=B.abs=function(){var w=new W(this);return w.s<0&&(w.s=1),w},B.comparedTo=function(w,S){return g(this,new W(w,S))},B.decimalPlaces=B.dp=function(w,S){var T,M,F,I=this;if(w!=null)return m(w,0,b),S==null?S=ee:m(S,0,8),xe(new W(I),w+I.e+1,S);if(!(T=I.c))return null;if(M=((F=T.length-1)-C(this.e/l))*l,F=T[F])for(;F%10==0;F/=10,M--);return M<0&&(M=0),M},B.dividedBy=B.div=function(w,S){return O(this,new W(w,S),re,ee)},B.dividedToIntegerBy=B.idiv=function(w,S){return O(this,new W(w,S),0,1)},B.exponentiatedBy=B.pow=function(w,S){var T,M,F,I,U,x,P,j,N,z=this;if(w=new W(w),w.c&&!w.isInteger())throw Error(s+"Exponent not an integer: "+je(w));if(S!=null&&(S=new W(S)),x=w.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!w.c||!w.c[0])return N=new W(Math.pow(+je(z),x?w.s*(2-v(w)):+je(w))),S?N.mod(S):N;if(P=w.s<0,S){if(S.c?!S.c[0]:!S.s)return new W(NaN);M=!P&&z.isInteger()&&S.isInteger(),M&&(z=z.mod(S))}else{if(w.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||x&&z.c[1]>=24e7:z.c[0]<8e13||x&&z.c[0]<=9999975e7)))return I=z.s<0&&v(w)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(x?(T=new W(.5),P&&(w.s=1),j=v(w)):(F=Math.abs(+je(w)),j=F%2),N=new W(Y);;){if(j){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):M&&(N=N.mod(S))}if(F){if(F=o(F/2),F===0)break;j=F%2}else if(w=w.times(T),xe(w,w.e+1,1),w.e>14)j=v(w);else{if(F=+je(w),F===0)break;j=F%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):M&&(z=z.mod(S))}return M?N:(P&&(N=Y.div(N)),S?N.mod(S):I?xe(N,K,ee,U):N)},B.integerValue=function(w){var S=new W(this);return w==null?w=ee:m(w,0,8),xe(S,S.e+1,w)},B.isEqualTo=B.eq=function(w,S){return g(this,new W(w,S))===0},B.isFinite=function(){return!!this.c},B.isGreaterThan=B.gt=function(w,S){return g(this,new W(w,S))>0},B.isGreaterThanOrEqualTo=B.gte=function(w,S){return(S=g(this,new W(w,S)))===1||S===0},B.isInteger=function(){return!!this.c&&C(this.e/l)>this.c.length-2},B.isLessThan=B.lt=function(w,S){return g(this,new W(w,S))<0},B.isLessThanOrEqualTo=B.lte=function(w,S){return(S=g(this,new W(w,S)))===-1||S===0},B.isNaN=function(){return!this.s},B.isNegative=function(){return this.s<0},B.isPositive=function(){return this.s>0},B.isZero=function(){return!!this.c&&this.c[0]==0},B.minus=function(w,S){var T,M,F,I,U=this,x=U.s;if(w=new W(w,S),S=w.s,!x||!S)return new W(NaN);if(x!=S)return w.s=-S,U.plus(w);var P=U.e/l,j=w.e/l,N=U.c,z=w.c;if(!P||!j){if(!N||!z)return N?(w.s=-S,w):new W(z?U:NaN);if(!N[0]||!z[0])return z[0]?(w.s=-S,w):new W(N[0]?U:ee==3?-0:0)}if(P=C(P),j=C(j),N=N.slice(),x=P-j){for((I=x<0)?(x=-x,F=N):(j=P,F=z),F.reverse(),S=x;S--;F.push(0));F.reverse()}else for(M=(I=(x=N.length)<(S=z.length))?x:S,x=S=0;S<M;S++)if(N[S]!=z[S]){I=N[S]<z[S];break}if(I&&(F=N,N=z,z=F,w.s=-w.s),S=(M=z.length)-(T=N.length),S>0)for(;S--;N[T++]=0);for(S=c-1;M>x;){if(N[--M]<z[M]){for(T=M;T&&!N[--T];N[T]=S);--N[T],N[M]+=c}N[M]-=z[M]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?It(w,N,j):(w.s=ee==3?-1:1,w.c=[w.e=0],w)},B.modulo=B.mod=function(w,S){var T,M,F=this;return w=new W(w,S),!F.c||!w.s||w.c&&!w.c[0]?new W(NaN):!w.c||F.c&&!F.c[0]?new W(F):(G==9?(M=w.s,w.s=1,T=O(F,w,0,3),w.s=M,T.s*=M):T=O(F,w,0,G),w=F.minus(T.times(w)),!w.c[0]&&G==1&&(w.s=F.s),w)},B.multipliedBy=B.times=function(w,S){var T,M,F,I,U,x,P,j,N,z,Z,te,Ee,Pe,Ne,we=this,Se=we.c,Ue=(w=new W(w,S)).c;if(!Se||!Ue||!Se[0]||!Ue[0])return!we.s||!w.s||Se&&!Se[0]&&!Ue||Ue&&!Ue[0]&&!Se?w.c=w.e=w.s=null:(w.s*=we.s,!Se||!Ue?w.c=w.e=null:(w.c=[0],w.e=0)),w;for(M=C(we.e/l)+C(w.e/l),w.s*=we.s,P=Se.length,z=Ue.length,P<z&&(Ee=Se,Se=Ue,Ue=Ee,F=P,P=z,z=F),F=P+z,Ee=[];F--;Ee.push(0));for(Pe=c,Ne=p,F=z;--F>=0;){for(T=0,Z=Ue[F]%Ne,te=Ue[F]/Ne|0,U=P,I=F+U;I>F;)j=Se[--U]%Ne,N=Se[U]/Ne|0,x=te*j+N*Z,j=Z*j+x%Ne*Ne+Ee[I]+T,T=(j/Pe|0)+(x/Ne|0)+te*N,Ee[I--]=j%Pe;Ee[I]=T}return T?++M:Ee.splice(0,1),It(w,Ee,M)},B.negated=function(){var w=new W(this);return w.s=-w.s||null,w},B.plus=function(w,S){var T,M=this,F=M.s;if(w=new W(w,S),S=w.s,!F||!S)return new W(NaN);if(F!=S)return w.s=-S,M.minus(w);var I=M.e/l,U=w.e/l,x=M.c,P=w.c;if(!I||!U){if(!x||!P)return new W(F/0);if(!x[0]||!P[0])return P[0]?w:new W(x[0]?M:F*0)}if(I=C(I),U=C(U),x=x.slice(),F=I-U){for(F>0?(U=I,T=P):(F=-F,T=x),T.reverse();F--;T.push(0));T.reverse()}for(F=x.length,S=P.length,F-S<0&&(T=P,P=x,x=T,S=F),F=0;S;)F=(x[--S]=x[S]+P[S]+F)/c|0,x[S]=c===x[S]?0:x[S]%c;return F&&(x=[F].concat(x),++U),It(w,x,U)},B.precision=B.sd=function(w,S){var T,M,F,I=this;if(w!=null&&w!==!!w)return m(w,1,b),S==null?S=ee:m(S,0,8),xe(new W(I),w,S);if(!(T=I.c))return null;if(F=T.length-1,M=F*l+1,F=T[F]){for(;F%10==0;F/=10,M--);for(F=T[0];F>=10;F/=10,M++);}return w&&I.e+1>M&&(M=I.e+1),M},B.shiftedBy=function(w){return m(w,-f,f),this.times("1e"+w)},B.squareRoot=B.sqrt=function(){var w,S,T,M,F,I=this,U=I.c,x=I.s,P=I.e,j=re+4,N=new W("0.5");if(x!==1||!U||!U[0])return new W(!x||x<0&&(!U||U[0])?NaN:U?I:1/0);if(x=Math.sqrt(+je(I)),x==0||x==1/0?(S=y(U),(S.length+P)%2==0&&(S+="0"),x=Math.sqrt(+S),P=C((P+1)/2)-(P<0||P%2),x==1/0?S="5e"+P:(S=x.toExponential(),S=S.slice(0,S.indexOf("e")+1)+P),T=new W(S)):T=new W(x+""),T.c[0]){for(P=T.e,x=P+j,x<3&&(x=0);;)if(F=T,T=N.times(F.plus(O(I,F,j,1))),y(F.c).slice(0,x)===(S=y(T.c)).slice(0,x))if(T.e<P&&--x,S=S.slice(x-3,x+1),S=="9999"||!M&&S=="4999"){if(!M&&(xe(F,F.e+re+2,0),F.times(F).eq(I))){T=F;break}j+=4,x+=4,M=1}else{(!+S||!+S.slice(1)&&S.charAt(0)=="5")&&(xe(T,T.e+re+2,1),w=!T.times(T).eq(I));break}}return xe(T,T.e+re+1,ee,w)},B.toExponential=function(w,S){return w!=null&&(m(w,0,b),w++),de(this,w,S,1)},B.toFixed=function(w,S){return w!=null&&(m(w,0,b),w=w+this.e+1),de(this,w,S)},B.toFormat=function(w,S,T){var M,F=this;if(T==null)w!=null&&S&&typeof S=="object"?(T=S,S=null):w&&typeof w=="object"?(T=w,w=S=null):T=ce;else if(typeof T!="object")throw Error(s+"Argument not an object: "+T);if(M=F.toFixed(w,S),F.c){var I,U=M.split("."),x=+T.groupSize,P=+T.secondaryGroupSize,j=T.groupSeparator||"",N=U[0],z=U[1],Z=F.s<0,te=Z?N.slice(1):N,Ee=te.length;if(P&&(I=x,x=P,P=I,Ee-=I),x>0&&Ee>0){for(I=Ee%x||x,N=te.substr(0,I);I<Ee;I+=x)N+=j+te.substr(I,x);P>0&&(N+=j+te.slice(I)),Z&&(N="-"+N)}M=z?N+(T.decimalSeparator||"")+((P=+T.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(T.fractionGroupSeparator||"")):z):N}return(T.prefix||"")+M+(T.suffix||"")},B.toFraction=function(w){var S,T,M,F,I,U,x,P,j,N,z,Z,te=this,Ee=te.c;if(w!=null&&(x=new W(w),!x.isInteger()&&(x.c||x.s!==1)||x.lt(Y)))throw Error(s+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+je(x));if(!Ee)return new W(te);for(S=new W(Y),j=T=new W(Y),M=P=new W(Y),Z=y(Ee),I=S.e=Z.length-te.e-1,S.c[0]=d[(U=I%l)<0?l+U:U],w=!w||x.comparedTo(S)>0?I>0?S:j:x,U=ie,ie=1/0,x=new W(Z),P.c[0]=0;N=O(x,S,0,1),F=T.plus(N.times(M)),F.comparedTo(w)!=1;)T=M,M=F,j=P.plus(N.times(F=j)),P=F,S=x.minus(N.times(F=S)),x=F;return F=O(w.minus(T),M,0,1),P=P.plus(F.times(j)),T=T.plus(F.times(M)),P.s=j.s=te.s,I=I*2,z=O(j,M,I,ee).minus(te).abs().comparedTo(O(P,T,I,ee).minus(te).abs())<1?[j,M]:[P,T],ie=U,z},B.toNumber=function(){return+je(this)},B.toPrecision=function(w,S){return w!=null&&m(w,1,b),de(this,w,S,2)},B.toString=function(w){var S,T=this,M=T.s,F=T.e;return F===null?M?(S="Infinity",M<0&&(S="-"+S)):S="NaN":(w==null?S=F<=ue||F>=fe?_(y(T.c),F):A(y(T.c),F,"0"):w===10&&De?(T=xe(new W(T),re+F+1,ee),S=A(y(T.c),T.e,"0")):(m(w,2,qe.length,"Base"),S=q(A(y(T.c),F,"0"),10,w,M,!0)),M<0&&T.c[0]&&(S="-"+S)),S},B.valueOf=B.toJSON=function(){return je(this)},B._isBigNumber=!0,D!=null&&W.set(D),W}function C(D){var O=D|0;return D>0||D===O?O:O-1}function y(D){for(var O,q,J=1,B=D.length,Y=D[0]+"";J<B;){for(O=D[J++]+"",q=l-O.length;q--;O="0"+O);Y+=O}for(B=Y.length;Y.charCodeAt(--B)===48;);return Y.slice(0,B+1||1)}function g(D,O){var q,J,B=D.c,Y=O.c,re=D.s,ee=O.s,ue=D.e,fe=O.e;if(!re||!ee)return null;if(q=B&&!B[0],J=Y&&!Y[0],q||J)return q?J?0:-ee:re;if(re!=ee)return re;if(q=re<0,J=ue==fe,!B||!Y)return J?0:!B^q?1:-1;if(!J)return ue>fe^q?1:-1;for(ee=(ue=B.length)<(fe=Y.length)?ue:fe,re=0;re<ee;re++)if(B[re]!=Y[re])return B[re]>Y[re]^q?1:-1;return ue==fe?0:ue>fe^q?1:-1}function m(D,O,q,J){if(D<O||D>q||D!==o(D))throw Error(s+(J||"Argument")+(typeof D=="number"?D<O||D>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function v(D){var O=D.c.length-1;return C(D.e/l)==O&&D.c[O]%2!=0}function _(D,O){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(O<0?"e":"e+")+O}function A(D,O,q){var J,B;if(O<0){for(B=q+".";++O;B+=q);D=B+D}else if(J=D.length,++O>J){for(B=q,O-=J;--O;B+=q);D+=B}else O<J&&(D=D.slice(0,O)+"."+D.slice(O));return D}e=k(),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)})(hm)});var ym=V((K1,gm)=>{var pm=gc(),mm=gm.exports;(function(){"use strict";function t(f){return f<10?"0"+f:f}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(f){return r.lastIndex=0,r.test(f)?'"'+f.replace(r,function(d){var p=s[d];return typeof p=="string"?p:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+f+'"'}function l(f,d){var p,b,k,C,y=n,g,m=d[f],v=m!=null&&(m instanceof pm||pm.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(f)),typeof a=="function"&&(m=a.call(d,f,m)),typeof m){case"string":return v?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(n+=o,g=[],Object.prototype.toString.apply(m)==="[object Array]"){for(C=m.length,p=0;p<C;p+=1)g[p]=l(p,m)||"null";return k=g.length===0?"[]":n?`[
|
|
43
|
+
`}yield n}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>jr(pp()))).HttpsProxyAgent,this.#s}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(um(),am))).default,this.#i}static mergeHeaders(e,...r){e=e instanceof Headers?e:new Headers(e);for(let n of r)(n instanceof Headers?n:new Headers(n)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};Gn.Gaxios=Si;Wn=Si});var Ke=V(rt=>{"use strict";var kw=rt&&rt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Sw=rt&&rt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kw(e,t,r)};Object.defineProperty(rt,"__esModule",{value:!0});rt.instance=rt.Gaxios=rt.GaxiosError=void 0;rt.request=Tw;var fm=dm();Object.defineProperty(rt,"Gaxios",{enumerable:!0,get:function(){return fm.Gaxios}});var vw=Wu();Object.defineProperty(rt,"GaxiosError",{enumerable:!0,get:function(){return vw.GaxiosError}});Sw(Vu(),rt);rt.instance=new fm.Gaxios;async function Tw(t){return rt.instance.request(t)}});var gc=V((hm,vi)=>{(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,C=1e9;function k(D){var O,q,J,B=W.prototype={constructor:W,toString:null,valueOf:null},Y=new W(1),re=20,ee=4,ue=-7,fe=21,ke=-1e7,ie=1e7,me=!1,G=1,K=0,ce={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},qe="0123456789abcdefghijklmnopqrstuvwxyz",De=!0;function W(w,S){var T,M,F,I,U,x,P,j,N=this;if(!(N instanceof W))return new W(w,S);if(S==null){if(w&&w._isBigNumber===!0){N.s=w.s,!w.c||w.e>ie?N.c=N.e=null:w.e<ke?N.c=[N.e=0]:(N.e=w.e,N.c=w.c.slice());return}if((x=typeof w=="number")&&w*0==0){if(N.s=1/w<0?(w=-w,-1):1,w===~~w){for(I=0,U=w;U>=10;U/=10,I++);I>ie?N.c=N.e=null:(N.e=I,N.c=[w]);return}j=String(w)}else{if(!r.test(j=String(w)))return J(N,j,x);N.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(I=j.indexOf("."))>-1&&(j=j.replace(".","")),(U=j.search(/e/i))>0?(I<0&&(I=U),I+=+j.slice(U+1),j=j.substring(0,U)):I<0&&(I=j.length)}else{if(m(S,2,qe.length,"Base"),S==10&&De)return N=new W(w),xe(N,re+N.e+1,ee);if(j=String(w),x=typeof w=="number"){if(w*0!=0)return J(N,j,x,S);if(N.s=1/w<0?(j=j.slice(1),-1):1,W.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(a+w)}else N.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(T=qe.slice(0,S),I=U=0,P=j.length;U<P;U++)if(T.indexOf(M=j.charAt(U))<0){if(M=="."){if(U>I){I=P;continue}}else if(!F&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){F=!0,U=-1,I=0;continue}return J(N,String(w),x,S)}x=!1,j=q(j,S,10,N.s),(I=j.indexOf("."))>-1?j=j.replace(".",""):I=j.length}for(U=0;j.charCodeAt(U)===48;U++);for(P=j.length;j.charCodeAt(--P)===48;);if(j=j.slice(U,++P)){if(P-=U,x&&W.DEBUG&&P>15&&(w>f||w!==o(w)))throw Error(a+N.s*w);if((I=I-U-1)>ie)N.c=N.e=null;else if(I<ke)N.c=[N.e=0];else{if(N.e=I,N.c=[],U=(I+1)%l,I<0&&(U+=l),U<P){for(U&&N.c.push(+j.slice(0,U)),P-=l;U<P;)N.c.push(+j.slice(U,U+=l));U=l-(j=j.slice(U)).length}else U-=P;for(;U--;j+="0");N.c.push(+j)}}else N.c=[N.e=0]}W.clone=k,W.ROUND_UP=0,W.ROUND_DOWN=1,W.ROUND_CEIL=2,W.ROUND_FLOOR=3,W.ROUND_HALF_UP=4,W.ROUND_HALF_DOWN=5,W.ROUND_HALF_EVEN=6,W.ROUND_HALF_CEIL=7,W.ROUND_HALF_FLOOR=8,W.EUCLID=9,W.config=W.set=function(w){var S,T;if(w!=null)if(typeof w=="object"){if(w.hasOwnProperty(S="DECIMAL_PLACES")&&(T=w[S],m(T,0,C,S),re=T),w.hasOwnProperty(S="ROUNDING_MODE")&&(T=w[S],m(T,0,8,S),ee=T),w.hasOwnProperty(S="EXPONENTIAL_AT")&&(T=w[S],T&&T.pop?(m(T[0],-C,0,S),m(T[1],0,C,S),ue=T[0],fe=T[1]):(m(T,-C,C,S),ue=-(fe=T<0?-T:T))),w.hasOwnProperty(S="RANGE"))if(T=w[S],T&&T.pop)m(T[0],-C,-1,S),m(T[1],1,C,S),ke=T[0],ie=T[1];else if(m(T,-C,C,S),T)ke=-(ie=T<0?-T:T);else throw Error(s+S+" cannot be zero: "+T);if(w.hasOwnProperty(S="CRYPTO"))if(T=w[S],T===!!T)if(T)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))me=T;else throw me=!T,Error(s+"crypto unavailable");else me=T;else throw Error(s+S+" not true or false: "+T);if(w.hasOwnProperty(S="MODULO_MODE")&&(T=w[S],m(T,0,9,S),G=T),w.hasOwnProperty(S="POW_PRECISION")&&(T=w[S],m(T,0,C,S),K=T),w.hasOwnProperty(S="FORMAT"))if(T=w[S],typeof T=="object")ce=T;else throw Error(s+S+" not an object: "+T);if(w.hasOwnProperty(S="ALPHABET"))if(T=w[S],typeof T=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(T))De=T.slice(0,10)=="0123456789",qe=T;else throw Error(s+S+" invalid: "+T)}else throw Error(s+"Object expected: "+w);return{DECIMAL_PLACES:re,ROUNDING_MODE:ee,EXPONENTIAL_AT:[ue,fe],RANGE:[ke,ie],CRYPTO:me,MODULO_MODE:G,POW_PRECISION:K,FORMAT:ce,ALPHABET:qe}},W.isBigNumber=function(w){if(!w||w._isBigNumber!==!0)return!1;if(!W.DEBUG)return!0;var S,T,M=w.c,F=w.e,I=w.s;e:if({}.toString.call(M)=="[object Array]"){if((I===1||I===-1)&&F>=-C&&F<=C&&F===o(F)){if(M[0]===0){if(F===0&&M.length===1)return!0;break e}if(S=(F+1)%l,S<1&&(S+=l),String(M[0]).length==S){for(S=0;S<M.length;S++)if(T=M[S],T<0||T>=c||T!==o(T))break e;if(T!==0)return!0}}}else if(M===null&&F===null&&(I===null||I===1||I===-1))return!0;throw Error(s+"Invalid BigNumber: "+w)},W.maximum=W.max=function(){return _e(arguments,-1)},W.minimum=W.min=function(){return _e(arguments,1)},W.random=(function(){var w=9007199254740992,S=Math.random()*w&2097151?function(){return o(Math.random()*w)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(T){var M,F,I,U,x,P=0,j=[],N=new W(Y);if(T==null?T=re:m(T,0,C),U=n(T/l),me)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(U*=2));P<U;)x=M[P]*131072+(M[P+1]>>>11),x>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),M[P]=F[0],M[P+1]=F[1]):(j.push(x%1e14),P+=2);P=U/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(U*=7);P<U;)x=(M[P]&31)*281474976710656+M[P+1]*1099511627776+M[P+2]*4294967296+M[P+3]*16777216+(M[P+4]<<16)+(M[P+5]<<8)+M[P+6],x>=9e15?crypto.randomBytes(7).copy(M,P):(j.push(x%1e14),P+=7);P=U/7}else throw me=!1,Error(s+"crypto unavailable");if(!me)for(;P<U;)x=S(),x<9e15&&(j[P++]=x%1e14);for(U=j[--P],T%=l,U&&T&&(x=d[l-T],j[P]=o(U/x)*x);j[P]===0;j.pop(),P--);if(P<0)j=[I=0];else{for(I=-1;j[0]===0;j.splice(0,1),I-=l);for(P=1,x=j[0];x>=10;x/=10,P++);P<l&&(I-=l-P)}return N.e=I,N.c=j,N}})(),W.sum=function(){for(var w=1,S=arguments,T=new W(S[0]);w<S.length;)T=T.plus(S[w++]);return T},q=(function(){var w="0123456789";function S(T,M,F,I){for(var U,x=[0],P,j=0,N=T.length;j<N;){for(P=x.length;P--;x[P]*=M);for(x[0]+=I.indexOf(T.charAt(j++)),U=0;U<x.length;U++)x[U]>F-1&&(x[U+1]==null&&(x[U+1]=0),x[U+1]+=x[U]/F|0,x[U]%=F)}return x.reverse()}return function(T,M,F,I,U){var x,P,j,N,z,Z,te,Ae,Pe=T.indexOf("."),Ne=re,we=ee;for(Pe>=0&&(N=K,K=0,T=T.replace(".",""),Ae=new W(M),Z=Ae.pow(T.length-Pe),K=N,Ae.c=S(A(y(Z.c),Z.e,"0"),10,F,w),Ae.e=Ae.c.length),te=S(T,M,F,U?(x=qe,w):(x=w,qe)),j=N=te.length;te[--N]==0;te.pop());if(!te[0])return x.charAt(0);if(Pe<0?--j:(Z.c=te,Z.e=j,Z.s=I,Z=O(Z,Ae,Ne,we,F),te=Z.c,z=Z.r,j=Z.e),P=j+Ne+1,Pe=te[P],N=F/2,z=z||P<0||te[P+1]!=null,z=we<4?(Pe!=null||z)&&(we==0||we==(Z.s<0?3:2)):Pe>N||Pe==N&&(we==4||z||we==6&&te[P-1]&1||we==(Z.s<0?8:7)),P<1||!te[0])T=z?A(x.charAt(1),-Ne,x.charAt(0)):x.charAt(0);else{if(te.length=P,z)for(--F;++te[--P]>F;)te[P]=0,P||(++j,te=[1].concat(te));for(N=te.length;!te[--N];);for(Pe=0,T="";Pe<=N;T+=x.charAt(te[Pe++]));T=A(T,j,x.charAt(0))}return T}})(),O=(function(){function w(M,F,I){var U,x,P,j,N=0,z=M.length,Z=F%p,te=F/p|0;for(M=M.slice();z--;)P=M[z]%p,j=M[z]/p|0,U=te*P+j*Z,x=Z*P+U%p*p+N,N=(x/I|0)+(U/p|0)+te*j,M[z]=x%I;return N&&(M=[N].concat(M)),M}function S(M,F,I,U){var x,P;if(I!=U)P=I>U?1:-1;else for(x=P=0;x<I;x++)if(M[x]!=F[x]){P=M[x]>F[x]?1:-1;break}return P}function T(M,F,I,U){for(var x=0;I--;)M[I]-=x,x=M[I]<F[I]?1:0,M[I]=x*U+M[I]-F[I];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,F,I,U,x){var P,j,N,z,Z,te,Ae,Pe,Ne,we,Se,Ue,bn,Cn,wn,dt,lr,Ye=M.s==F.s?1:-1,$e=M.c,ve=F.c;if(!$e||!$e[0]||!ve||!ve[0])return new W(!M.s||!F.s||($e?ve&&$e[0]==ve[0]:!ve)?NaN:$e&&$e[0]==0||!ve?Ye*0:Ye/0);for(Pe=new W(Ye),Ne=Pe.c=[],j=M.e-F.e,Ye=I+j+1,x||(x=c,j=_(M.e/l)-_(F.e/l),Ye=Ye/l|0),N=0;ve[N]==($e[N]||0);N++);if(ve[N]>($e[N]||0)&&j--,Ye<0)Ne.push(1),z=!0;else{for(Cn=$e.length,dt=ve.length,N=0,Ye+=2,Z=o(x/(ve[0]+1)),Z>1&&(ve=w(ve,Z,x),$e=w($e,Z,x),dt=ve.length,Cn=$e.length),bn=dt,we=$e.slice(0,dt),Se=we.length;Se<dt;we[Se++]=0);lr=ve.slice(),lr=[0].concat(lr),wn=ve[0],ve[1]>=x/2&&wn++;do{if(Z=0,P=S(ve,we,dt,Se),P<0){if(Ue=we[0],dt!=Se&&(Ue=Ue*x+(we[1]||0)),Z=o(Ue/wn),Z>1)for(Z>=x&&(Z=x-1),te=w(ve,Z,x),Ae=te.length,Se=we.length;S(te,we,Ae,Se)==1;)Z--,T(te,dt<Ae?lr:ve,Ae,x),Ae=te.length,P=1;else Z==0&&(P=Z=1),te=ve.slice(),Ae=te.length;if(Ae<Se&&(te=[0].concat(te)),T(we,te,Se,x),Se=we.length,P==-1)for(;S(ve,we,dt,Se)<1;)Z++,T(we,dt<Se?lr:ve,Se,x),Se=we.length}else P===0&&(Z++,we=[0]);Ne[N++]=Z,we[0]?we[Se++]=$e[bn]||0:(we=[$e[bn]],Se=1)}while((bn++<Cn||we[0]!=null)&&Ye--);z=we[0]!=null,Ne[0]||Ne.splice(0,1)}if(x==c){for(N=1,Ye=Ne[0];Ye>=10;Ye/=10,N++);xe(Pe,I+(Pe.e=N+j*l-1)+1,U,z)}else Pe.e=j,Pe.r=+z;return Pe}})();function de(w,S,T,M){var F,I,U,x,P;if(T==null?T=ee:m(T,0,8),!w.c)return w.toString();if(F=w.c[0],U=w.e,S==null)P=y(w.c),P=M==1||M==2&&(U<=ue||U>=fe)?b(P,U):A(P,U,"0");else if(w=xe(new W(w),S,T),I=w.e,P=y(w.c),x=P.length,M==1||M==2&&(S<=I||I<=ue)){for(;x<S;P+="0",x++);P=b(P,I)}else if(S-=U+(M===2&&I>U),P=A(P,I,"0"),I+1>x){if(--S>0)for(P+=".";S--;P+="0");}else if(S+=I-x,S>0)for(I+1==x&&(P+=".");S--;P+="0");return w.s<0&&F?"-"+P:P}function _e(w,S){for(var T,M,F=1,I=new W(w[0]);F<w.length;F++)M=new W(w[F]),(!M.s||(T=g(I,M))===S||T===0&&I.s===S)&&(I=M);return I}function It(w,S,T){for(var M=1,F=S.length;!S[--F];S.pop());for(F=S[0];F>=10;F/=10,M++);return(T=M+T*l-1)>ie?w.c=w.e=null:T<ke?w.c=[w.e=0]:(w.e=T,w.c=S),w}J=(function(){var w=/^(-?)0([xbo])(?=\w[\w.]*$)/i,S=/^([^.]+)\.$/,T=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(I,U,x,P){var j,N=x?U:U.replace(F,"");if(M.test(N))I.s=isNaN(N)?null:N<0?-1:1;else{if(!x&&(N=N.replace(w,function(z,Z,te){return j=(te=te.toLowerCase())=="x"?16:te=="b"?2:8,!P||P==j?Z:z}),P&&(j=P,N=N.replace(S,"$1").replace(T,"0.$1")),U!=N))return new W(N,j);if(W.DEBUG)throw Error(s+"Not a"+(P?" base "+P:"")+" number: "+U);I.s=null}I.c=I.e=null}})();function xe(w,S,T,M){var F,I,U,x,P,j,N,z=w.c,Z=d;if(z){e:{for(F=1,x=z[0];x>=10;x/=10,F++);if(I=S-F,I<0)I+=l,U=S,P=z[j=0],N=o(P/Z[F-U-1]%10);else if(j=n((I+1)/l),j>=z.length)if(M){for(;z.length<=j;z.push(0));P=N=0,F=1,I%=l,U=I-l+1}else break e;else{for(P=x=z[j],F=1;x>=10;x/=10,F++);I%=l,U=I-l+F,N=U<0?0:o(P/Z[F-U-1]%10)}if(M=M||S<0||z[j+1]!=null||(U<0?P:P%Z[F-U-1]),M=T<4?(N||M)&&(T==0||T==(w.s<0?3:2)):N>5||N==5&&(T==4||M||T==6&&(I>0?U>0?P/Z[F-U]:0:z[j-1])%10&1||T==(w.s<0?8:7)),S<1||!z[0])return z.length=0,M?(S-=w.e+1,z[0]=Z[(l-S%l)%l],w.e=-S||0):z[0]=w.e=0,w;if(I==0?(z.length=j,x=1,j--):(z.length=j+1,x=Z[l-I],z[j]=U>0?o(P/Z[F-U]%Z[U])*x:0),M)for(;;)if(j==0){for(I=1,U=z[0];U>=10;U/=10,I++);for(U=z[0]+=x,x=1;U>=10;U/=10,x++);I!=x&&(w.e++,z[0]==c&&(z[0]=1));break}else{if(z[j]+=x,z[j]!=c)break;z[j--]=0,x=1}for(I=z.length;z[--I]===0;z.pop());}w.e>ie?w.c=w.e=null:w.e<ke&&(w.c=[w.e=0])}return w}function je(w){var S,T=w.e;return T===null?w.toString():(S=y(w.c),S=T<=ue||T>=fe?b(S,T):A(S,T,"0"),w.s<0?"-"+S:S)}return B.absoluteValue=B.abs=function(){var w=new W(this);return w.s<0&&(w.s=1),w},B.comparedTo=function(w,S){return g(this,new W(w,S))},B.decimalPlaces=B.dp=function(w,S){var T,M,F,I=this;if(w!=null)return m(w,0,C),S==null?S=ee:m(S,0,8),xe(new W(I),w+I.e+1,S);if(!(T=I.c))return null;if(M=((F=T.length-1)-_(this.e/l))*l,F=T[F])for(;F%10==0;F/=10,M--);return M<0&&(M=0),M},B.dividedBy=B.div=function(w,S){return O(this,new W(w,S),re,ee)},B.dividedToIntegerBy=B.idiv=function(w,S){return O(this,new W(w,S),0,1)},B.exponentiatedBy=B.pow=function(w,S){var T,M,F,I,U,x,P,j,N,z=this;if(w=new W(w),w.c&&!w.isInteger())throw Error(s+"Exponent not an integer: "+je(w));if(S!=null&&(S=new W(S)),x=w.e>14,!z.c||!z.c[0]||z.c[0]==1&&!z.e&&z.c.length==1||!w.c||!w.c[0])return N=new W(Math.pow(+je(z),x?w.s*(2-v(w)):+je(w))),S?N.mod(S):N;if(P=w.s<0,S){if(S.c?!S.c[0]:!S.s)return new W(NaN);M=!P&&z.isInteger()&&S.isInteger(),M&&(z=z.mod(S))}else{if(w.e>9&&(z.e>0||z.e<-1||(z.e==0?z.c[0]>1||x&&z.c[1]>=24e7:z.c[0]<8e13||x&&z.c[0]<=9999975e7)))return I=z.s<0&&v(w)?-0:0,z.e>-1&&(I=1/I),new W(P?1/I:I);K&&(I=n(K/l+2))}for(x?(T=new W(.5),P&&(w.s=1),j=v(w)):(F=Math.abs(+je(w)),j=F%2),N=new W(Y);;){if(j){if(N=N.times(z),!N.c)break;I?N.c.length>I&&(N.c.length=I):M&&(N=N.mod(S))}if(F){if(F=o(F/2),F===0)break;j=F%2}else if(w=w.times(T),xe(w,w.e+1,1),w.e>14)j=v(w);else{if(F=+je(w),F===0)break;j=F%2}z=z.times(z),I?z.c&&z.c.length>I&&(z.c.length=I):M&&(z=z.mod(S))}return M?N:(P&&(N=Y.div(N)),S?N.mod(S):I?xe(N,K,ee,U):N)},B.integerValue=function(w){var S=new W(this);return w==null?w=ee:m(w,0,8),xe(S,S.e+1,w)},B.isEqualTo=B.eq=function(w,S){return g(this,new W(w,S))===0},B.isFinite=function(){return!!this.c},B.isGreaterThan=B.gt=function(w,S){return g(this,new W(w,S))>0},B.isGreaterThanOrEqualTo=B.gte=function(w,S){return(S=g(this,new W(w,S)))===1||S===0},B.isInteger=function(){return!!this.c&&_(this.e/l)>this.c.length-2},B.isLessThan=B.lt=function(w,S){return g(this,new W(w,S))<0},B.isLessThanOrEqualTo=B.lte=function(w,S){return(S=g(this,new W(w,S)))===-1||S===0},B.isNaN=function(){return!this.s},B.isNegative=function(){return this.s<0},B.isPositive=function(){return this.s>0},B.isZero=function(){return!!this.c&&this.c[0]==0},B.minus=function(w,S){var T,M,F,I,U=this,x=U.s;if(w=new W(w,S),S=w.s,!x||!S)return new W(NaN);if(x!=S)return w.s=-S,U.plus(w);var P=U.e/l,j=w.e/l,N=U.c,z=w.c;if(!P||!j){if(!N||!z)return N?(w.s=-S,w):new W(z?U:NaN);if(!N[0]||!z[0])return z[0]?(w.s=-S,w):new W(N[0]?U:ee==3?-0:0)}if(P=_(P),j=_(j),N=N.slice(),x=P-j){for((I=x<0)?(x=-x,F=N):(j=P,F=z),F.reverse(),S=x;S--;F.push(0));F.reverse()}else for(M=(I=(x=N.length)<(S=z.length))?x:S,x=S=0;S<M;S++)if(N[S]!=z[S]){I=N[S]<z[S];break}if(I&&(F=N,N=z,z=F,w.s=-w.s),S=(M=z.length)-(T=N.length),S>0)for(;S--;N[T++]=0);for(S=c-1;M>x;){if(N[--M]<z[M]){for(T=M;T&&!N[--T];N[T]=S);--N[T],N[M]+=c}N[M]-=z[M]}for(;N[0]==0;N.splice(0,1),--j);return N[0]?It(w,N,j):(w.s=ee==3?-1:1,w.c=[w.e=0],w)},B.modulo=B.mod=function(w,S){var T,M,F=this;return w=new W(w,S),!F.c||!w.s||w.c&&!w.c[0]?new W(NaN):!w.c||F.c&&!F.c[0]?new W(F):(G==9?(M=w.s,w.s=1,T=O(F,w,0,3),w.s=M,T.s*=M):T=O(F,w,0,G),w=F.minus(T.times(w)),!w.c[0]&&G==1&&(w.s=F.s),w)},B.multipliedBy=B.times=function(w,S){var T,M,F,I,U,x,P,j,N,z,Z,te,Ae,Pe,Ne,we=this,Se=we.c,Ue=(w=new W(w,S)).c;if(!Se||!Ue||!Se[0]||!Ue[0])return!we.s||!w.s||Se&&!Se[0]&&!Ue||Ue&&!Ue[0]&&!Se?w.c=w.e=w.s=null:(w.s*=we.s,!Se||!Ue?w.c=w.e=null:(w.c=[0],w.e=0)),w;for(M=_(we.e/l)+_(w.e/l),w.s*=we.s,P=Se.length,z=Ue.length,P<z&&(Ae=Se,Se=Ue,Ue=Ae,F=P,P=z,z=F),F=P+z,Ae=[];F--;Ae.push(0));for(Pe=c,Ne=p,F=z;--F>=0;){for(T=0,Z=Ue[F]%Ne,te=Ue[F]/Ne|0,U=P,I=F+U;I>F;)j=Se[--U]%Ne,N=Se[U]/Ne|0,x=te*j+N*Z,j=Z*j+x%Ne*Ne+Ae[I]+T,T=(j/Pe|0)+(x/Ne|0)+te*N,Ae[I--]=j%Pe;Ae[I]=T}return T?++M:Ae.splice(0,1),It(w,Ae,M)},B.negated=function(){var w=new W(this);return w.s=-w.s||null,w},B.plus=function(w,S){var T,M=this,F=M.s;if(w=new W(w,S),S=w.s,!F||!S)return new W(NaN);if(F!=S)return w.s=-S,M.minus(w);var I=M.e/l,U=w.e/l,x=M.c,P=w.c;if(!I||!U){if(!x||!P)return new W(F/0);if(!x[0]||!P[0])return P[0]?w:new W(x[0]?M:F*0)}if(I=_(I),U=_(U),x=x.slice(),F=I-U){for(F>0?(U=I,T=P):(F=-F,T=x),T.reverse();F--;T.push(0));T.reverse()}for(F=x.length,S=P.length,F-S<0&&(T=P,P=x,x=T,S=F),F=0;S;)F=(x[--S]=x[S]+P[S]+F)/c|0,x[S]=c===x[S]?0:x[S]%c;return F&&(x=[F].concat(x),++U),It(w,x,U)},B.precision=B.sd=function(w,S){var T,M,F,I=this;if(w!=null&&w!==!!w)return m(w,1,C),S==null?S=ee:m(S,0,8),xe(new W(I),w,S);if(!(T=I.c))return null;if(F=T.length-1,M=F*l+1,F=T[F]){for(;F%10==0;F/=10,M--);for(F=T[0];F>=10;F/=10,M++);}return w&&I.e+1>M&&(M=I.e+1),M},B.shiftedBy=function(w){return m(w,-f,f),this.times("1e"+w)},B.squareRoot=B.sqrt=function(){var w,S,T,M,F,I=this,U=I.c,x=I.s,P=I.e,j=re+4,N=new W("0.5");if(x!==1||!U||!U[0])return new W(!x||x<0&&(!U||U[0])?NaN:U?I:1/0);if(x=Math.sqrt(+je(I)),x==0||x==1/0?(S=y(U),(S.length+P)%2==0&&(S+="0"),x=Math.sqrt(+S),P=_((P+1)/2)-(P<0||P%2),x==1/0?S="5e"+P:(S=x.toExponential(),S=S.slice(0,S.indexOf("e")+1)+P),T=new W(S)):T=new W(x+""),T.c[0]){for(P=T.e,x=P+j,x<3&&(x=0);;)if(F=T,T=N.times(F.plus(O(I,F,j,1))),y(F.c).slice(0,x)===(S=y(T.c)).slice(0,x))if(T.e<P&&--x,S=S.slice(x-3,x+1),S=="9999"||!M&&S=="4999"){if(!M&&(xe(F,F.e+re+2,0),F.times(F).eq(I))){T=F;break}j+=4,x+=4,M=1}else{(!+S||!+S.slice(1)&&S.charAt(0)=="5")&&(xe(T,T.e+re+2,1),w=!T.times(T).eq(I));break}}return xe(T,T.e+re+1,ee,w)},B.toExponential=function(w,S){return w!=null&&(m(w,0,C),w++),de(this,w,S,1)},B.toFixed=function(w,S){return w!=null&&(m(w,0,C),w=w+this.e+1),de(this,w,S)},B.toFormat=function(w,S,T){var M,F=this;if(T==null)w!=null&&S&&typeof S=="object"?(T=S,S=null):w&&typeof w=="object"?(T=w,w=S=null):T=ce;else if(typeof T!="object")throw Error(s+"Argument not an object: "+T);if(M=F.toFixed(w,S),F.c){var I,U=M.split("."),x=+T.groupSize,P=+T.secondaryGroupSize,j=T.groupSeparator||"",N=U[0],z=U[1],Z=F.s<0,te=Z?N.slice(1):N,Ae=te.length;if(P&&(I=x,x=P,P=I,Ae-=I),x>0&&Ae>0){for(I=Ae%x||x,N=te.substr(0,I);I<Ae;I+=x)N+=j+te.substr(I,x);P>0&&(N+=j+te.slice(I)),Z&&(N="-"+N)}M=z?N+(T.decimalSeparator||"")+((P=+T.fractionGroupSize)?z.replace(new RegExp("\\d{"+P+"}\\B","g"),"$&"+(T.fractionGroupSeparator||"")):z):N}return(T.prefix||"")+M+(T.suffix||"")},B.toFraction=function(w){var S,T,M,F,I,U,x,P,j,N,z,Z,te=this,Ae=te.c;if(w!=null&&(x=new W(w),!x.isInteger()&&(x.c||x.s!==1)||x.lt(Y)))throw Error(s+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+je(x));if(!Ae)return new W(te);for(S=new W(Y),j=T=new W(Y),M=P=new W(Y),Z=y(Ae),I=S.e=Z.length-te.e-1,S.c[0]=d[(U=I%l)<0?l+U:U],w=!w||x.comparedTo(S)>0?I>0?S:j:x,U=ie,ie=1/0,x=new W(Z),P.c[0]=0;N=O(x,S,0,1),F=T.plus(N.times(M)),F.comparedTo(w)!=1;)T=M,M=F,j=P.plus(N.times(F=j)),P=F,S=x.minus(N.times(F=S)),x=F;return F=O(w.minus(T),M,0,1),P=P.plus(F.times(j)),T=T.plus(F.times(M)),P.s=j.s=te.s,I=I*2,z=O(j,M,I,ee).minus(te).abs().comparedTo(O(P,T,I,ee).minus(te).abs())<1?[j,M]:[P,T],ie=U,z},B.toNumber=function(){return+je(this)},B.toPrecision=function(w,S){return w!=null&&m(w,1,C),de(this,w,S,2)},B.toString=function(w){var S,T=this,M=T.s,F=T.e;return F===null?M?(S="Infinity",M<0&&(S="-"+S)):S="NaN":(w==null?S=F<=ue||F>=fe?b(y(T.c),F):A(y(T.c),F,"0"):w===10&&De?(T=xe(new W(T),re+F+1,ee),S=A(y(T.c),T.e,"0")):(m(w,2,qe.length,"Base"),S=q(A(y(T.c),F,"0"),10,w,M,!0)),M<0&&T.c[0]&&(S="-"+S)),S},B.valueOf=B.toJSON=function(){return je(this)},B._isBigNumber=!0,D!=null&&W.set(D),W}function _(D){var O=D|0;return D>0||D===O?O:O-1}function y(D){for(var O,q,J=1,B=D.length,Y=D[0]+"";J<B;){for(O=D[J++]+"",q=l-O.length;q--;O="0"+O);Y+=O}for(B=Y.length;Y.charCodeAt(--B)===48;);return Y.slice(0,B+1||1)}function g(D,O){var q,J,B=D.c,Y=O.c,re=D.s,ee=O.s,ue=D.e,fe=O.e;if(!re||!ee)return null;if(q=B&&!B[0],J=Y&&!Y[0],q||J)return q?J?0:-ee:re;if(re!=ee)return re;if(q=re<0,J=ue==fe,!B||!Y)return J?0:!B^q?1:-1;if(!J)return ue>fe^q?1:-1;for(ee=(ue=B.length)<(fe=Y.length)?ue:fe,re=0;re<ee;re++)if(B[re]!=Y[re])return B[re]>Y[re]^q?1:-1;return ue==fe?0:ue>fe^q?1:-1}function m(D,O,q,J){if(D<O||D>q||D!==o(D))throw Error(s+(J||"Argument")+(typeof D=="number"?D<O||D>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(D))}function v(D){var O=D.c.length-1;return _(D.e/l)==O&&D.c[O]%2!=0}function b(D,O){return(D.length>1?D.charAt(0)+"."+D.slice(1):D)+(O<0?"e":"e+")+O}function A(D,O,q){var J,B;if(O<0){for(B=q+".";++O;B+=q);D=B+D}else if(J=D.length,++O>J){for(B=q,O-=J;--O;B+=q);D+=B}else O<J&&(D=D.slice(0,O)+"."+D.slice(O));return D}e=k(),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)})(hm)});var ym=V((K1,gm)=>{var pm=gc(),mm=gm.exports;(function(){"use strict";function t(f){return f<10?"0"+f:f}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(f){return r.lastIndex=0,r.test(f)?'"'+f.replace(r,function(d){var p=s[d];return typeof p=="string"?p:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+f+'"'}function l(f,d){var p,C,k,_,y=n,g,m=d[f],v=m!=null&&(m instanceof pm||pm.isBigNumber(m));switch(m&&typeof m=="object"&&typeof m.toJSON=="function"&&(m=m.toJSON(f)),typeof a=="function"&&(m=a.call(d,f,m)),typeof m){case"string":return v?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(n+=o,g=[],Object.prototype.toString.apply(m)==="[object Array]"){for(_=m.length,p=0;p<_;p+=1)g[p]=l(p,m)||"null";return k=g.length===0?"[]":n?`[
|
|
44
44
|
`+n+g.join(`,
|
|
45
45
|
`+n)+`
|
|
46
|
-
`+y+"]":"["+g.join(",")+"]",n=y,k}if(a&&typeof a=="object")for(
|
|
46
|
+
`+y+"]":"["+g.join(",")+"]",n=y,k}if(a&&typeof a=="object")for(_=a.length,p=0;p<_;p+=1)typeof a[p]=="string"&&(C=a[p],k=l(C,m),k&&g.push(c(C)+(n?": ":":")+k));else Object.keys(m).forEach(function(b){var A=l(b,m);A&&g.push(c(b)+(n?": ":":")+A)});return k=g.length===0?"{}":n?`{
|
|
47
47
|
`+n+g.join(`,
|
|
48
48
|
`+n)+`
|
|
49
|
-
`+y+"}":"{"+g.join(",")+"}",n=y,k}}typeof mm.stringify!="function"&&(mm.stringify=function(f,d,p){var
|
|
50
|
-
`,r:"\r",t:" "},s,a=function(y){throw{name:"SyntaxError",message:y,at:r,text:s}},c=function(y){return y&&y!==n&&a("Expected '"+y+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},l=function(){var y,g="";for(n==="-"&&(g="-",c("-"));n>="0"&&n<="9";)g+=n,c();if(n===".")for(g+=".";c()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,c(),(n==="-"||n==="+")&&(g+=n,c());n>="0"&&n<="9";)g+=n,c();if(y=+g,!isFinite(y))a("Bad number");else return Ti==null&&(Ti=gc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Ti(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new Ti(y):y},f=function(){var y,g,m="",v;if(n==='"')for(var _=r;c();){if(n==='"')return r-1>_&&(m+=s.substring(_,r-1)),c(),m;if(n==="\\"){if(r-1>_&&(m+=s.substring(_,r-1)),c(),n==="u"){for(v=0,g=0;g<4&&(y=parseInt(c(),16),!!isFinite(y));g+=1)v=v*16+y;m+=String.fromCharCode(v)}else if(typeof o[n]=="string")m+=o[n];else break;_=r}}a("Bad string")},d=function(){for(;n&&n<=" ";)c()},p=function(){switch(n){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 '"+n+"'")},b,k=function(){var y=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),y;for(;n;){if(y.push(b()),d(),n==="]")return c("]"),y;c(","),d()}}a("Bad array")},C=function(){var y,g=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),g;for(;n;){if(y=f(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&a('Duplicate key "'+y+'"'),Dw.test(y)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?b():g[y]=b():Rw.test(y)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?b():g[y]=b():g[y]=b(),d(),n==="}")return c("}"),g;c(","),d()}}a("Bad object")};return b=function(){switch(d(),n){case"{":return C();case"[":return k();case'"':return f();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(y,g){var m;return s=y+"",r=0,n=" ",m=b(),d(),n&&a("Syntax error"),typeof g=="function"?(function v(_,A){var D,O,q=_[A];return q&&typeof q=="object"&&Object.keys(q).forEach(function(J){O=v(q,J),O!==void 0?q[J]=O:delete q[J]}),g.call(_,A,q)})({"":m},""):m}};_m.exports=xw});var Em=V((Q1,Di)=>{var Cm=ym().stringify,wm=bm();Di.exports=function(t){return{parse:wm(t),stringify:Cm}};Di.exports.parse=wm();Di.exports.stringify=Cm});var yc=V($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.GCE_LINUX_BIOS_PATHS=void 0;$t.isGoogleCloudServerless=Sm;$t.isGoogleComputeEngineLinux=vm;$t.isGoogleComputeEngineMACAddress=Tm;$t.isGoogleComputeEngine=Dm;$t.detectGCPResidency=Fw;var Am=X("fs"),km=X("os");$t.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Ow=/^42:01/;function Sm(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function vm(){if((0,km.platform)()!=="linux")return!1;try{(0,Am.statSync)($t.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Am.readFileSync)($t.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Tm(){let t=(0,km.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(Ow.test(r))return!0}return!1}function Dm(){return vm()||Tm()}function Fw(){return Sm()||Dm()}});var Rm=V(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.Colours=void 0;var Xe=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="")}};Ri.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var Pm=V(Te=>{"use strict";var Pw=Te&&Te.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Iw=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xm=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Pw(r,e,n[o]);return Iw(r,e),r}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=bc;Te.getDebugBackend=Nw;Te.getStructuredBackend=Mw;Te.setBackend=jw;Te.log=Fm;var Bw=X("events"),jo=xm(X("process")),Om=xm(X("util")),mt=Rm(),qt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(qt||(Te.LogSeverity=qt={}));var Lo=class extends Bw.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,o)=>this.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(qt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(qt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(qt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(qt.ERROR,...n),this.func.sublog=n=>Fm(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};Te.AdhocDebugLogger=Lo;Te.placeholder=new Lo("",()=>{}).func;var Jn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=jo.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){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(r,...n)}catch(o){console.error(o)}}};Te.DebugLogBackendBase=Jn;var _c=class extends Jn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var o;let s=`${mt.Colours.green}${e}${mt.Colours.reset}`,a=`${mt.Colours.yellow}${jo.pid}${mt.Colours.reset}`,c;switch(r.severity){case qt.ERROR:c=`${mt.Colours.red}${r.severity}${mt.Colours.reset}`;break;case qt.INFO:c=`${mt.Colours.magenta}${r.severity}${mt.Colours.reset}`;break;case qt.WARNING:c=`${mt.Colours.yellow}${r.severity}${mt.Colours.reset}`;break;default:c=(o=r.severity)!==null&&o!==void 0?o:qt.DEFAULT;break}let l=Om.formatWithOptions({colors:mt.Colours.enabled},...n),f=Object.assign({},r);delete f.severity;let d=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",p=d?`${mt.Colours.grey}${d}${mt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,d?` ${p}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function bc(){return new _c}var Cc=class extends Jn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...o)=>{r(o[0],...o.slice(1))}}setFilters(){var e;let r=(e=jo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";jo.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function Nw(t){return new Cc(t)}var wc=class extends Jn{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:qt.INFO,l=Object.assign({severity:c,message:Om.format(...s)},o),f=JSON.stringify(l);n?n(o,f):console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function Mw(t){return new wc(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Ec=new Map,gt;function jw(t){gt=t,Ec.clear()}function Fm(t,e){if(!gt&&!jo.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=Ec.get(t);if(r)return r.func;if(gt===null)return Te.placeholder;gt===void 0&&(gt=bc());let n=(()=>{let o;return new Lo(t,(a,...c)=>{if(o!==gt){if(gt===null)return;gt===void 0&&(gt=bc()),o=gt}gt?.log(t,a,...c)})})();return Ec.set(t,n),n.func}});var Ac=V(pn=>{"use strict";var Lw=pn&&pn.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Uw=pn&&pn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Lw(e,t,r)};Object.defineProperty(pn,"__esModule",{value:!0});Uw(Pm(),pn)});var $o=V(ae=>{"use strict";var Bm=ae&&ae.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),$w=ae&&ae.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qw=ae&&ae.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Bm(r,e,n[o]);return $w(r,e),r}})(),zw=ae&&ae.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Bm(e,t,r)};Object.defineProperty(ae,"__esModule",{value:!0});ae.gcpResidencyCache=ae.METADATA_SERVER_DETECTION=ae.HEADERS=ae.HEADER_VALUE=ae.HEADER_NAME=ae.SECONDARY_HOST_ADDRESS=ae.HOST_ADDRESS=ae.BASE_PATH=void 0;ae.instance=Kw;ae.project=Yw;ae.universe=Qw;ae.bulk=Xw;ae.isAvailable=eE;ae.resetIsAvailableCache=tE;ae.getGCPResidency=vc;ae.setGCPResidency=Nm;ae.requestTimeout=Mm;var kc=Ke(),Hw=Em(),Ww=yc(),Gw=qw(Ac());ae.BASE_PATH="/computeMetadata/v1";ae.HOST_ADDRESS="http://169.254.169.254";ae.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ae.HEADER_NAME="Metadata-Flavor";ae.HEADER_VALUE="Google";ae.HEADERS=Object.freeze({[ae.HEADER_NAME]:ae.HEADER_VALUE});var Im=Gw.log("gcp-metadata");ae.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 Sc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ae.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ae.BASE_PATH,t).href}function Jw(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 Uo(t,e={},r=3,n=!1){let o=new Headers(ae.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((b,k)=>o.set(k,b)),s=p.metadataKey,a=p.params||a,r=p.noResponseRetries||r,n=p.fastFail||n}else s=t;typeof e=="string"?s+=`/${e}`:(Jw(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,b)=>o.set(b,p)),a=e.params||a);let c=n?Vw:kc.request,l={url:`${Sc()}/${s}`,headers:o,retryConfig:{noResponseRetries:r},params:a,responseType:"text",timeout:Mm()};Im.info("instance request %j",l);let f=await c(l);Im.info("instance metadata is %s",f.data);let d=f.headers.get(ae.HEADER_NAME);if(d!==ae.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ae.HEADER_NAME} header. Expected '${ae.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof f.data=="string")try{return Hw.parse(f.data)}catch{}return f.data}async function Vw(t){let e={...t,url:t.url?.toString().replace(Sc(),Sc(ae.SECONDARY_HOST_ADDRESS))},r=(0,kc.request)(t),n=(0,kc.request)(e);return Promise.any([r,n])}function Kw(t){return Uo("instance",t)}function Yw(t){return Uo("project",t)}function Qw(t){return Uo("universe",t)}async function Xw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Uo(r),o=r.metadataKey;e[o]=n})())),e}function Zw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var xi;async function eE(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ae.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ae.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return vc();case"ping-only":}}try{return xi===void 0&&(xi=Uo("instance",void 0,Zw(),!(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 r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function tE(){xi=void 0}ae.gcpResidencyCache=null;function vc(){return ae.gcpResidencyCache===null&&Nm(),ae.gcpResidencyCache}function Nm(t=null){ae.gcpResidencyCache=t!==null?t:(0,Ww.detectGCPResidency)()}function Mm(){return vc()?0:3e3}zw(yc(),ae)});var Um=V(Oi=>{"use strict";Oi.byteLength=nE;Oi.toByteArray=sE;Oi.fromByteArray=uE;var er=[],Dt=[],rE=typeof Uint8Array<"u"?Uint8Array:Array,Tc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(mn=0,jm=Tc.length;mn<jm;++mn)er[mn]=Tc[mn],Dt[Tc.charCodeAt(mn)]=mn;var mn,jm;Dt[45]=62;Dt[95]=63;function Lm(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function nE(t){var e=Lm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function oE(t,e,r){return(e+r)*3/4-r}function sE(t){var e,r=Lm(t),n=r[0],o=r[1],s=new rE(oE(t,n,o)),a=0,c=o>0?n-4:n,l;for(l=0;l<c;l+=4)e=Dt[t.charCodeAt(l)]<<18|Dt[t.charCodeAt(l+1)]<<12|Dt[t.charCodeAt(l+2)]<<6|Dt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=Dt[t.charCodeAt(l)]<<2|Dt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=Dt[t.charCodeAt(l)]<<10|Dt[t.charCodeAt(l+1)]<<4|Dt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function iE(t){return er[t>>18&63]+er[t>>12&63]+er[t>>6&63]+er[t&63]}function aE(t,e,r){for(var n,o=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(iE(n));return o.join("")}function uE(t){for(var e,r=t.length,n=r%3,o=[],s=16383,a=0,c=r-n;a<c;a+=s)o.push(aE(t,a,a+s>c?c:a+s));return n===1?(e=t[r-1],o.push(er[e>>2]+er[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],o.push(er[e>>10]+er[e>>4&63]+er[e<<2&63]+"=")),o.join("")}});var Rc=V(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromArrayBufferToHex=cE;function cE(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var $m=V(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.BrowserCrypto=void 0;var Vn=Um(),lE=Rc(),xc=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 r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return Vn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Vn.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),a=Vn.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(r),s=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),a=await window.crypto.subtle.sign(n,s,o);return Vn.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let r=Vn.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Vn.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,lE.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(r))}};Fi.BrowserCrypto=xc});var qm=V(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.NodeCrypto=void 0;var Kn=X("crypto"),Oc=class{async sha256DigestBase64(e){return Kn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Kn.randomBytes(e).toString("base64")}async verify(e,r,n){let o=Kn.createVerify("RSA-SHA256");return o.update(r),o.end(),o.verify(e,n,"base64")}async sign(e,r){let n=Kn.createSign("RSA-SHA256");return n.update(r),n.end(),n.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 Kn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:fE(e);return dE(Kn.createHmac("sha256",n).update(r).digest())}};Pi.NodeCrypto=Oc;function dE(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function fE(t){return Buffer.from(t)}});var qo=V(wr=>{"use strict";var hE=wr&&wr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),pE=wr&&wr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&hE(e,t,r)};Object.defineProperty(wr,"__esModule",{value:!0});wr.createCrypto=yE;wr.hasBrowserCrypto=zm;var mE=$m(),gE=qm();pE(Rc(),wr);function yE(){return zm()?new mE.BrowserCrypto:new gE.NodeCrypto}function zm(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Yn=V((Fc,Wm)=>{var Ii=X("buffer"),tr=Ii.Buffer;function Hm(t,e){for(var r in t)e[r]=t[r]}tr.from&&tr.alloc&&tr.allocUnsafe&&tr.allocUnsafeSlow?Wm.exports=Ii:(Hm(Ii,Fc),Fc.Buffer=gn);function gn(t,e,r){return tr(t,e,r)}gn.prototype=Object.create(tr.prototype);Hm(tr,gn);gn.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return tr(t,e,r)};gn.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=tr(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};gn.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return tr(t)};gn.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Ii.SlowBuffer(t)}});var Jm=V((ux,Gm)=>{"use strict";function Pc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var _E={ES256:Pc(256),ES384:Pc(384),ES512:Pc(521)};function bE(t){var e=_E[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Gm.exports=bE});var Ic=V((cx,Zm)=>{"use strict";var Bi=Yn().Buffer,Km=Jm(),Ni=128,Ym=0,CE=32,wE=16,EE=2,Qm=wE|CE|Ym<<6,Mi=EE|Ym<<6;function AE(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xm(t){if(Bi.isBuffer(t))return t;if(typeof t=="string")return Bi.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function kE(t,e){t=Xm(t);var r=Km(e),n=r+1,o=t.length,s=0;if(t[s++]!==Qm)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(Ni|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==Mi)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(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=s;if(s+=c,t[s++]!==Mi)throw new Error('Could not find expected "int" for "s"');var f=t[s++];if(o-s!==f)throw new Error('"s" specified length of "'+f+'", expected "'+(o-s)+'"');if(n<f)throw new Error('"s" specified length of "'+f+'", max of "'+n+'" is acceptable');var d=s;if(s+=f,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=r-c,b=r-f,k=Bi.allocUnsafe(p+c+b+f);for(s=0;s<p;++s)k[s]=0;t.copy(k,s,l+Math.max(-p,0),l+c),s=r;for(var C=s;s<C+b;++s)k[s]=0;return t.copy(k,s,d+Math.max(-b,0),d+f),k=k.toString("base64"),k=AE(k),k}function Vm(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var o=t[e+n]>=Ni;return o&&--n,n}function SE(t,e){t=Xm(t);var r=Km(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var o=Vm(t,0,r),s=Vm(t,r,t.length),a=r-o,c=r-s,l=2+a+1+1+c,f=l<Ni,d=Bi.allocUnsafe((f?2:3)+l),p=0;return d[p++]=Qm,f?d[p++]=l:(d[p++]=Ni|1,d[p++]=l&255),d[p++]=Mi,d[p++]=a,o<0?(d[p++]=0,p+=t.copy(d,p,0,r)):p+=t.copy(d,p,o,r),d[p++]=Mi,d[p++]=c,s<0?(d[p++]=0,t.copy(d,p,r)):t.copy(d,p,r+s),d}Zm.exports={derToJose:kE,joseToDer:SE}});var zt=V(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.LRUCache=void 0;Er.snakeToCamel=tg;Er.originalOrCamelOptions=RE;Er.removeUndefinedValuesInObject=xE;Er.isValidFile=OE;Er.getWellKnownCertificateConfigFileLocation=FE;var vE=X("fs"),TE=X("os"),Bc=X("path"),DE="certificate_config.json",eg="gcloud";function tg(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function RE(t){function e(r){let n=t||{};return n[r]??n[tg(r)]}return{get:e}}var Nc=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};Er.LRUCache=Nc;function xE(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function OE(t){try{return(await vE.promises.lstat(t)).isFile()}catch{return!1}}function FE(){let t=process.env.CLOUDSDK_CONFIG||(PE()?Bc.join(process.env.APPDATA||"",eg):Bc.join(process.env.HOME||"",".config",eg));return Bc.join(t,DE)}function PE(){return TE.platform().startsWith("win")}});var rg=V((dx,IE)=>{IE.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 Mc=V(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.USER_AGENT=Gr.PRODUCT_NAME=Gr.pkg=void 0;var ng=rg();Gr.pkg=ng;var og="google-api-nodejs-client";Gr.PRODUCT_NAME=og;var BE=`${og}/${ng.version}`;Gr.USER_AGENT=BE});var yt=V(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.AuthClient=Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Ht.DEFAULT_UNIVERSE=void 0;var NE=X("events"),jc=Ke(),ME=zt(),jE=Ac(),Lc=Mc();Ht.DEFAULT_UNIVERSE="googleapis.com";Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Uc=class t extends NE.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Ht.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,ME.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??Ht.DEFAULT_UNIVERSE,this.transporter=e.transporter??new jc.Gaxios(e.transporterOptions),r.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 r=e[0],n=e[1],o,s=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&jc.Gaxios.mergeHeaders(s,r.headers),n&&jc.Gaxios.mergeHeaders(s,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:s,url:o}):this.request({...n,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,r){let n=r.get("x-goog-user-project"),o=r.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,jE.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${Lc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${Lc.USER_AGENT}`):e.headers.set("User-Agent",Lc.USER_AGENT);try{let n=e,o=n[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;n[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 r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Ht.AuthClient=Uc});var qc=V(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.LoginTicket=void 0;var $c=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}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()}}};ji.LoginTicket=$c});var yn=V(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.OAuth2Client=rr.ClientAuthentication=rr.CertificateFormat=rr.CodeChallengeMethod=void 0;var sg=Ke(),LE=X("querystring"),UE=X("stream"),$E=Ic(),ig=zt(),zc=qo(),Qn=yt(),qE=qc(),ag;(function(t){t.Plain="plain",t.S256="S256"})(ag||(rr.CodeChallengeMethod=ag={}));var Ar;(function(t){t.PEM="PEM",t.JWK="JWK"})(Ar||(rr.CertificateFormat=Ar={}));var zo;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(zo||(rr.ClientAuthentication=zo={}));var Hc=class t extends Qn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ar.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),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||zo.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()+"?"+LE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,zc.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:s}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(o=>r(null,o.tokens,o.res),o=>r(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=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===zo.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===zo.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,ig.removeUndefinedValuesInObject)(o)),headers:n};Qn.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 r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={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:r,data:new URLSearchParams((0,ig.removeUndefinedValuesInObject)(n))};Qn.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof sg.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(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let r=await this.refreshAccessTokenAsync();if(!r.credentials||r.credentials&&!r.credentials.access_token)throw new Error("Could not refresh access token.");return{token:r.credentials.access_token,res:r.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let c=new Headers({authorization:r.token_type+" "+r.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 n=null,o=null;try{n=await this.refreshToken(r.refresh_token),o=n.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:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Qn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(o=>r(null,o),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),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,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=sg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let o=n.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 UE.Readable,f=s===401||s===403;if(!r&&f&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&f&&!l&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=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()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,zc.hasBrowserCrypto)()?Ar.JWK:Ar.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,o;switch(r){case Ar.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ar.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let f={...t.RETRY_CONFIG,url:o};Qn.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),n=await this.transporter.request(f)}catch(f){throw f instanceof Error&&(f.message=`Failed to retrieve verification certificates: ${f.message}`),f}let s=n?.headers.get("cache-control"),a=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;f&&(a=Number(f)*1e3)}let c={};switch(r){case Ar.PEM:c=n.data;break;case Ar.JWK:for(let f of n.data.keys)c[f.kid]=f;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};Qn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,o,s){let a=(0,zc.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],f=c[2],d,p;try{d=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(_){throw _ instanceof Error&&(_.message=`Can't parse token envelope: ${c[0]}': ${_.message}`),_}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(_){throw _ instanceof Error&&(_.message=`Can't parse token payload '${c[0]}`),_}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let b=r[d.kid];if(d.alg==="ES256"&&(f=$E.joseToDer(f,"ES256").toString("base64")),!await a.verify(b,l,f))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 g=new Date().getTime()/1e3;if(y>=g+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=C-t.CLOCK_SKEW_SECS_,v=y+t.CLOCK_SKEW_SECS_;if(g<m)throw new Error("Token used too early, "+g+" < "+m+": "+JSON.stringify(p));if(g>v)throw new Error("Token used too late, "+g+" > "+v+": "+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 n<"u"&&n!==null){let _=p.aud,A=!1;if(n.constructor===Array?A=n.indexOf(_)>-1:A=_===n,!A)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new qE.LoginTicket(d,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}};rr.OAuth2Client=Hc});var Gc=V(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.Compute=void 0;var zE=Ke(),ug=$o(),HE=yn(),Wc=class extends HE.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`,r;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),r=await ug.instance(o)}catch(o){throw o instanceof zE.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let o={property:r};n=await ug.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.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:r.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))}};Li.Compute=Wc});var Vc=V(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.IdTokenClient=void 0;var WE=yn(),Jc=class extends WE.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 r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};Ui.IdTokenClient=Jc});var Kc=V(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.GCPEnv=void 0;Xn.clear=GE;Xn.getEnv=JE;var cg=$o(),nr;(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"})(nr||(Xn.GCPEnv=nr={}));var Ho;function GE(){Ho=void 0}async function JE(){return Ho||(Ho=VE(),Ho)}async function VE(){let t=nr.NONE;return KE()?t=nr.APP_ENGINE:YE()?t=nr.CLOUD_FUNCTIONS:await eA()?await ZE()?t=nr.KUBERNETES_ENGINE:QE()?t=nr.CLOUD_RUN:XE()?t=nr.CLOUD_RUN_JOBS:t=nr.COMPUTE_ENGINE:t=nr.NONE,t}function KE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function YE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function QE(){return!!process.env.K_CONFIGURATION}function XE(){return!!process.env.CLOUD_RUN_JOB}async function ZE(){try{return await cg.instance("attributes/cluster-name"),!0}catch{return!1}}async function eA(){return cg.isAvailable()}});var Yc=V((bx,lg)=>{var $i=Yn().Buffer,tA=X("stream"),rA=X("util");function qi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=$i.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=$i.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+")")}rA.inherits(qi,tA);qi.prototype.write=function(e){this.buffer=$i.concat([this.buffer,$i.from(e)]),this.emit("data",e)};qi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};lg.exports=qi});var fg=V((Cx,dg)=>{"use strict";var Wo=X("buffer").Buffer,Qc=X("buffer").SlowBuffer;dg.exports=zi;function zi(t,e){if(!Wo.isBuffer(t)||!Wo.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}zi.install=function(){Wo.prototype.equal=Qc.prototype.equal=function(e){return zi(this,e)}};var nA=Wo.prototype.equal,oA=Qc.prototype.equal;zi.restore=function(){Wo.prototype.equal=nA,Qc.prototype.equal=oA}});var tl=V((wx,wg)=>{var eo=Yn().Buffer,Rt=X("crypto"),pg=Ic(),hg=X("util"),sA=`"%s" is not a valid algorithm.
|
|
49
|
+
`+y+"}":"{"+g.join(",")+"}",n=y,k}}typeof mm.stringify!="function"&&(mm.stringify=function(f,d,p){var C;if(n="",o="",typeof p=="number")for(C=0;C<p;C+=1)o+=" ";else typeof p=="string"&&(o=p);if(a=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return l("",{"":f})})})()});var bm=V((Y1,_m)=>{var Ti=null,Dw=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,Rw=/(?: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)/,xw=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 r,n,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
50
|
+
`,r:"\r",t:" "},s,a=function(y){throw{name:"SyntaxError",message:y,at:r,text:s}},c=function(y){return y&&y!==n&&a("Expected '"+y+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},l=function(){var y,g="";for(n==="-"&&(g="-",c("-"));n>="0"&&n<="9";)g+=n,c();if(n===".")for(g+=".";c()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,c(),(n==="-"||n==="+")&&(g+=n,c());n>="0"&&n<="9";)g+=n,c();if(y=+g,!isFinite(y))a("Bad number");else return Ti==null&&(Ti=gc()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Ti(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new Ti(y):y},f=function(){var y,g,m="",v;if(n==='"')for(var b=r;c();){if(n==='"')return r-1>b&&(m+=s.substring(b,r-1)),c(),m;if(n==="\\"){if(r-1>b&&(m+=s.substring(b,r-1)),c(),n==="u"){for(v=0,g=0;g<4&&(y=parseInt(c(),16),!!isFinite(y));g+=1)v=v*16+y;m+=String.fromCharCode(v)}else if(typeof o[n]=="string")m+=o[n];else break;b=r}}a("Bad string")},d=function(){for(;n&&n<=" ";)c()},p=function(){switch(n){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 '"+n+"'")},C,k=function(){var y=[];if(n==="["){if(c("["),d(),n==="]")return c("]"),y;for(;n;){if(y.push(C()),d(),n==="]")return c("]"),y;c(","),d()}}a("Bad array")},_=function(){var y,g=Object.create(null);if(n==="{"){if(c("{"),d(),n==="}")return c("}"),g;for(;n;){if(y=f(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(g,y)&&a('Duplicate key "'+y+'"'),Dw.test(y)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?C():g[y]=C():Rw.test(y)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?C():g[y]=C():g[y]=C(),d(),n==="}")return c("}"),g;c(","),d()}}a("Bad object")};return C=function(){switch(d(),n){case"{":return _();case"[":return k();case'"':return f();case"-":return l();default:return n>="0"&&n<="9"?l():p()}},function(y,g){var m;return s=y+"",r=0,n=" ",m=C(),d(),n&&a("Syntax error"),typeof g=="function"?(function v(b,A){var D,O,q=b[A];return q&&typeof q=="object"&&Object.keys(q).forEach(function(J){O=v(q,J),O!==void 0?q[J]=O:delete q[J]}),g.call(b,A,q)})({"":m},""):m}};_m.exports=xw});var Em=V((Q1,Di)=>{var Cm=ym().stringify,wm=bm();Di.exports=function(t){return{parse:wm(t),stringify:Cm}};Di.exports.parse=wm();Di.exports.stringify=Cm});var yc=V($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.GCE_LINUX_BIOS_PATHS=void 0;$t.isGoogleCloudServerless=Sm;$t.isGoogleComputeEngineLinux=vm;$t.isGoogleComputeEngineMACAddress=Tm;$t.isGoogleComputeEngine=Dm;$t.detectGCPResidency=Fw;var Am=X("fs"),km=X("os");$t.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Ow=/^42:01/;function Sm(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function vm(){if((0,km.platform)()!=="linux")return!1;try{(0,Am.statSync)($t.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,Am.readFileSync)($t.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function Tm(){let t=(0,km.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:r}of e)if(Ow.test(r))return!0}return!1}function Dm(){return vm()||Tm()}function Fw(){return Sm()||Dm()}});var Rm=V(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.Colours=void 0;var Xe=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="")}};Ri.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var Pm=V(Te=>{"use strict";var Pw=Te&&Te.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Iw=Te&&Te.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xm=Te&&Te.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Pw(r,e,n[o]);return Iw(r,e),r}})();Object.defineProperty(Te,"__esModule",{value:!0});Te.env=Te.DebugLogBackendBase=Te.placeholder=Te.AdhocDebugLogger=Te.LogSeverity=void 0;Te.getNodeBackend=bc;Te.getDebugBackend=Nw;Te.getStructuredBackend=Mw;Te.setBackend=jw;Te.log=Fm;var Bw=X("events"),jo=xm(X("process")),Om=xm(X("util")),mt=Rm(),qt;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(qt||(Te.LogSeverity=qt={}));var Lo=class extends Bw.EventEmitter{constructor(e,r){super(),this.namespace=e,this.upstream=r,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(n,o)=>this.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(qt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(qt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(qt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(qt.ERROR,...n),this.func.sublog=n=>Fm(n,this.func)}invoke(e,...r){if(this.upstream)try{this.upstream(e,...r)}catch{}try{this.emit("log",e,r)}catch{}}invokeSeverity(e,...r){this.invoke({severity:e},...r)}};Te.AdhocDebugLogger=Lo;Te.placeholder=new Lo("",()=>{}).func;var Jn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let r=(e=jo.env[Te.env.nodeEnables])!==null&&e!==void 0?e:"*";r==="all"&&(r="*"),this.filters=r.split(",")}log(e,r,...n){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(r,...n)}catch(o){console.error(o)}}};Te.DebugLogBackendBase=Jn;var _c=class extends Jn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(r,...n)=>{var o;let s=`${mt.Colours.green}${e}${mt.Colours.reset}`,a=`${mt.Colours.yellow}${jo.pid}${mt.Colours.reset}`,c;switch(r.severity){case qt.ERROR:c=`${mt.Colours.red}${r.severity}${mt.Colours.reset}`;break;case qt.INFO:c=`${mt.Colours.magenta}${r.severity}${mt.Colours.reset}`;break;case qt.WARNING:c=`${mt.Colours.yellow}${r.severity}${mt.Colours.reset}`;break;default:c=(o=r.severity)!==null&&o!==void 0?o:qt.DEFAULT;break}let l=Om.formatWithOptions({colors:mt.Colours.enabled},...n),f=Object.assign({},r);delete f.severity;let d=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",p=d?`${mt.Colours.grey}${d}${mt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,d?` ${p}`:"")}:()=>{}}setFilters(){let r=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${r}$`,"i")}};function bc(){return new _c}var Cc=class extends Jn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let r=this.debugPkg(e);return(n,...o)=>{r(o[0],...o.slice(1))}}setFilters(){var e;let r=(e=jo.env.NODE_DEBUG)!==null&&e!==void 0?e:"";jo.env.NODE_DEBUG=`${r}${r?",":""}${this.filters.join(",")}`}};function Nw(t){return new Cc(t)}var wc=class extends Jn{constructor(e){var r;super(),this.upstream=(r=e)!==null&&r!==void 0?r:void 0}makeLogger(e){var r;let n=(r=this.upstream)===null||r===void 0?void 0:r.makeLogger(e);return(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:qt.INFO,l=Object.assign({severity:c,message:Om.format(...s)},o),f=JSON.stringify(l);n?n(o,f):console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function Mw(t){return new wc(t)}Te.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Ec=new Map,gt;function jw(t){gt=t,Ec.clear()}function Fm(t,e){if(!gt&&!jo.env[Te.env.nodeEnables]||!t)return Te.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let r=Ec.get(t);if(r)return r.func;if(gt===null)return Te.placeholder;gt===void 0&&(gt=bc());let n=(()=>{let o;return new Lo(t,(a,...c)=>{if(o!==gt){if(gt===null)return;gt===void 0&&(gt=bc()),o=gt}gt?.log(t,a,...c)})})();return Ec.set(t,n),n.func}});var Ac=V(pn=>{"use strict";var Lw=pn&&pn.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Uw=pn&&pn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Lw(e,t,r)};Object.defineProperty(pn,"__esModule",{value:!0});Uw(Pm(),pn)});var $o=V(ae=>{"use strict";var Bm=ae&&ae.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),$w=ae&&ae.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qw=ae&&ae.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Bm(r,e,n[o]);return $w(r,e),r}})(),zw=ae&&ae.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Bm(e,t,r)};Object.defineProperty(ae,"__esModule",{value:!0});ae.gcpResidencyCache=ae.METADATA_SERVER_DETECTION=ae.HEADERS=ae.HEADER_VALUE=ae.HEADER_NAME=ae.SECONDARY_HOST_ADDRESS=ae.HOST_ADDRESS=ae.BASE_PATH=void 0;ae.instance=Kw;ae.project=Yw;ae.universe=Qw;ae.bulk=Xw;ae.isAvailable=eE;ae.resetIsAvailableCache=tE;ae.getGCPResidency=vc;ae.setGCPResidency=Nm;ae.requestTimeout=Mm;var kc=Ke(),Hw=Em(),Ww=yc(),Gw=qw(Ac());ae.BASE_PATH="/computeMetadata/v1";ae.HOST_ADDRESS="http://169.254.169.254";ae.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";ae.HEADER_NAME="Metadata-Flavor";ae.HEADER_VALUE="Google";ae.HEADERS=Object.freeze({[ae.HEADER_NAME]:ae.HEADER_VALUE});var Im=Gw.log("gcp-metadata");ae.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 Sc(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||ae.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(ae.BASE_PATH,t).href}function Jw(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 Uo(t,e={},r=3,n=!1){let o=new Headers(ae.HEADERS),s="",a={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((C,k)=>o.set(k,C)),s=p.metadataKey,a=p.params||a,r=p.noResponseRetries||r,n=p.fastFail||n}else s=t;typeof e=="string"?s+=`/${e}`:(Jw(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,C)=>o.set(C,p)),a=e.params||a);let c=n?Vw:kc.request,l={url:`${Sc()}/${s}`,headers:o,retryConfig:{noResponseRetries:r},params:a,responseType:"text",timeout:Mm()};Im.info("instance request %j",l);let f=await c(l);Im.info("instance metadata is %s",f.data);let d=f.headers.get(ae.HEADER_NAME);if(d!==ae.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ae.HEADER_NAME} header. Expected '${ae.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof f.data=="string")try{return Hw.parse(f.data)}catch{}return f.data}async function Vw(t){let e={...t,url:t.url?.toString().replace(Sc(),Sc(ae.SECONDARY_HOST_ADDRESS))},r=(0,kc.request)(t),n=(0,kc.request)(e);return Promise.any([r,n])}function Kw(t){return Uo("instance",t)}function Yw(t){return Uo("project",t)}function Qw(t){return Uo("universe",t)}async function Xw(t){let e={};return await Promise.all(t.map(r=>(async()=>{let n=await Uo(r),o=r.metadataKey;e[o]=n})())),e}function Zw(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var xi;async function eE(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in ae.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(ae.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return vc();case"ping-only":}}try{return xi===void 0&&(xi=Uo("instance",void 0,Zw(),!(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 r="UNKNOWN";e.code&&(r=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${r}`,"MetadataLookupWarning")}return!1}}function tE(){xi=void 0}ae.gcpResidencyCache=null;function vc(){return ae.gcpResidencyCache===null&&Nm(),ae.gcpResidencyCache}function Nm(t=null){ae.gcpResidencyCache=t!==null?t:(0,Ww.detectGCPResidency)()}function Mm(){return vc()?0:3e3}zw(yc(),ae)});var Um=V(Oi=>{"use strict";Oi.byteLength=nE;Oi.toByteArray=sE;Oi.fromByteArray=uE;var er=[],Dt=[],rE=typeof Uint8Array<"u"?Uint8Array:Array,Tc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(mn=0,jm=Tc.length;mn<jm;++mn)er[mn]=Tc[mn],Dt[Tc.charCodeAt(mn)]=mn;var mn,jm;Dt[45]=62;Dt[95]=63;function Lm(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function nE(t){var e=Lm(t),r=e[0],n=e[1];return(r+n)*3/4-n}function oE(t,e,r){return(e+r)*3/4-r}function sE(t){var e,r=Lm(t),n=r[0],o=r[1],s=new rE(oE(t,n,o)),a=0,c=o>0?n-4:n,l;for(l=0;l<c;l+=4)e=Dt[t.charCodeAt(l)]<<18|Dt[t.charCodeAt(l+1)]<<12|Dt[t.charCodeAt(l+2)]<<6|Dt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=Dt[t.charCodeAt(l)]<<2|Dt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=Dt[t.charCodeAt(l)]<<10|Dt[t.charCodeAt(l+1)]<<4|Dt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function iE(t){return er[t>>18&63]+er[t>>12&63]+er[t>>6&63]+er[t&63]}function aE(t,e,r){for(var n,o=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(iE(n));return o.join("")}function uE(t){for(var e,r=t.length,n=r%3,o=[],s=16383,a=0,c=r-n;a<c;a+=s)o.push(aE(t,a,a+s>c?c:a+s));return n===1?(e=t[r-1],o.push(er[e>>2]+er[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],o.push(er[e>>10]+er[e>>4&63]+er[e<<2&63]+"=")),o.join("")}});var Rc=V(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromArrayBufferToHex=cE;function cE(t){return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}});var $m=V(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.BrowserCrypto=void 0;var Vn=Um(),lE=Rc(),xc=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 r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return Vn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let r=new Uint8Array(e);return window.crypto.getRandomValues(r),Vn.fromByteArray(r)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,r,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(r),a=Vn.toByteArray(t.padBase64(n)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,r){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(r),s=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),a=await window.crypto.subtle.sign(n,s,o);return Vn.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let r=Vn.toByteArray(t.padBase64(e));return new TextDecoder().decode(r)}encodeBase64StringUtf8(e){let r=new TextEncoder().encode(e);return Vn.fromByteArray(r)}async sha256DigestHex(e){let r=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",r);return(0,lE.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(r))}};Fi.BrowserCrypto=xc});var qm=V(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.NodeCrypto=void 0;var Kn=X("crypto"),Oc=class{async sha256DigestBase64(e){return Kn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Kn.randomBytes(e).toString("base64")}async verify(e,r,n){let o=Kn.createVerify("RSA-SHA256");return o.update(r),o.end(),o.verify(e,n,"base64")}async sign(e,r){let n=Kn.createSign("RSA-SHA256");return n.update(r),n.end(),n.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 Kn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,r){let n=typeof e=="string"?e:fE(e);return dE(Kn.createHmac("sha256",n).update(r).digest())}};Pi.NodeCrypto=Oc;function dE(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function fE(t){return Buffer.from(t)}});var qo=V(wr=>{"use strict";var hE=wr&&wr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),pE=wr&&wr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&hE(e,t,r)};Object.defineProperty(wr,"__esModule",{value:!0});wr.createCrypto=yE;wr.hasBrowserCrypto=zm;var mE=$m(),gE=qm();pE(Rc(),wr);function yE(){return zm()?new mE.BrowserCrypto:new gE.NodeCrypto}function zm(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Yn=V((Fc,Wm)=>{var Ii=X("buffer"),tr=Ii.Buffer;function Hm(t,e){for(var r in t)e[r]=t[r]}tr.from&&tr.alloc&&tr.allocUnsafe&&tr.allocUnsafeSlow?Wm.exports=Ii:(Hm(Ii,Fc),Fc.Buffer=gn);function gn(t,e,r){return tr(t,e,r)}gn.prototype=Object.create(tr.prototype);Hm(tr,gn);gn.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return tr(t,e,r)};gn.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=tr(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};gn.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return tr(t)};gn.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Ii.SlowBuffer(t)}});var Jm=V((ux,Gm)=>{"use strict";function Pc(t){var e=(t/8|0)+(t%8===0?0:1);return e}var _E={ES256:Pc(256),ES384:Pc(384),ES512:Pc(521)};function bE(t){var e=_E[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Gm.exports=bE});var Ic=V((cx,Zm)=>{"use strict";var Bi=Yn().Buffer,Km=Jm(),Ni=128,Ym=0,CE=32,wE=16,EE=2,Qm=wE|CE|Ym<<6,Mi=EE|Ym<<6;function AE(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Xm(t){if(Bi.isBuffer(t))return t;if(typeof t=="string")return Bi.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function kE(t,e){t=Xm(t);var r=Km(e),n=r+1,o=t.length,s=0;if(t[s++]!==Qm)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(Ni|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==Mi)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(n<c)throw new Error('"r" specified length of "'+c+'", max of "'+n+'" is acceptable');var l=s;if(s+=c,t[s++]!==Mi)throw new Error('Could not find expected "int" for "s"');var f=t[s++];if(o-s!==f)throw new Error('"s" specified length of "'+f+'", expected "'+(o-s)+'"');if(n<f)throw new Error('"s" specified length of "'+f+'", max of "'+n+'" is acceptable');var d=s;if(s+=f,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=r-c,C=r-f,k=Bi.allocUnsafe(p+c+C+f);for(s=0;s<p;++s)k[s]=0;t.copy(k,s,l+Math.max(-p,0),l+c),s=r;for(var _=s;s<_+C;++s)k[s]=0;return t.copy(k,s,d+Math.max(-C,0),d+f),k=k.toString("base64"),k=AE(k),k}function Vm(t,e,r){for(var n=0;e+n<r&&t[e+n]===0;)++n;var o=t[e+n]>=Ni;return o&&--n,n}function SE(t,e){t=Xm(t);var r=Km(e),n=t.length;if(n!==r*2)throw new TypeError('"'+e+'" signatures must be "'+r*2+'" bytes, saw "'+n+'"');var o=Vm(t,0,r),s=Vm(t,r,t.length),a=r-o,c=r-s,l=2+a+1+1+c,f=l<Ni,d=Bi.allocUnsafe((f?2:3)+l),p=0;return d[p++]=Qm,f?d[p++]=l:(d[p++]=Ni|1,d[p++]=l&255),d[p++]=Mi,d[p++]=a,o<0?(d[p++]=0,p+=t.copy(d,p,0,r)):p+=t.copy(d,p,o,r),d[p++]=Mi,d[p++]=c,s<0?(d[p++]=0,t.copy(d,p,r)):t.copy(d,p,r+s),d}Zm.exports={derToJose:kE,joseToDer:SE}});var zt=V(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.LRUCache=void 0;Er.snakeToCamel=tg;Er.originalOrCamelOptions=RE;Er.removeUndefinedValuesInObject=xE;Er.isValidFile=OE;Er.getWellKnownCertificateConfigFileLocation=FE;var vE=X("fs"),TE=X("os"),Bc=X("path"),DE="certificate_config.json",eg="gcloud";function tg(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function RE(t){function e(r){let n=t||{};return n[r]??n[tg(r)]}return{get:e}}var Nc=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,r){this.#e.delete(e),this.#e.set(e,{value:r,lastAccessed:Date.now()})}set(e,r){this.#t(e,r),this.#r()}get(e){let r=this.#e.get(e);if(r)return this.#t(e,r.value),this.#r(),r.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,r=this.#e.entries().next();for(;!r.done&&(this.#e.size>this.capacity||r.value[1].lastAccessed<e);)this.#e.delete(r.value[0]),r=this.#e.entries().next()}};Er.LRUCache=Nc;function xE(t){return Object.entries(t).forEach(([e,r])=>{(r===void 0||r==="undefined")&&delete t[e]}),t}async function OE(t){try{return(await vE.promises.lstat(t)).isFile()}catch{return!1}}function FE(){let t=process.env.CLOUDSDK_CONFIG||(PE()?Bc.join(process.env.APPDATA||"",eg):Bc.join(process.env.HOME||"",".config",eg));return Bc.join(t,DE)}function PE(){return TE.platform().startsWith("win")}});var rg=V((dx,IE)=>{IE.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 Mc=V(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.USER_AGENT=Gr.PRODUCT_NAME=Gr.pkg=void 0;var ng=rg();Gr.pkg=ng;var og="google-api-nodejs-client";Gr.PRODUCT_NAME=og;var BE=`${og}/${ng.version}`;Gr.USER_AGENT=BE});var yt=V(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.AuthClient=Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Ht.DEFAULT_UNIVERSE=void 0;var NE=X("events"),jc=Ke(),ME=zt(),jE=Ac(),Lc=Mc();Ht.DEFAULT_UNIVERSE="googleapis.com";Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Uc=class t extends NE.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Ht.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Ht.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let r=(0,ME.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=r.get("project_id")??null,this.quotaProjectId=r.get("quota_project_id"),this.credentials=r.get("credentials")??{},this.universeDomain=r.get("universe_domain")??Ht.DEFAULT_UNIVERSE,this.transporter=e.transporter??new jc.Gaxios(e.transporterOptions),r.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 r=e[0],n=e[1],o,s=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&jc.Gaxios.mergeHeaders(s,r.headers),n&&jc.Gaxios.mergeHeaders(s,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:s,url:o}):this.request({...n,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,r){let n=r.get("x-goog-user-project"),o=r.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,jE.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let r=e.headers.get("User-Agent");r?r.includes(`${Lc.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${r} ${Lc.USER_AGENT}`):e.headers.set("User-Agent",Lc.USER_AGENT);try{let n=e,o=n[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;n[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 r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] response %j",n,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let r=e.config,n=r[t.RequestMethodNameSymbol],o=r[t.RequestLogIdSymbol];n?t.log.info("%s [%s] error %j",n,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,r){try{let n=e;n[t.RequestMethodNameSymbol]=r}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Ht.AuthClient=Uc});var qc=V(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.LoginTicket=void 0;var $c=class{envelope;payload;constructor(e,r){this.envelope=e,this.payload=r}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()}}};ji.LoginTicket=$c});var yn=V(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.OAuth2Client=rr.ClientAuthentication=rr.CertificateFormat=rr.CodeChallengeMethod=void 0;var sg=Ke(),LE=X("querystring"),UE=X("stream"),$E=Ic(),ig=zt(),zc=qo(),Qn=yt(),qE=qc(),ag;(function(t){t.Plain="plain",t.S256="S256"})(ag||(rr.CodeChallengeMethod=ag={}));var Ar;(function(t){t.PEM="PEM",t.JWK="JWK"})(Ar||(rr.CertificateFormat=Ar={}));var zo;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(zo||(rr.ClientAuthentication=zo={}));var Hc=class t extends Qn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ar.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},r,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:r,redirectUri:n}),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||zo.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()+"?"+LE.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,zc.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:s}}getToken(e,r){let n=typeof e=="string"?{code:e}:e;if(r)this.getTokenAsync(n).then(o=>r(null,o.tokens,o.res),o=>r(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let r=this.endpoints.oauth2TokenUrl.toString(),n=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===zo.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===zo.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:r,data:new URLSearchParams((0,ig.removeUndefinedValuesInObject)(o)),headers:n};Qn.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 r=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,r),r}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let r=this.endpoints.oauth2TokenUrl.toString(),n={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:r,data:new URLSearchParams((0,ig.removeUndefinedValuesInObject)(n))};Qn.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof sg.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(r=>e(null,r.credentials,r.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),r=e.tokens;return r.refresh_token=this.credentials.refresh_token,this.credentials=r,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(r=>e(null,r.token,r.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let r=await this.refreshAccessTokenAsync();if(!r.credentials||r.credentials&&!r.credentials.access_token)throw new Error("Could not refresh access token.");return{token:r.credentials.access_token,res:r.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let r=this.credentials;if(!r.access_token&&!r.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(r.access_token&&!this.isTokenExpiring()){r.token_type=r.token_type||"Bearer";let c=new Headers({authorization:r.token_type+" "+r.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 n=null,o=null;try{n=await this.refreshToken(r.refresh_token),o=n.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:n.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let r=new URL(this.endpoints.oauth2RevokeUrl);return r.searchParams.append("token",e),r}revokeToken(e,r){let n={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Qn.AuthClient.setMethodName(n,"revokeToken"),r)this.transporter.request(n).then(o=>r(null,o),r);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(r=>e(null,r),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,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=sg.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let o=n.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 UE.Readable,f=s===401||s===403;if(!r&&f&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!r&&f&&!l&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,r){if(r&&typeof r!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(r)this.verifyIdTokenAsync(e).then(n=>r(null,n),r);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let r=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,r.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:r}=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()}),n=Object.assign({expiry_date:new Date().getTime()+r.expires_in*1e3,scopes:r.scope.split(" ")},r);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(r=>e(null,r.certs,r.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),r=(0,zc.hasBrowserCrypto)()?Ar.JWK:Ar.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===r)return{certs:this.certificateCache,format:r};let n,o;switch(r){case Ar.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ar.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${r}`)}try{let f={...t.RETRY_CONFIG,url:o};Qn.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),n=await this.transporter.request(f)}catch(f){throw f instanceof Error&&(f.message=`Failed to retrieve verification certificates: ${f.message}`),f}let s=n?.headers.get("cache-control"),a=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;f&&(a=Number(f)*1e3)}let c={};switch(r){case Ar.PEM:c=n.data;break;case Ar.JWK:for(let f of n.data.keys)c[f.kid]=f;break;default:throw new Error(`Unsupported certificate format ${r}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=r,{certs:c,format:r,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(r=>e(null,r.pubkeys,r.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,r=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...t.RETRY_CONFIG,url:r};Qn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,r,n,o,s){let a=(0,zc.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],f=c[2],d,p;try{d=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token envelope: ${c[0]}': ${b.message}`),b}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(b){throw b instanceof Error&&(b.message=`Can't parse token payload '${c[0]}`),b}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(r,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let C=r[d.kid];if(d.alg==="ES256"&&(f=$E.joseToDer(f,"ES256").toString("base64")),!await a.verify(C,l,f))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 _=Number(p.iat);if(isNaN(_))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 g=new Date().getTime()/1e3;if(y>=g+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let m=_-t.CLOCK_SKEW_SECS_,v=y+t.CLOCK_SKEW_SECS_;if(g<m)throw new Error("Token used too early, "+g+" < "+m+": "+JSON.stringify(p));if(g>v)throw new Error("Token used too late, "+g+" > "+v+": "+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 n<"u"&&n!==null){let b=p.aud,A=!1;if(n.constructor===Array?A=n.indexOf(b)>-1:A=b===n,!A)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new qE.LoginTicket(d,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}};rr.OAuth2Client=Hc});var Gc=V(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.Compute=void 0;var zE=Ke(),ug=$o(),HE=yn(),Wc=class extends HE.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`,r;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),r=await ug.instance(o)}catch(o){throw o instanceof zE.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let n=r;return r&&r.expires_in&&(n.expiry_date=new Date().getTime()+r.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let r=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let o={property:r};n=await ug.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return n}wrapError(e){let r=e.response;r&&r.status&&(e.status=r.status,r.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:r.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))}};Li.Compute=Wc});var Vc=V(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.IdTokenClient=void 0;var WE=yn(),Jc=class extends WE.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 r=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:r,expiry_date:this.getIdTokenExpiryDate(r)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let r=e.split(".")[1];if(r)return JSON.parse(Buffer.from(r,"base64").toString("ascii")).exp*1e3}};Ui.IdTokenClient=Jc});var Kc=V(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.GCPEnv=void 0;Xn.clear=GE;Xn.getEnv=JE;var cg=$o(),nr;(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"})(nr||(Xn.GCPEnv=nr={}));var Ho;function GE(){Ho=void 0}async function JE(){return Ho||(Ho=VE(),Ho)}async function VE(){let t=nr.NONE;return KE()?t=nr.APP_ENGINE:YE()?t=nr.CLOUD_FUNCTIONS:await eA()?await ZE()?t=nr.KUBERNETES_ENGINE:QE()?t=nr.CLOUD_RUN:XE()?t=nr.CLOUD_RUN_JOBS:t=nr.COMPUTE_ENGINE:t=nr.NONE,t}function KE(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function YE(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function QE(){return!!process.env.K_CONFIGURATION}function XE(){return!!process.env.CLOUD_RUN_JOB}async function ZE(){try{return await cg.instance("attributes/cluster-name"),!0}catch{return!1}}async function eA(){return cg.isAvailable()}});var Yc=V((bx,lg)=>{var $i=Yn().Buffer,tA=X("stream"),rA=X("util");function qi(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=$i.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=$i.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+")")}rA.inherits(qi,tA);qi.prototype.write=function(e){this.buffer=$i.concat([this.buffer,$i.from(e)]),this.emit("data",e)};qi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};lg.exports=qi});var fg=V((Cx,dg)=>{"use strict";var Wo=X("buffer").Buffer,Qc=X("buffer").SlowBuffer;dg.exports=zi;function zi(t,e){if(!Wo.isBuffer(t)||!Wo.isBuffer(e)||t.length!==e.length)return!1;for(var r=0,n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}zi.install=function(){Wo.prototype.equal=Qc.prototype.equal=function(e){return zi(this,e)}};var nA=Wo.prototype.equal,oA=Qc.prototype.equal;zi.restore=function(){Wo.prototype.equal=nA,Qc.prototype.equal=oA}});var tl=V((wx,wg)=>{var eo=Yn().Buffer,Rt=X("crypto"),pg=Ic(),hg=X("util"),sA=`"%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".`,Go="secret must be a string or buffer",Zn="key must be a string or a buffer",iA="key must be a string, a buffer or an object",Zc=typeof Rt.createPublicKey=="function";Zc&&(Zn+=" or a KeyObject",Go+="or a KeyObject");function mg(t){if(!eo.isBuffer(t)&&typeof t!="string"&&(!Zc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Wt(Zn)}function gg(t){if(!eo.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Wt(iA)}function aA(t){if(!eo.isBuffer(t)){if(typeof t=="string")return t;if(!Zc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Wt(Go)}}function el(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function yg(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Wt(t){var e=[].slice.call(arguments,1),r=hg.format.bind(hg,t).apply(null,e);return new TypeError(r)}function uA(t){return eo.isBuffer(t)||typeof t=="string"}function Jo(t){return uA(t)||(t=JSON.stringify(t)),t}function _g(t){return function(r,n){aA(n),r=Jo(r);var o=Rt.createHmac("sha"+t,n),s=(o.update(r),o.digest("base64"));return el(s)}}var Xc,cA="timingSafeEqual"in Rt?function(e,r){return e.byteLength!==r.byteLength?!1:Rt.timingSafeEqual(e,r)}:function(e,r){return Xc||(Xc=fg()),Xc(e,r)};function lA(t){return function(r,n,o){var s=_g(t)(r,o);return cA(eo.from(n),eo.from(s))}}function bg(t){return function(r,n){gg(n),r=Jo(r);var o=Rt.createSign("RSA-SHA"+t),s=(o.update(r),o.sign(n,"base64"));return el(s)}}function Cg(t){return function(r,n,o){mg(o),r=Jo(r),n=yg(n);var s=Rt.createVerify("RSA-SHA"+t);return s.update(r),s.verify(o,n,"base64")}}function dA(t){return function(r,n){gg(n),r=Jo(r);var o=Rt.createSign("RSA-SHA"+t),s=(o.update(r),o.sign({key:n,padding:Rt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Rt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return el(s)}}function fA(t){return function(r,n,o){mg(o),r=Jo(r),n=yg(n);var s=Rt.createVerify("RSA-SHA"+t);return s.update(r),s.verify({key:o,padding:Rt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Rt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function hA(t){var e=bg(t);return function(){var n=e.apply(null,arguments);return n=pg.derToJose(n,"ES"+t),n}}function pA(t){var e=Cg(t);return function(n,o,s){o=pg.joseToDer(o,"ES"+t).toString("base64");var a=e(n,o,s);return a}}function mA(){return function(){return""}}function gA(){return function(e,r){return r===""}}wg.exports=function(e){var r={hs:_g,rs:bg,ps:dA,es:hA,none:mA},n={hs:lA,rs:Cg,ps:fA,es:pA,none:gA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Wt(sA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:r[s](a),verify:n[s](a)}}});var rl=V((Ex,Eg)=>{var yA=X("buffer").Buffer;Eg.exports=function(e){return typeof e=="string"?e:typeof e=="number"||yA.isBuffer(e)?e.toString():JSON.stringify(e)}});var Dg=V((Ax,Tg)=>{var _A=Yn().Buffer,Ag=Yc(),bA=tl(),CA=X("stream"),kg=rl(),nl=X("util");function Sg(t,e){return _A.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function wA(t,e,r){r=r||"utf8";var n=Sg(kg(t),"binary"),o=Sg(kg(e),r);return nl.format("%s.%s",n,o)}function vg(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,o=t.encoding,s=bA(e.alg),a=wA(e,r,o),c=s.sign(a,n);return nl.format("%s.%s",a,c)}function Hi(t){var e=t.secret||t.privateKey||t.key,r=new Ag(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Ag(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))}nl.inherits(Hi,CA);Hi.prototype.sign=function(){try{var e=vg({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(r){this.readable=!1,this.emit("error",r),this.emit("close")}};Hi.sign=vg;Tg.exports=Hi});var jg=V((kx,Mg)=>{var xg=Yn().Buffer,Rg=Yc(),EA=tl(),AA=X("stream"),Og=rl(),kA=X("util"),SA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function vA(t){return Object.prototype.toString.call(t)==="[object Object]"}function TA(t){if(vA(t))return t;try{return JSON.parse(t)}catch{return}}function Fg(t){var e=t.split(".",1)[0];return TA(xg.from(e,"base64").toString("binary"))}function DA(t){return t.split(".",2).join(".")}function Pg(t){return t.split(".")[2]}function RA(t,e){e=e||"utf8";var r=t.split(".")[1];return xg.from(r,"base64").toString(e)}function Ig(t){return SA.test(t)&&!!Fg(t)}function Bg(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=Og(t);var o=Pg(t),s=DA(t),a=EA(e);return a.verify(s,o,r)}function Ng(t,e){if(e=e||{},t=Og(t),!Ig(t))return null;var r=Fg(t);if(!r)return null;var n=RA(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:Pg(t)}}function to(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new Rg(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new Rg(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))}kA.inherits(to,AA);to.prototype.verify=function(){try{var e=Bg(this.signature.buffer,this.algorithm,this.key.buffer),r=Ng(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};to.decode=Ng;to.isValid=Ig;to.verify=Bg;Mg.exports=to});var ol=V(Jr=>{var Lg=Dg(),Wi=jg(),xA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Jr.ALGORITHMS=xA;Jr.sign=Lg.sign;Jr.verify=Wi.verify;Jr.decode=Wi.decode;Jr.isValid=Wi.isValid;Jr.createSign=function(e){return new Lg(e)};Jr.createVerify=function(e){return new Wi(e)}});var ey=V(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.GoogleToken=void 0;var Ug=Gi(X("fs")),OA=Ke(),FA=Gi(ol()),PA=Gi(X("path")),IA=X("util");function Gi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Gi=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,f={__proto__:null,default:s};if(s===null||kr(s)!="object"&&typeof s!="function")return f;if(c=a?n:r){if(c.has(s))return c.get(s);c.set(s,f)}for(var d in s)d!=="default"&&{}.hasOwnProperty.call(s,d)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,d))&&(l.get||l.set)?c(f,d,l):f[d]=s[d]);return f})(t,e)}function kr(t){"@babel/helpers - typeof";return kr=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},kr(t)}function BA(t,e){Kg(t,e),e.add(t)}function NA(t,e,r){Kg(t,e),e.set(t,r)}function Kg(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function $g(t,e,r){return t.set(Gt(t,e),r),r}function qg(t,e){return t.get(Gt(t,e))}function Gt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function zg(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Xg(n.key),n)}}function Yg(t,e,r){return e&&zg(t.prototype,e),r&&zg(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function Qg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function MA(t,e,r){return e=Qo(e),jA(t,ll()?Reflect.construct(e,r||[],Qo(t).constructor):e.apply(t,r))}function jA(t,e){if(e&&(kr(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return LA(t)}function LA(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function UA(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&&Yo(t,e)}function sl(t){var e=typeof Map=="function"?new Map:void 0;return sl=function(n){if(n===null||!qA(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,o)}function o(){return $A(n,arguments,Qo(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Yo(o,n)},sl(t)}function $A(t,e,r){if(ll())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var o=new(t.bind.apply(t,n));return r&&Yo(o,r.prototype),o}function ll(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ll=function(){return!!t})()}function qA(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Yo(t,e){return Yo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Yo(t,e)}function Qo(t){return Qo=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Qo(t)}function _t(t,e,r){return(e=Xg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Xg(t){var e=zA(t,"string");return kr(e)=="symbol"?e:e+""}function zA(t,e){if(kr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(kr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ct(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function s(k,C,y,g){var m=C&&C.prototype instanceof c?C:c,v=Object.create(m.prototype);return bt(v,"_invoke",(function(_,A,D){var O,q,J,B=0,Y=D||[],re=!1,ee={p:0,n:0,v:t,a:ue,f:ue.bind(t,4),d:function(ke,ie){return O=ke,q=0,J=t,ee.n=ie,a}};function ue(fe,ke){for(q=fe,J=ke,e=0;!re&&B&&!ie&&e<Y.length;e++){var ie,me=Y[e],G=ee.p,K=me[2];fe>3?(ie=K===ke)&&(J=me[(q=me[4])?5:(q=3,3)],me[4]=me[5]=t):me[0]<=G&&((ie=fe<2&&G<me[1])?(q=0,ee.v=ke,ee.n=me[1]):G<K&&(ie=fe<3||me[0]>ke||ke>K)&&(me[4]=fe,me[5]=ke,ee.n=K,q=0))}if(ie||fe>1)return a;throw re=!0,ke}return function(fe,ke,ie){if(B>1)throw TypeError("Generator is already running");for(re&&ke===1&&ue(ke,ie),q=ke,J=ie;(e=q<2?t:J)||!re;){O||(q?q<3?(q>1&&(ee.n=-1),ue(q,J)):ee.n=J:ee.v=J);try{if(B=2,O){if(q||(fe="next"),e=O[fe]){if(!(e=e.call(O,J)))throw TypeError("iterator result is not an object");if(!e.done)return e;J=e.value,q<2&&(q=0)}else q===1&&(e=O.return)&&e.call(O),q<2&&(J=TypeError("The iterator does not provide a '"+fe+"' method"),q=1);O=t}else if((e=(re=ee.n<0)?J:_.call(A,ee))!==a)break}catch(me){O=t,q=1,J=me}finally{B=1}}return{value:e,done:re}}})(k,y,g),!0),v}var a={};function c(){}function l(){}function f(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(bt(e={},n,function(){return this}),e),p=f.prototype=c.prototype=Object.create(d);function b(k){return Object.setPrototypeOf?Object.setPrototypeOf(k,f):(k.__proto__=f,bt(k,o,"GeneratorFunction")),k.prototype=Object.create(p),k}return l.prototype=f,bt(p,"constructor",f),bt(f,"constructor",l),l.displayName="GeneratorFunction",bt(f,o,"GeneratorFunction"),bt(p),bt(p,o,"Generator"),bt(p,n,function(){return this}),bt(p,"toString",function(){return"[object Generator]"}),(Ct=function(){return{w:s,m:b}})()}function bt(t,e,r,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}bt=function(a,c,l,f){if(c)o?o(a,c,{value:l,enumerable:!f,configurable:!f,writable:!f}):a[c]=l;else{var d=function(b,k){bt(a,b,function(C){return this._invoke(b,k,C)})};d("next",0),d("throw",1),d("return",2)}},bt(t,e,r,n)}function Hg(t,e,r,n,o,s,a){try{var c=t[s](a),l=c.value}catch(f){return void r(f)}c.done?e(l):Promise.resolve(l).then(n,o)}function ro(t){return function(){var e=this,r=arguments;return new Promise(function(n,o){var s=t.apply(e,r);function a(l){Hg(s,n,o,a,c,"next",l)}function c(l){Hg(s,n,o,a,c,"throw",l)}a(void 0)})}}var Wg=Ug.readFile?(0,IA.promisify)(Ug.readFile):ro(Ct().m(function t(){return Ct().w(function(e){for(;;)switch(e.n){case 0:throw new Ko("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Gg="https://oauth2.googleapis.com/token",HA="https://oauth2.googleapis.com/revoke?token=",Ko=(function(t){function e(r,n){var o;return Qg(this,e),o=MA(this,e,[r]),_t(o,"code",void 0),o.code=n,o}return UA(e,t),Yg(e)})(sl(Error)),Vo=new WeakMap,or=new WeakSet,vx=Ji.GoogleToken=(function(){function t(e){Qg(this,t),BA(this,or),_t(this,"expiresAt",void 0),_t(this,"key",void 0),_t(this,"keyFile",void 0),_t(this,"iss",void 0),_t(this,"sub",void 0),_t(this,"scope",void 0),_t(this,"rawToken",void 0),_t(this,"tokenExpires",void 0),_t(this,"email",void 0),_t(this,"additionalClaims",void 0),_t(this,"eagerRefreshThresholdMillis",void 0),_t(this,"transporter",{request:function(n){return(0,OA.request)(n)}}),NA(this,Vo,void 0),Gt(or,this,Zg).call(this,e)}return Yg(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 r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),o=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(kr(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var o=r;Gt(or,this,Jg).call(this,n).then(function(s){return o(null,s)},r);return}return Gt(or,this,Jg).call(this,n)}},{key:"getCredentials",value:(function(){var e=ro(Ct().m(function n(o){var s,a,c,l,f,d,p;return Ct().w(function(b){for(;;)switch(b.n){case 0:s=PA.extname(o),p=s,b.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return b.n=2,Wg(o,"utf8");case 2:if(a=b.v,c=JSON.parse(a),l=c.private_key,f=c.client_email,!(!l||!f)){b.n=3;break}throw new Ko("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return b.a(2,{privateKey:l,clientEmail:f});case 4:return b.n=5,Wg(o,"utf8");case 5:return d=b.v,b.a(2,{privateKey:d});case 6:throw new Ko("*.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 Ko("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return b.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){Gt(or,this,Vg).call(this).then(function(){return r()},r);return}return Gt(or,this,Vg).call(this)}}])})();function Jg(t){return il.apply(this,arguments)}function il(){return il=ro(Ct().m(function t(e){return Ct().w(function(r){for(;;)switch(r.n){case 0:if(!(qg(Vo,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,qg(Vo,this));case 1:return r.p=1,r.n=2,$g(Vo,this,Gt(or,this,WA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,$g(Vo,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),il.apply(this,arguments)}function WA(t){return al.apply(this,arguments)}function al(){return al=ro(Ct().m(function t(e){var r;return Ct().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||Gt(or,this,GA).call(this);case 4:return n.a(2,Gt(or,this,JA).call(this))}},t,this)})),al.apply(this,arguments)}function GA(){if(!this.iss)throw new Ko("email is required.","MISSING_CREDENTIALS")}function Vg(){return ul.apply(this,arguments)}function ul(){return ul=ro(Ct().m(function t(){var e;return Ct().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=HA+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:Gt(or,this,Zg).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),ul.apply(this,arguments)}function Zg(){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,kr(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function JA(){return cl.apply(this,arguments)}function cl(){return cl=ro(Ct().m(function t(){var e,r,n,o,s,a,c,l,f,d;return Ct().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:Gg,exp:e+3600,iat:e,sub:this.sub},r),o=FA.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:Gg,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,d=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(a=d.response)!==null&&a!==void 0&&a.data?(c=d.response)===null||c===void 0?void 0:c.data:{},l.error&&(f=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(f)),d;case 4:return p.a(2)}},t,this,[[1,3]])})),cl.apply(this,arguments)}});var fl=V(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.JWTAccess=void 0;var VA=ol(),KA=zt(),ty={alg:"RS256",typ:"JWT"},dl=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new KA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,o){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let o=this.getCachedKey(e,n),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),f;if(Array.isArray(n)&&(n=n.join(" ")),n?f={iss:this.email,sub:this.email,scope:n,exp:l,iat:c}:f={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},r){for(let C in f)if(r[C])throw new Error(`The '${C}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...ty,kid:this.keyId}:ty,p=Object.assign(f,r),b=VA.sign({header:d,payload:p,secret:this.key}),k=new Headers({authorization:`Bearer ${b}`});return this.cache.set(o,{expiration:l*1e3,headers:k}),k}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,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(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",n).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(s)}})})}};Vi.JWTAccess=dl});var pl=V(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.JWT=void 0;var ry=ey(),YA=fl(),QA=yn(),Ki=yt(),hl=class t extends QA.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 r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Ki.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Ki.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Ki.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new YA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Ki.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new ry.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 r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.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(r=>e(null,r),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(),n={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",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new ry.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,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(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 r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Yi.JWT=hl});var gl=V(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.UserRefreshClient=no.USER_REFRESH_ACCOUNT_TYPE=void 0;var XA=yn(),ZA=yt();no.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var ml=class t extends XA.OAuth2Client{_refreshToken;constructor(e,r,n,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,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 r={...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 ZA.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).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,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),r()}catch(s){return n(s)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};no.UserRefreshClient=ml});var _l=V(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.Impersonated=oo.IMPERSONATED_ACCOUNT_TYPE=void 0;var ny=yn(),ek=Ke(),tk=zt();oo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var yl=class t extends ny.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 ny.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,tk.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 r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,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 r=0,n="";throw e instanceof ek.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};oo.Impersonated=yl});var Cl=V(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.OAuthClientAuthHandler=void 0;Xo.getErrorFromOAuthErrorResponse=ok;var so=Ke(),rk=qo(),nk=["PUT","POST","PATCH"],bl=class{#e=(0,rk.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new so.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new so.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=so.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=so.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=so.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${n}:${o}`);so.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!nk.includes(r))throw new Error(`${r} 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"]}}}};Xo.OAuthClientAuthHandler=bl;function ok(t,e){let r=t.error,n=t.error_description,o=t.error_uri,s=`Error code ${r}`;typeof n<"u"&&(s+=`: ${n}`),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 Xi=V(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.StsCredentials=void 0;var sk=Ke(),ik=yt(),oy=Cl(),ak=zt(),wl=class t extends oy.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){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:n&&JSON.stringify(n)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,ak.removeUndefinedValuesInObject)(o))};ik.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 sk.GaxiosError&&a.response?(0,oy.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};Qi.StsCredentials=wl});var Vr=V(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.BaseExternalAccountClient=xt.CLOUD_RESOURCE_MANAGER=xt.EXTERNAL_ACCOUNT_TYPE=xt.EXPIRATION_TIME_OFFSET=void 0;var uk=Ke(),ck=X("stream"),El=yt(),lk=Xi(),sy=zt(),dk=Mc(),fk="urn:ietf:params:oauth:grant-type:token-exchange",hk="urn:ietf:params:oauth:token-type:access_token",Al="https://www.googleapis.com/auth/cloud-platform",pk=3600;xt.EXPIRATION_TIME_OFFSET=300*1e3;xt.EXTERNAL_ACCOUNT_TYPE="external_account";xt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var mk="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",gk="https://sts.{universeDomain}/v1/token",kl=class t extends El.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,sy.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==xt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${xt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=r.get("client_id"),s=r.get("client_secret");this.tokenUrl=r.get("token_url")??gk.replace("{universeDomain}",this.universeDomain);let a=r.get("subject_token_type"),c=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),f=r.get("service_account_impersonation"),d=(0,sy.originalOrCamelOptions)(f).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new lk.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[Al],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let p=new RegExp(mk);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=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=pk),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(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};El.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=uk.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof ck.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:fk,audience:this.audience,requestedTokenType:hk,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Al]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(r,o,n);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 r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};El.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Al]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${dk.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};xt.BaseExternalAccountClient=kl});var iy=V(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.FileSubjectTokenSupplier=void 0;var vl=X("util"),Tl=X("fs"),yk=(0,vl.promisify)(Tl.readFile??(()=>{})),_k=(0,vl.promisify)(Tl.realpath??(()=>{})),bk=(0,vl.promisify)(Tl.lstat??(()=>{})),Sl=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 _k(e),!(await bk(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 r,n=await yk(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};Zi.FileSubjectTokenSupplier=Sl});var ay=V(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.UrlSubjectTokenSupplier=void 0;var Ck=yt(),Dl=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 r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};Ck.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};ea.UrlSubjectTokenSupplier=Dl});var uy=V(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.CertificateSubjectTokenSupplier=wt.InvalidConfigurationError=wt.CertificateSourceUnavailableError=wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var ta=zt(),ra=X("fs"),na=X("crypto"),wk=X("https");wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var sr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};wt.CertificateSourceUnavailableError=sr;var Ot=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};wt.InvalidConfigurationError=Ot;var Rl=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ot("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ot("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ot("Cannot create mTLS Agent with missing certificate or key");return new wk.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,ta.isValidFile)(e))return e;throw new sr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,ta.isValidFile)(r))return r;throw new sr(`Path from environment variable "${wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,ta.getWellKnownCertificateConfigFileLocation)();if(await(0,ta.isValidFile)(n))return n;throw new sr(`Could not find certificate configuration file. Searched override path, the "${wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await ra.promises.readFile(e,"utf8")}catch{throw new sr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),o=n?.cert_configs?.workload?.cert_path,s=n?.cert_configs?.workload?.key_path;if(!o||!s)throw new Ot(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(n){throw n instanceof Ot?n:new Ot(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,o;try{n=await ra.promises.readFile(e),new na.X509Certificate(n)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sr(`Failed to read certificate file at ${e}: ${a}`)}try{o=await ra.promises.readFile(r),(0,na.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sr(`Failed to read private key file at ${r}: ${a}`)}return{cert:n,key:o}}async#n(e){let r=new na.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let s=((await ra.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,f)=>{try{return new na.X509Certificate(l)}catch(d){let p=d instanceof Error?d.message:String(d);throw new Ot(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>r.raw.equals(l.raw)),c;if(a===-1)c=[r,...s];else if(a===0)c=s;else throw new Ot(`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(n){if(n instanceof Ot)throw n;let o=n instanceof Error?n.message:String(n);throw new sr(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};wt.CertificateSubjectTokenSupplier=Rl});var Fl=V(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.IdentityPoolClient=void 0;var Ek=Vr(),xl=zt(),Ak=iy(),kk=ay(),cy=uy(),Sk=Xi(),ly=Ke(),Ol=class t extends Ek.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,xl.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&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,xl.originalOrCamelOptions)(n),a=(0,xl.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 f=s.get("file"),d=s.get("url"),p=s.get("certificate"),b=s.get("headers");if(f&&d||d&&p||f&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new Ak.FileSubjectTokenSupplier({filePath:f,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new kk.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:b,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let k=new cy.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=k}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 cy.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Sk.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new ly.Gaxios({agent:r})}),this.transporter=new ly.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};oa.IdentityPoolClient=Ol});var Il=V(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.AwsRequestSigner=void 0;var sa=Ke(),fy=qo(),dy="AWS4-HMAC-SHA256",vk="aws4_request",Pl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,fy.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",s=e.body||r,a=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await Dk({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}),d=sa.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:l.host},a||{});c.token&&sa.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let p={url:n,method:o,headers:d};return s!==void 0&&(p.body=s),p}};ia.AwsRequestSigner=Pl;async function Zo(t,e,r){return await t.signWithHmacSha256(e,r)}async function Tk(t,e,r,n,o){let s=await Zo(t,`AWS4${e}`,r),a=await Zo(t,s,n),c=await Zo(t,a,o);return await Zo(t,c,"aws4_request")}async function Dk(t){let e=sa.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=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=sa.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",f=[...c.keys()].sort();f.forEach(v=>{l+=`${v}:${c.get(v)}
|
|
53
|
-
`});let d=f.join(";"),p=await t.crypto.sha256DigestHex(r),
|
|
52
|
+
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Go="secret must be a string or buffer",Zn="key must be a string or a buffer",iA="key must be a string, a buffer or an object",Zc=typeof Rt.createPublicKey=="function";Zc&&(Zn+=" or a KeyObject",Go+="or a KeyObject");function mg(t){if(!eo.isBuffer(t)&&typeof t!="string"&&(!Zc||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw Wt(Zn)}function gg(t){if(!eo.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw Wt(iA)}function aA(t){if(!eo.isBuffer(t)){if(typeof t=="string")return t;if(!Zc||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw Wt(Go)}}function el(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function yg(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var r=0;r<e;++r)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function Wt(t){var e=[].slice.call(arguments,1),r=hg.format.bind(hg,t).apply(null,e);return new TypeError(r)}function uA(t){return eo.isBuffer(t)||typeof t=="string"}function Jo(t){return uA(t)||(t=JSON.stringify(t)),t}function _g(t){return function(r,n){aA(n),r=Jo(r);var o=Rt.createHmac("sha"+t,n),s=(o.update(r),o.digest("base64"));return el(s)}}var Xc,cA="timingSafeEqual"in Rt?function(e,r){return e.byteLength!==r.byteLength?!1:Rt.timingSafeEqual(e,r)}:function(e,r){return Xc||(Xc=fg()),Xc(e,r)};function lA(t){return function(r,n,o){var s=_g(t)(r,o);return cA(eo.from(n),eo.from(s))}}function bg(t){return function(r,n){gg(n),r=Jo(r);var o=Rt.createSign("RSA-SHA"+t),s=(o.update(r),o.sign(n,"base64"));return el(s)}}function Cg(t){return function(r,n,o){mg(o),r=Jo(r),n=yg(n);var s=Rt.createVerify("RSA-SHA"+t);return s.update(r),s.verify(o,n,"base64")}}function dA(t){return function(r,n){gg(n),r=Jo(r);var o=Rt.createSign("RSA-SHA"+t),s=(o.update(r),o.sign({key:n,padding:Rt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Rt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return el(s)}}function fA(t){return function(r,n,o){mg(o),r=Jo(r),n=yg(n);var s=Rt.createVerify("RSA-SHA"+t);return s.update(r),s.verify({key:o,padding:Rt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Rt.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function hA(t){var e=bg(t);return function(){var n=e.apply(null,arguments);return n=pg.derToJose(n,"ES"+t),n}}function pA(t){var e=Cg(t);return function(n,o,s){o=pg.joseToDer(o,"ES"+t).toString("base64");var a=e(n,o,s);return a}}function mA(){return function(){return""}}function gA(){return function(e,r){return r===""}}wg.exports=function(e){var r={hs:_g,rs:bg,ps:dA,es:hA,none:mA},n={hs:lA,rs:Cg,ps:fA,es:pA,none:gA},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw Wt(sA,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:r[s](a),verify:n[s](a)}}});var rl=V((Ex,Eg)=>{var yA=X("buffer").Buffer;Eg.exports=function(e){return typeof e=="string"?e:typeof e=="number"||yA.isBuffer(e)?e.toString():JSON.stringify(e)}});var Dg=V((Ax,Tg)=>{var _A=Yn().Buffer,Ag=Yc(),bA=tl(),CA=X("stream"),kg=rl(),nl=X("util");function Sg(t,e){return _A.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function wA(t,e,r){r=r||"utf8";var n=Sg(kg(t),"binary"),o=Sg(kg(e),r);return nl.format("%s.%s",n,o)}function vg(t){var e=t.header,r=t.payload,n=t.secret||t.privateKey,o=t.encoding,s=bA(e.alg),a=wA(e,r,o),c=s.sign(a,n);return nl.format("%s.%s",a,c)}function Hi(t){var e=t.secret||t.privateKey||t.key,r=new Ag(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=r,this.payload=new Ag(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))}nl.inherits(Hi,CA);Hi.prototype.sign=function(){try{var e=vg({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(r){this.readable=!1,this.emit("error",r),this.emit("close")}};Hi.sign=vg;Tg.exports=Hi});var jg=V((kx,Mg)=>{var xg=Yn().Buffer,Rg=Yc(),EA=tl(),AA=X("stream"),Og=rl(),kA=X("util"),SA=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function vA(t){return Object.prototype.toString.call(t)==="[object Object]"}function TA(t){if(vA(t))return t;try{return JSON.parse(t)}catch{return}}function Fg(t){var e=t.split(".",1)[0];return TA(xg.from(e,"base64").toString("binary"))}function DA(t){return t.split(".",2).join(".")}function Pg(t){return t.split(".")[2]}function RA(t,e){e=e||"utf8";var r=t.split(".")[1];return xg.from(r,"base64").toString(e)}function Ig(t){return SA.test(t)&&!!Fg(t)}function Bg(t,e,r){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}t=Og(t);var o=Pg(t),s=DA(t),a=EA(e);return a.verify(s,o,r)}function Ng(t,e){if(e=e||{},t=Og(t),!Ig(t))return null;var r=Fg(t);if(!r)return null;var n=RA(t);return(r.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:r,payload:n,signature:Pg(t)}}function to(t){t=t||{};var e=t.secret||t.publicKey||t.key,r=new Rg(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=r,this.signature=new Rg(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))}kA.inherits(to,AA);to.prototype.verify=function(){try{var e=Bg(this.signature.buffer,this.algorithm,this.key.buffer),r=Ng(this.signature.buffer,this.encoding);return this.emit("done",e,r),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};to.decode=Ng;to.isValid=Ig;to.verify=Bg;Mg.exports=to});var ol=V(Jr=>{var Lg=Dg(),Wi=jg(),xA=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Jr.ALGORITHMS=xA;Jr.sign=Lg.sign;Jr.verify=Wi.verify;Jr.decode=Wi.decode;Jr.isValid=Wi.isValid;Jr.createSign=function(e){return new Lg(e)};Jr.createVerify=function(e){return new Wi(e)}});var ey=V(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.GoogleToken=void 0;var Ug=Gi(X("fs")),OA=Ke(),FA=Gi(ol()),PA=Gi(X("path")),IA=X("util");function Gi(t,e){if(typeof WeakMap=="function")var r=new WeakMap,n=new WeakMap;return(Gi=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,f={__proto__:null,default:s};if(s===null||kr(s)!="object"&&typeof s!="function")return f;if(c=a?n:r){if(c.has(s))return c.get(s);c.set(s,f)}for(var d in s)d!=="default"&&{}.hasOwnProperty.call(s,d)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,d))&&(l.get||l.set)?c(f,d,l):f[d]=s[d]);return f})(t,e)}function kr(t){"@babel/helpers - typeof";return kr=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},kr(t)}function BA(t,e){Kg(t,e),e.add(t)}function NA(t,e,r){Kg(t,e),e.set(t,r)}function Kg(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function $g(t,e,r){return t.set(Gt(t,e),r),r}function qg(t,e){return t.get(Gt(t,e))}function Gt(t,e,r){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:r;throw new TypeError("Private element is not present on this object")}function zg(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Xg(n.key),n)}}function Yg(t,e,r){return e&&zg(t.prototype,e),r&&zg(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function Qg(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function MA(t,e,r){return e=Qo(e),jA(t,ll()?Reflect.construct(e,r||[],Qo(t).constructor):e.apply(t,r))}function jA(t,e){if(e&&(kr(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return LA(t)}function LA(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function UA(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&&Yo(t,e)}function sl(t){var e=typeof Map=="function"?new Map:void 0;return sl=function(n){if(n===null||!qA(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,o)}function o(){return $A(n,arguments,Qo(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Yo(o,n)},sl(t)}function $A(t,e,r){if(ll())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var o=new(t.bind.apply(t,n));return r&&Yo(o,r.prototype),o}function ll(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ll=function(){return!!t})()}function qA(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Yo(t,e){return Yo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Yo(t,e)}function Qo(t){return Qo=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Qo(t)}function _t(t,e,r){return(e=Xg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Xg(t){var e=zA(t,"string");return kr(e)=="symbol"?e:e+""}function zA(t,e){if(kr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(kr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ct(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function s(k,_,y,g){var m=_&&_.prototype instanceof c?_:c,v=Object.create(m.prototype);return bt(v,"_invoke",(function(b,A,D){var O,q,J,B=0,Y=D||[],re=!1,ee={p:0,n:0,v:t,a:ue,f:ue.bind(t,4),d:function(ke,ie){return O=ke,q=0,J=t,ee.n=ie,a}};function ue(fe,ke){for(q=fe,J=ke,e=0;!re&&B&&!ie&&e<Y.length;e++){var ie,me=Y[e],G=ee.p,K=me[2];fe>3?(ie=K===ke)&&(J=me[(q=me[4])?5:(q=3,3)],me[4]=me[5]=t):me[0]<=G&&((ie=fe<2&&G<me[1])?(q=0,ee.v=ke,ee.n=me[1]):G<K&&(ie=fe<3||me[0]>ke||ke>K)&&(me[4]=fe,me[5]=ke,ee.n=K,q=0))}if(ie||fe>1)return a;throw re=!0,ke}return function(fe,ke,ie){if(B>1)throw TypeError("Generator is already running");for(re&&ke===1&&ue(ke,ie),q=ke,J=ie;(e=q<2?t:J)||!re;){O||(q?q<3?(q>1&&(ee.n=-1),ue(q,J)):ee.n=J:ee.v=J);try{if(B=2,O){if(q||(fe="next"),e=O[fe]){if(!(e=e.call(O,J)))throw TypeError("iterator result is not an object");if(!e.done)return e;J=e.value,q<2&&(q=0)}else q===1&&(e=O.return)&&e.call(O),q<2&&(J=TypeError("The iterator does not provide a '"+fe+"' method"),q=1);O=t}else if((e=(re=ee.n<0)?J:b.call(A,ee))!==a)break}catch(me){O=t,q=1,J=me}finally{B=1}}return{value:e,done:re}}})(k,y,g),!0),v}var a={};function c(){}function l(){}function f(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(bt(e={},n,function(){return this}),e),p=f.prototype=c.prototype=Object.create(d);function C(k){return Object.setPrototypeOf?Object.setPrototypeOf(k,f):(k.__proto__=f,bt(k,o,"GeneratorFunction")),k.prototype=Object.create(p),k}return l.prototype=f,bt(p,"constructor",f),bt(f,"constructor",l),l.displayName="GeneratorFunction",bt(f,o,"GeneratorFunction"),bt(p),bt(p,o,"Generator"),bt(p,n,function(){return this}),bt(p,"toString",function(){return"[object Generator]"}),(Ct=function(){return{w:s,m:C}})()}function bt(t,e,r,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}bt=function(a,c,l,f){if(c)o?o(a,c,{value:l,enumerable:!f,configurable:!f,writable:!f}):a[c]=l;else{var d=function(C,k){bt(a,C,function(_){return this._invoke(C,k,_)})};d("next",0),d("throw",1),d("return",2)}},bt(t,e,r,n)}function Hg(t,e,r,n,o,s,a){try{var c=t[s](a),l=c.value}catch(f){return void r(f)}c.done?e(l):Promise.resolve(l).then(n,o)}function ro(t){return function(){var e=this,r=arguments;return new Promise(function(n,o){var s=t.apply(e,r);function a(l){Hg(s,n,o,a,c,"next",l)}function c(l){Hg(s,n,o,a,c,"throw",l)}a(void 0)})}}var Wg=Ug.readFile?(0,IA.promisify)(Ug.readFile):ro(Ct().m(function t(){return Ct().w(function(e){for(;;)switch(e.n){case 0:throw new Ko("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),Gg="https://oauth2.googleapis.com/token",HA="https://oauth2.googleapis.com/revoke?token=",Ko=(function(t){function e(r,n){var o;return Qg(this,e),o=MA(this,e,[r]),_t(o,"code",void 0),o.code=n,o}return UA(e,t),Yg(e)})(sl(Error)),Vo=new WeakMap,or=new WeakSet,vx=Ji.GoogleToken=(function(){function t(e){Qg(this,t),BA(this,or),_t(this,"expiresAt",void 0),_t(this,"key",void 0),_t(this,"keyFile",void 0),_t(this,"iss",void 0),_t(this,"sub",void 0),_t(this,"scope",void 0),_t(this,"rawToken",void 0),_t(this,"tokenExpires",void 0),_t(this,"email",void 0),_t(this,"additionalClaims",void 0),_t(this,"eagerRefreshThresholdMillis",void 0),_t(this,"transporter",{request:function(n){return(0,OA.request)(n)}}),NA(this,Vo,void 0),Gt(or,this,Zg).call(this,e)}return Yg(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 r=new Date().getTime();return this.rawToken&&this.expiresAt?r>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var r,n=new Date().getTime(),o=(r=this.eagerRefreshThresholdMillis)!==null&&r!==void 0?r:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(kr(r)==="object"&&(n=r,r=void 0),n=Object.assign({forceRefresh:!1},n),r){var o=r;Gt(or,this,Jg).call(this,n).then(function(s){return o(null,s)},r);return}return Gt(or,this,Jg).call(this,n)}},{key:"getCredentials",value:(function(){var e=ro(Ct().m(function n(o){var s,a,c,l,f,d,p;return Ct().w(function(C){for(;;)switch(C.n){case 0:s=PA.extname(o),p=s,C.n=p===".json"?1:p===".der"||p===".crt"||p===".pem"?4:p===".p12"||p===".pfx"?6:7;break;case 1:return C.n=2,Wg(o,"utf8");case 2:if(a=C.v,c=JSON.parse(a),l=c.private_key,f=c.client_email,!(!l||!f)){C.n=3;break}throw new Ko("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return C.a(2,{privateKey:l,clientEmail:f});case 4:return C.n=5,Wg(o,"utf8");case 5:return d=C.v,C.a(2,{privateKey:d});case 6:throw new Ko("*.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 Ko("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return C.a(2)}},n)}));function r(n){return e.apply(this,arguments)}return r})()},{key:"revokeToken",value:function(r){if(r){Gt(or,this,Vg).call(this).then(function(){return r()},r);return}return Gt(or,this,Vg).call(this)}}])})();function Jg(t){return il.apply(this,arguments)}function il(){return il=ro(Ct().m(function t(e){return Ct().w(function(r){for(;;)switch(r.n){case 0:if(!(qg(Vo,this)&&!e.forceRefresh)){r.n=1;break}return r.a(2,qg(Vo,this));case 1:return r.p=1,r.n=2,$g(Vo,this,Gt(or,this,WA).call(this,e));case 2:return r.a(2,r.v);case 3:return r.p=3,$g(Vo,this,void 0),r.f(3);case 4:return r.a(2)}},t,this,[[1,,3,4]])})),il.apply(this,arguments)}function WA(t){return al.apply(this,arguments)}function al(){return al=ro(Ct().m(function t(e){var r;return Ct().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:r=n.v,this.key=r.privateKey,this.iss=r.clientEmail||this.iss,r.clientEmail||Gt(or,this,GA).call(this);case 4:return n.a(2,Gt(or,this,JA).call(this))}},t,this)})),al.apply(this,arguments)}function GA(){if(!this.iss)throw new Ko("email is required.","MISSING_CREDENTIALS")}function Vg(){return ul.apply(this,arguments)}function ul(){return ul=ro(Ct().m(function t(){var e;return Ct().w(function(r){for(;;)switch(r.n){case 0:if(this.accessToken){r.n=1;break}throw new Error("No token to revoke.");case 1:return e=HA+this.accessToken,r.n=2,this.transporter.request({url:e,retry:!0});case 2:Gt(or,this,Zg).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return r.a(2)}},t,this)})),ul.apply(this,arguments)}function Zg(){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,kr(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function JA(){return cl.apply(this,arguments)}function cl(){return cl=ro(Ct().m(function t(){var e,r,n,o,s,a,c,l,f,d;return Ct().w(function(p){for(;;)switch(p.n){case 0:return e=Math.floor(new Date().getTime()/1e3),r=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:Gg,exp:e+3600,iat:e,sub:this.sub},r),o=FA.sign({header:{alg:"RS256"},payload:n,secret:this.key}),p.p=1,p.n=2,this.transporter.request({method:"POST",url:Gg,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,d=p.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(a=d.response)!==null&&a!==void 0&&a.data?(c=d.response)===null||c===void 0?void 0:c.data:{},l.error&&(f=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(f)),d;case 4:return p.a(2)}},t,this,[[1,3]])})),cl.apply(this,arguments)}});var fl=V(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.JWTAccess=void 0;var VA=ol(),KA=zt(),ty={alg:"RS256",typ:"JWT"},dl=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new KA.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,r,n,o){this.email=e,this.key=r,this.keyId=n,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,r){let n=e;if(r&&Array.isArray(r)&&r.length?n=e?`${e}_${r.join("_")}`:`${r.join("_")}`:typeof r=="string"&&(n=e?`${e}_${r}`:r),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,r,n){let o=this.getCachedKey(e,n),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),f;if(Array.isArray(n)&&(n=n.join(" ")),n?f={iss:this.email,sub:this.email,scope:n,exp:l,iat:c}:f={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},r){for(let _ in f)if(r[_])throw new Error(`The '${_}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...ty,kid:this.keyId}:ty,p=Object.assign(f,r),C=VA.sign({header:d,payload:p,secret:this.key}),k=new Headers({authorization:`Bearer ${C}`});return this.cache.set(o,{expiration:l*1e3,headers:k}),k}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,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{e||n(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",n).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(s)}})})}};Vi.JWTAccess=dl});var pl=V(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.JWT=void 0;var ry=ey(),YA=fl(),QA=yn(),Ki=yt(),hl=class t extends QA.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 r=new t(this);return r.scopes=e,r}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let r=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Ki.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Ki.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Ki.DEFAULT_UNIVERSE}`);if(!this.apiKey&&r)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new YA.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Ki.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let r=new ry.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 r.getToken({forceRefresh:!0}),!r.idToken)throw new Error("Unknown error: Failed to fetch ID token");return r.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(r=>e(null,r),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(),n={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",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new ry.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,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((r,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),r()}catch(s){n(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 r=await this.createGToken().getCredentials(this.keyFile);return{private_key:r.privateKey,client_email:r.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Yi.JWT=hl});var gl=V(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.UserRefreshClient=no.USER_REFRESH_ACCOUNT_TYPE=void 0;var XA=yn(),ZA=yt();no.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var ml=class t extends XA.OAuth2Client{_refreshToken;constructor(e,r,n,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:r,refreshToken:n,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 r={...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 ZA.AuthClient.setMethodName(r,"fetchIdToken"),(await this.transporter.request(r)).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,r){if(r)this.fromStreamAsync(e).then(()=>r(),r);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((r,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),r()}catch(s){return n(s)}})})}static fromJSON(e){let r=new t;return r.fromJSON(e),r}};no.UserRefreshClient=ml});var _l=V(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.Impersonated=oo.IMPERSONATED_ACCOUNT_TYPE=void 0;var ny=yn(),ek=Ke(),tk=zt();oo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var yl=class t extends ny.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 ny.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,tk.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 r=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${r}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,r=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:n,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 r=0,n="";throw e instanceof ek.GaxiosError&&(r=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),r&&n?(e.message=`${r}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,r){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:r?.includeEmail??!0,useEmailAzp:r?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};oo.Impersonated=yl});var Cl=V(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.OAuthClientAuthHandler=void 0;Xo.getErrorFromOAuthErrorResponse=ok;var so=Ke(),rk=qo(),nk=["PUT","POST","PATCH"],bl=class{#e=(0,rk.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new so.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new so.Gaxios)}applyClientAuthenticationOptions(e,r){e.headers=so.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,r),r||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,r){if(r)e.headers=so.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${r}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=so.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${n}:${o}`);so.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let r=(e.method||"GET").toUpperCase();if(!nk.includes(r))throw new Error(`${r} 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"]}}}};Xo.OAuthClientAuthHandler=bl;function ok(t,e){let r=t.error,n=t.error_description,o=t.error_uri,s=`Error code ${r}`;typeof n<"u"&&(s+=`: ${n}`),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 Xi=V(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.StsCredentials=void 0;var sk=Ke(),ik=yt(),oy=Cl(),ak=zt(),wl=class t extends oy.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},r){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:r}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,r,n){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:n&&JSON.stringify(n)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:r,data:new URLSearchParams((0,ak.removeUndefinedValuesInObject)(o))};ik.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 sk.GaxiosError&&a.response?(0,oy.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};Qi.StsCredentials=wl});var Vr=V(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.BaseExternalAccountClient=xt.CLOUD_RESOURCE_MANAGER=xt.EXTERNAL_ACCOUNT_TYPE=xt.EXPIRATION_TIME_OFFSET=void 0;var uk=Ke(),ck=X("stream"),El=yt(),lk=Xi(),sy=zt(),dk=Mc(),fk="urn:ietf:params:oauth:grant-type:token-exchange",hk="urn:ietf:params:oauth:token-type:access_token",Al="https://www.googleapis.com/auth/cloud-platform",pk=3600;xt.EXPIRATION_TIME_OFFSET=300*1e3;xt.EXTERNAL_ACCOUNT_TYPE="external_account";xt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var mk="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",gk="https://sts.{universeDomain}/v1/token",kl=class t extends El.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let r=(0,sy.originalOrCamelOptions)(e),n=r.get("type");if(n&&n!==xt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${xt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=r.get("client_id"),s=r.get("client_secret");this.tokenUrl=r.get("token_url")??gk.replace("{universeDomain}",this.universeDomain);let a=r.get("subject_token_type"),c=r.get("workforce_pool_user_project"),l=r.get("service_account_impersonation_url"),f=r.get("service_account_impersonation"),d=(0,sy.originalOrCamelOptions)(f).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(r.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new lk.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=r.get("scopes")||[Al],this.cachedAccessToken=null,this.audience=r.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let p=new RegExp(mk);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=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=pk),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(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let r=await this.getRequestHeaders(),n={...t.RETRY_CONFIG,headers:r,url:`${this.cloudResourceManagerURL.toString()}${e}`};El.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=uk.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof ck.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),r={grantType:fk,audience:this.audience,requestedTokenType:hk,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Al]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(r,o,n);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 r=e.match(/\/projects\/([^/]+)/);return r?r[1]:null}async getImpersonatedAccessToken(e){let r={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};El.AuthClient.setMethodName(r,"getImpersonatedAccessToken");let n=await this.transporter.request(r),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Al]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),r=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${dk.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${r} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};xt.BaseExternalAccountClient=kl});var iy=V(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.FileSubjectTokenSupplier=void 0;var vl=X("util"),Tl=X("fs"),yk=(0,vl.promisify)(Tl.readFile??(()=>{})),_k=(0,vl.promisify)(Tl.realpath??(()=>{})),bk=(0,vl.promisify)(Tl.lstat??(()=>{})),Sl=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 _k(e),!(await bk(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 r,n=await yk(e,{encoding:"utf8"});if(this.formatType==="text"?r=n:this.formatType==="json"&&this.subjectTokenFieldName&&(r=JSON.parse(n)[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source file");return r}};Zi.FileSubjectTokenSupplier=Sl});var ay=V(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.UrlSubjectTokenSupplier=void 0;var Ck=yt(),Dl=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 r={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};Ck.AuthClient.setMethodName(r,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(r)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(r)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};ea.UrlSubjectTokenSupplier=Dl});var uy=V(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.CertificateSubjectTokenSupplier=wt.InvalidConfigurationError=wt.CertificateSourceUnavailableError=wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var ta=zt(),ra=X("fs"),na=X("crypto"),wk=X("https");wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var sr=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};wt.CertificateSourceUnavailableError=sr;var Ot=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};wt.InvalidConfigurationError=Ot;var Rl=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ot("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ot("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ot("Cannot create mTLS Agent with missing certificate or key");return new wk.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:r}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,r),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,ta.isValidFile)(e))return e;throw new sr(`Provided certificate config path is invalid: ${e}`)}let r=process.env[wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(r){if(await(0,ta.isValidFile)(r))return r;throw new sr(`Path from environment variable "${wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${r}`)}let n=(0,ta.getWellKnownCertificateConfigFileLocation)();if(await(0,ta.isValidFile)(n))return n;throw new sr(`Could not find certificate configuration file. Searched override path, the "${wt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,r;try{r=await ra.promises.readFile(e,"utf8")}catch{throw new sr(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(r),o=n?.cert_configs?.workload?.cert_path,s=n?.cert_configs?.workload?.key_path;if(!o||!s)throw new Ot(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(n){throw n instanceof Ot?n:new Ot(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,r){let n,o;try{n=await ra.promises.readFile(e),new na.X509Certificate(n)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sr(`Failed to read certificate file at ${e}: ${a}`)}try{o=await ra.promises.readFile(r),(0,na.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new sr(`Failed to read private key file at ${r}: ${a}`)}return{cert:n,key:o}}async#n(e){let r=new na.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([r.raw.toString("base64")]);try{let s=((await ra.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,f)=>{try{return new na.X509Certificate(l)}catch(d){let p=d instanceof Error?d.message:String(d);throw new Ot(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${p}`)}}),a=s.findIndex(l=>r.raw.equals(l.raw)),c;if(a===-1)c=[r,...s];else if(a===0)c=s;else throw new Ot(`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(n){if(n instanceof Ot)throw n;let o=n instanceof Error?n.message:String(n);throw new sr(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};wt.CertificateSubjectTokenSupplier=Rl});var Fl=V(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.IdentityPoolClient=void 0;var Ek=Vr(),xl=zt(),Ak=iy(),kk=ay(),cy=uy(),Sk=Xi(),ly=Ke(),Ol=class t extends Ek.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let r=(0,xl.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&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,xl.originalOrCamelOptions)(n),a=(0,xl.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 f=s.get("file"),d=s.get("url"),p=s.get("certificate"),C=s.get("headers");if(f&&d||d&&p||f&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new Ak.FileSubjectTokenSupplier({filePath:f,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new kk.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:C,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let k=new cy.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=k}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 cy.CertificateSubjectTokenSupplier){let r=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Sk.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new ly.Gaxios({agent:r})}),this.transporter=new ly.Gaxios({...this.transporter.defaults||{},agent:r})}return e}};oa.IdentityPoolClient=Ol});var Il=V(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.AwsRequestSigner=void 0;var sa=Ke(),fy=qo(),dy="AWS4-HMAC-SHA256",vk="aws4_request",Pl=class{getCredentials;region;crypto;constructor(e,r){this.getCredentials=e,this.region=r,this.crypto=(0,fy.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let r=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",s=e.body||r,a=e.headers,c=await this.getCredentials(),l=new URL(n);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await Dk({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}),d=sa.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:l.host},a||{});c.token&&sa.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let p={url:n,method:o,headers:d};return s!==void 0&&(p.body=s),p}};ia.AwsRequestSigner=Pl;async function Zo(t,e,r){return await t.signWithHmacSha256(e,r)}async function Tk(t,e,r,n,o){let s=await Zo(t,`AWS4${e}`,r),a=await Zo(t,s,n),c=await Zo(t,a,o);return await Zo(t,c,"aws4_request")}async function Dk(t){let e=sa.Gaxios.mergeHeaders(t.additionalAmzHeaders),r=t.requestPayload||"",n=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=sa.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",f=[...c.keys()].sort();f.forEach(v=>{l+=`${v}:${c.get(v)}
|
|
53
|
+
`});let d=f.join(";"),p=await t.crypto.sha256DigestHex(r),C=`${t.method.toUpperCase()}
|
|
54
54
|
${t.canonicalUri}
|
|
55
55
|
${t.canonicalQuerystring}
|
|
56
56
|
${l}
|
|
57
57
|
${d}
|
|
58
|
-
${p}`,k=`${a}/${t.region}/${n}/${vk}`,
|
|
58
|
+
${p}`,k=`${a}/${t.region}/${n}/${vk}`,_=`${dy}
|
|
59
59
|
${s}
|
|
60
60
|
${k}
|
|
61
|
-
`+await t.crypto.sha256DigestHex(b),y=await Tk(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,n),g=await Zo(t.crypto,y,C),m=`${dy} Credential=${t.securityCredentials.accessKeyId}/${k}, SignedHeaders=${d}, Signature=${(0,fy.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var hy=V(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.DefaultAwsSecurityCredentialsSupplier=void 0;var aa=yt(),Bl=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.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.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 n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};aa.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),o=await this.#r(n,r,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return aa.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return aa.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return aa.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){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}};ua.DefaultAwsSecurityCredentialsSupplier=Bl});var Ml=V(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.AwsClient=void 0;var Rk=Il(),xk=Vr(),Ok=hy(),py=zt(),Fk=Ke(),Nl=class t extends xk.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 r=(0,py.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&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,py.originalOrCamelOptions)(n);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 Ok.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 Rk.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"}),r=[];return Fk.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>r.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};ca.AwsClient=Nl});var ql=V(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.InvalidSubjectTokenError=Le.InvalidMessageFieldError=Le.InvalidCodeFieldError=Le.InvalidTokenTypeFieldError=Le.InvalidExpirationTimeFieldError=Le.InvalidSuccessFieldError=Le.InvalidVersionFieldError=Le.ExecutableResponseError=Le.ExecutableResponse=void 0;var la="urn:ietf:params:oauth:token-type:saml2",jl="urn:ietf:params:oauth:token-type:id_token",Ll="urn:ietf:params:oauth:token-type:jwt",Ul=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new da("Executable response must contain a 'version' field.");if(e.success===void 0)throw new fa("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!==la&&this.tokenType!==jl&&this.tokenType!==Ll)throw new ha(`Executable response must contain a 'token_type' field when successful and it must be one of ${jl}, ${Ll}, or ${la}.`);if(this.tokenType===la){if(!e.saml_response)throw new es(`Executable response must contain a 'saml_response' field when token_type=${la}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new es(`Executable response must contain a 'id_token' field when token_type=${jl} or ${Ll}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new pa("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)}};Le.ExecutableResponse=Ul;var ir=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Le.ExecutableResponseError=ir;var da=class extends ir{};Le.InvalidVersionFieldError=da;var fa=class extends ir{};Le.InvalidSuccessFieldError=fa;var $l=class extends ir{};Le.InvalidExpirationTimeFieldError=$l;var ha=class extends ir{};Le.InvalidTokenTypeFieldError=ha;var pa=class extends ir{};Le.InvalidCodeFieldError=pa;var ma=class extends ir{};Le.InvalidMessageFieldError=ma;var es=class extends ir{};Le.InvalidSubjectTokenError=es});var Wl=V(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.PluggableAuthHandler=io.ExecutableError=void 0;var _n=ql(),Pk=X("child_process"),zl=X("fs"),ga=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};io.ExecutableError=ga;var Hl=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((r,n)=>{let o=Pk.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(),n(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),f=new _n.ExecutableResponse(l);return r(f)}catch(l){return l instanceof _n.ExecutableResponseError?n(l):n(new _n.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return n(new ga(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await zl.promises.realpath(this.outputFile)}catch{return}if(!(await zl.promises.lstat(e)).isFile())return;let r=await zl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new _n.ExecutableResponse(n).isValid()?new _n.ExecutableResponse(n):void 0}catch(n){throw n instanceof _n.ExecutableResponseError?n:new _n.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};io.PluggableAuthHandler=Hl});var Jl=V(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.PluggableAuthClient=ao.ExecutableError=void 0;var Ik=Vr(),Bk=ql(),my=Wl(),Nk=Wl();Object.defineProperty(ao,"ExecutableError",{enumerable:!0,get:function(){return Nk.ExecutableError}});var Mk=30*1e3,gy=5*1e3,yy=120*1e3,jk="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",_y=1,Gl=class extends Ik.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=Mk;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<gy||this.timeoutMillis>yy)throw new Error(`Timeout must be between ${gy} and ${yy} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new my.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[jk]!=="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 r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>_y)throw new Error(`Version of executable is not currently supported, maximum supported version is ${_y}.`);if(!e.success)throw new my.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Bk.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}};ao.PluggableAuthClient=Gl});var Kl=V(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.ExternalAccountClient=void 0;var Lk=Vr(),Uk=Fl(),$k=Ml(),qk=Jl(),Vl=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===Lk.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new $k.AwsClient(e):e.credential_source?.executable?new qk.PluggableAuthClient(e):new Uk.IdentityPoolClient(e):null}};ya.ExternalAccountClient=Vl});var Ey=V(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.ExternalAccountAuthorizedUserClient=uo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Cy=yt(),by=Cl(),wy=Ke(),zk=X("stream"),Hk=Vr();uo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var Wk="https://sts.{universeDomain}/v1/oauthtoken",Yl=class t extends by.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};Cy.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),s=o.data;return s.res=o,s}catch(o){throw o instanceof wy.GaxiosError&&o.response?(0,by.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Ql=class extends Cy.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Yl({tokenRefreshEndpoint:e.token_url??Wk.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=Hk.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(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=wy.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof zk.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}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 r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};uo.ExternalAccountAuthorizedUserClient=Ql});var vy=V(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.GoogleAuth=Jt.GoogleAuthExceptionMessages=void 0;var Gk=X("child_process"),ts=X("fs"),Jk=Ke(),rs=$o(),Vk=X("os"),Xl=X("path"),Kk=qo(),Yk=Gc(),Qk=Vc(),Xk=Kc(),co=pl(),Ay=gl(),lo=_l(),Zk=Kl(),ns=Vr(),Zl=yt(),ky=Ey(),Sy=zt();Jt.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.
|
|
61
|
+
`+await t.crypto.sha256DigestHex(C),y=await Tk(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,n),g=await Zo(t.crypto,y,_),m=`${dy} Credential=${t.securityCredentials.accessKeyId}/${k}, SignedHeaders=${d}, Signature=${(0,fy.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:m,canonicalQuerystring:t.canonicalQuerystring}}});var hy=V(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.DefaultAwsSecurityCredentialsSupplier=void 0;var aa=yt(),Bl=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.#n)return this.#n;let r=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&r.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 n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:r};aa.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let r=new Headers;this.imdsV2SessionTokenUrl&&r.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(r,e.transporter),o=await this.#r(n,r,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let r={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return aa.AuthClient.setMethodName(r,"#getImdsV2SessionToken"),(await e.request(r)).data}async#t(e,r){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return aa.AuthClient.setMethodName(n,"#getAwsRoleName"),(await r.request(n)).data}async#r(e,r,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:r};return aa.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){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}};ua.DefaultAwsSecurityCredentialsSupplier=Bl});var Ml=V(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.AwsClient=void 0;var Rk=Il(),xk=Vr(),Ok=hy(),py=zt(),Fk=Ke(),Nl=class t extends xk.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 r=(0,py.originalOrCamelOptions)(e),n=r.get("credential_source"),o=r.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&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,py.originalOrCamelOptions)(n);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 Ok.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 Rk.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"}),r=[];return Fk.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>r.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:r}))}};ca.AwsClient=Nl});var ql=V(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.InvalidSubjectTokenError=Le.InvalidMessageFieldError=Le.InvalidCodeFieldError=Le.InvalidTokenTypeFieldError=Le.InvalidExpirationTimeFieldError=Le.InvalidSuccessFieldError=Le.InvalidVersionFieldError=Le.ExecutableResponseError=Le.ExecutableResponse=void 0;var la="urn:ietf:params:oauth:token-type:saml2",jl="urn:ietf:params:oauth:token-type:id_token",Ll="urn:ietf:params:oauth:token-type:jwt",Ul=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new da("Executable response must contain a 'version' field.");if(e.success===void 0)throw new fa("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!==la&&this.tokenType!==jl&&this.tokenType!==Ll)throw new ha(`Executable response must contain a 'token_type' field when successful and it must be one of ${jl}, ${Ll}, or ${la}.`);if(this.tokenType===la){if(!e.saml_response)throw new es(`Executable response must contain a 'saml_response' field when token_type=${la}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new es(`Executable response must contain a 'id_token' field when token_type=${jl} or ${Ll}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new pa("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)}};Le.ExecutableResponse=Ul;var ir=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Le.ExecutableResponseError=ir;var da=class extends ir{};Le.InvalidVersionFieldError=da;var fa=class extends ir{};Le.InvalidSuccessFieldError=fa;var $l=class extends ir{};Le.InvalidExpirationTimeFieldError=$l;var ha=class extends ir{};Le.InvalidTokenTypeFieldError=ha;var pa=class extends ir{};Le.InvalidCodeFieldError=pa;var ma=class extends ir{};Le.InvalidMessageFieldError=ma;var es=class extends ir{};Le.InvalidSubjectTokenError=es});var Wl=V(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.PluggableAuthHandler=io.ExecutableError=void 0;var _n=ql(),Pk=X("child_process"),zl=X("fs"),ga=class extends Error{code;constructor(e,r){super(`The executable failed with exit code: ${r} and error message: ${e}.`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}};io.ExecutableError=ga;var Hl=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((r,n)=>{let o=Pk.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(),n(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),f=new _n.ExecutableResponse(l);return r(f)}catch(l){return l instanceof _n.ExecutableResponseError?n(l):n(new _n.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return n(new ga(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await zl.promises.realpath(this.outputFile)}catch{return}if(!(await zl.promises.lstat(e)).isFile())return;let r=await zl.promises.readFile(e,{encoding:"utf8"});if(r!=="")try{let n=JSON.parse(r);return new _n.ExecutableResponse(n).isValid()?new _n.ExecutableResponse(n):void 0}catch(n){throw n instanceof _n.ExecutableResponseError?n:new _n.ExecutableResponseError(`The output file contained an invalid response: ${r}`)}}static parseCommand(e){let r=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!r)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n<r.length;n++)r[n][0]==='"'&&r[n].slice(-1)==='"'&&(r[n]=r[n].slice(1,-1));return r}};io.PluggableAuthHandler=Hl});var Jl=V(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.PluggableAuthClient=ao.ExecutableError=void 0;var Ik=Vr(),Bk=ql(),my=Wl(),Nk=Wl();Object.defineProperty(ao,"ExecutableError",{enumerable:!0,get:function(){return Nk.ExecutableError}});var Mk=30*1e3,gy=5*1e3,yy=120*1e3,jk="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",_y=1,Gl=class extends Ik.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=Mk;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<gy||this.timeoutMillis>yy)throw new Error(`Timeout must be between ${gy} and ${yy} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new my.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[jk]!=="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 r=new Map;r.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),r.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),r.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&r.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&r.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(r)}if(e.version>_y)throw new Error(`Version of executable is not currently supported, maximum supported version is ${_y}.`);if(!e.success)throw new my.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Bk.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}};ao.PluggableAuthClient=Gl});var Kl=V(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.ExternalAccountClient=void 0;var Lk=Vr(),Uk=Fl(),$k=Ml(),qk=Jl(),Vl=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===Lk.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new $k.AwsClient(e):e.credential_source?.executable?new qk.PluggableAuthClient(e):new Uk.IdentityPoolClient(e):null}};ya.ExternalAccountClient=Vl});var Ey=V(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.ExternalAccountAuthorizedUserClient=uo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Cy=yt(),by=Cl(),wy=Ke(),zk=X("stream"),Hk=Vr();uo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var Wk="https://sts.{universeDomain}/v1/oauthtoken",Yl=class t extends by.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,r){let n={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:r,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};Cy.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),s=o.data;return s.res=o,s}catch(o){throw o instanceof wy.GaxiosError&&o.response?(0,by.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Ql=class extends Cy.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let r={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Yl({tokenRefreshEndpoint:e.token_url??Wk.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:r}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=Hk.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(),r=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(r)}request(e,r){if(r)this.requestAsync(e).then(n=>r(null,n),n=>r(n,n.response));else return this.requestAsync(e)}async requestAsync(e,r=!1){let n;try{let o=await this.getRequestHeaders();e.headers=wy.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof zk.Readable;if(!r&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}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 r=new Date().getTime();return e.expiry_date?r>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};uo.ExternalAccountAuthorizedUserClient=Ql});var vy=V(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.GoogleAuth=Jt.GoogleAuthExceptionMessages=void 0;var Gk=X("child_process"),ts=X("fs"),Jk=Ke(),rs=$o(),Vk=X("os"),Xl=X("path"),Kk=qo(),Yk=Gc(),Qk=Vc(),Xk=Kc(),co=pl(),Ay=gl(),lo=_l(),Zk=Kl(),ns=Vr(),Zl=yt(),ky=Ey(),Sy=zt();Jt.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:
|
|
@@ -69,8 +69,8 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var ed
|
|
|
69
69
|
${this.toMarkdown(o,r+1)}`:`${n}- ${o}`).join(`
|
|
70
70
|
`):typeof e=="object"&&e!==null?Object.entries(e).map(([o,s])=>typeof s=="object"&&s!==null?`${n}${o}:
|
|
71
71
|
${this.toMarkdown(s,r+1)}`:`${n}${o}: ${s}`).join(`
|
|
72
|
-
`):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var ds,Vd=Me(()=>{"use strict";ds=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 r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:o=!0,prefix:s,metadata:a}=r||{},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,r,n,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:r,headers:n,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(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,r,n,o,s)}catch(f){if(c=f,l===a.maxAttempts)break;let d=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${d}ms...`,f.message),await this.delay(d)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,r),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,n,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}`)}}}});import{writeFileSync as mD,existsSync as gD,mkdirSync as yD}from"fs";import{join as A0}from"path";import{tmpdir as _D}from"os";var fs,Kd=Me(()=>{"use strict";fs=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=_D();this.baseDir=A0(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{gD(this.baseDir)||yD(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${r}-${e}-${s}${n}`}else o=`${r}-${e}${n}`;return A0(this.baseDir,o)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let o={...e,timestamp:Date.now(),sessionId:n},s=this.getFilePath(n);return mD(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Yd,go,k0=Me(()=>{"use strict";Jd();Vd();Kd();Yd=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),o=r.type+"_"+Date.now();this.registerHandler(o,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new ls(e.config);case"webhook":return new ds(e.config);case"temp-file":return new fs(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,r){let n={...this.defaultOptions,...r},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,n)?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,r,n){let o={...this.defaultOptions,...n},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(r,o)?s.success.push(c):s.failed.push(c)}catch(f){console.error(`[OutputManager] Handler ${c} failed:`,f),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,r,n){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,r,n)}},go=new Yd});import CD from"fastify";import wD from"@fastify/cors";var mh=jr(Iu(),1);import{readFileSync as kb,existsSync as hh}from"fs";import{join as ph}from"path";import{config as Sb}from"dotenv";var Pn=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:ph(process.cwd(),this.options.jsonPath);if(hh(e))try{let r=kb(e,"utf-8"),n=mh.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:ph(process.cwd(),this.options.envPath);if(hh(e))try{let r=Sb({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}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,r){this.config[e]=r}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 st(t,e=500,r="internal_error",n="api_error"){let o=new Error(t);return o.statusCode=e,o.code=r,o.type=n,o}async function gh(t,e,r){e.log.error(t);let n=t.statusCode||500,o={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(o)}import{ProxyAgent as vb}from"undici";function yh(t,e,r,n,o){let s=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([f,d])=>{d&&s.set(f,d)});let a,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let f=new AbortController,d=()=>f.abort();r.signal.addEventListener("abort",d),c.addEventListener("abort",d),a=f.signal}else a=c;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return r.httpsProxy&&(l.dispatcher=new vb(new URL(r.httpsProxy).toString())),o?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var _h="2.0.85";In();var ju=new Map,Ob=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Fb=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Pb=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Do(t,e,r){let n=c=>{if(r instanceof Headers)return r.get(c);let l=Object.keys(r).find(f=>f.toLowerCase()===c);return l?r[l]:null},o=Mu(n,Ob),s=Mu(n,Fb),a=Mu(n,Pb);(o||s||a)&&ju.set(t,{provider:t,remaining:Ch(o),limit:Ch(s),reset:Nb(a),capturedAt:Date.now()})}function Ib(t){return ju.get(t)}function Bb(){return Array.from(ju.values())}function Mu(t,e){for(let r of e){let n=t(r);if(n)return n}return null}function Ch(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Nb(t){if(!t)return null;let e=t.trim();if(!e)return null;let r=Number(e);if(Number.isFinite(r))return r>1e12?Math.floor(r/1e3):r>1e9?Math.floor(r):Math.floor(Date.now()/1e3+r);let n=Date.parse(e);if(Number.isFinite(n))return Math.floor(n/1e3);let o=Mb(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function Mb(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,r=0,n=!1;for(let o of t.matchAll(e)){n=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":r+=s;break;case"s":r+=s*1e3;break;case"m":r+=s*60*1e3;break;case"h":r+=s*60*60*1e3;break;case"d":r+=s*24*60*60*1e3;break}}return n?r:null}Js();async function jb(t,e,r,n){let o=t.body,s=t.provider,a=r.providerService.getProvider(s);if(!a)throw st(`Provider '${s}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:f}=await wh(o,a,n,t.headers,{req:t}),d=await Eh(c,l,a,r,f,n,{req:t});try{a?.baseUrl&&d?.headers&&Do(s,a.baseUrl,d.headers)}catch{}let p=await Ah(c,d,a,n,f,{req:t});return kh(p,e,o)}catch(c){let l=await Lb(t,e,r,n,c);if(l)return l;throw c}}async function Lb(t,e,r,n,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=r.configService.get("fallback"),f=it();if(!r.configService.get("Router")?.enableFallback)return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let p=m=>{let[v,..._]=m.split(","),A=v?.trim(),D=_.join(",").trim();return!A||!D?null:{provider:A,model:D,key:`${A},${D}`}},b=[];if(c){let m=a?.[s];Array.isArray(m)&&m.length>0?b.push({name:`${c}/${s}`,models:m}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&b.push({name:`global/${s}`,models:l[s]}),b.length===0)return null;let k=t.provider||"",C=t.body.model||"",y=new Set;k&&C&&(f.recordFailure(k,C,o?.message),y.add(`${k},${C}`));let g=b.reduce((m,v)=>m+v.models.length,0);t.log.warn(`Request failed for ${s}, trying ${g} fallback models across ${b.length} fallback stage(s)`);for(let m of b){t.log.info(`Trying ${m.name} fallback stage with ${m.models.length} models`);for(let v of m.models){let _=p(v);if(!_){t.log.warn(`Fallback model '${v}' is invalid, skipping`);continue}if(y.has(_.key))continue;y.add(_.key);let A=_.provider,D=_.model;try{if(!f.isAvailable(A,D)){t.log.warn(`Fallback model ${v} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${v}`);let O={...t.body};O.model=D;let q={...t,provider:A,body:O},J=r.providerService.getProvider(A);if(!J){t.log.warn(`Fallback provider '${A}' not found, skipping`);continue}let{requestBody:B,config:Y,bypass:re}=await wh(O,J,n,t.headers,{req:q}),ee=await Eh(B,Y,J,r,re,n,{req:q});try{J?.baseUrl&&ee?.headers&&Do(A,J.baseUrl,ee.headers)}catch{}let ue=await Ah(B,ee,J,n,re,{req:q});return t.log.info(`Fallback model ${v} succeeded`),f.recordSuccess(A,D),k&&C&&(To().promote(k,C,s,A,D),t.log.info(`Promoted fallback model ${A},${D} for ${k},${C}:${s}`),f.forceOpen(k,C,o?.message),t.log.info(`Marked original model ${k},${C} as unavailable`)),t.provider=A,t.body=O,kh(ue,e,O)}catch(O){f.recordFailure(A,D,O.message),t.log.warn(`Fallback model ${_.key} failed: ${O.message}`),r.recordUsage?.({provider:A,model:D,originalModel:t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:O.message,sessionId:t.usageSessionId||t.id,stream:t.body.stream});continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function wh(t,e,r,n,o){let s=JSON.parse(JSON.stringify(t)),a={},c=!1;if(c=Ub(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],a.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(s);l.body?(s=l.body,a=l.config||{}):s=l}if(!c&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let f=await l.transformRequestIn(s,e,o);f.body?(s=f.body,a={...a,...f.config}):s=f}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(s=await l.transformRequestIn(s,e,o));return{requestBody:s,config:a,bypass:c}}function Ub(t,e,r){return t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r.model]?.use.length||t.transformer?.[r.model]?.use.length===1&&t.transformer?.[r.model]?.use[0].name===e.name)}async function Eh(t,e,r,n,o,s,a){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let d=n.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(o&&typeof s.auth=="function"){let d=await s.auth(t,r);if(d.body){t=d.body;let p=e.headers||{};d.config?.headers&&(p={...p,...d.config.headers},delete p.host,delete d.config.headers),e={...e,...d.config,headers:p}}else t=d}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];let f=await yh(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,n.log);if(!f.ok){let d=await f.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${f.status}): ${d}`),st(`Error from provider(${r.name},${t.model}: ${f.status}): ${d}`,f.status,"provider_response_error")}return f}async function Ah(t,e,r,n,o,s){let a=e;if(!o&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));return!o&&n.transformResponseIn&&(a=await n.transformResponseIn(a,s)),a}function kh(t,e,r){return t.ok||e.code(t.status),r.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(t.body)):t.json()}var Lu=async t=>{t.get("/",async()=>({message:"LLMs API",version:_h})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:it().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,o)=>jb(n,o,t,r));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(r,n)=>{let{name:o,baseUrl:s,apiKey:a,models:c}=r.body;if(!o?.trim())throw st("Provider name is required",400,"invalid_request");if(!s||!$b(s))throw st("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw st("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw st("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(r.body.name))throw st(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(r.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=t.providerService.getProvider(r.params.id);if(!n)throw st("Provider not found",404,"provider_not_found");return n}),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(r,n)=>{let o=t.providerService.updateProvider(r.params.id,r.body);if(!o)throw st("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!t.providerService.deleteProvider(r.params.id))throw st("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(r,n)=>{if(!t.providerService.toggleProvider(r.params.id,r.body.enabled))throw st("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function $b(t){try{return new URL(t),!0}catch{return!1}}var Bn=class{constructor(e,r,n){this.configService=e;this.transformerService=r;this.logger=n;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(r=>{try{if(!r.name||!r.api_base_url||!r.api_key)return;let n={};r.transformer&&Object.keys(r.transformer).forEach(o=>{o==="use"?Array.isArray(r.transformer.use)&&(n.use=r.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(r.transformer[o]?.use)&&(n[o]={use:r.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:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],quotaToken:r.quota_token,transformer:r.transformer?n:void 0}),this.logger.info(`${r.name} provider registered`)}catch(n){this.logger.error(`${r.name} provider registered error: ${n}`)}})}registerProvider(e){let r={...e};return this.providers.set(r.name,r),e.models.forEach(n=>{let o=`${r.name},${n}`,s={provider:r.name,model:n,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(n)||this.modelRoutes.set(n,s)}),r}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,r){let n=this.providers.get(e);if(!n)return null;let o={...n,...r,updatedAt:new Date};return this.providers.set(e,o),r.models&&(n.models.forEach(s=>{let a=`${n.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),r.models.forEach(s=>{let a=`${n.name},${s}`,c={provider:n.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let o=`${r.name},${n}`;this.modelRoutes.delete(o),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,r){return!!this.providers.get(e)}resolveModelRoute(e){let r=this.modelRoutes.get(e);if(!r)return null;let n=this.providers.get(r.provider);return n?{provider:n,originalModel:e,targetModel:r.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push(n),e.push(`${r.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((r,n)=>{if(Array.isArray(n)){let[o,s={}]=n;r[o]=s}else r[n]={};return r},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push({id:n,object:"model",owned_by:r.name,provider:r.name}),e.push({id:`${r.name},${n}`,object:"model",owned_by:r.name,provider:r.name})})}),{object:"list",data:e}}};var Ve=[];for(let t=0;t<256;++t)Ve.push((t+256).toString(16).slice(1));function Sh(t,e=0){return(Ve[t[e+0]]+Ve[t[e+1]]+Ve[t[e+2]]+Ve[t[e+3]]+"-"+Ve[t[e+4]]+Ve[t[e+5]]+"-"+Ve[t[e+6]]+Ve[t[e+7]]+"-"+Ve[t[e+8]]+Ve[t[e+9]]+"-"+Ve[t[e+10]]+Ve[t[e+11]]+Ve[t[e+12]]+Ve[t[e+13]]+Ve[t[e+14]]+Ve[t[e+15]]).toLowerCase()}import{randomFillSync as qb}from"crypto";var Ys=new Uint8Array(256),Ks=Ys.length;function Uu(){return Ks>Ys.length-16&&(qb(Ys),Ks=0),Ys.slice(Ks,Ks+=16)}import{randomUUID as zb}from"crypto";var $u={randomUUID:zb};function Hb(t,e,r){if($u.randomUUID&&!e&&!t)return $u.randomUUID();t=t||{};let n=t.random??t.rng?.()??Uu();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[r+o]=n[o];return e}return Sh(n)}var Yt=Hb;var vh=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Th=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var Qs=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,r){let n={};return this.useBearer?(n.authorization=`Bearer ${r.apiKey}`,n["x-api-key"]=void 0):(n["x-api-key"]=r.apiKey,n.authorization=void 0),{body:e,config:{headers:n}}}async transformRequestOut(e){let r=[];if(e.system){if(typeof e.system=="string")r.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}));r.push({role:"system",content:s})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(s=>{if(s.role==="user"||s.role==="assistant"){if(typeof s.content=="string"){r.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 f={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};r.push(f)});let c=s.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&r.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?Th(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(d=>d.type==="text"&&d.text);c.length&&(a.content=c.map(d=>d.text).join(`
|
|
73
|
-
`));let l=s.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(a.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let f=s.content.find(d=>d.type==="thinking");f&&(a.thinking={content:f.thinking,signature:f.signature}),r.push(a)}return}}});let o={messages:r,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:vh(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 transformResponseIn(e,r){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,r);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,r);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(r=>({type:"function",function:{name:r.name,description:r.description||"",parameters:r.input_schema}}))}async convertOpenAIStreamToAnthropic(e,r){return new ReadableStream({start:async o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,c=null,l="unknown",f=!1,d=!1,p=!1,
|
|
72
|
+
`):`${n}${e}`}async output(e,r={}){try{let n=this.formatData(e,r);switch(this.config.level||"log"){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;case"debug":console.debug(n);break;case"log":default:console.log(n);break}return!0}catch(n){return console.error("[ConsoleOutputHandler] Output failed:",n),!1}}}});var ds,Vd=Me(()=>{"use strict";ds=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 r=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${r}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,r){let{format:n="json",timestamp:o=!0,prefix:s,metadata:a}=r||{},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,r,n,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:r,headers:n,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(r=>setTimeout(r,e))}async sendWithRetry(e,r,n,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,r,n,o,s)}catch(f){if(c=f,l===a.maxAttempts)break;let d=a.backoffMs*Math.pow(2,l-1);console.warn(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${d}ms...`,f.message),await this.delay(d)}throw c}async output(e,r={}){let n=r.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,r),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,n,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}`)}}}});import{writeFileSync as mD,existsSync as gD,mkdirSync as yD}from"fs";import{join as A0}from"path";import{tmpdir as _D}from"os";var fs,Kd=Me(()=>{"use strict";fs=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let r=_D();this.baseDir=A0(r,this.config.subdirectory),this.ensureDir()}ensureDir(){try{gD(this.baseDir)||yD(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let r=e.match(/_session_([a-f0-9-]+)/i);return r?r[1]:null}catch{return null}}getFilePath(e){let r=this.config.prefix||"session",n=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${r}-${e}-${s}${n}`}else o=`${r}-${e}${n}`;return A0(this.baseDir,o)}async output(e,r={}){try{let n=r.metadata?.sessionId;if(!n)return!1;let o={...e,timestamp:Date.now(),sessionId:n},s=this.getFilePath(n);return mD(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Yd,go,k0=Me(()=>{"use strict";Jd();Vd();Kd();Yd=class{handlers=new Map;defaultOptions={};registerHandler(e,r){this.handlers.set(e,r)}registerHandlers(e){for(let r of e)if(r.enabled!==!1)try{let n=this.createHandler(r),o=r.type+"_"+Date.now();this.registerHandler(o,n)}catch(n){console.error(`[OutputManager] Failed to register ${r.type} handler:`,n)}}createHandler(e){switch(e.type){case"console":return new ls(e.config);case"webhook":return new ds(e.config);case"temp-file":return new fs(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,r){let n={...this.defaultOptions,...r},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,n)?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,r,n){let o={...this.defaultOptions,...n},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(r,o)?s.success.push(c):s.failed.push(c)}catch(f){console.error(`[OutputManager] Handler ${c} failed:`,f),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,r,n){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,r,n)}},go=new Yd});import CD from"fastify";import wD from"@fastify/cors";var mh=jr(Iu(),1);import{readFileSync as kb,existsSync as hh}from"fs";import{join as ph}from"path";import{config as Sb}from"dotenv";var Pn=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:ph(process.cwd(),this.options.jsonPath);if(hh(e))try{let r=kb(e,"utf-8"),n=mh.default.parse(r);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(r){console.warn(`Failed to load JSON config from ${e}:`,r)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:ph(process.cwd(),this.options.envPath);if(hh(e))try{let r=Sb({path:e});r.parsed&&(this.config={...this.config,...this.parseEnvConfig(r.parsed)})}catch(r){console.warn(`Failed to load .env config from ${e}:`,r)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let r={};return Object.assign(r,e),r}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,r){let n=this.config[e];return n!==void 0?n:r}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,r){this.config[e]=r}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 st(t,e=500,r="internal_error",n="api_error"){let o=new Error(t);return o.statusCode=e,o.code=r,o.type=n,o}async function gh(t,e,r){e.log.error(t);let n=t.statusCode||500,o={error:{message:t.message+t.stack||"Internal Server Error",type:t.type||"api_error",code:t.code||"internal_error"}};return r.code(n).send(o)}import{ProxyAgent as vb}from"undici";function yh(t,e,r,n,o){let s=new Headers({"Content-Type":"application/json"});r.headers&&Object.entries(r.headers).forEach(([f,d])=>{d&&s.set(f,d)});let a,c=AbortSignal.timeout(r.TIMEOUT??60*1e3*60);if(r.signal){let f=new AbortController,d=()=>f.abort();r.signal.addEventListener("abort",d),c.addEventListener("abort",d),a=f.signal}else a=c;let l={method:"POST",headers:s,body:JSON.stringify(e),signal:a};return r.httpsProxy&&(l.dispatcher=new vb(new URL(r.httpsProxy).toString())),o?.debug({reqId:n.req.id,request:l,headers:Object.fromEntries(s.entries()),requestUrl:typeof t=="string"?t:t.toString(),useProxy:r.httpsProxy},"final request"),fetch(typeof t=="string"?t:t.toString(),l)}var _h="2.0.85";In();var ju=new Map,Ob=["x-ratelimit-remaining-tokens","x-ratelimit-remaining-requests","x-ratelimit-remaining"],Fb=["x-ratelimit-limit-tokens","x-ratelimit-limit-requests","x-ratelimit-limit"],Pb=["x-ratelimit-reset-tokens","x-ratelimit-reset-requests","x-ratelimit-reset"];function Do(t,e,r){let n=c=>{if(r instanceof Headers)return r.get(c);let l=Object.keys(r).find(f=>f.toLowerCase()===c);return l?r[l]:null},o=Mu(n,Ob),s=Mu(n,Fb),a=Mu(n,Pb);(o||s||a)&&ju.set(t,{provider:t,remaining:Ch(o),limit:Ch(s),reset:Nb(a),capturedAt:Date.now()})}function Ib(t){return ju.get(t)}function Bb(){return Array.from(ju.values())}function Mu(t,e){for(let r of e){let n=t(r);if(n)return n}return null}function Ch(t){if(!t)return null;let e=Number(t.trim().replace(/,/g,""));return Number.isFinite(e)?e:null}function Nb(t){if(!t)return null;let e=t.trim();if(!e)return null;let r=Number(e);if(Number.isFinite(r))return r>1e12?Math.floor(r/1e3):r>1e9?Math.floor(r):Math.floor(Date.now()/1e3+r);let n=Date.parse(e);if(Number.isFinite(n))return Math.floor(n/1e3);let o=Mb(e);return o===null?null:Math.floor((Date.now()+o)/1e3)}function Mb(t){let e=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/gi,r=0,n=!1;for(let o of t.matchAll(e)){n=!0;let s=Number(o[1]),a=o[2].toLowerCase();if(Number.isFinite(s))switch(a){case"ms":r+=s;break;case"s":r+=s*1e3;break;case"m":r+=s*60*1e3;break;case"h":r+=s*60*60*1e3;break;case"d":r+=s*24*60*60*1e3;break}}return n?r:null}Js();async function jb(t,e,r,n){let o=t.body,s=t.provider,a=r.providerService.getProvider(s);if(!a)throw st(`Provider '${s}' not found`,404,"provider_not_found");try{let{requestBody:c,config:l,bypass:f}=await wh(o,a,n,t.headers,{req:t}),d=await Eh(c,l,a,r,f,n,{req:t});try{a?.baseUrl&&d?.headers&&Do(s,a.baseUrl,d.headers)}catch{}let p=await Ah(c,d,a,n,f,{req:t});return kh(p,e,o)}catch(c){let l=await Lb(t,e,r,n,c);if(l)return l;throw c}}async function Lb(t,e,r,n,o){let s=t.scenarioType||"default",a=t.familyFallback,c=t.modelFamily,l=r.configService.get("fallback"),f=it();if(!r.configService.get("Router")?.enableFallback)return t.log.info("Fallback disabled by configuration, skipping fallback attempts"),null;let p=m=>{let[v,...b]=m.split(","),A=v?.trim(),D=b.join(",").trim();return!A||!D?null:{provider:A,model:D,key:`${A},${D}`}},C=[];if(c){let m=a?.[s];Array.isArray(m)&&m.length>0?C.push({name:`${c}/${s}`,models:m}):t.log.warn(`No ${c} fallback configured for ${s}; will try global ${s} fallback`)}if(Array.isArray(l?.[s])&&l[s].length>0&&C.push({name:`global/${s}`,models:l[s]}),C.length===0)return null;let k=t.provider||"",_=t.body.model||"",y=new Set;k&&_&&(f.recordFailure(k,_,o?.message),y.add(`${k},${_}`),r.recordUsage?.({provider:k,model:_,originalModel:t.originalModel||_,scenarioType:s,modelFamily:t.modelFamily,errorMessage:o?.message||String(o),sessionId:t.usageSessionId||t.id,stream:t.body.stream,inputTokens:t.tokenCount||0}));let g=C.reduce((m,v)=>m+v.models.length,0);t.log.warn(`Request failed for ${s}, trying ${g} fallback models across ${C.length} fallback stage(s)`);for(let m of C){t.log.info(`Trying ${m.name} fallback stage with ${m.models.length} models`);for(let v of m.models){let b=p(v);if(!b){t.log.warn(`Fallback model '${v}' is invalid, skipping`);continue}if(y.has(b.key))continue;y.add(b.key);let A=b.provider,D=b.model;try{if(!f.isAvailable(A,D)){t.log.warn(`Fallback model ${v} unavailable (fail pool), skipping`);continue}t.log.info(`Trying fallback model: ${v}`);let O={...t.body};O.model=D;let q={...t,provider:A,body:O},J=r.providerService.getProvider(A);if(!J){t.log.warn(`Fallback provider '${A}' not found, skipping`);continue}let{requestBody:B,config:Y,bypass:re}=await wh(O,J,n,t.headers,{req:q}),ee=await Eh(B,Y,J,r,re,n,{req:q});try{J?.baseUrl&&ee?.headers&&Do(A,J.baseUrl,ee.headers)}catch{}let ue=await Ah(B,ee,J,n,re,{req:q});return t.log.info(`Fallback model ${v} succeeded`),f.recordSuccess(A,D),k&&_&&(To().promote(k,_,s,A,D),t.log.info(`Promoted fallback model ${A},${D} for ${k},${_}:${s}`),f.forceOpen(k,_,o?.message),t.log.info(`Marked original model ${k},${_} as unavailable`)),t.provider=A,t.body=O,kh(ue,e,O)}catch(O){f.recordFailure(A,D,O.message),t.log.warn(`Fallback model ${b.key} failed: ${O.message}`),r.recordUsage?.({provider:A,model:D,originalModel:t.body.model,scenarioType:s,modelFamily:t.modelFamily,errorMessage:O.message,sessionId:t.usageSessionId||t.id,stream:t.body.stream});continue}}}return t.log.error(`All fallback models failed for ${s}`),null}async function wh(t,e,r,n,o){let s=JSON.parse(JSON.stringify(t)),a={},c=!1;if(c=Ub(e,r,t),c&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],a.headers=n),!c&&typeof r.transformRequestOut=="function"){let l=await r.transformRequestOut(s);l.body?(s=l.body,a=l.config||{}):s=l}if(!c&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let f=await l.transformRequestIn(s,e,o);f.body?(s=f.body,a={...a,...f.config}):s=f}if(!c&&e.transformer?.[t.model]?.use?.length)for(let l of e.transformer[t.model].use)!l||typeof l.transformRequestIn!="function"||(s=await l.transformRequestIn(s,e,o));return{requestBody:s,config:a,bypass:c}}function Ub(t,e,r){return t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r.model]?.use.length||t.transformer?.[r.model]?.use.length===1&&t.transformer?.[r.model]?.use[0].name===e.name)}async function Eh(t,e,r,n,o,s,a){let c=e.url||new URL(r.baseUrl);if(!e.TIMEOUT){let d=n.configService.get("API_TIMEOUT_MS");d&&(e.TIMEOUT=typeof d=="string"?parseInt(d,10):d)}if(o&&typeof s.auth=="function"){let d=await s.auth(t,r);if(d.body){t=d.body;let p=e.headers||{};d.config?.headers&&(p={...p,...d.config.headers},delete p.host,delete d.config.headers),e={...e,...d.config,headers:p}}else t=d}let l={Authorization:`Bearer ${r.apiKey}`,...e?.headers||{}};for(let d in l)(l[d]==="undefined"||["authorization","Authorization"].includes(d)&&l[d]?.includes("undefined"))&&delete l[d];let f=await yh(c,t,{httpsProxy:n.configService.getHttpsProxy(),...e,headers:JSON.parse(JSON.stringify(l))},a,n.log);if(!f.ok){let d=await f.text();throw n.log.error(`[provider_response_error] Error from provider(${r.name},${t.model}: ${f.status}): ${d}`),st(`Error from provider(${r.name},${t.model}: ${f.status}): ${d}`,f.status,"provider_response_error")}return f}async function Ah(t,e,r,n,o,s){let a=e;if(!o&&r.transformer?.use?.length)for(let c of Array.from(r.transformer.use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));if(!o&&r.transformer?.[t.model]?.use?.length)for(let c of Array.from(r.transformer[t.model].use).reverse())!c||typeof c.transformResponseOut!="function"||(a=await c.transformResponseOut(a,s));return!o&&n.transformResponseIn&&(a=await n.transformResponseIn(a,s)),a}function kh(t,e,r){return t.ok||e.code(t.status),r.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(t.body)):t.json()}var Lu=async t=>{t.get("/",async()=>({message:"LLMs API",version:_h})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()})),t.get("/providers/health",async()=>({states:it().getAllStates().map(o=>({provider:o.provider,model:o.model,status:o.status,failureCount:o.failureCount,successCount:o.successCount,lastFailureTime:o.lastFailureTime,lastError:o.lastError})),timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:r}of e)r.endPoint&&t.post(r.endPoint,async(n,o)=>jb(n,o,t,r));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(r,n)=>{let{name:o,baseUrl:s,apiKey:a,models:c}=r.body;if(!o?.trim())throw st("Provider name is required",400,"invalid_request");if(!s||!$b(s))throw st("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw st("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw st("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(r.body.name))throw st(`Provider with name '${r.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(r.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{let n=t.providerService.getProvider(r.params.id);if(!n)throw st("Provider not found",404,"provider_not_found");return n}),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(r,n)=>{let o=t.providerService.updateProvider(r.params.id,r.body);if(!o)throw st("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async r=>{if(!t.providerService.deleteProvider(r.params.id))throw st("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(r,n)=>{if(!t.providerService.toggleProvider(r.params.id,r.body.enabled))throw st("Provider not found",404,"provider_not_found");return{message:`Provider ${r.body.enabled?"enabled":"disabled"} successfully`}})};function $b(t){try{return new URL(t),!0}catch{return!1}}var Bn=class{constructor(e,r,n){this.configService=e;this.transformerService=r;this.logger=n;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(r=>{try{if(!r.name||!r.api_base_url||!r.api_key)return;let n={};r.transformer&&Object.keys(r.transformer).forEach(o=>{o==="use"?Array.isArray(r.transformer.use)&&(n.use=r.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(r.transformer[o]?.use)&&(n[o]={use:r.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:r.name,baseUrl:r.api_base_url,apiKey:r.api_key,models:r.models||[],quotaToken:r.quota_token,transformer:r.transformer?n:void 0}),this.logger.info(`${r.name} provider registered`)}catch(n){this.logger.error(`${r.name} provider registered error: ${n}`)}})}registerProvider(e){let r={...e};return this.providers.set(r.name,r),e.models.forEach(n=>{let o=`${r.name},${n}`,s={provider:r.name,model:n,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(n)||this.modelRoutes.set(n,s)}),r}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,r){let n=this.providers.get(e);if(!n)return null;let o={...n,...r,updatedAt:new Date};return this.providers.set(e,o),r.models&&(n.models.forEach(s=>{let a=`${n.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),r.models.forEach(s=>{let a=`${n.name},${s}`,c={provider:n.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let r=this.providers.get(e);return r?(r.models.forEach(n=>{let o=`${r.name},${n}`;this.modelRoutes.delete(o),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,r){return!!this.providers.get(e)}resolveModelRoute(e){let r=this.modelRoutes.get(e);if(!r)return null;let n=this.providers.get(r.provider);return n?{provider:n,originalModel:e,targetModel:r.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push(n),e.push(`${r.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((r,n)=>{if(Array.isArray(n)){let[o,s={}]=n;r[o]=s}else r[n]={};return r},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(r=>{r.models.forEach(n=>{e.push({id:n,object:"model",owned_by:r.name,provider:r.name}),e.push({id:`${r.name},${n}`,object:"model",owned_by:r.name,provider:r.name})})}),{object:"list",data:e}}};var Ve=[];for(let t=0;t<256;++t)Ve.push((t+256).toString(16).slice(1));function Sh(t,e=0){return(Ve[t[e+0]]+Ve[t[e+1]]+Ve[t[e+2]]+Ve[t[e+3]]+"-"+Ve[t[e+4]]+Ve[t[e+5]]+"-"+Ve[t[e+6]]+Ve[t[e+7]]+"-"+Ve[t[e+8]]+Ve[t[e+9]]+"-"+Ve[t[e+10]]+Ve[t[e+11]]+Ve[t[e+12]]+Ve[t[e+13]]+Ve[t[e+14]]+Ve[t[e+15]]).toLowerCase()}import{randomFillSync as qb}from"crypto";var Ys=new Uint8Array(256),Ks=Ys.length;function Uu(){return Ks>Ys.length-16&&(qb(Ys),Ks=0),Ys.slice(Ks,Ks+=16)}import{randomUUID as zb}from"crypto";var $u={randomUUID:zb};function Hb(t,e,r){if($u.randomUUID&&!e&&!t)return $u.randomUUID();t=t||{};let n=t.random??t.rng?.()??Uu();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[r+o]=n[o];return e}return Sh(n)}var Yt=Hb;var vh=t=>t<=0?"none":t<=1024?"low":t<=8192?"medium":"high";var Th=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var Qs=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,r){let n={};return this.useBearer?(n.authorization=`Bearer ${r.apiKey}`,n["x-api-key"]=void 0):(n["x-api-key"]=r.apiKey,n.authorization=void 0),{body:e,config:{headers:n}}}async transformRequestOut(e){let r=[];if(e.system){if(typeof e.system=="string")r.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}));r.push({role:"system",content:s})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(s=>{if(s.role==="user"||s.role==="assistant"){if(typeof s.content=="string"){r.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 f={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};r.push(f)});let c=s.content.filter(l=>l.type==="text"&&l.text||l.type==="image"&&l.source);c.length&&r.push({role:"user",content:c.map(l=>l?.type==="image"?{type:"image_url",image_url:{url:l.source?.type==="base64"?Th(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(d=>d.type==="text"&&d.text);c.length&&(a.content=c.map(d=>d.text).join(`
|
|
73
|
+
`));let l=s.content.filter(d=>d.type==="tool_use"&&d.id);l.length&&(a.tool_calls=l.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}})));let f=s.content.find(d=>d.type==="thinking");f&&(a.thinking={content:f.thinking,signature:f.signature}),r.push(a)}return}}});let o={messages:r,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:vh(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 transformResponseIn(e,r){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,r);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,r);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(r=>({type:"function",function:{name:r.name,description:r.description||"",parameters:r.input_schema}}))}async convertOpenAIStreamToAnthropic(e,r){return new ReadableStream({start:async o=>{let s=new TextEncoder,a=`msg_${Date.now()}`,c=null,l="unknown",f=!1,d=!1,p=!1,C=new Map,k=new Map,_=0,y=0,g=0,m=!1,v=!1,b=0,A=-1,D=()=>{let B=b;return b++,B},O=B=>{if(!m)try{o.enqueue(B);let Y=new TextDecoder().decode(B);this.logger.debug({reqId:r.req.id,data:Y,type:"send data"})}catch(Y){if(Y instanceof TypeError&&Y.message.includes("Controller is already closed"))m=!0;else throw this.logger.debug({reqId:r.req.id,error:Y instanceof Error?Y.message:String(Y),type:"send data error"}),Y}},q=()=>{if(!m)try{if(A>=0){let Y={type:"content_block_stop",index:A};O(s.encode(`event: content_block_stop
|
|
74
74
|
data: ${JSON.stringify(Y)}
|
|
75
75
|
|
|
76
76
|
`)),A=-1}c?(O(s.encode(`event: message_delta
|
|
@@ -83,7 +83,7 @@ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_
|
|
|
83
83
|
data: ${JSON.stringify(B)}
|
|
84
84
|
|
|
85
85
|
`)),o.close(),m=!0}catch(B){if(B instanceof TypeError&&B.message.includes("Controller is already closed"))m=!0;else throw B}},J=null;try{J=e.getReader();let B=new TextDecoder,Y="";for(;!m;){let{done:re,value:ee}=await J.read();if(re)break;Y+=B.decode(ee,{stream:!0});let ue=Y.split(`
|
|
86
|
-
`);Y=ue.pop()||"";for(let fe of ue){if(m||p)break;if(!fe.startsWith("data:"))continue;let ke=fe.slice(5).trim();if(this.logger.debug({reqId:r.req.id,type:"recieved data",data:ke}),ke!=="[DONE]")try{let ie=JSON.parse(ke);if(
|
|
86
|
+
`);Y=ue.pop()||"";for(let fe of ue){if(m||p)break;if(!fe.startsWith("data:"))continue;let ke=fe.slice(5).trim();if(this.logger.debug({reqId:r.req.id,type:"recieved data",data:ke}),ke!=="[DONE]")try{let ie=JSON.parse(ke);if(_++,this.logger.debug({reqId:r.req.id,response:ie,tppe:"Original Response"}),ie.error){let G={type:"error",message:{type:"api_error",message:JSON.stringify(ie.error)}};O(s.encode(`event: error
|
|
87
87
|
data: ${JSON.stringify(G)}
|
|
88
88
|
|
|
89
89
|
`));continue}if(l=ie.model||l,!f&&!m&&!p){f=!0;let G={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};O(s.encode(`event: message_start
|
|
@@ -125,7 +125,7 @@ data: ${JSON.stringify(xe)}
|
|
|
125
125
|
`)),A=-1}let De=D();k.set(ce,De);let W=K.id||`call_${Date.now()}_${ce}`,de=K.function?.name||`tool_${ce}`,_e={type:"content_block_start",index:De,content_block:{type:"tool_use",id:W,name:de,input:{}}};O(s.encode(`event: content_block_start
|
|
126
126
|
data: ${JSON.stringify(_e)}
|
|
127
127
|
|
|
128
|
-
`)),A=De;let It={id:W,name:de,arguments:"",contentBlockIndex:De};
|
|
128
|
+
`)),A=De;let It={id:W,name:de,arguments:"",contentBlockIndex:De};C.set(ce,It)}else if(K.id&&K.function?.name){let De=C.get(ce);De.id.startsWith("call_")&&De.name.startsWith("tool_")&&(De.id=K.id,De.name=K.function.name)}if(K.function?.arguments&&!m&&!p){let De=k.get(ce);if(De===void 0)continue;let W=C.get(ce);W&&(W.arguments+=K.function.arguments);try{let de={type:"content_block_delta",index:De,delta:{type:"input_json_delta",partial_json:K.function.arguments}};O(s.encode(`event: content_block_delta
|
|
129
129
|
data: ${JSON.stringify(de)}
|
|
130
130
|
|
|
131
131
|
`))}catch{try{let de=K.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),_e={type:"content_block_delta",index:De,delta:{type:"input_json_delta",partial_json:de}};O(s.encode(`event: content_block_delta
|
|
@@ -134,118 +134,118 @@ data: ${JSON.stringify(_e)}
|
|
|
134
134
|
`))}catch(de){console.error(de)}}}}}if(me?.finish_reason&&!m&&!p){if(y===0&&g===0&&console.error("Warning: No content in the stream response!"),A>=0){let G={type:"content_block_stop",index:A};O(s.encode(`event: content_block_stop
|
|
135
135
|
data: ${JSON.stringify(G)}
|
|
136
136
|
|
|
137
|
-
`)),A=-1}m||(c={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[me.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:(ie.usage?.prompt_tokens||0)-(ie.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:ie.usage?.completion_tokens||0,cache_read_input_tokens:ie.usage?.prompt_tokens_details?.cached_tokens||0}});break}}catch(ie){this.logger?.error(`parseError: ${ie.name} message: ${ie.message} stack: ${ie.stack} data: ${ke}`)}}}q()}catch(B){if(!m)try{o.error(B)}catch(Y){console.error(Y)}}finally{if(J)try{J.releaseLock()}catch(B){console.error(B)}}},cancel:o=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${o}`)}})}convertOpenAIResponseToAnthropic(e,r){this.logger.debug({reqId:r.req.id,response:e},"Original OpenAI response");try{let n=e.choices[0];if(!n)throw new Error("No choices found in OpenAI response");let o=[];if(n.message.annotations){let a=`srvtoolu_${Yt()}`;o.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:a,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&o.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(a=>{let c={};try{let l=a.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:a.function.arguments||""}}o.push({type:"tool_use",id:a.id,name:a.function.name,input:c})}),n.message?.thinking?.content&&o.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let s={id:e.id,type:"message",role:"assistant",model:e.model,content:o,stop_reason:n.finish_reason==="stop"?"end_turn":n.finish_reason==="length"?"max_tokens":n.finish_reason==="tool_calls"?"tool_use":n.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:(e.usage?.prompt_tokens||0)-(e.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:e.usage?.completion_tokens||0,cache_read_input_tokens:e.usage?.prompt_tokens_details?.cached_tokens||0}};return this.logger.debug({reqId:r.req.id,result:s},"Conversion complete, final Anthropic response"),s}catch{throw st(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Nn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function Wb(t,e){t.includes("null")&&(e.nullable=!0);let r=t.filter(n=>n!=="null");if(r.length===1){let n=r[0].toUpperCase();e.type=Object.values(Nn).includes(n)?n:Nn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let o=n.toUpperCase();e.anyOf.push({type:Object.values(Nn).includes(o)?o:Nn.TYPE_UNSPECIFIED})}}}function Ro(t){let e={},r=["items"],n=["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)&&Wb(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(Nn).includes(l)?l:Nn.TYPE_UNSPECIFIED}else if(r.includes(a))e[a]=Ro(c);else if(n.includes(a)){let l=[];for(let f of c){if(f.type=="null"){e.nullable=!0;continue}l.push(Ro(f))}e[a]=l}else if(o.includes(a)){let l={};for(let[f,d]of Object.entries(c))l[f]=Ro(d);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}return e}function Gb(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=Ro(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Ro(e.response));return t}function Xs(t){let e=[],r=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));r?.length&&e.push(Gb({functionDeclarations:r})),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 f;l.role==="assistant"?f="model":(["user","system"].includes(l.role),f="user");let d=[];if(typeof l.content=="string"){let p={text:l.content};l?.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),d.push(p)}else Array.isArray(l.content)?d.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?d.push({text:l.content.text}):d.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&d.push(...l.tool_calls.map((p,
|
|
138
|
-
`)||"",d={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:f,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:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata?.candidatesTokenCount||0,prompt_tokens:n.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n.usageMetadata?.cachedContentTokenCount||0},total_tokens:n.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(d),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,o=new TextEncoder,s=!1,a=!1,c=!1,l="",f=0,d=-1,p=new ReadableStream({async start(
|
|
137
|
+
`)),A=-1}m||(c={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[me.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:(ie.usage?.prompt_tokens||0)-(ie.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:ie.usage?.completion_tokens||0,cache_read_input_tokens:ie.usage?.prompt_tokens_details?.cached_tokens||0}});break}}catch(ie){this.logger?.error(`parseError: ${ie.name} message: ${ie.message} stack: ${ie.stack} data: ${ke}`)}}}q()}catch(B){if(!m)try{o.error(B)}catch(Y){console.error(Y)}}finally{if(J)try{J.releaseLock()}catch(B){console.error(B)}}},cancel:o=>{this.logger.debug({reqId:r.req.id},`cancle stream: ${o}`)}})}convertOpenAIResponseToAnthropic(e,r){this.logger.debug({reqId:r.req.id,response:e},"Original OpenAI response");try{let n=e.choices[0];if(!n)throw new Error("No choices found in OpenAI response");let o=[];if(n.message.annotations){let a=`srvtoolu_${Yt()}`;o.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:a,content:n.message.annotations.map(c=>({type:"web_search_result",url:c.url_citation.url,title:c.url_citation.title}))})}n.message.content&&o.push({type:"text",text:n.message.content}),n.message.tool_calls&&n.message.tool_calls.length>0&&n.message.tool_calls.forEach(a=>{let c={};try{let l=a.function.arguments||"{}";typeof l=="object"?c=l:typeof l=="string"&&(c=JSON.parse(l))}catch{c={text:a.function.arguments||""}}o.push({type:"tool_use",id:a.id,name:a.function.name,input:c})}),n.message?.thinking?.content&&o.push({type:"thinking",thinking:n.message.thinking.content,signature:n.message.thinking.signature});let s={id:e.id,type:"message",role:"assistant",model:e.model,content:o,stop_reason:n.finish_reason==="stop"?"end_turn":n.finish_reason==="length"?"max_tokens":n.finish_reason==="tool_calls"?"tool_use":n.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:(e.usage?.prompt_tokens||0)-(e.usage?.prompt_tokens_details?.cached_tokens||0),output_tokens:e.usage?.completion_tokens||0,cache_read_input_tokens:e.usage?.prompt_tokens_details?.cached_tokens||0}};return this.logger.debug({reqId:r.req.id,result:s},"Conversion complete, final Anthropic response"),s}catch{throw st(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Nn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function Wb(t,e){t.includes("null")&&(e.nullable=!0);let r=t.filter(n=>n!=="null");if(r.length===1){let n=r[0].toUpperCase();e.type=Object.values(Nn).includes(n)?n:Nn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of r){let o=n.toUpperCase();e.anyOf.push({type:Object.values(Nn).includes(o)?o:Nn.TYPE_UNSPECIFIED})}}}function Ro(t){let e={},r=["items"],n=["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)&&Wb(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(Nn).includes(l)?l:Nn.TYPE_UNSPECIFIED}else if(r.includes(a))e[a]=Ro(c);else if(n.includes(a)){let l=[];for(let f of c){if(f.type=="null"){e.nullable=!0;continue}l.push(Ro(f))}e[a]=l}else if(o.includes(a)){let l={};for(let[f,d]of Object.entries(c))l[f]=Ro(d);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}return e}function Gb(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=Ro(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Ro(e.response));return t}function Xs(t){let e=[],r=t.tools?.filter(l=>l.function.name!=="web_search")?.map(l=>({name:l.function.name,description:l.function.description,parametersJsonSchema:l.function.parameters}));r?.length&&e.push(Gb({functionDeclarations:r})),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 f;l.role==="assistant"?f="model":(["user","system"].includes(l.role),f="user");let d=[];if(typeof l.content=="string"){let p={text:l.content};l?.thinking?.signature&&(p.thoughtSignature=l.thinking.signature),d.push(p)}else Array.isArray(l.content)?d.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?d.push({text:l.content.text}):d.push({text:JSON.stringify(l.content)}));if(Array.isArray(l.tool_calls)&&d.push(...l.tool_calls.map((p,C)=>({functionCall:{id:p.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:p.function.name,args:JSON.parse(p.function.arguments||"{}")},thoughtSignature:C===0&&l.thinking?.signature?l.thinking?.signature:void 0}))),d.length===0&&d.push({text:""}),o.push({role:f,parts:d}),f==="model"&&l.tool_calls){let p=l.tool_calls.map(C=>{let k=s.find(_=>_.tool_call_id===C.id);return{functionResponse:{name:C?.function?.name,response:{result:k?.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],f,d=t.reasoning.max_tokens;typeof d<"u"&&(d>=l[0]&&d<=l[1]?f=d:d<l[0]?f=l[0]:d>l[1]&&(f=l[1]),a.thinkingConfig.thinkingBudget=f)}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 Zs(t){let e=t.contents,r=t.tools,n=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,c=t.tool_choice,l={messages:[],model:n,max_tokens:o,temperature:s,stream:a,tool_choice:c};return Array.isArray(e)&&e.forEach(f=>{typeof f=="string"?l.messages.push({role:"user",content:f}):typeof f.text=="string"?l.messages.push({role:"user",content:f.text||null}):f.role==="user"?l.messages.push({role:"user",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):f.role==="model"&&l.messages.push({role:"assistant",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(r)&&(l.tools=[],r.forEach(f=>{Array.isArray(f.functionDeclarations)&&f.functionDeclarations.forEach(d=>{l.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),l}async function ei(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json();r?.debug({response:n},`${e} response:`);let o="",s="",a=n.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||{})}}))||[],f=c?.filter(p=>p.text)?.map(p=>p.text)?.join(`
|
|
138
|
+
`)||"",d={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:f,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:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata?.candidatesTokenCount||0,prompt_tokens:n.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:n.usageMetadata?.cachedContentTokenCount||0},total_tokens:n.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:n.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(d),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let n=new TextDecoder,o=new TextEncoder,s=!1,a=!1,c=!1,l="",f=0,d=-1,p=new ReadableStream({async start(C){let k=async(g,m)=>{if(g.startsWith("data: ")){let v=g.slice(6).trim();if(v){r?.debug({chunkStr:v},`${e} chunk:`);try{let b=JSON.parse(v);if(!b.candidates||!b.candidates[0]){r?.debug({chunkStr:v},"Invalid chunk structure");return}let A=b.candidates[0],D=A.content?.parts||[];D.filter(B=>B.text&&B.thought===!0).forEach(B=>{c||(c=!0);let Y={choices:[{delta:{role:"assistant",content:null,thinking:{content:B.text}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
|
|
139
139
|
|
|
140
|
-
`))});let O=D.find(B=>B.thoughtSignature)?.thoughtSignature;if(O&&!s){if(!c){let Y={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:
|
|
140
|
+
`))});let O=D.find(B=>B.thoughtSignature)?.thoughtSignature;if(O&&!s){if(!c){let Y={choices:[{delta:{role:"assistant",content:null,thinking:{content:"(no content)"}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
|
|
141
141
|
|
|
142
|
-
`))}let B={choices:[{delta:{role:"assistant",content:null,thinking:{signature:O}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:
|
|
142
|
+
`))}let B={choices:[{delta:{role:"assistant",content:null,thinking:{signature:O}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(m.enqueue(o.encode(`data: ${JSON.stringify(B)}
|
|
143
143
|
|
|
144
|
-
`)),s=!0,f++,l){let Y={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:
|
|
144
|
+
`)),s=!0,f++,l){let Y={choices:[{delta:{role:"assistant",content:l},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
|
|
145
145
|
|
|
146
146
|
`)),l="",a||(a=!0)}}let q=D.filter(B=>B.functionCall).map(B=>({id:B.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:B.functionCall?.name,arguments:JSON.stringify(B.functionCall?.args||{})}})),J=D.filter(B=>B.text&&B.thought!==!0).map(B=>B.text).join(`
|
|
147
|
-
`);if(!J&&s&&!a){let B={choices:[{delta:{role:"assistant",content:"(no content)"},index:f,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:
|
|
147
|
+
`);if(!J&&s&&!a){let B={choices:[{delta:{role:"assistant",content:"(no content)"},index:f,finish_reason:null,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(B)}
|
|
148
148
|
|
|
149
|
-
`)),a||(a=!0)}if(c&&J&&!s)if(
|
|
149
|
+
`)),a||(a=!0)}if(c&&J&&!s)if(b.modelVersion.includes("3")){l+=J;return}else{let B={choices:[{delta:{role:"assistant",content:null,thinking:{signature:`ccr_${+new Date}`}},finish_reason:null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};m.enqueue(o.encode(`data: ${JSON.stringify(B)}
|
|
150
150
|
|
|
151
|
-
`)),s=!0}if(J){l||f++;let B={choices:[{delta:{role:"assistant",content:J},finish_reason:A.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:
|
|
151
|
+
`)),s=!0}if(J){l||f++;let B={choices:[{delta:{role:"assistant",content:J},finish_reason:A.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(B.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((Y,re)=>{let ee=A?.groundingMetadata?.groundingSupports?.filter(ue=>ue.groundingChunkIndices?.includes(re));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(B)}
|
|
152
152
|
|
|
153
|
-
`)),!a&&J&&(a=!0)}q.length>0&&(q.forEach(B=>{f++,d++;let Y={choices:[{delta:{role:"assistant",tool_calls:[{...B,index:d}]},finish_reason:A.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:
|
|
153
|
+
`)),!a&&J&&(a=!0)}q.length>0&&(q.forEach(B=>{f++,d++;let Y={choices:[{delta:{role:"assistant",tool_calls:[{...B,index:d}]},finish_reason:A.finishReason?.toLowerCase()||null,index:f,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b.responseId||"",model:b.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:b.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b.usageMetadata?.cachedContentTokenCount||0},total_tokens:b.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b.usageMetadata?.thoughtsTokenCount||0}}};A?.groundingMetadata?.groundingChunks?.length&&(Y.choices[0].delta.annotations=A.groundingMetadata.groundingChunks.map((re,ee)=>{let ue=A?.groundingMetadata?.groundingSupports?.filter(fe=>fe.groundingChunkIndices?.includes(ee));return{type:"url_citation",url_citation:{url:re?.web?.uri||"",title:re?.web?.title||"",content:ue?.[0]?.segment?.text||"",start_index:ue?.[0]?.segment?.startIndex||0,end_index:ue?.[0]?.segment?.endIndex||0}}})),m.enqueue(o.encode(`data: ${JSON.stringify(Y)}
|
|
154
154
|
|
|
155
|
-
`))}),!a&&J&&(a=!0))}catch(
|
|
156
|
-
`);y=v.pop()||"";for(let
|
|
155
|
+
`))}),!a&&J&&(a=!0))}catch(b){r?.error(`Error parsing ${e} stream chunk`,v,b.message)}}}},_=t.body.getReader(),y="";try{for(;;){let{done:g,value:m}=await _.read();if(g){y&&await k(y,C);break}y+=n.decode(m,{stream:!0});let v=y.split(`
|
|
156
|
+
`);y=v.pop()||"";for(let b of v)await k(b,C)}}catch(g){C.error(g)}finally{C.close()}}});return new Response(p,{status:t.status,statusText:t.statusText,headers:t.headers})}}var ti=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,r){return{body:Xs(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,r.baseUrl),headers:{"x-goog-api-key":r.apiKey,Authorization:void 0}}}}transformRequestOut=Zs;async transformResponseOut(e){return ei(e,this.name,this.logger)}};async function kS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>jr(id(),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:
|
|
157
157
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
158
158
|
2. Run "gcloud auth application-default login"
|
|
159
|
-
3. Use Google Cloud environment with default service account`)}}var Ca=class{name="vertex-gemini";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&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&&(n=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!n)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 kS();return{body:Xs(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,r.baseUrl.endsWith("/")?r.baseUrl:r.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Zs(e)}async transformResponseOut(e){return ei(e,this.name)}};var wa=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let r=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),n=e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content)||r;return e.messages.forEach(o=>{if(o.role==="assistant"){let s=o.thinking?.content,a=o.thinking?.signature,c="";if(typeof o.content=="string"){let f=/<thinking>([\s\S]*?)<\/thinking>/g.exec(o.content);f&&(c=f[1].trim(),o.content=o.content.replace(f[0],"").trim())}s&&typeof s=="string"&&s.trim()?(o.reasoning_content=s,a&&(o.reasoning_content_signature=a)):c&&(o.reasoning_content=c),n&&!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 r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(
|
|
160
|
-
`);for(let g of y)g.trim()&&k.enqueue(
|
|
161
|
-
`))},p=(
|
|
159
|
+
3. Use Google Cloud environment with default service account`)}}var Ca=class{name="vertex-gemini";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&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&&(n=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!n)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 kS();return{body:Xs(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,r.baseUrl.endsWith("/")?r.baseUrl:r.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${s}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Zs(e)}async transformResponseOut(e){return ei(e,this.name)}};var wa=class{name="deepseek";async transformRequestIn(e){e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192);let r=e.model?.includes("reasoner")||e.model?.includes("v4")||e.model?.includes("pro")||e.model?.includes("think"),n=e.thinking||e.reasoning?.enabled||e.messages.some(o=>o.thinking?.content)||r;return e.messages.forEach(o=>{if(o.role==="assistant"){let s=o.thinking?.content,a=o.thinking?.signature,c="";if(typeof o.content=="string"){let f=/<thinking>([\s\S]*?)<\/thinking>/g.exec(o.content);f&&(c=f[1].trim(),o.content=o.content.replace(f[0],"").trim())}s&&typeof s=="string"&&s.trim()?(o.reasoning_content=s,a&&(o.reasoning_content_signature=a)):c&&(o.reasoning_content=c),n&&!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 r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(C,k,_)=>{let y=C.split(`
|
|
160
|
+
`);for(let g of y)g.trim()&&k.enqueue(_.encode(g+`
|
|
161
|
+
`))},p=(C,k)=>{let{controller:_,encoder:y}=k;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let g=JSON.parse(C.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){k.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let v=`data: ${JSON.stringify(m)}
|
|
162
162
|
|
|
163
|
-
`;
|
|
163
|
+
`;_.enqueue(y.encode(v));return}if(g.choices?.[0]?.delta?.content&&k.reasoningContent()&&!k.isReasoningComplete()){k.setReasoningComplete(!0);let m=Date.now().toString(),v=g.choices[0].delta.content,b={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:k.reasoningContent(),signature:m}}}]};delete b.choices[0].delta.reasoning_content;let A=`data: ${JSON.stringify(b)}
|
|
164
164
|
|
|
165
|
-
`;
|
|
165
|
+
`;_.enqueue(y.encode(A));let D={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:v}}]};delete D.choices[0].delta.reasoning_content;let O=`data: ${JSON.stringify(D)}
|
|
166
166
|
|
|
167
|
-
`;
|
|
167
|
+
`;_.enqueue(y.encode(O));return}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){let m=`data: ${JSON.stringify(g)}
|
|
168
168
|
|
|
169
|
-
`;
|
|
170
|
-
`))}else
|
|
171
|
-
`))};try{for(;;){let{done:
|
|
169
|
+
`;_.enqueue(y.encode(m))}}catch{_.enqueue(y.encode(C+`
|
|
170
|
+
`))}else _.enqueue(y.encode(C+`
|
|
171
|
+
`))};try{for(;;){let{done:C,value:k}=await f.read();if(C){a.trim()&&d(a,l,n);break}let _=r.decode(k,{stream:!0});a+=_;let y=a.split(`
|
|
172
172
|
`);a=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>o,appendReasoningContent:m=>o+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
|
|
173
|
-
`))}}}catch(
|
|
173
|
+
`))}}}catch(C){console.error("Stream error:",C),l.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}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 Ea=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.
|
|
174
174
|
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.
|
|
175
175
|
Examples:
|
|
176
176
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
177
|
-
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 r=await e.json();if(r?.choices?.[0]?.message.tool_calls?.length&&r?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=r?.choices[0]?.message.tool_calls[0],o=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=o.response||"",delete r.choices[0].message.tool_calls}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o=-1,s="",a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(
|
|
178
|
-
`);for(let g of y)g.trim()&&k.enqueue(
|
|
179
|
-
`))},p=(
|
|
177
|
+
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 r=await e.json();if(r?.choices?.[0]?.message.tool_calls?.length&&r?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=r?.choices[0]?.message.tool_calls[0],o=JSON.parse(n.function.arguments||"{}");r.choices[0].message.content=o.response||"",delete r.choices[0].message.tool_calls}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o=-1,s="",a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(C,k,_)=>{let y=C.split(`
|
|
178
|
+
`);for(let g of y)g.trim()&&k.enqueue(_.encode(g+`
|
|
179
|
+
`))},p=(C,k)=>{let{controller:_,encoder:y,exitToolIndex:g,setExitToolIndex:m,appendExitToolResponse:v}=k;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let b=JSON.parse(C.slice(6));if(b.choices[0]?.delta?.tool_calls?.length){let A=b.choices[0].delta.tool_calls[0];if(A.function?.name==="ExitTool"){m(A.index);return}else if(g()>-1&&A.index===g()&&A.function.arguments){v(A.function.arguments);try{let D=JSON.parse(k.exitToolResponse());b.choices=[{delta:{role:"assistant",content:D.response||""}}];let O=`data: ${JSON.stringify(b)}
|
|
180
180
|
|
|
181
|
-
`;
|
|
181
|
+
`;_.enqueue(y.encode(O))}catch{}return}}if(b.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0){let A=`data: ${JSON.stringify(b)}
|
|
182
182
|
|
|
183
|
-
`;
|
|
184
|
-
`))}else
|
|
185
|
-
`))};try{for(;;){let{done:
|
|
183
|
+
`;_.enqueue(y.encode(A))}}catch{_.enqueue(y.encode(C+`
|
|
184
|
+
`))}else _.enqueue(y.encode(C+`
|
|
185
|
+
`))};try{for(;;){let{done:C,value:k}=await f.read();if(C){a.trim()&&d(a,l,n);break}let _=r.decode(k,{stream:!0});a+=_;let y=a.split(`
|
|
186
186
|
`);a=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,exitToolIndex:()=>o,setExitToolIndex:m=>o=m,exitToolResponse:()=>s,appendExitToolResponse:m=>s+=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
|
|
187
|
-
`))}}}catch(
|
|
187
|
+
`))}}}catch(C){console.error("Stream error:",C),l.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}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 Aa=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",f=new ReadableStream({async start(d){let p=e.body.getReader(),C=(_,y,g)=>{let m=_.split(`
|
|
188
188
|
`);for(let v of m)v.trim()&&y.enqueue(g.encode(v+`
|
|
189
|
-
`))},k=(
|
|
189
|
+
`))},k=(_,y)=>{let{controller:g,encoder:m}=y;if(_.startsWith("data: ")&&_.trim()!=="data: [DONE]"){let v=_.slice(6);try{let b=JSON.parse(v);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"){g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
|
|
190
190
|
|
|
191
|
-
`));return}
|
|
191
|
+
`));return}b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0);let A=b.choices?.[0]?.delta?.reasoning||b.choices?.[0]?.delta?.reasoning_content;if(A){y.appendReasoningContent(A);let B={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:A}}}]};B.choices?.[0]?.delta&&(delete B.choices[0].delta.reasoning,delete B.choices[0].delta.reasoning_content);let Y=`data: ${JSON.stringify(B)}
|
|
192
192
|
|
|
193
|
-
`;g.enqueue(m.encode(Y));return}if(
|
|
193
|
+
`;g.enqueue(m.encode(Y));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let B=Date.now().toString(),Y=b.choices[0].delta.content,re={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:B}}}]};re.choices?.[0]?.delta&&delete re.choices[0].delta.reasoning;let ee=`data: ${JSON.stringify(re)}
|
|
194
194
|
|
|
195
|
-
`;g.enqueue(m.encode(ee));let ue={...
|
|
195
|
+
`;g.enqueue(m.encode(ee));let ue={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:Y}}]};ue.choices?.[0]?.delta&&(delete ue.choices[0].delta.reasoning,delete ue.choices[0].delta.reasoning_content);let fe=`data: ${JSON.stringify(ue)}
|
|
196
196
|
|
|
197
|
-
`;g.enqueue(m.encode(fe));return}
|
|
197
|
+
`;g.enqueue(m.encode(fe));return}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.reasoning_content&&delete b.choices[0].delta.reasoning_content,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(B=>{B.id=`call_${Yt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0);let D=b.choices?.[0]?.delta,O=D&&Object.keys(D).length>0,q=b.choices?.[0]?.finish_reason,J=b.usage;if(O||q||J){let B=`data: ${JSON.stringify(b)}
|
|
198
198
|
|
|
199
|
-
`;g.enqueue(m.encode(B))}}catch{g.enqueue(m.encode(
|
|
200
|
-
`))}}else g.enqueue(m.encode(
|
|
201
|
-
`))};try{for(;;){let{done:
|
|
202
|
-
`);l=v.pop()||"";for(let
|
|
199
|
+
`;g.enqueue(m.encode(B))}}catch{g.enqueue(m.encode(_+`
|
|
200
|
+
`))}}else g.enqueue(m.encode(_+`
|
|
201
|
+
`))};try{for(;;){let{done:_,value:y}=await p.read();if(_){l.trim()&&C(l,d,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(v){console.warn("Failed to decode chunk",v);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let v=l.split(`
|
|
202
|
+
`);l=v.pop()||"";for(let b of v)if(b.trim())try{k(b,{controller:d,encoder:n,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:",b,A),d.enqueue(n.encode(b+`
|
|
203
203
|
`))}continue}let m=l.split(`
|
|
204
|
-
`);l=m.pop()||"";for(let v of m)if(v.trim())try{k(v,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:
|
|
205
|
-
`))}}}catch(
|
|
206
|
-
`);for(let m of g)m.trim()&&
|
|
207
|
-
`))},
|
|
204
|
+
`);l=m.pop()||"";for(let v of m)if(v.trim())try{k(v,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:b=>o=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",v,b),d.enqueue(n.encode(v+`
|
|
205
|
+
`))}}}catch(_){console.error("Stream error:",_),d.error(_)}finally{try{p.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}d.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 ka=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 Sa=class{name="groq";async transformRequestIn(e){return e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(r=>{delete r.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o=!1,s="",a=!1,c="",l=new ReadableStream({async start(f){let d=e.body.getReader(),p=(k,_,y)=>{let g=k.split(`
|
|
206
|
+
`);for(let m of g)m.trim()&&_.enqueue(y.encode(m+`
|
|
207
|
+
`))},C=(k,_)=>{let{controller:y,encoder:g}=_;if(k.startsWith("data: ")&&k.trim()!=="data: [DONE]"){let m=k.slice(6);try{let v=JSON.parse(m);if(v.error)throw new Error(JSON.stringify(v));v.choices?.[0]?.delta?.content&&!_.hasTextContent()&&_.setHasTextContent(!0),v.choices?.[0]?.delta?.tool_calls?.length&&v.choices?.[0]?.delta?.tool_calls.forEach(A=>{A.id=`call_${Yt()}`}),v.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof v.choices[0].index=="number"?v.choices[0].index+=1:v.choices[0].index=1);let b=`data: ${JSON.stringify(v)}
|
|
208
208
|
|
|
209
|
-
`;y.enqueue(g.encode(
|
|
209
|
+
`;y.enqueue(g.encode(b))}catch{y.enqueue(g.encode(k+`
|
|
210
210
|
`))}}else y.enqueue(g.encode(k+`
|
|
211
|
-
`))};try{for(;;){let{done:k,value:
|
|
212
|
-
`);c=m.pop()||"";for(let v of m)if(v.trim())try{
|
|
211
|
+
`))};try{for(;;){let{done:k,value:_}=await d.read();if(k){c.trim()&&p(c,f,n);break}if(!_||_.length===0)continue;let y;try{y=r.decode(_,{stream:!0})}catch(m){console.warn("Failed to decode chunk",m);continue}if(y.length===0)continue;if(c+=y,c.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let m=c.split(`
|
|
212
|
+
`);c=m.pop()||"";for(let v of m)if(v.trim())try{C(v,{controller:f,encoder:n,hasTextContent:()=>o,setHasTextContent:b=>o=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",v,b),f.enqueue(n.encode(v+`
|
|
213
213
|
`))}continue}let g=c.split(`
|
|
214
|
-
`);c=g.pop()||"";for(let m of g)if(m.trim())try{
|
|
214
|
+
`);c=g.pop()||"";for(let m of g)if(m.trim())try{C(m,{controller:f,encoder:n,hasTextContent:()=>o,setHasTextContent:v=>o=v,reasoningContent:()=>s,appendReasoningContent:v=>s+=v,isReasoningComplete:()=>a,setReasoningComplete:v=>a=v})}catch(v){console.error("Error processing line:",m,v),f.enqueue(n.encode(m+`
|
|
215
215
|
`))}}}catch(k){console.error("Stream error:",k),f.error(k)}finally{try{d.releaseLock()}catch(k){console.error("Error releasing reader lock:",k)}f.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(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control}):r.cache_control&&delete r.cache_control}),e}};var Uy=jr(Iu());var Sr=class extends Error{constructor(e,r){super(`${e} at position ${r}`),this.position=r}};function Py(t){return/^[0-9A-Fa-f]$/.test(t)}function Yr(t){return t>="0"&&t<="9"}function Iy(t){return t>=" "}function os(t){return`,:[]/{}()
|
|
216
216
|
+`.includes(t)}function ad(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function ud(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var cd=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,ld=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function dd(t){return`,[]/{}
|
|
217
217
|
+`.includes(t)}function fd(t){return ss(t)||SS.test(t)}var SS=/^[[{\w-]$/;function By(t){return t===`
|
|
218
218
|
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function Kr(t,e){let r=t.charCodeAt(e);return r===32||r===10||r===9||r===13}function Ny(t,e){let r=t.charCodeAt(e);return r===32||r===9||r===13}function My(t,e){let r=t.charCodeAt(e);return r===160||r>=8192&&r<=8202||r===8239||r===8287||r===12288}function ss(t){return hd(t)||Ta(t)}function hd(t){return t==='"'||t==="\u201C"||t==="\u201D"}function pd(t){return t==='"'}function Ta(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function md(t){return t==="'"}function fo(t,e){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=t.lastIndexOf(e);return n!==-1?t.substring(0,n)+(r?"":t.substring(n+1)):t}function Ft(t,e){let r=t.length;if(!Kr(t,r-1))return t+e;for(;Kr(t,r-1);)r--;return t.substring(0,r)+e+t.substring(r)}function jy(t,e,r){return t.substring(0,e)+t.substring(e+r)}function Ly(t){return/[,\n][ \t\r]*$/.test(t)}var vS={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},TS={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
219
219
|
`,r:"\r",t:" "};function gd(t){let e=0,r="";f(["```","[```","{```"]),s()||fe(),f(["```","```]","```}"]);let o=p(",");for(o&&a(),fd(t[e])&&Ly(r)?(o||(r=Ft(r,",")),m()):o&&(r=fo(r,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return r;ue();function s(){a();let G=y()||g()||v()||A()||D()||q(!1)||J();return a(),G}function a(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,K=e,ce=c(G);do ce=l(),ce&&(ce=c(G));while(ce);return e>K}function c(G){let K=G?Kr:Ny,ce="";for(;;)if(K(t,e))ce+=t[e],e++;else if(My(t,e))ce+=" ",e++;else break;return ce.length>0?(r+=ce,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!DS(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
|
|
220
|
-
`;)e++;return!0}return!1}function f(G){if(d(G)){if(ad(t[e]))for(;e<t.length&&ud(t[e]);)e++;return a(),!0}return!1}function d(G){c(!0);for(let K of G){let ce=e+K.length;if(t.slice(e,ce)===K)return e=ce,!0}return!1}function p(G){return t[e]===G?(r+=t[e],e++,!0):!1}function
|
|
220
|
+
`;)e++;return!0}return!1}function f(G){if(d(G)){if(ad(t[e]))for(;e<t.length&&ud(t[e]);)e++;return a(),!0}return!1}function d(G){c(!0);for(let K of G){let ce=e+K.length;if(t.slice(e,ce)===K)return e=ce,!0}return!1}function p(G){return t[e]===G?(r+=t[e],e++,!0):!1}function C(G){return t[e]===G?(e++,!0):!1}function k(){return C("\\")}function _(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),C(","),!0):!1}function y(){if(t[e]==="{"){r+="{",e++,a(),C(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="}";){let K;if(G?(K=!0,G=!1):(K=p(","),K||(r=Ft(r,",")),a()),_(),!(v()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?r=fo(r,","):ke();break}a();let qe=p(":"),De=e>=t.length;qe||(fd(t[e])||De?r=Ft(r,":"):ie()),s()||(qe||De?r+="null":ie())}return t[e]==="}"?(r+="}",e++):r=Ft(r,"}"),!0}return!1}function g(){if(t[e]==="["){r+="[",e++,a(),C(",")&&a();let G=!0;for(;e<t.length&&t[e]!=="]";)if(G?G=!1:p(",")||(r=Ft(r,",")),_(),!s()){r=fo(r,",");break}return t[e]==="]"?(r+="]",e++):r=Ft(r,"]"),!0}return!1}function m(){let G=!0,K=!0;for(;K;)G?G=!1:p(",")||(r=Ft(r,",")),K=s();K||(r=fo(r,",")),r=`[
|
|
221
221
|
${r}
|
|
222
|
-
]`}function v(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ce=t[e]==="\\";if(ce&&(e++,ce=!0),ss(t[e])){let qe=pd(t[e])?pd:md(t[e])?md:Ta(t[e])?Ta:hd,De=e,W=r.length,de='"';for(e++;;){if(e>=t.length){let _e=B(e-1);return!G&&os(t.charAt(_e))?(e=De,r=r.substring(0,W),v(!0)):(de=Ft(de,'"'),r+=de,!0)}if(e===K)return de=Ft(de,'"'),r+=de,!0;if(qe(t[e])){let _e=e,It=de.length;if(de+='"',e++,r+=de,a(!1),G||e>=t.length||os(t[e])||ss(t[e])||Yr(t[e]))return
|
|
223
|
-
`);for(let A of
|
|
224
|
-
`))},
|
|
222
|
+
]`}function v(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ce=t[e]==="\\";if(ce&&(e++,ce=!0),ss(t[e])){let qe=pd(t[e])?pd:md(t[e])?md:Ta(t[e])?Ta:hd,De=e,W=r.length,de='"';for(e++;;){if(e>=t.length){let _e=B(e-1);return!G&&os(t.charAt(_e))?(e=De,r=r.substring(0,W),v(!0)):(de=Ft(de,'"'),r+=de,!0)}if(e===K)return de=Ft(de,'"'),r+=de,!0;if(qe(t[e])){let _e=e,It=de.length;if(de+='"',e++,r+=de,a(!1),G||e>=t.length||os(t[e])||ss(t[e])||Yr(t[e]))return b(),!0;let xe=B(_e-1),je=t.charAt(xe);if(je===",")return e=De,r=r.substring(0,W),v(!1,xe);if(os(je))return e=De,r=r.substring(0,W),v(!0);r=r.substring(0,W),e=_e+1,de=`${de.substring(0,It)}\\${de.substring(It)}`}else if(G&&dd(t[e])){if(t[e-1]===":"&&cd.test(t.substring(De+1,e+2)))for(;e<t.length&&ld.test(t[e]);)de+=t[e],e++;return de=Ft(de,'"'),r+=de,b(),!0}else if(t[e]==="\\"){let _e=t.charAt(e+1);if(TS[_e]!==void 0)de+=t.slice(e,e+2),e+=2;else if(_e==="u"){let xe=2;for(;xe<6&&Py(t[e+xe]);)xe++;xe===6?(de+=t.slice(e,e+6),e+=6):e+xe>=t.length?e=t.length:me()}else de+=_e,e+=2}else{let _e=t.charAt(e);_e==='"'&&t[e-1]!=="\\"?(de+=`\\${_e}`,e++):By(_e)?(de+=vS[_e],e++):(Iy(_e)||ee(_e),de+=_e,e++)}ce&&k()}}return!1}function b(){let G=!1;for(a();t[e]==="+";){G=!0,e++,a(),r=fo(r,'"',!0);let K=r.length;v()?r=jy(r,K,1):r=Ft(r,'"')}return G}function A(){let G=e;if(t[e]==="-"){if(e++,Y())return re(G),!0;if(!Yr(t[e]))return e=G,!1}for(;Yr(t[e]);)e++;if(t[e]==="."){if(e++,Y())return re(G),!0;if(!Yr(t[e]))return e=G,!1;for(;Yr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,Y())return re(G),!0;if(!Yr(t[e]))return e=G,!1;for(;Yr(t[e]);)e++}if(!Y())return e=G,!1;if(e>G){let K=t.slice(G,e),ce=/^0\d/.test(K);return r+=ce?`"${K}"`:K,!0}return!1}function D(){return O("true","true")||O("false","false")||O("null","null")||O("True","true")||O("False","false")||O("None","null")}function O(G,K){return t.slice(e,e+G.length)===G?(r+=K,e+=G.length,!0):!1}function q(G){let K=e;if(ad(t[e])){for(;e<t.length&&ud(t[e]);)e++;let ce=e;for(;Kr(t,ce);)ce++;if(t[ce]==="(")return e=ce+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!dd(t[e])&&!ss(t[e])&&(!G||t[e]!==":");)e++;if(t[e-1]===":"&&cd.test(t.substring(K,e+2)))for(;e<t.length&&ld.test(t[e]);)e++;if(e>K){for(;Kr(t,e-1)&&e>0;)e--;let ce=t.slice(K,e);return r+=ce==="undefined"?"null":JSON.stringify(ce),t[e]==='"'&&e++,!0}}function J(){if(t[e]==="/"){let G=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,r+=`"${t.substring(G,e)}"`,!0}}function B(G){let K=G;for(;K>0&&Kr(t,K);)K--;return K}function Y(){return e>=t.length||os(t[e])||Kr(t,e)}function re(G){r+=`${t.slice(G,e)}0`}function ee(G){throw new Sr(`Invalid character ${JSON.stringify(G)}`,e)}function ue(){throw new Sr(`Unexpected character ${JSON.stringify(t[e])}`,e)}function fe(){throw new Sr("Unexpected end of json string",t.length)}function ke(){throw new Sr("Object key expected",e)}function ie(){throw new Sr("Colon expected",e)}function me(){let G=t.slice(e,e+6);throw new Sr(`Invalid unicode character "${G}"`,e)}}function DS(t,e){return t[e]==="*"&&t[e+1]==="/"}function yd(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(r){try{let n=Uy.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let o=gd(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${r.message}. JSON5 parsing failed: ${n.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Da=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();if(r?.choices?.[0]?.message?.tool_calls?.length)for(let n of r.choices[0].message.tool_calls)n.function?.arguments&&(n.function.arguments=yd(n.function.arguments,this.logger));return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o={},s=!1,a="",c=!1,l=!1,f="",d=new ReadableStream({async start(p){let C=e.body.getReader(),k=(g,m,v)=>{let b=g.split(`
|
|
223
|
+
`);for(let A of b)A.trim()&&m.enqueue(v.encode(A+`
|
|
224
|
+
`))},_=(g,m,v)=>{let b="";try{b=yd(o.arguments||"",this.logger)}catch(q){console.error(`${q.message} ${q.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),b=o.arguments||""}let A={role:"assistant",tool_calls:[{function:{name:o.name,arguments:b},id:o.id,index:o.index,type:"function"}]},D={...g,choices:[{...g.choices[0],delta:A}]};D.choices[0].delta.content!==void 0&&delete D.choices[0].delta.content;let O=`data: ${JSON.stringify(D)}
|
|
225
225
|
|
|
226
|
-
`;m.enqueue(v.encode(O))},y=(g,m)=>{let{controller:v,encoder:
|
|
226
|
+
`;m.enqueue(v.encode(O))},y=(g,m)=>{let{controller:v,encoder:b}=m;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let A=g.slice(6);try{let D=JSON.parse(A);if(D.choices?.[0]?.delta?.tool_calls?.length){let q=D.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:q.index,name:q.function?.name||"",id:q.id||"",arguments:q.function?.arguments||""},q.function?.arguments&&(q.function.arguments="");let J=`data: ${JSON.stringify(D)}
|
|
227
227
|
|
|
228
|
-
`;v.enqueue(
|
|
228
|
+
`;v.enqueue(b.encode(J));return}else if(o.index===q.index){q.function?.arguments&&(o.arguments+=q.function.arguments);return}else{_(D,v,b),o={index:q.index,name:q.function?.name||"",id:q.id||"",arguments:q.function?.arguments||""};return}}if(D.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){_(D,v,b),o={};return}D.choices?.[0]?.delta?.tool_calls?.length&&m.hasTextContent()&&(typeof D.choices[0].index=="number"?D.choices[0].index+=1:D.choices[0].index=1);let O=`data: ${JSON.stringify(D)}
|
|
229
229
|
|
|
230
|
-
`;v.enqueue(
|
|
231
|
-
`))}}else v.enqueue(
|
|
232
|
-
`))};try{for(;;){let{done:g,value:m}=await
|
|
230
|
+
`;v.enqueue(b.encode(O))}catch{v.enqueue(b.encode(g+`
|
|
231
|
+
`))}}else v.enqueue(b.encode(g+`
|
|
232
|
+
`))};try{for(;;){let{done:g,value:m}=await C.read();if(g){f.trim()&&k(f,p,n);break}if(!m||m.length===0)continue;let v;try{v=r.decode(m,{stream:!0})}catch(A){console.warn("Failed to decode chunk",A);continue}if(v.length===0)continue;if(f+=v,f.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let A=f.split(`
|
|
233
233
|
`);f=A.pop()||"";for(let D of A)if(D.trim())try{y(D,{controller:p,encoder:n,hasTextContent:()=>s,setHasTextContent:O=>s=O,reasoningContent:()=>a,appendReasoningContent:O=>a+=O,isReasoningComplete:()=>c,setReasoningComplete:O=>c=O})}catch(O){console.error("Error processing line:",D,O),p.enqueue(n.encode(D+`
|
|
234
|
-
`))}continue}let
|
|
235
|
-
`);f=
|
|
236
|
-
`))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{
|
|
237
|
-
`);for(let g of y)g.trim()&&k.enqueue(
|
|
238
|
-
`))},p=(
|
|
234
|
+
`))}continue}let b=f.split(`
|
|
235
|
+
`);f=b.pop()||"";for(let A of b)if(A.trim())try{y(A,{controller:p,encoder:n,hasTextContent:()=>s,setHasTextContent:D=>s=D,reasoningContent:()=>a,appendReasoningContent:D=>a+=D,isReasoningComplete:()=>c,setReasoningComplete:D=>c=D})}catch(D){console.error("Error processing line:",A,D),p.enqueue(n.encode(A+`
|
|
236
|
+
`))}}}catch(g){console.error("Stream error:",g),p.error(g)}finally{try{C.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}p.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 Ra=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 r=await e.json();return r.choices[0]?.message.reasoning_content&&(r.thinking={content:r.choices[0]?.message.reasoning_content}),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o="",s=!1,a="",c=new ReadableStream({async start(l){let f=e.body.getReader(),d=(C,k,_)=>{let y=C.split(`
|
|
237
|
+
`);for(let g of y)g.trim()&&k.enqueue(_.encode(g+`
|
|
238
|
+
`))},p=(C,k)=>{let{controller:_,encoder:y}=k;if(this.logger?.debug({line:C},"Processing reason line"),C.startsWith("data: ")&&C.trim()!=="data: [DONE]")try{let g=JSON.parse(C.slice(6));if(console.log(JSON.stringify(g)),g.choices?.[0]?.delta?.reasoning_content){k.appendReasoningContent(g.choices[0].delta.reasoning_content);let m={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete m.choices[0].delta.reasoning_content;let v=`data: ${JSON.stringify(m)}
|
|
239
239
|
|
|
240
|
-
`;
|
|
240
|
+
`;_.enqueue(y.encode(v));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&k.reasoningContent()&&!k.isReasoningComplete()){k.setReasoningComplete(!0);let m=Date.now().toString(),v={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:k.reasoningContent(),signature:m}}}]};delete v.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(v)}
|
|
241
241
|
|
|
242
|
-
`;
|
|
242
|
+
`;_.enqueue(y.encode(b))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){k.isReasoningComplete()&&g.choices[0].index++;let m=`data: ${JSON.stringify(g)}
|
|
243
243
|
|
|
244
|
-
`;
|
|
245
|
-
`))}else
|
|
246
|
-
`))};try{for(;;){let{done:
|
|
244
|
+
`;_.enqueue(y.encode(m))}}catch{_.enqueue(y.encode(C+`
|
|
245
|
+
`))}else _.enqueue(y.encode(C+`
|
|
246
|
+
`))};try{for(;;){let{done:C,value:k}=await f.read();if(C){a.trim()&&d(a,l,n);break}let _=r.decode(k,{stream:!0});a+=_;let y=a.split(`
|
|
247
247
|
`);a=y.pop()||"";for(let g of y)if(g.trim())try{p(g,{controller:l,encoder:n,reasoningContent:()=>o,appendReasoningContent:m=>o+=m,isReasoningComplete:()=>s,setReasoningComplete:m=>s=m})}catch(m){console.error("Error processing line:",g,m),l.enqueue(n.encode(g+`
|
|
248
|
-
`))}}}catch(
|
|
248
|
+
`))}}}catch(C){console.error("Stream error:",C),l.error(C)}finally{try{f.releaseLock()}catch(C){console.error("Error releasing reader lock:",C)}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 Oa=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function $y(t){let e=[];for(let n=0;n<t.messages.length;n++){let o=t.messages[n],s=n===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 r={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&&(r.tools=t.tools.map(n=>({name:n.function.name,description:n.function.description,input_schema:n.function.parameters}))),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),r}function qy(t){let e=t,n={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&&(n.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"?n.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(n.tool_choice=e.tool_choice.name)),n}async function zy(t,e,r){if(t.headers.get("Content-Type")?.includes("application/json")){let n=await t.json(),o;n.tool_use&&n.tool_use.length>0&&(o=n.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.model,object:"chat.completion",usage:{completion_tokens:n.usage.output_tokens,prompt_tokens:n.usage.input_tokens,total_tokens:n.usage.input_tokens+n.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 n=new TextDecoder,o=new TextEncoder,s=(c,l)=>{if(c.startsWith("data: ")){let f=c.slice(6).trim();if(f){r?.debug({chunkStr:f},`${e} chunk:`);try{let d=JSON.parse(f);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let p={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
|
|
249
249
|
|
|
250
250
|
`))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let p={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
|
|
251
251
|
|
|
@@ -257,31 +257,31 @@ ${r}
|
|
|
257
257
|
|
|
258
258
|
`));else{let p={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};l.enqueue(o.encode(`data: ${JSON.stringify(p)}
|
|
259
259
|
|
|
260
|
-
`))}}catch(d){r?.error(`Error parsing ${e} stream chunk`,f,d.message)}}}},a=new ReadableStream({async start(c){let l=t.body.getReader(),f="";try{for(;;){let{done:d,value:p}=await l.read();if(d){f&&s(f,c);break}f+=n.decode(p,{stream:!0});let
|
|
261
|
-
`);f=
|
|
260
|
+
`))}}catch(d){r?.error(`Error parsing ${e} stream chunk`,f,d.message)}}}},a=new ReadableStream({async start(c){let l=t.body.getReader(),f="";try{for(;;){let{done:d,value:p}=await l.read();if(d){f&&s(f,c);break}f+=n.decode(p,{stream:!0});let C=f.split(`
|
|
261
|
+
`);f=C.pop()||"";for(let k of C)s(k,c)}}catch(d){c.error(d)}finally{c.close()}}});return new Response(a,{status:t.status,statusText:t.statusText,headers:t.headers})}return t}async function RS(){try{let{GoogleAuth:t}=await Promise.resolve().then(()=>jr(id(),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:
|
|
262
262
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
263
263
|
2. Run "gcloud auth application-default login"
|
|
264
|
-
3. Use Google Cloud environment with default service account`)}}var Fa=class{name="vertex-claude";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&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&&(n=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!n)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 RS();return{body:$y(e),config:{url:new URL(`/v1/projects/${n}/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 qy(e)}async transformResponseOut(e){return zy(e,this.name,this.logger)}};var Pa=class{name="cerebras";async transformRequestIn(e,r){let n=JSON.parse(JSON.stringify(e));return n.reasoning?delete n.reasoning:n.disable_reasoning=!1,{body:n,config:{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Ia=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ba=class{name="OpenAI";endPoint="/v1/chat/completions"};var Na=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let r={...e},n=Object.entries(this.options);for(let[o,s]of n)if(o in r)if(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);else continue;else r[o]=this.cloneValue(s);return r}async transformResponseOut(e){return e}deepMergeObjects(e,r){let n={...e};for(let[o,s]of Object.entries(r))o in n&&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):n[o]=this.cloneValue(s);return n}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.cloneValue(n));let r={};for(let[n,o]of Object.entries(e))r[n]=this.cloneValue(o);return r}};var Ma=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",f=new ReadableStream({async start(d){let p=e.body.getReader(),
|
|
264
|
+
3. Use Google Cloud environment with default service account`)}}var Fa=class{name="vertex-claude";async transformRequestIn(e,r){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&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&&(n=l.project_id)}catch(a){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!n)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 RS();return{body:$y(e),config:{url:new URL(`/v1/projects/${n}/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 qy(e)}async transformResponseOut(e){return zy(e,this.name,this.logger)}};var Pa=class{name="cerebras";async transformRequestIn(e,r){let n=JSON.parse(JSON.stringify(e));return n.reasoning?delete n.reasoning:n.disable_reasoning=!1,{body:n,config:{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Ia=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ba=class{name="OpenAI";endPoint="/v1/chat/completions"};var Na=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let r={...e},n=Object.entries(this.options);for(let[o,s]of n)if(o in r)if(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);else continue;else r[o]=this.cloneValue(s);return r}async transformResponseOut(e){return e}deepMergeObjects(e,r){let n={...e};for(let[o,s]of Object.entries(r))o in n&&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):n[o]=this.cloneValue(s);return n}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.cloneValue(n));let r={};for(let[n,o]of Object.entries(e))r[n]=this.cloneValue(o);return r}};var Ma=class{constructor(e){this.options=e}static TransformerName="vercel";endPoint="/v1/chat/completions";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(r=>{Array.isArray(r.content)&&r.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(r=>{Array.isArray(r.content)?r.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):r.cache_control&&delete r.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let r=await e.json();return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let r=new TextDecoder,n=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",f=new ReadableStream({async start(d){let p=e.body.getReader(),C=(_,y,g)=>{let m=_.split(`
|
|
265
265
|
`);for(let v of m)v.trim()&&y.enqueue(g.encode(v+`
|
|
266
|
-
`))},k=(
|
|
266
|
+
`))},k=(_,y)=>{let{controller:g,encoder:m}=y;if(_.startsWith("data: ")&&_.trim()!=="data: [DONE]"){let v=_.slice(6);try{let b=JSON.parse(v);if(b.usage&&(this.logger?.debug({usage:b.usage,hasToolCall:c},"usage"),b.choices[0].finish_reason=c?"tool_calls":"stop"),b.choices?.[0]?.finish_reason==="error"&&g.enqueue(m.encode(`data: ${JSON.stringify({error:b.choices?.[0].error})}
|
|
267
267
|
|
|
268
|
-
`)),
|
|
268
|
+
`)),b.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),b.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(b.choices[0].delta.reasoning);let D={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,thinking:{content:b.choices[0].delta.reasoning}}}]};D.choices?.[0]?.delta&&delete D.choices[0].delta.reasoning;let O=`data: ${JSON.stringify(D)}
|
|
269
269
|
|
|
270
|
-
`;g.enqueue(m.encode(O));return}if(
|
|
270
|
+
`;g.enqueue(m.encode(O));return}if(b.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let D=Date.now().toString(),O={...b,choices:[{...b.choices?.[0],delta:{...b.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:D}}}]};O.choices?.[0]?.delta&&delete O.choices[0].delta.reasoning;let q=`data: ${JSON.stringify(O)}
|
|
271
271
|
|
|
272
|
-
`;g.enqueue(m.encode(q))}
|
|
272
|
+
`;g.enqueue(m.encode(q))}b.choices?.[0]?.delta?.reasoning&&delete b.choices[0].delta.reasoning,b.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(b.choices?.[0]?.delta?.tool_calls[0].id,10))&&b.choices?.[0]?.delta?.tool_calls.forEach(D=>{D.id=`call_${Yt()}`}),b.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),b.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof b.choices[0].index=="number"?b.choices[0].index+=1:b.choices[0].index=1);let A=`data: ${JSON.stringify(b)}
|
|
273
273
|
|
|
274
|
-
`;g.enqueue(m.encode(A))}catch{g.enqueue(m.encode(
|
|
275
|
-
`))}}else g.enqueue(m.encode(
|
|
276
|
-
`))};try{for(;;){let{done:
|
|
277
|
-
`);l=v.pop()||"";for(let
|
|
274
|
+
`;g.enqueue(m.encode(A))}catch{g.enqueue(m.encode(_+`
|
|
275
|
+
`))}}else g.enqueue(m.encode(_+`
|
|
276
|
+
`))};try{for(;;){let{done:_,value:y}=await p.read();if(_){l.trim()&&C(l,d,n);break}if(!y||y.length===0)continue;let g;try{g=r.decode(y,{stream:!0})}catch(v){console.warn("Failed to decode chunk",v);continue}if(g.length===0)continue;if(l+=g,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let v=l.split(`
|
|
277
|
+
`);l=v.pop()||"";for(let b of v)if(b.trim())try{k(b,{controller:d,encoder:n,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:",b,A),d.enqueue(n.encode(b+`
|
|
278
278
|
`))}continue}let m=l.split(`
|
|
279
|
-
`);l=m.pop()||"";for(let v of m)if(v.trim())try{k(v,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:
|
|
280
|
-
`))}}}catch(
|
|
279
|
+
`);l=m.pop()||"";for(let v of m)if(v.trim())try{k(v,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:b=>o=b,reasoningContent:()=>s,appendReasoningContent:b=>s+=b,isReasoningComplete:()=>a,setReasoningComplete:b=>a=b})}catch(b){console.error("Error processing line:",v,b),d.enqueue(n.encode(v+`
|
|
280
|
+
`))}}}catch(_){console.error("Stream error:",_),d.error(_)}finally{try{p.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}d.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 ja=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 r=[],n=e.messages.filter(o=>o.role==="system");if(n.length>0){let o=n[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),r.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,r.push(s);return}if(o.role==="assistant"&&Array.isArray(o.tool_calls)){o.tool_calls.forEach(s=>{r.push({type:"function_call",arguments:s.function.arguments,name:s.function.name,call_id:s.id})});return}r.push(o)}}),e.input=r,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 r=e.headers.get("Content-Type")||"";if(r.includes("application/json")){let n=await e.json();if(n.object==="response"&&n.output){let o=this.convertResponseToChat(n);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(r.includes("text/event-stream")){if(!e.body)return e;let n=new TextDecoder,o=new TextEncoder,s="",a=!1,c=this,l=new ReadableStream({async start(f){let d=e.body.getReader(),p=-1,C="",k=_=>(_!==C&&(p++,C=_),p);try{for(;;){let{done:_,value:y}=await d.read();if(_){a||f.enqueue(o.encode(`data: [DONE]
|
|
281
281
|
|
|
282
|
-
`));break}let g=n.decode(y,{stream:!0});s+=g;let m=s.split(/\r?\n/);s=m.pop()||"";for(let v of m)if(v.trim())try{if(v.startsWith("event: "))continue;if(v.startsWith("data: ")){let
|
|
282
|
+
`));break}let g=n.decode(y,{stream:!0});s+=g;let m=s.split(/\r?\n/);s=m.pop()||"";for(let v of m)if(v.trim())try{if(v.startsWith("event: "))continue;if(v.startsWith("data: ")){let b=v.slice(5).trim();if(b==="[DONE]"){a=!0,f.enqueue(o.encode(`data: [DONE]
|
|
283
283
|
|
|
284
|
-
`));continue}try{let A=JSON.parse(
|
|
284
|
+
`));continue}try{let A=JSON.parse(b);if(A.type==="response.output_text.delta"){let D={id:A.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:A.response?.model,choices:[{index:k(A.type),delta:{content:A.delta||""},finish_reason:null}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
|
|
285
285
|
|
|
286
286
|
`))}else if(A.type==="response.output_item.added"&&A.item?.type==="function_call"){let D={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:k(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}]};f.enqueue(o.encode(`data: ${JSON.stringify(D)}
|
|
287
287
|
|
|
@@ -299,56 +299,56 @@ ${r}
|
|
|
299
299
|
|
|
300
300
|
`))}}catch{f.enqueue(o.encode(v+`
|
|
301
301
|
`))}}else f.enqueue(o.encode(v+`
|
|
302
|
-
`))}catch(
|
|
302
|
+
`))}catch(b){console.error("Error processing line:",v,b),f.enqueue(o.encode(v+`
|
|
303
303
|
`))}}s.trim()&&f.enqueue(o.encode(s+`
|
|
304
304
|
`)),a||f.enqueue(o.encode(`data: [DONE]
|
|
305
305
|
|
|
306
|
-
`))}catch(
|
|
306
|
+
`))}catch(_){console.error("Stream error:",_),f.error(_)}finally{try{d.releaseLock()}catch(_){console.error("Error releasing reader lock:",_)}f.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,r){let n={...e};if(delete n.cache_control,e.type==="text")return{type:r==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){console.log(e);let o={type:r==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),o}return null}convertResponseToChat(e){let r=e.output?.find(f=>f.type==="message"),n=e.output?.find(f=>f.type==="function_call"),o;r?.content?.length&&r?.content[0].annotations&&(o=r.content[0].annotations.map(f=>({type:"url_citation",url_citation:{url:f.url||"",title:f.title||"",content:"",start_index:f.start_index||0,end_index:f.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(r&&r.reasoning&&(c={content:r.reasoning}),r&&r.content){let f=[],d=[];if(r.content.forEach(p=>{if(p.type==="output_text")f.push(p.text||"");else if(p.type==="output_image"){let C=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});C&&d.push(C)}else if(p.type==="output_image_base64"){let C=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});C&&d.push(C)}}),d.length>0){let p=[];f.length>0&&p.push({type:"text",text:f.join("")}),p.push(...d),s=p}else s=f.join("")}return n&&(a=[{id:n.call_id||n.id,function:{name:n.name,arguments:n.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}};var _d=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
307
307
|
|
|
308
308
|
Output format:
|
|
309
309
|
<reasoning_content>
|
|
310
310
|
Your detailed thinking process goes here
|
|
311
311
|
</reasoning_content>
|
|
312
312
|
Your final answer must follow after the closing tag above.`,xS=10,La=class{name="forcereasoning";async transformRequestIn(e){let r=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||r<xS)&&(r++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
|
|
313
|
-
${o.content}`),delete o.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:_d}):n.content=[{type:"text",text:_d},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:_d}]}),e}async transformResponseOut(e){let r="<reasoning_content>",n="</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 f=e.body.getReader(),d="",p="SEARCHING",
|
|
313
|
+
${o.content}`),delete o.thinking)});let n=e.messages[e.messages.length-1];return n.role==="user"&&(Array.isArray(n.content)?n.content.push({type:"text",text:_d}):n.content=[{type:"text",text:_d},{type:"text",text:n.content||""}]),n.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:_d}]}),e}async transformResponseOut(e){let r="<reasoning_content>",n="</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 f=e.body.getReader(),d="",p="SEARCHING",C="",k="",_=(y,g)=>{if(typeof g!="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)}
|
|
314
314
|
|
|
315
|
-
`)));return}let m=
|
|
315
|
+
`)));return}let m=C+g;for(C="";m.length>0;)if(p==="SEARCHING"){let v=m.indexOf(r);if(v!==-1)m=m.substring(v+r.length),p="REASONING";else{for(let b=r.length-1;b>0;b--)if(m.endsWith(r.substring(0,b))){C=m.substring(m.length-b);break}m=""}}else if(p==="REASONING"){let v=m.indexOf(n);if(v!==-1){let b=m.substring(0,v);if(b.length>0){let O={...y.choices[0].delta,thinking:{content:b}};delete O.content;let q={...y,choices:[{...y.choices[0],delta:O,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(q)}
|
|
316
316
|
|
|
317
317
|
`))}let A={...y.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete A.content;let D={...y,choices:[{...y.choices[0],delta:A,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
|
|
318
318
|
|
|
319
|
-
`)),o++,m=m.substring(v+n.length),p="FINAL"}else{let
|
|
319
|
+
`)),o++,m=m.substring(v+n.length),p="FINAL"}else{let b=m;for(let A=n.length-1;A>0;A--)if(m.endsWith(n.substring(0,A))){C=m.substring(m.length-A),b=m.substring(0,m.length-A);break}if(b.length>0){let A={...y.choices[0].delta,thinking:{content:b}};delete A.content;let D={...y,choices:[{...y.choices[0],delta:A,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
|
|
320
320
|
|
|
321
|
-
`))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))k+=m;else{let
|
|
321
|
+
`))}m=""}}else if(p==="FINAL"){if(m.length>0)if(/^\s*$/.test(m))k+=m;else{let b=k+m,A={...y.choices[0].delta,content:b};A.thinking&&delete A.thinking;let D={...y,choices:[{...y.choices[0],delta:A}]};l.enqueue(a.encode(`data: ${JSON.stringify(D)}
|
|
322
322
|
|
|
323
323
|
`)),k=""}o++,m=""}};try{for(;;){let{done:y,value:g}=await f.read();if(y)break;let m=s.decode(g,{stream:!0});d+=m;let v=d.split(`
|
|
324
|
-
`);d=v.pop()||"";for(let
|
|
324
|
+
`);d=v.pop()||"";for(let b of v)if(b.trim()){if(b.trim()==="data: [DONE]"){l.enqueue(a.encode(b+`
|
|
325
325
|
|
|
326
|
-
`));break}if(
|
|
327
|
-
`))}else l.enqueue(a.encode(
|
|
326
|
+
`));break}if(b.startsWith("data:"))try{let A=JSON.parse(b.slice(5));_(A,A.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(b+`
|
|
327
|
+
`))}else l.enqueue(a.encode(b+`
|
|
328
328
|
`))}}}catch(y){console.error("Stream error:",y),l.error(y)}finally{try{f.releaseLock()}catch(y){console.error("Error releasing reader lock:",y)}if(p==="REASONING"){let g={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(g)}
|
|
329
329
|
|
|
330
330
|
`))}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 Ua=class{name="kimi";async transformRequestIn(e){return(e.thinking||e.reasoning?.enabled||e.messages.some(n=>n.thinking?.content))&&e.messages.forEach(n=>{if(n.role==="assistant"){let o=n.thinking?.content,s=n.thinking?.signature;o&&typeof o=="string"&&o.trim()&&(n.reasoning_content=o,s&&(n.reasoning_content_signature=s)),n.tool_calls&&n.tool_calls.length>0&&(n.reasoning_content||(n.reasoning_content="")),n.thinking&&delete n.thinking}}),e}async transformResponseOut(e){let r=e.headers.get("Content-Type");if(r?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,o=new TextEncoder,s="",a="",c=new ReadableStream({async start(l){let f=e.body.getReader();try{for(;;){let{done:d,value:p}=await f.read();if(d){a.trim()&&l.enqueue(o.encode(a+`
|
|
331
|
-
`));break}let
|
|
332
|
-
`);a=k.pop()||"";for(let
|
|
331
|
+
`));break}let C=n.decode(p,{stream:!0});a+=C;let k=a.split(`
|
|
332
|
+
`);a=k.pop()||"";for(let _ of k)if(_.trim())if(_.startsWith("data: ")&&_.trim()!=="data: [DONE]")try{let y=JSON.parse(_.slice(6));if(y.choices?.[0]?.delta?.reasoning_content){s+=y.choices[0].delta.reasoning_content;let g={...y,choices:[{...y.choices[0],delta:{thinking:{content:y.choices[0].delta.reasoning_content}}}]};delete g.choices[0].delta.reasoning_content,l.enqueue(o.encode(`data: ${JSON.stringify(g)}
|
|
333
333
|
|
|
334
334
|
`));continue}if(y.choices?.[0]?.delta?.content&&s&&!y.choices[0]?.delta?.reasoning_content){let g=Date.now().toString(),m={...y,choices:[{...y.choices[0],delta:{content:null,thinking:{content:s,signature:g}}}]};l.enqueue(o.encode(`data: ${JSON.stringify(m)}
|
|
335
335
|
|
|
336
336
|
`)),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)}
|
|
337
337
|
|
|
338
|
-
`))}catch{l.enqueue(o.encode(
|
|
339
|
-
`))}else l.enqueue(o.encode(
|
|
338
|
+
`))}catch{l.enqueue(o.encode(_+`
|
|
339
|
+
`))}else l.enqueue(o.encode(_+`
|
|
340
340
|
`))}}catch(d){l.error(d)}finally{try{f.releaseLock()}catch{}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":r||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}if(r?.includes("application/json")){let n=await e.json();return n.choices?.[0]?.message?.reasoning_content&&(n.choices[0].message.thinking={content:n.choices[0].message.reasoning_content},delete n.choices[0].message.reasoning_content),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var Hy={AnthropicTransformer:Qs,GeminiTransformer:ti,VertexGeminiTransformer:Ca,VertexClaudeTransformer:Fa,DeepseekTransformer:wa,TooluseTransformer:Ea,OpenrouterTransformer:Aa,OpenAITransformer:Ba,MaxTokenTransformer:ka,GroqTransformer:Sa,CleancacheTransformer:va,EnhanceToolTransformer:Da,ReasoningTransformer:Ra,SamplingTransformer:xa,MaxCompletionTokens:Oa,CerebrasTransformer:Pa,StreamOptionsTransformer:Ia,CustomParamsTransformer:Na,VercelTransformer:Ma,OpenAIResponsesTransformer:ja,ForceReasoningTransformer:La,KimiTransformer:Ua};var ho=class{constructor(e,r){this.configService=e;this.logger=r}transformers=new Map;registerTransformer(e,r){this.transformers.set(e,r),this.logger.info(`register transformer: ${e}${r.endPoint?` (endpoint: ${r.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((r,n)=>{typeof r=="object"&&r.endPoint&&e.push({name:n,transformer:r})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((r,n)=>{typeof r=="object"&&!r.endPoint&&e.push({name:n,transformer:r})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let r=X(X.resolve(e.path));if(r){let n=new r(e.options);if(n&&typeof n=="object"&&(n.logger=this.logger),!n.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(n.name,n),!0}}return!1}catch(r){return this.logger.error(`load transformer (${e.path})
|
|
341
341
|
error: ${r.message}
|
|
342
342
|
stack: ${r.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
343
343
|
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(Hy).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let r=new e;r&&typeof r=="object"&&(r.logger=this.logger),this.registerTransformer(r.name,r)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let r of e)await this.registerTransformerFromConfig(r)}};import{get_encoding as OS}from"tiktoken";var is=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=OS(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 r=this.encoding;if(!r)throw new Error("Encoding not initialized");let n=0,{messages:o,system:s,tools:a}=e;return Array.isArray(o)&&o.forEach(c=>{typeof c.content=="string"?n+=r.encode(c.content).length:Array.isArray(c.content)&&c.content.forEach(l=>{if(l.type==="text")n+=r.encode(l.text).length;else if(l.type==="tool_use")n+=r.encode(JSON.stringify(l.input)).length;else if(l.type==="tool_result"){let f=typeof l.content=="string"?l.content:JSON.stringify(l.content);n+=r.encode(f).length}})}),typeof s=="string"?n+=r.encode(s).length:Array.isArray(s)&&s.forEach(c=>{c.type==="text"&&(typeof c.text=="string"?n+=r.encode(c.text).length:Array.isArray(c.text)&&c.text.forEach(l=>{n+=r.encode(l||"").length}))}),a&&a.forEach(c=>{c.description&&(n+=r.encode(c.name+c.description).length),c.input_schema&&(n+=r.encode(JSON.stringify(c.input_schema)).length)}),n}isInitialized(){return this.encoding!==void 0}encodeText(e){let r=this.encoding;if(!r)throw new Error("Encoding not initialized");return Array.from(r.encode(e))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as Ha}from"path";import{homedir as $T}from"os";import{existsSync as Ed,mkdirSync as qT}from"fs";import{promises as Wa}from"fs";var FS=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let n=e;for(let o=0;o<r.length;++o){let s=r[o];n=n[s]??=Object.create(null)}n.end=r}return e}split(t){let e=[],r=t.length,n=0,o=0;for(;o<r;){let s=this.trie,a=null,c=o;for(;c<r&&(s=s[t[c]]);)s.end&&(a=s.end),++c;a?(o>n&&e.push(t.slice(n,o)),e.push(a),o+=a.length,n=o):++o}return n<r&&e.push(t.slice(n)),e}},PS=FS,IS=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}},BS=IS,Qy=(()=>{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(),r=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+r),r+=1);let n=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,n[s]]))})(),NS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),MS=NS(Qy),Wy=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",jS=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|[${Wy}])]+`,` ?[^\\s${Wy}]+`]]),as="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",lF=new RegExp(`^[${as}]+$`,"gu"),Cd=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"),$a=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[n,o]of jS)r=r.replaceAll(n,o);return new RegExp(r,"gu")}else if(t.String!==void 0){let r=LS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},LS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),US=(t,e,r)=>{let n=[],o=0;for(;o<t.length;){if(n.push(t[o]),(e.get(t[o])??r)!==r){++o;continue}for(;++o<t.length&&(e.get(t[o])??r)===r;)e.get(n.at(-1))!==r&&(n[n.length-1]+=t[o])}return n},$S=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,qS=t=>Number.isInteger(t)||typeof t=="bigint",zS=t=>{let e=0;for(let r of t)++e;return e},HS=t=>Xy(t.toLowerCase()),Pt=(...t)=>Array.prototype.concat.apply([],t),wd=t=>new Map(Object.entries(t)),WS=(t,e)=>{let r=[],n=0;for(let o of t.matchAll(e)){let s=o[0];n<o.index&&r.push(t.slice(n,o.index)),s.length>0&&r.push(s),n=o.index+s.length}return n<t.length&&r.push(t.slice(n)),r},Xy=t=>t.replace(new RegExp("\\p{M}","gu"),""),Gy=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let n of r)if(!(n in t))return`${e} must contain a "${n}" property`;return null},GS=t=>t.match(/\S+/g)||[],JS=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},us=JS,VS=class extends us{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},vr=VS,KS=class extends vr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r],o=n.charCodeAt(0);$S(o)?(e.push(" "),e.push(n),e.push(" ")):e.push(n)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
|
|
344
|
-
`: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 r of t){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}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}},YS=KS,QS=class extends vr{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}},XS=QS,ZS=class extends vr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Zy(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},ev=ZS,tv=class extends vr{normalize(t){let e=$a(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},rv=tv,nv=class extends vr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},qa=nv,ov=class extends qa{constructor(){super(...arguments),this.form="NFC"}},sv=ov,iv=class extends qa{constructor(){super(...arguments),this.form="NFD"}},av=iv,uv=class extends qa{constructor(){super(...arguments),this.form="NFKC"}},cv=uv,lv=class extends qa{constructor(){super(...arguments),this.form="NFKD"}},dv=lv,fv=class extends vr{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}},hv=fv,pv=class extends vr{normalize(t){return Xy(t)}},mv=pv,gv=class extends vr{normalize(t){return t.toLowerCase()}},yv=gv,_v=class extends vr{normalize(t){return t=this.config.prepend+t,t}},bv=_v;function Cv(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new YS(t);case"Precompiled":return new XS(t);case"Sequence":return new ev(t);case"Replace":return new rv(t);case"NFC":return new sv(t);case"NFD":return new av(t);case"NFKC":return new cv(t);case"NFKD":return new dv(t);case"Strip":return new hv(t);case"StripAccents":return new mv(t);case"Lowercase":return new yv(t);case"Prepend":return new bv(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Zy=Cv,wv=class extends us{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},ur=wv,Ev=class extends ur{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=Qy,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(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},Av=Ev,kv=class extends ur{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Sv=kv,vv=class extends ur{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:r=void 0}=e??{},n=t.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},Tv=vv,Dv=class extends ur{constructor(t){super(),this.config=t,this.pattern=$a(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):WS(t,this.pattern)}},Rv=Dv,xv=class extends ur{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${as}]+|[${as}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Ov=xv,Fv=class extends ur{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)||[]}},Pv=Fv,Iv=class extends ur{constructor(){super(),this.pattern=new RegExp(`[^\\s${as}]+|[${as}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Bv=Iv,Nv=class extends ur{constructor(t){super(),this.config=t,this.pattern=$a(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Mv=Nv,jv=class extends ur{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>e0(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},Lv=jv,Uv=class extends ur{pre_tokenize_text(t){return GS(t)}},$v=Uv;function qv(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Bv;case"Sequence":return new Lv(t);case"Whitespace":return new Sv;case"WhitespaceSplit":return new $v;case"Metaspace":return new Tv(t);case"ByteLevel":return new Av(t);case"Split":return new Rv(t);case"Punctuation":return new Ov(t);case"Digits":return new Pv(t);case"Replace":return new Mv(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var e0=qv,zv=class extends us{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=US(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)}},za=zv,Hv=class extends za{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=wd(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,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let n=[...r];if(n.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<n.length;){let c=n.length,l=null;for(;s<c;){let f=n.slice(s,c).join("");if(s>0&&(f=this.config.continuing_subword_prefix+f),this.tokens_to_ids.has(f)){l=f;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},Jy=Hv,Vy=class t0{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new t0(!1,new Map)}},Wv=class{constructor(){this.root=Vy.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let n=e.children.get(r);n===void 0&&(n=Vy.default(),e.children.set(r,n)),e=n}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let n of t){if(r+=n,e=e.children.get(n),e===void 0)return;e.is_leaf&&(yield r)}}},Gv=Wv,bd=class r0{constructor(e,r,n,o,s){this.token_id=e,this.node_id=r,this.pos=n,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new r0(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},Jv=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new bd(this.bos_token_id??0,0,0,0,0),o=new bd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(n)}insert(t,e,r,n){let o=this.nodes.length,s=new bd(n,o,t,e,r);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 f=l.backtrace_score+s.score;(c===null||f>a)&&(c=l.clone(),a=f)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}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)}},Vv=Jv;function Kv(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let n=1;n<t.length;++n)t[n]<e&&(e=t[n],r=n);return[e,r]}var Yv=class extends za{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=t.vocab[n];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,o)=>[n,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=Kv(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Gv,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,n=0;for(;n<e.length;){let o=!1,s=[],a=e.slice(n).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let f=this.tokens_to_ids.get(l),d=this.scores[f],p=zS(l);t.insert(n,p,d,f),!o&&p===r&&(o=!0)}o||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new Vv(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let n=this.tokenize(r);e.push(...n)}return e}},Ky=Yv,Qv=class{constructor(t=(r,n)=>r>n,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 r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}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 r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_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}},Xv=Qv,Zv=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()}},eT=Zv,tT=class extends za{constructor(t){super(t),this.tokens_to_ids=wd(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[r,n]of this.tokens_to_ids)this.vocab[n]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),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 eT(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 r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let o=new Xv((c,l)=>c.score<l.score),s={token:r[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[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 f={...c.prev};c.prev.deleted=!0,c.prev=f,f.prev?f.prev.next=f:s=f}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)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let o=0;o<n.length-1;++o)n[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,n),n}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let n=this.bpe(r);for(let o of n)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}},Yy=tT,rT=class extends za{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=wd(e.target_lang?r[e.target_lang]:r),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[n,o]of this.tokens_to_ids)this.vocab[o]=n}encode(t){return t}},nT=rT;function oT(t,e){switch(t.type){case"WordPiece":return new Jy(t);case"Unigram":return new Ky(t,e.eos_token);case"BPE":return new Yy(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Ky(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new Yy(t):new Jy(t):new nT(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 sT=oT,iT=class extends us{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},cs=iT,aT=class extends cs{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of n)"SpecialToken"in a?r&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Pt(o,t),s=Pt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Pt(o,e),s=Pt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},uT=aT,cT=class extends cs{post_process(t,e=null){return{tokens:e?Pt(t,e):t}}},lT=cT,dT=class extends cs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Pt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=[],s=r?[this.sep[0]]:[];t=Pt(t,o,e,s),n=Pt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},fT=dT,hT=class extends cs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Pt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=r?[this.sep[0]]:[],s=r?[this.sep[0]]:[];t=Pt(t,o,e,s),n=Pt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},pT=hT,mT=class extends cs{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>n0(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let o of this.processors)n=o.post_process(n.tokens,e,r);return n}},gT=mT;function yT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new uT(t);case"ByteLevel":return new lT(t);case"BertProcessing":return new fT(t);case"RobertaProcessing":return new pT(t);case"Sequence":return new gT(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var n0=yT,_T=class extends us{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("")}},cr=_T,bT=class extends cr{constructor(t){super(t),this.byte_decoder=MS,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(""),r=new Uint8Array([...e].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let n of t)this.added_tokens.find(o=>o.content===n)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(n)):r.push(n);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},CT=bT,wT=class extends cr{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let n=this.config.prefix;n&&e.startsWith(n)?e=e.replace(n,""):e=" "+e}return this.cleanup&&(e=Cd(e)),e})}},ET=wT,AT=class extends cr{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),e.push(n)}return e}},kT=AT,ST=class extends cr{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},vT=ST,TT=class extends cr{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 n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let r=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=Cd(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},DT=TT,RT=class extends cr{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>o0(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},xT=RT,OT=class extends cr{decode_chain(t){let e=$a(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},FT=OT,PT=class extends cr{decode_chain(t){return[t.join("")]}},IT=PT,BT=class extends cr{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 r=0;for(let o=0;o<this.start&&e[o]===this.content;++o)r=o+1;let n=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){n=s;continue}else break}return e.slice(r,n)})}},NT=BT,MT=class extends cr{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let o=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let s=parseInt(n.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)r.push(o);else{if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},jT=MT;function LT(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new CT(t);case"WordPiece":return new ET(t);case"Metaspace":return new kT(t);case"BPEDecoder":return new vT(t);case"CTC":return new DT(t);case"Sequence":return new xT(t);case"Replace":return new FT(t);case"Fuse":return new IT(t);case"Strip":return new NT(t);case"ByteFallback":return new jT(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var o0=LT,UT=class{constructor(t,e){let r=Gy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=Gy(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=Zy(this.tokenizer.normalizer),this.pre_tokenizer=e0(this.tokenizer.pre_tokenizer),this.model=sT(this.tokenizer.model,this.config),this.post_processor=n0(this.tokenizer.post_processor),this.decoder=o0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new BS(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 PS(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:r=!0,return_token_type_ids:n=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return n&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!qS(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(r=r.filter(o=>!this.special_tokens.includes(o)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(n=n.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=Cd(n)),n}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((r,n)=>{let o=this.added_tokens_map.get(r);o&&(o.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),o.rstrip&&n<e.length-1&&(e[n+1]=e[n+1].trimStart()))}),e.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=HS(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(n,o,r):{tokens:Pt(n??[],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}},s0=UT;var Ga=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,r,n={}){this.modelId=e,this.logger=r,this.options=n,this.cacheDir=n.cacheDir||Ha($T(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Ha(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Ha(e,"tokenizer.json"),tokenizerConfig:Ha(e,"tokenizer_config.json")}}ensureDir(e){Ed(e)||qT(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Ed(e.tokenizerJson)||!Ed(e.tokenizerConfig))return null;let[r,n]=await Promise.all([Wa.readFile(e.tokenizerJson,"utf-8"),Wa.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(r),tokenizerConfig:JSON.parse(n)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),r={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 n=new AbortController,o=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.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([Wa.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Wa.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 r=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new s0(r.tokenizerJson,r.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 r=this.extractTextFromRequest(e);return this.tokenizer.encode(r).ids.length}catch(r){throw this.logger?.error(`Error counting tokens: ${r.message}`),r}}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 r=[],{messages:n,system:o,tools:s}=e;if(Array.isArray(n)){for(let a of n)if(typeof a.content=="string")r.push(a.content);else if(Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?r.push(c.text):c.type==="tool_use"&&c.input?r.push(JSON.stringify(c.input)):c.type==="tool_result"&&r.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")r.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")r.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&r.push(c)}}if(s)for(let a of s)a.name&&r.push(a.name),a.description&&r.push(a.description),a.input_schema&&r.push(JSON.stringify(a.input_schema));return r.join(" ")}};var Ja=class{type="api";name;config;logger;options;constructor(e,r,n={}){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=r,this.options=n;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 r=this.formatRequestBody(e),n={"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:n,body:JSON.stringify(r),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(r){throw r.name==="AbortError"?new Error("API tokenizer request timed out"):r}}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(r=>({role:r.role,content:this.extractTextFromMessage(r)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(r=>r.type==="text"&&r.text?r.text:r.type==="tool_use"&&r.input?JSON.stringify(r.input):r.type==="tool_result"?typeof r.content=="string"?r.content:JSON.stringify(r.content):"").join(" "):""}extractConcatenatedText(e){let r=[];return e.messages&&e.messages.forEach(n=>{r.push(this.extractTextFromMessage(n))}),typeof e.system=="string"?r.push(e.system):Array.isArray(e.system)&&e.system.forEach(n=>{n.type==="text"&&(typeof n.text=="string"?r.push(n.text):Array.isArray(n.text)&&n.text.forEach(o=>{o&&r.push(o)}))}),e.tools&&e.tools.forEach(n=>{n.name&&r.push(n.name),n.description&&r.push(n.description),n.input_schema&&r.push(JSON.stringify(n.input_schema))}),r.join(" ")}extractTokenCount(e){try{let r=this.config.responseField,n=r.split("."),o=e;for(let s of n){if(o==null)throw new Error(`Field path '${r}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${r}', got ${typeof o}`);return o}catch(r){throw this.logger?.error(`Failed to extract token count from API response: ${r.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${r.message}`)}}};var po=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,r,n={}){this.configService=e,this.logger=r,this.options={timeout:n.timeout??3e4,...n}}async initialize(){try{this.fallbackTokenizer=new is("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 r=this.getCacheKey(e);if(this.tokenizers.has(r))return this.tokenizers.get(r);let n;try{switch(e.type){case"tiktoken":n=new is(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Ga(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new Ja(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 n.initialize(),this.tokenizers.set(r,n),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${r})`),n}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,r){let n=r?await this.getTokenizer(r):this.fallbackTokenizer;return{tokenCount:await n.countTokens(e),tokenizerUsed:n.name,cached:!1}}getTokenizerConfigForModel(e,r){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[r]?o.tokenizer.models[r]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(r){this.logger?.error(`Error disposing tokenizer: ${r}`)}}),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)}`}}};import{get_encoding as HT}from"tiktoken";var Ad=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}values(){return Array.from(this.cache.values())}},kd=new Ad(100);In();import{readFile as Rd}from"fs/promises";import{opendir as WT,stat as GT}from"fs/promises";import{join as xd}from"path";import{CLAUDE_PROJECTS_DIR as i0,HOME_DIR as a0}from"@wengine-ai/claude-code-router-shared";var Sd=new Map;function vd(t,e){t&&Sd.set(t,{...e,provider:t,capturedAt:Date.now()})}function Td(t){let e=Sd.get(t);return e?{...e}:void 0}function zT(){return Array.from(Sd.values()).map(t=>({...t}))}Js();var Tr=HT("cl100k_base"),l0=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?n+=Tr.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?n+=Tr.encode(s.text).length:s.type==="tool_use"?n+=Tr.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(n+=Tr.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?n+=Tr.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?n+=Tr.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{n+=Tr.encode(s||"").length}))}),r&&r.forEach(o=>{o.description&&(n+=Tr.encode(o.name+o.description).length),o.input_schema&&(n+=Tr.encode(JSON.stringify(o.input_schema)).length)}),n},d0=async(t,e)=>{if(t.sessionId){let r=await p0(t.sessionId);if(r){let n=xd(a0,r,"config.json"),o=xd(a0,r,`${t.sessionId}.json`);try{let s=JSON.parse(await Rd(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await Rd(n,"utf8"));if(s&&s.Router)return s.Router}catch{}}}};function Va(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 f0(t){let e=Va(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),o=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:r};let s=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:r}:{family:null,extended:r}}function JT(t,e){if(!e||!t)return null;let r=Va(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=f0(t);if(n&&e[n])return e[n];for(let[o,s]of Object.entries(e)){let a=Va(o);if(a&&r.includes(a))return s}return null}function h0(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function u0(t){if(!t?.includes(","))return null;let[e,...r]=t.split(","),n=e.trim(),o=r.join(",").trim();return!n||!o?null:{providerName:n,routeModel:o}}function nt(t,e,r,n){let o=u0(t);if(!o)return t;let{providerName:s,routeModel:a}=o;if(n&&!r){let d=To(),p=d.getPromotion(s,a,n,e);if(p){let b=u0(p);if(b){let k=e.find(y=>y.name.toLowerCase()===b.providerName.toLowerCase()),C=k?.models?.find(y=>String(y).toLowerCase()===b.routeModel.toLowerCase());if(k&&C)return`${k.name},${C}`}d.clear(s,a,n)}}if(!r&&!it().isAvailable(s,a))return null;let c=Td(s);if(c){let d=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,p=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(d||p)return null}let l=e.find(d=>d.name.toLowerCase()===s.toLowerCase()),f=l?.models?.find(d=>String(d).toLowerCase()===a.toLowerCase());return l&&f?`${l.name},${f}`:t}function Vt(t,e,r,n,o){let s=it(),a=[r?.[t],n?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let f=nt(l,e);if(f)return f}return null}function VT(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function KT(t){let e=Va(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(n=>n.test(e))}function YT(t,e,r,n,o,s,a){let c=r.longContextThreshold||6e4,l=Math.max(e,h0(o)),f=t.modelFamily;if((s||l>2e5)&&r.extendedContext){let k=nt(r.extendedContext,n,!1,"extendedContext");if(k)return t.log.info(`Family: using extended context model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let C=Vt("extendedContext",n,r.fallback,a,f);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&&(r.longContext||r.fallback?.longContext?.length||a?.longContext?.length)){let k=r.longContext?nt(r.longContext,n,!1,"longContext"):null;if(k)return t.log.info(`Family: using long context model, tokens: ${l}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let C=Vt("longContext",n,r.fallback,a,f);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(k=>k.type?.startsWith("web_search"))&&r.webSearch){let k=nt(r.webSearch,n,!1,"webSearch");if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let C=Vt("webSearch",n,r.fallback,a,f);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&&r.think){let k=nt(r.think,n,!1,"think");if(k)return{model:k,scenarioType:"think",isFallback:!1};let C=Vt("think",n,r.fallback,a,f);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(r.default){let k=nt(r.default,n,!1,"default");if(k)return{model:k,scenarioType:"default",isFallback:!1};let C=Vt("default",n,r.fallback,a,f);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 QT=async(t,e,r,n)=>{let o=await d0(t,r),s=r.get("providers")||[],a=o||r.get("Router"),c=r.get("fallback");if(t.body.model.includes(",")){let m=nt(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 v=Vt("default",s,void 0,c);if(v)return t.log.info(`Using fallback for explicit model: ${v}`),{model:v,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:l,extended:f}=f0(t.body.model),d=a?.families?.[l||""];if(d&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${l}${f?" (1M)":""}`),t.modelFamily=l,t.familyFallback=d.fallback;let m=YT(t,e,d,s,n,f,c);if(m)return{model:m.model,scenarioType:m.scenarioType}}let p=JT(t.body.model,a?.models);if(p){let m=nt(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 b=Math.max(e,h0(n)),k=a?.extendedContextThreshold||2e5;if(b>k&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${b}, estimated: ${e}, threshold: ${k}`);let m=nt(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 v=Vt("extendedContext",s,void 0,c);if(v)return{model:v,scenarioType:"extendedContext"}}let C=a?.longContextThreshold||6e4;if(b>C&&a?.longContext){t.log.info(`Using long context model due to token count: ${b}, estimated: ${e}, threshold: ${C}`);let m=nt(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 v=Vt("longContext",s,void 0,c);if(v)return{model:v,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 g=r.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 m=nt(g.background,s,!1,"background");if(m)return{model:m,scenarioType:"background"};t.log.warn(`Background model ${g.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=nt(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 v=Vt("webSearch",s,void 0,c);if(v)return{model:v,scenarioType:"webSearch"}}if(t.body.thinking&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let m=nt(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 v=Vt("think",s,void 0,c);if(v)return{model:v,scenarioType:"think"}}if(a?.default){let m=nt(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 v=Vt("default",s,void 0,c);if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Od=async(t,e,r)=>{let{configService:n,event:o}=r;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let k=t.body.metadata.user_id.split("_session_");k.length>1&&(t.sessionId=k[1])}let a=await d0(t,n)||n.get("Router"),c=n.get("providers")||[],l=kd.get(t.sessionId),{messages:f,system:d=[],tools:p}=t.body,b=n.get("REWRITE_SYSTEM_PROMPT");if(b&&d.length>1&&d[1]?.text?.includes("<env>")){let k=await Rd(b,"utf-8");d[1].text=`${k}<env>${d[1].text.split("<env>").pop()}`}try{let[k,C]=t.body.model.split(","),y=r.tokenizerService?.getTokenizerConfigForModel(k,C),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:f,system:d,tools:p},y)).tokenCount:g=l0(f,d,p),t.tokenCount=g;let m,v=n.get("CUSTOM_ROUTER_PATH");if(v)try{m=await X(v)(t,n.getAll(),{event:o})}catch(_){t.log.error(`failed to load custom router: ${_.message}`)}if(m)t.scenarioType="default";else{let _=await QT(t,g,n,l);m=_.model,t.scenarioType=_.scenarioType}if(a?.image&&m!==a.image&&VT(t)&&!KT(m)){let _=nt(a.image,c,!1,"image");_?(t.log.info(`Using image model fallback for ${m}`),m=_,t.scenarioType="image"):t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${m}`)}t.body.model=m}catch(k){t.log.error(`Error in router middleware: ${k.message}`),t.body.model=a?.default,t.scenarioType="default"}},Dr=new Map,c0=1e3;function Dd(){if(Dr.size<=c0)return;let t=[...Dr.keys()].slice(0,Dr.size-c0);for(let e of t)Dr.delete(e)}var p0=async t=>{if(Dr.has(t)){let e=Dr.get(t);return!e||e===""?null:e}try{let e=await WT(i0),r=[];for await(let s of e)s.isDirectory()&&r.push(s.name);let n=r.map(async s=>{let a=xd(i0,s,`${t}.jsonl`);try{return(await GT(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(n);for(let s of o)if(s)return Dr.set(t,s),Dd(),s;return Dr.set(t,""),Dd(),null}catch(e){return console.error("Error searching for project by session:",e),Dr.set(t,""),Dd(),null}};In();var Rr=class{async fetchJson(e,r,n,o){if(!r.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.apiKey}`},signal:AbortSignal.timeout(n)};if(o)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(o).toString())}catch{}try{let a=await fetch(e,s);return a.ok?await a.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}},Fd=class extends Rr{async queryQuota(e,r,n){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,r,n),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>Ae(l?.total_balance)!==void 0);if(!a)return null;let c=Ae(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},Pd=class extends Rr{async queryQuota(e,r,n){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,r,n))?.data;if(!s||typeof s!="object")return null;let a={},c=Ae(s.limit),l=Ae(s.limit_remaining),f=Ae(s.usage),d=Ae(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),f!==void 0&&(a.usedBalance=f),d!==void 0&&(a.usedDailyBalance=d),this.hasQuotaData(a)?a:null}},Id=class extends Rr{async queryQuota(e,r,n){let o=sD(e.baseUrl),a=(await this.fetchJson(o,e,r,n))?.data;if(!a||typeof a!="object")return null;let c={},l=Ae(a.totalBalance),f=Ae(a.balance);return l!==void 0&&(c.totalBalance=l),f!==void 0&&(c.remainingBalance=f),l!==void 0&&f!==void 0&&(c.usedBalance=Math.max(0,l-f)),this.hasQuotaData(c)?c:null}},Bd=class extends Rr{async queryQuota(e,r,n){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=o.trim();s.toLowerCase().startsWith("bearer ")||s.startsWith("ey")&&(s=`Bearer ${s}`);let a={method:"GET",headers:{Accept:"application/json",Authorization:s},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:c}=await import("undici");a.dispatcher=new c(new URL(n).toString())}catch{}try{let c=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",a);if(!c.ok)return null;let l=await c.json(),f=Array.isArray(l?.data?.limits)?l.data.limits:[],d=null,p=null,b=null;for(let C of f)C.type==="TOKENS_LIMIT"?C.unit===3?d=C:C.unit===6?p=C:d||(d=C):C.type==="TIME_LIMIT"&&(b=C);let k={};if(d){let C=Ae(d.currentValue),y=Ae(d.usage),g=Ae(d.remaining),m=Ae(d.percentage);C!==void 0?k.usedDailyBalance=C:m!==void 0&&(k.usedDailyBalance=m,k.limitDaily=100),y!==void 0?k.limitDaily=y:C!==void 0&&g!==void 0&&(k.limitDaily=C+g),d.nextResetTime&&(k.resetTime=new Date(d.nextResetTime).toISOString())}if(p){let C=Ae(p.currentValue),y=Ae(p.usage),g=Ae(p.remaining),m=Ae(p.percentage);C!==void 0?k.usedBalance=C:m!==void 0&&(k.usedBalance=m,k.totalBalance=100),y!==void 0?k.totalBalance=y:C!==void 0&&g!==void 0&&(k.totalBalance=C+g),p.nextResetTime&&!k.resetTime&&(k.resetTime=new Date(p.nextResetTime).toISOString())}if(b){if(k.usedDailyBalance===void 0){let C=Ae(b.currentValue);C!==void 0&&(k.usedDailyBalance=C)}if(k.limitDaily===void 0){let C=Ae(b.usage),y=Ae(b.currentValue),g=Ae(b.remaining);C!==void 0?k.limitDaily=C:y!==void 0&&g!==void 0&&(k.limitDaily=y+g)}b.nextResetTime&&!k.resetTime&&(k.resetTime=new Date(b.nextResetTime).toISOString())}return this.hasQuotaData(k)?k:null}catch{return null}}},Nd=class extends Rr{async queryQuota(e,r,n){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(r)};if(n)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(n).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 f=(await c.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(f)||f.length===0)return null;let d=f[0]?.codingPlanQuotaInfo;if(!d)return null;let p={},b=Ae(d.per5HourUsedQuota),k=Ae(d.per5HourTotalQuota);b!==void 0&&(p.usedDailyBalance=b),k!==void 0&&(p.limitDaily=k);let C=Ae(d.perWeekUsedQuota),y=Ae(d.perWeekTotalQuota);return C!==void 0&&(p.usedBalance=C),y!==void 0&&(p.totalBalance=y),this.hasQuotaData(p)?p:null}catch{return null}}},Md=class extends Rr{async queryQuota(e,r,n){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(r)};if(n)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(n).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={},f=Array.isArray(c?.limits)?c.limits:[];if(f.length>0&&f[0]?.detail){let p=f[0].detail,b=Ae(p.limit),k=Ae(p.remaining),C=p.resetTime;b!==void 0&&k!==void 0&&(l.usedDailyBalance=Math.max(0,b-k),l.limitDaily=b),C&&(l.resetTime=new Date(C).toISOString())}let d=c?.usage;if(d){let p=Ae(d.limit),b=Ae(d.remaining),k=d.resetTime;p!==void 0&&b!==void 0&&(l.usedBalance=Math.max(0,p-b),l.remainingBalance=b,l.totalBalance=p),k&&!l.resetTime&&(l.resetTime=new Date(k).toISOString())}return this.hasQuotaData(l)?l:null}catch{return null}}},jd=class extends Rr{async queryQuota(e,r,n){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=Ud(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com",c={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:l}=await import("undici");c.dispatcher=new l(new URL(n).toString())}catch{}try{let l=await fetch(`https://${a}/v1/api/openplatform/coding_plan/remains`,c);if(!l.ok)return null;let f=await l.json();if(f?.base_resp){let _=f.base_resp.status_code;if(_!==void 0&&_!==0)return null}let d=Array.isArray(f?.model_remains)?f.model_remains:[];if(d.length===0)return null;let p=d[0],b={},k=Ae(p.current_interval_total_count),C=Ae(p.current_interval_usage_count),y=Ae(p.end_time);k!==void 0&&C!==void 0&&(b.usedDailyBalance=Math.max(0,k-C),b.limitDaily=k),y&&(b.resetTime=new Date(y).toISOString());let g=Ae(p.current_weekly_total_count),m=Ae(p.current_weekly_usage_count),v=Ae(p.weekly_end_time);return g!==void 0&&m!==void 0&&(b.usedBalance=Math.max(0,g-m),b.remainingBalance=m,b.totalBalance=g),v&&!b.resetTime&&(b.resetTime=new Date(v).toISOString()),this.hasQuotaData(b)?b:null}catch{return null}}},XT=new Fd,ZT=new Pd,eD=new Id,tD=new Bd,rD=new Nd,nD=new Md,oD=new jd;function Ld(t){let e=Ud(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?nD:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?oD:e==="deepseek.com"||e.endsWith(".deepseek.com")?XT:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?ZT:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?eD:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?tD:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?rD:null:null}function sD(t){let e=Ud(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Ud(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function Ae(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 r=Number(e);return Number.isFinite(r)?r:void 0}var iD={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function aD(t){try{let e=new URL(t),r=e.pathname;return r.endsWith("/v1/messages")?r=r.slice(0,-12):r.endsWith("/messages")?r=r.slice(0,-9):r.endsWith("/v1/chat/completions")?r=r.slice(0,-20):r.endsWith("/chat/completions")&&(r=r.slice(0,-17)),r.endsWith("/v1")||(r=r.endsWith("/")?`${r}v1`:`${r}/v1`),e.pathname=`${r}/models`,e.toString()}catch{return null}}function uD(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function $d(t,e,r){let n=aD(t.baseUrl);if(!n)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(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=await fetch(n,o);if(s.headers&&Do(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,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"}}}var Ka=class{config;quotaProbeTimer;healthProbeTimer;getProviders;getHttpsProxy;logger;running=!1;constructor(e,r,n,o){this.config={...iD,...r},this.getProviders=e,this.getHttpsProxy=n,this.logger=o}start(){!this.config.enabled||this.running||(this.running=!0,setTimeout(()=>{this.running&&(this.runQuotaProbe(),this.runHealthProbe())},this.config.initialDelayMs),this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*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.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&!this.config.excludeProviders.includes(a.name)),r=this.getHttpsProxy?.(),n=it();if(e.length===0)return;let o=[];for(let a of e){let c=Ld(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,r).then(f=>{if(f){vd(a.name,f),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let d=f.limitDaily!==void 0&&f.usedDailyBalance!==void 0&&f.usedDailyBalance>=f.limitDaily,p=f.totalBalance!==void 0&&f.usedBalance!==void 0&&f.usedBalance>=f.totalBalance;if(d||p){let b=d?`Quota exhausted: 5h limit reached (${f.usedDailyBalance}/${f.limitDaily})`:`Quota exhausted: 7d balance depleted (${f.usedBalance}/${f.totalBalance})`;for(let k of l)n.forceOpen(a.name,k,b);this.logger?.warn?.(`${b} for ${a.name}, marked as unhealthy`)}}})}),uD(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:$d(a,this.config.probeTimeoutMs,r).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=it(),r=this.getProviders().filter(s=>s?.name&&!this.config.excludeProviders.includes(s.name)),n=this.getHttpsProxy?.();if(r.length===0)return;this.logger?.debug?.(`Running health probe for ${r.length} providers`);let o=await Promise.allSettled(r.map(s=>$d(s,this.config.probeTimeoutMs,n)));for(let s=0;s<r.length;s++){let a=r[s],c=o[s],l=Array.isArray(a.models)?a.models:[];if(c.status==="fulfilled"){let f=c.value;if(f.success){for(let d of l)e.recordSuccess(a.name,d);this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let d of l)e.recordFailure(a.name,d,f.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${f.error}`)}}else{for(let f of l)e.recordFailure(a.name,f,c.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${c.reason}`)}}}async probeProviderManually(e){let n=this.getProviders().find(c=>c.name===e);if(!n)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;let o=this.getHttpsProxy?.(),s=await $d(n,this.config.probeTimeoutMs,o),a=Array.isArray(n.models)?n.models:[];if(s.success)for(let c of a)it().recordSuccess(n.name,c);else for(let c of a)it().recordFailure(n.name,c,s.error);return s.success}},Qr=null;function m0(t,e,r,n){return Qr||(Qr=new Ka(t,e,r,n)),Qr}function qd(t,e,r,n){let o=m0(t,e,r,n);return o.start(),o}function zd(){Qr&&Qr.stop()}function cD(){Qr&&(Qr.stop(),Qr=null)}var Hd=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,r={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:r.enabled!==!1,options:r})}async enablePlugin(e,r){let n=this.plugins.get(e),o=this.pluginInstances.get(e);if(!n||!o)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(o.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${r}: ${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,r){let n=this.plugins.get(e);n&&(n.enabled=r)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},g0=new Hd;var T0=jr(w0(),1);var mo=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
|
|
344
|
+
`: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 r of t){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}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}},YS=KS,QS=class extends vr{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}},XS=QS,ZS=class extends vr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Zy(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},ev=ZS,tv=class extends vr{normalize(t){let e=$a(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},rv=tv,nv=class extends vr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},qa=nv,ov=class extends qa{constructor(){super(...arguments),this.form="NFC"}},sv=ov,iv=class extends qa{constructor(){super(...arguments),this.form="NFD"}},av=iv,uv=class extends qa{constructor(){super(...arguments),this.form="NFKC"}},cv=uv,lv=class extends qa{constructor(){super(...arguments),this.form="NFKD"}},dv=lv,fv=class extends vr{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}},hv=fv,pv=class extends vr{normalize(t){return Xy(t)}},mv=pv,gv=class extends vr{normalize(t){return t.toLowerCase()}},yv=gv,_v=class extends vr{normalize(t){return t=this.config.prepend+t,t}},bv=_v;function Cv(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new YS(t);case"Precompiled":return new XS(t);case"Sequence":return new ev(t);case"Replace":return new rv(t);case"NFC":return new sv(t);case"NFD":return new av(t);case"NFKC":return new cv(t);case"NFKD":return new dv(t);case"Strip":return new hv(t);case"StripAccents":return new mv(t);case"Lowercase":return new yv(t);case"Prepend":return new bv(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Zy=Cv,wv=class extends us{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},ur=wv,Ev=class extends ur{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=Qy,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(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},Av=Ev,kv=class extends ur{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Sv=kv,vv=class extends ur{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:r=void 0}=e??{},n=t.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},Tv=vv,Dv=class extends ur{constructor(t){super(),this.config=t,this.pattern=$a(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):WS(t,this.pattern)}},Rv=Dv,xv=class extends ur{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${as}]+|[${as}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Ov=xv,Fv=class extends ur{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)||[]}},Pv=Fv,Iv=class extends ur{constructor(){super(),this.pattern=new RegExp(`[^\\s${as}]+|[${as}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Bv=Iv,Nv=class extends ur{constructor(t){super(),this.config=t,this.pattern=$a(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Mv=Nv,jv=class extends ur{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>e0(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,e):r,[t])}},Lv=jv,Uv=class extends ur{pre_tokenize_text(t){return GS(t)}},$v=Uv;function qv(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Bv;case"Sequence":return new Lv(t);case"Whitespace":return new Sv;case"WhitespaceSplit":return new $v;case"Metaspace":return new Tv(t);case"ByteLevel":return new Av(t);case"Split":return new Rv(t);case"Punctuation":return new Ov(t);case"Digits":return new Pv(t);case"Replace":return new Mv(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var e0=qv,zv=class extends us{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=US(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)}},za=zv,Hv=class extends za{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=wd(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,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let n=[...r];if(n.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<n.length;){let c=n.length,l=null;for(;s<c;){let f=n.slice(s,c).join("");if(s>0&&(f=this.config.continuing_subword_prefix+f),this.tokens_to_ids.has(f)){l=f;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},Jy=Hv,Vy=class t0{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new t0(!1,new Map)}},Wv=class{constructor(){this.root=Vy.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let n=e.children.get(r);n===void 0&&(n=Vy.default(),e.children.set(r,n)),e=n}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let n of t){if(r+=n,e=e.children.get(n),e===void 0)return;e.is_leaf&&(yield r)}}},Gv=Wv,bd=class r0{constructor(e,r,n,o,s){this.token_id=e,this.node_id=r,this.pos=n,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new r0(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},Jv=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new bd(this.bos_token_id??0,0,0,0,0),o=new bd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(n)}insert(t,e,r,n){let o=this.nodes.length,s=new bd(n,o,t,e,r);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 f=l.backtrace_score+s.score;(c===null||f>a)&&(c=l.clone(),a=f)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}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)}},Vv=Jv;function Kv(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let n=1;n<t.length;++n)t[n]<e&&(e=t[n],r=n);return[e,r]}var Yv=class extends za{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=t.vocab[n];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,o)=>[n,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=Kv(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Gv,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,n=0;for(;n<e.length;){let o=!1,s=[],a=e.slice(n).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let f=this.tokens_to_ids.get(l),d=this.scores[f],p=zS(l);t.insert(n,p,d,f),!o&&p===r&&(o=!0)}o||t.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(t){let e=new Vv(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let n=this.tokenize(r);e.push(...n)}return e}},Ky=Yv,Qv=class{constructor(t=(r,n)=>r>n,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 r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}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 r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_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}},Xv=Qv,Zv=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()}},eT=Zv,tT=class extends za{constructor(t){super(t),this.tokens_to_ids=wd(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[r,n]of this.tokens_to_ids)this.vocab[n]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),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 eT(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 r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let o=new Xv((c,l)=>c.score<l.score),s={token:r[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<r.length;++c){let l={bias:c/r.length,token:r[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 f={...c.prev};c.prev.deleted=!0,c.prev=f,f.prev?f.prev.next=f:s=f}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)n.push(c.token)}else n=r;if(this.continuing_subword_suffix)for(let o=0;o<n.length-1;++o)n[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,n),n}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let n=this.bpe(r);for(let o of n)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}},Yy=tT,rT=class extends za{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=wd(e.target_lang?r[e.target_lang]:r),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[n,o]of this.tokens_to_ids)this.vocab[o]=n}encode(t){return t}},nT=rT;function oT(t,e){switch(t.type){case"WordPiece":return new Jy(t);case"Unigram":return new Ky(t,e.eos_token);case"BPE":return new Yy(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Ky(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new Yy(t):new Jy(t):new nT(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 sT=oT,iT=class extends us{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},cs=iT,aT=class extends cs{post_process(t,e=null,r=!0){let n=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of n)"SpecialToken"in a?r&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Pt(o,t),s=Pt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Pt(o,e),s=Pt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},uT=aT,cT=class extends cs{post_process(t,e=null){return{tokens:e?Pt(t,e):t}}},lT=cT,dT=class extends cs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Pt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=[],s=r?[this.sep[0]]:[];t=Pt(t,o,e,s),n=Pt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},fT=dT,hT=class extends cs{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Pt([this.cls[0]],t,[this.sep[0]]));let n=new Array(t.length).fill(0);if(e){let o=r?[this.sep[0]]:[],s=r?[this.sep[0]]:[];t=Pt(t,o,e,s),n=Pt(n,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:n}}},pT=hT,mT=class extends cs{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>n0(e))}post_process(t,e=null,r=!0){let n={tokens:t};for(let o of this.processors)n=o.post_process(n.tokens,e,r);return n}},gT=mT;function yT(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new uT(t);case"ByteLevel":return new lT(t);case"BertProcessing":return new fT(t);case"RobertaProcessing":return new pT(t);case"Sequence":return new gT(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var n0=yT,_T=class extends us{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("")}},cr=_T,bT=class extends cr{constructor(t){super(t),this.byte_decoder=MS,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(""),r=new Uint8Array([...e].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let n of t)this.added_tokens.find(o=>o.content===n)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(n)):r.push(n);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},CT=bT,wT=class extends cr{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let n=this.config.prefix;n&&e.startsWith(n)?e=e.replace(n,""):e=" "+e}return this.cleanup&&(e=Cd(e)),e})}},ET=wT,AT=class extends cr{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let n=t[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),e.push(n)}return e}},kT=AT,ST=class extends cr{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},vT=ST,TT=class extends cr{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 n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let r=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=Cd(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},DT=TT,RT=class extends cr{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>o0(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},xT=RT,OT=class extends cr{decode_chain(t){let e=$a(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(n=>n.replaceAll(e,r))}},FT=OT,PT=class extends cr{decode_chain(t){return[t.join("")]}},IT=PT,BT=class extends cr{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 r=0;for(let o=0;o<this.start&&e[o]===this.content;++o)r=o+1;let n=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){n=s;continue}else break}return e.slice(r,n)})}},NT=BT,MT=class extends cr{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let n of t){let o=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let s=parseInt(n.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)r.push(o);else{if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}e.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));e.push(n),r=[]}return e}},jT=MT;function LT(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new CT(t);case"WordPiece":return new ET(t);case"Metaspace":return new kT(t);case"BPEDecoder":return new vT(t);case"CTC":return new DT(t);case"Sequence":return new xT(t);case"Replace":return new FT(t);case"Fuse":return new IT(t);case"Strip":return new NT(t);case"ByteFallback":return new jT(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var o0=LT,UT=class{constructor(t,e){let r=Gy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=Gy(e,"Config");if(n)throw new Error(n);this.tokenizer=t,this.config=e,this.normalizer=Zy(this.tokenizer.normalizer),this.pre_tokenizer=e0(this.tokenizer.pre_tokenizer),this.model=sT(this.tokenizer.model,this.config),this.post_processor=n0(this.tokenizer.post_processor),this.decoder=o0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new BS(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 PS(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:r=!0,return_token_type_ids:n=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return n&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!qS(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(r=r.filter(o=>!this.special_tokens.includes(o)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(n=n.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=Cd(n)),n}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((r,n)=>{let o=this.added_tokens_map.get(r);o&&(o.lstrip&&n>0&&(e[n-1]=e[n-1].trimEnd()),o.rstrip&&n<e.length-1&&(e[n+1]=e[n+1].trimStart()))}),e.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=HS(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(r,{section_index:n}):[r];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let n=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(n,o,r):{tokens:Pt(n??[],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}},s0=UT;var Ga=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,r,n={}){this.modelId=e,this.logger=r,this.options=n,this.cacheDir=n.cacheDir||Ha($T(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Ha(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Ha(e,"tokenizer.json"),tokenizerConfig:Ha(e,"tokenizer_config.json")}}ensureDir(e){Ed(e)||qT(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Ed(e.tokenizerJson)||!Ed(e.tokenizerConfig))return null;let[r,n]=await Promise.all([Wa.readFile(e.tokenizerJson,"utf-8"),Wa.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(r),tokenizerConfig:JSON.parse(n)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),r={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 n=new AbortController,o=setTimeout(()=>n.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(r.json,{signal:n.signal}),fetch(r.config,{signal:n.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([Wa.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),Wa.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 r=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new s0(r.tokenizerJson,r.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 r=this.extractTextFromRequest(e);return this.tokenizer.encode(r).ids.length}catch(r){throw this.logger?.error(`Error counting tokens: ${r.message}`),r}}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 r=[],{messages:n,system:o,tools:s}=e;if(Array.isArray(n)){for(let a of n)if(typeof a.content=="string")r.push(a.content);else if(Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?r.push(c.text):c.type==="tool_use"&&c.input?r.push(JSON.stringify(c.input)):c.type==="tool_result"&&r.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")r.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")r.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&r.push(c)}}if(s)for(let a of s)a.name&&r.push(a.name),a.description&&r.push(a.description),a.input_schema&&r.push(JSON.stringify(a.input_schema));return r.join(" ")}};var Ja=class{type="api";name;config;logger;options;constructor(e,r,n={}){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=r,this.options=n;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 r=this.formatRequestBody(e),n={"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:n,body:JSON.stringify(r),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(r){throw r.name==="AbortError"?new Error("API tokenizer request timed out"):r}}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(r=>({role:r.role,content:this.extractTextFromMessage(r)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(r=>r.type==="text"&&r.text?r.text:r.type==="tool_use"&&r.input?JSON.stringify(r.input):r.type==="tool_result"?typeof r.content=="string"?r.content:JSON.stringify(r.content):"").join(" "):""}extractConcatenatedText(e){let r=[];return e.messages&&e.messages.forEach(n=>{r.push(this.extractTextFromMessage(n))}),typeof e.system=="string"?r.push(e.system):Array.isArray(e.system)&&e.system.forEach(n=>{n.type==="text"&&(typeof n.text=="string"?r.push(n.text):Array.isArray(n.text)&&n.text.forEach(o=>{o&&r.push(o)}))}),e.tools&&e.tools.forEach(n=>{n.name&&r.push(n.name),n.description&&r.push(n.description),n.input_schema&&r.push(JSON.stringify(n.input_schema))}),r.join(" ")}extractTokenCount(e){try{let r=this.config.responseField,n=r.split("."),o=e;for(let s of n){if(o==null)throw new Error(`Field path '${r}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${r}', got ${typeof o}`);return o}catch(r){throw this.logger?.error(`Failed to extract token count from API response: ${r.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${r.message}`)}}};var po=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,r,n={}){this.configService=e,this.logger=r,this.options={timeout:n.timeout??3e4,...n}}async initialize(){try{this.fallbackTokenizer=new is("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 r=this.getCacheKey(e);if(this.tokenizers.has(r))return this.tokenizers.get(r);let n;try{switch(e.type){case"tiktoken":n=new is(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),n=new Ga(e.model,this.logger,{timeout:this.options.timeout});break;case"api":n=new Ja(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 n.initialize(),this.tokenizers.set(r,n),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${r})`),n}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,r){let n=r?await this.getTokenizer(r):this.fallbackTokenizer;return{tokenCount:await n.countTokens(e),tokenizerUsed:n.name,cached:!1}}getTokenizerConfigForModel(e,r){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[r]?o.tokenizer.models[r]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(r){this.logger?.error(`Error disposing tokenizer: ${r}`)}}),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)}`}}};import{get_encoding as HT}from"tiktoken";var Ad=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let r=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,r),r}put(e,r){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,r)}values(){return Array.from(this.cache.values())}},kd=new Ad(100);In();import{readFile as Rd}from"fs/promises";import{opendir as WT,stat as GT}from"fs/promises";import{join as xd}from"path";import{CLAUDE_PROJECTS_DIR as i0,HOME_DIR as a0}from"@wengine-ai/claude-code-router-shared";var Sd=new Map;function vd(t,e){t&&Sd.set(t,{...e,provider:t,capturedAt:Date.now()})}function Td(t){let e=Sd.get(t);return e?{...e}:void 0}function zT(){return Array.from(Sd.values()).map(t=>({...t}))}Js();var Tr=HT("cl100k_base"),l0=(t,e,r)=>{let n=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?n+=Tr.encode(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?n+=Tr.encode(s.text).length:s.type==="tool_use"?n+=Tr.encode(JSON.stringify(s.input)).length:s.type==="tool_result"&&(n+=Tr.encode(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?n+=Tr.encode(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?n+=Tr.encode(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{n+=Tr.encode(s||"").length}))}),r&&r.forEach(o=>{o.description&&(n+=Tr.encode(o.name+o.description).length),o.input_schema&&(n+=Tr.encode(JSON.stringify(o.input_schema)).length)}),n},d0=async(t,e)=>{if(t.sessionId){let r=await p0(t.sessionId);if(r){let n=xd(a0,r,"config.json"),o=xd(a0,r,`${t.sessionId}.json`);try{let s=JSON.parse(await Rd(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await Rd(n,"utf8"));if(s&&s.Router)return s.Router}catch{}}}};function Va(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 f0(t){let e=Va(t),r=e.includes("[1m]")||e.endsWith("[1m"),n=e.replace(/\[1m\]|\[1m$/g,""),o=n.match(/^ccr-(opus|sonnet|haiku)$/i);if(o)return{family:o[1].toLowerCase(),extended:r};let s=n.match(/claude-(?:\d+-\d+-|\d+-)?(sonnet|opus|haiku)(?:-|$)/i)||n.match(/claude-(sonnet|opus|haiku)(?:-|$)/i);return s?{family:s[1].toLowerCase(),extended:r}:{family:null,extended:r}}function JT(t,e){if(!e||!t)return null;let r=Va(t);if(e[t])return e[t];if(e[r])return e[r];let{family:n}=f0(t);if(n&&e[n])return e[n];for(let[o,s]of Object.entries(e)){let a=Va(o);if(a&&r.includes(a))return s}return null}function h0(t){return t?(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0):0}function u0(t){if(!t?.includes(","))return null;let[e,...r]=t.split(","),n=e.trim(),o=r.join(",").trim();return!n||!o?null:{providerName:n,routeModel:o}}function nt(t,e,r,n){let o=u0(t);if(!o)return t;let{providerName:s,routeModel:a}=o;if(n&&!r){let d=To(),p=d.getPromotion(s,a,n,e);if(p){let C=u0(p);if(C){let k=e.find(y=>y.name.toLowerCase()===C.providerName.toLowerCase()),_=k?.models?.find(y=>String(y).toLowerCase()===C.routeModel.toLowerCase());if(k&&_)return`${k.name},${_}`}d.clear(s,a,n)}}if(!r&&!it().isAvailable(s,a))return null;let c=Td(s);if(c){let d=c.limitDaily!==void 0&&c.usedDailyBalance!==void 0&&c.usedDailyBalance>=c.limitDaily,p=c.totalBalance!==void 0&&c.usedBalance!==void 0&&c.usedBalance>=c.totalBalance;if(d||p)return null}let l=e.find(d=>d.name.toLowerCase()===s.toLowerCase()),f=l?.models?.find(d=>String(d).toLowerCase()===a.toLowerCase());return l&&f?`${l.name},${f}`:t}function Vt(t,e,r,n,o){let s=it(),a=[r?.[t],n?.[t]];for(let c of a)if(!(!Array.isArray(c)||c.length===0))for(let l of c){let f=nt(l,e);if(f)return f}return null}function VT(t){return t.body.messages?.some(e=>e.role==="user"&&Array.isArray(e.content)&&e.content.some(r=>r.type==="image"||r.type==="image_url"||Array.isArray(r?.content)&&r.content.some(n=>n.type==="image"||n.type==="image_url")))}function KT(t){let e=Va(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(n=>n.test(e))}function YT(t,e,r,n,o,s,a){let c=r.longContextThreshold||6e4,l=Math.max(e,h0(o)),f=t.modelFamily;if((s||l>2e5)&&r.extendedContext){let k=nt(r.extendedContext,n,!1,"extendedContext");if(k)return t.log.info(`Family: using extended context model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:k,scenarioType:"extendedContext",isFallback:!1};let _=Vt("extendedContext",n,r.fallback,a,f);if(_)return t.log.info(`Family: using extended context fallback model (1M+), tokens: ${l}, estimated: ${e}, explicit: ${s}`),{model:_,scenarioType:"extendedContext",isFallback:!0};t.log.warn("Family: extendedContext model unavailable (fail pool), skipping")}if(l>c&&(r.longContext||r.fallback?.longContext?.length||a?.longContext?.length)){let k=r.longContext?nt(r.longContext,n,!1,"longContext"):null;if(k)return t.log.info(`Family: using long context model, tokens: ${l}, estimated: ${e}`),{model:k,scenarioType:"longContext",isFallback:!1};let _=Vt("longContext",n,r.fallback,a,f);if(_)return t.log.info(`Family: using long context fallback model, tokens: ${l}, estimated: ${e}`),{model:_,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(k=>k.type?.startsWith("web_search"))&&r.webSearch){let k=nt(r.webSearch,n,!1,"webSearch");if(k)return{model:k,scenarioType:"webSearch",isFallback:!1};let _=Vt("webSearch",n,r.fallback,a,f);if(_)return t.log.info("Family: using webSearch fallback model"),{model:_,scenarioType:"webSearch",isFallback:!0};t.log.warn("Family: webSearch model unavailable (fail pool), skipping")}if(t.body.thinking&&r.think){let k=nt(r.think,n,!1,"think");if(k)return{model:k,scenarioType:"think",isFallback:!1};let _=Vt("think",n,r.fallback,a,f);if(_)return t.log.info("Family: using think fallback model"),{model:_,scenarioType:"think",isFallback:!0};t.log.warn("Family: think model unavailable (fail pool), skipping")}if(r.default){let k=nt(r.default,n,!1,"default");if(k)return{model:k,scenarioType:"default",isFallback:!1};let _=Vt("default",n,r.fallback,a,f);if(_)return t.log.info("Family: using default fallback model"),{model:_,scenarioType:"default",isFallback:!0};t.log.warn("Family: default model unavailable (fail pool), skipping")}return null}var QT=async(t,e,r,n)=>{let o=await d0(t,r),s=r.get("providers")||[],a=o||r.get("Router"),c=r.get("fallback");if(t.body.model.includes(",")){let m=nt(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 v=Vt("default",s,void 0,c);if(v)return t.log.info(`Using fallback for explicit model: ${v}`),{model:v,scenarioType:"default"};t.log.warn(`No fallback available for explicit model ${t.body.model}, continuing through routing logic`)}let{family:l,extended:f}=f0(t.body.model),d=a?.families?.[l||""];if(d&&a?.enableFamilyRouting){t.log.info(`Using model family routing for: ${l}${f?" (1M)":""}`),t.modelFamily=l,t.familyFallback=d.fallback;let m=YT(t,e,d,s,n,f,c);if(m)return{model:m.model,scenarioType:m.scenarioType}}let p=JT(t.body.model,a?.models);if(p){let m=nt(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 C=Math.max(e,h0(n)),k=a?.extendedContextThreshold||2e5;if(C>k&&a?.extendedContext){t.log.info(`Using extended context (1M) model due to token count: ${C}, estimated: ${e}, threshold: ${k}`);let m=nt(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 v=Vt("extendedContext",s,void 0,c);if(v)return{model:v,scenarioType:"extendedContext"}}let _=a?.longContextThreshold||6e4;if(C>_&&a?.longContext){t.log.info(`Using long context model due to token count: ${C}, estimated: ${e}, threshold: ${_}`);let m=nt(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 v=Vt("longContext",s,void 0,c);if(v)return{model:v,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 g=r.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 m=nt(g.background,s,!1,"background");if(m)return{model:m,scenarioType:"background"};t.log.warn(`Background model ${g.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=nt(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 v=Vt("webSearch",s,void 0,c);if(v)return{model:v,scenarioType:"webSearch"}}if(t.body.thinking&&a?.think){t.log.info(`Using think model for ${t.body.thinking}`);let m=nt(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 v=Vt("think",s,void 0,c);if(v)return{model:v,scenarioType:"think"}}if(a?.default){let m=nt(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 v=Vt("default",s,void 0,c);if(v)return{model:v,scenarioType:"default"}}return{model:void 0,scenarioType:"default"}},Od=async(t,e,r)=>{let{configService:n,event:o}=r;if(t.originalModel=t.body.model,t.body.metadata?.user_id){let k=t.body.metadata.user_id.split("_session_");k.length>1&&(t.sessionId=k[1])}let a=await d0(t,n)||n.get("Router"),c=n.get("providers")||[],l=kd.get(t.sessionId),{messages:f,system:d=[],tools:p}=t.body,C=n.get("REWRITE_SYSTEM_PROMPT");if(C&&d.length>1&&d[1]?.text?.includes("<env>")){let k=await Rd(C,"utf-8");d[1].text=`${k}<env>${d[1].text.split("<env>").pop()}`}try{let[k,_]=t.body.model.split(","),y=r.tokenizerService?.getTokenizerConfigForModel(k,_),g;r.tokenizerService?g=(await r.tokenizerService.countTokens({messages:f,system:d,tools:p},y)).tokenCount:g=l0(f,d,p),t.tokenCount=g;let m,v=n.get("CUSTOM_ROUTER_PATH");if(v)try{m=await X(v)(t,n.getAll(),{event:o})}catch(b){t.log.error(`failed to load custom router: ${b.message}`)}if(m)t.scenarioType="default";else{let b=await QT(t,g,n,l);m=b.model,t.scenarioType=b.scenarioType}if(a?.image&&m!==a.image&&VT(t)&&!KT(m)){let b=nt(a.image,c,!1,"image");b?(t.log.info(`Using image model fallback for ${m}`),m=b,t.scenarioType="image"):t.log.warn(`Image model ${a.image} unavailable (fail pool), keeping ${m}`)}t.body.model=m}catch(k){t.log.error(`Error in router middleware: ${k.message}`),t.body.model=a?.default,t.scenarioType="default"}},Dr=new Map,c0=1e3;function Dd(){if(Dr.size<=c0)return;let t=[...Dr.keys()].slice(0,Dr.size-c0);for(let e of t)Dr.delete(e)}var p0=async t=>{if(Dr.has(t)){let e=Dr.get(t);return!e||e===""?null:e}try{let e=await WT(i0),r=[];for await(let s of e)s.isDirectory()&&r.push(s.name);let n=r.map(async s=>{let a=xd(i0,s,`${t}.jsonl`);try{return(await GT(a)).isFile()?s:null}catch{return null}}),o=await Promise.all(n);for(let s of o)if(s)return Dr.set(t,s),Dd(),s;return Dr.set(t,""),Dd(),null}catch(e){return console.error("Error searching for project by session:",e),Dr.set(t,""),Dd(),null}};In();var Rr=class{async fetchJson(e,r,n,o){if(!r.apiKey)return null;let s={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${r.apiKey}`},signal:AbortSignal.timeout(n)};if(o)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(o).toString())}catch{}try{let a=await fetch(e,s);return a.ok?await a.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}},Fd=class extends Rr{async queryQuota(e,r,n){let o=await this.fetchJson("https://api.deepseek.com/user/balance",e,r,n),a=(Array.isArray(o?.balance_infos)?o.balance_infos:[]).find(l=>Ee(l?.total_balance)!==void 0);if(!a)return null;let c=Ee(a.total_balance);return c===void 0?null:{totalBalance:c,currency:typeof a.currency=="string"?a.currency:void 0}}},Pd=class extends Rr{async queryQuota(e,r,n){let s=(await this.fetchJson("https://openrouter.ai/api/v1/key",e,r,n))?.data;if(!s||typeof s!="object")return null;let a={},c=Ee(s.limit),l=Ee(s.limit_remaining),f=Ee(s.usage),d=Ee(s.usage_daily);return c!==void 0&&(a.totalBalance=c),l!==void 0&&(a.remainingBalance=l),f!==void 0&&(a.usedBalance=f),d!==void 0&&(a.usedDailyBalance=d),this.hasQuotaData(a)?a:null}},Id=class extends Rr{async queryQuota(e,r,n){let o=sD(e.baseUrl),a=(await this.fetchJson(o,e,r,n))?.data;if(!a||typeof a!="object")return null;let c={},l=Ee(a.totalBalance),f=Ee(a.balance);return l!==void 0&&(c.totalBalance=l),f!==void 0&&(c.remainingBalance=f),l!==void 0&&f!==void 0&&(c.usedBalance=Math.max(0,l-f)),this.hasQuotaData(c)?c:null}},Bd=class extends Rr{async queryQuota(e,r,n){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=o.trim();s.toLowerCase().startsWith("bearer ")||s.startsWith("ey")&&(s=`Bearer ${s}`);let a={method:"GET",headers:{Accept:"application/json",Authorization:s},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:c}=await import("undici");a.dispatcher=new c(new URL(n).toString())}catch{}try{let c=await fetch("https://api.z.ai/api/monitor/usage/quota/limit",a);if(!c.ok)return null;let l=await c.json(),f=Array.isArray(l?.data?.limits)?l.data.limits:[],d=null,p=null,C=null;for(let _ of f)_.type==="TOKENS_LIMIT"?_.unit===3?d=_:_.unit===6?p=_:d||(d=_):_.type==="TIME_LIMIT"&&(C=_);let k={};if(d){let _=Ee(d.currentValue),y=Ee(d.usage),g=Ee(d.remaining),m=Ee(d.percentage);_!==void 0?k.usedDailyBalance=_:m!==void 0&&(k.usedDailyBalance=m,k.limitDaily=100),y!==void 0?k.limitDaily=y:_!==void 0&&g!==void 0&&(k.limitDaily=_+g),d.nextResetTime&&(k.resetTime=new Date(d.nextResetTime).toISOString())}if(p){let _=Ee(p.currentValue),y=Ee(p.usage),g=Ee(p.remaining),m=Ee(p.percentage);_!==void 0?k.usedBalance=_:m!==void 0&&(k.usedBalance=m,k.totalBalance=100),y!==void 0?k.totalBalance=y:_!==void 0&&g!==void 0&&(k.totalBalance=_+g),p.nextResetTime&&!k.resetTime&&(k.resetTime=new Date(p.nextResetTime).toISOString())}if(C){if(k.usedDailyBalance===void 0){let _=Ee(C.currentValue);_!==void 0&&(k.usedDailyBalance=_)}if(k.limitDaily===void 0){let _=Ee(C.usage),y=Ee(C.currentValue),g=Ee(C.remaining);_!==void 0?k.limitDaily=_:y!==void 0&&g!==void 0&&(k.limitDaily=y+g)}C.nextResetTime&&!k.resetTime&&(k.resetTime=new Date(C.nextResetTime).toISOString())}return this.hasQuotaData(k)?k:null}catch{return null}}},Nd=class extends Rr{async queryQuota(e,r,n){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(r)};if(n)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(n).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 f=(await c.json())?.data?.DataV2?.data?.data?.codingPlanInstanceInfos;if(!Array.isArray(f)||f.length===0)return null;let d=f[0]?.codingPlanQuotaInfo;if(!d)return null;let p={},C=Ee(d.per5HourUsedQuota),k=Ee(d.per5HourTotalQuota);C!==void 0&&(p.usedDailyBalance=C),k!==void 0&&(p.limitDaily=k);let _=Ee(d.perWeekUsedQuota),y=Ee(d.perWeekTotalQuota);return _!==void 0&&(p.usedBalance=_),y!==void 0&&(p.totalBalance=y),this.hasQuotaData(p)?p:null}catch{return null}}},Md=class extends Rr{async queryQuota(e,r,n){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(r)};if(n)try{let{ProxyAgent:a}=await import("undici");s.dispatcher=new a(new URL(n).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={},f=Array.isArray(c?.limits)?c.limits:[];if(f.length>0&&f[0]?.detail){let p=f[0].detail,C=Ee(p.limit),k=Ee(p.remaining),_=p.resetTime;C!==void 0&&k!==void 0&&(l.usedDailyBalance=Math.max(0,C-k),l.limitDaily=C),_&&(l.resetTime=new Date(_).toISOString())}let d=c?.usage;if(d){let p=Ee(d.limit),C=Ee(d.remaining),k=Ee(d.used),_=d.resetTime;p!==void 0&&(l.totalBalance=p,k!==void 0?l.usedBalance=k:C!==void 0&&(l.usedBalance=Math.max(0,p-C),l.remainingBalance=C)),_&&!l.resetTime&&(l.resetTime=new Date(_).toISOString())}return this.hasQuotaData(l)?l:null}catch{return null}}},jd=class extends Rr{async queryQuota(e,r,n){let o=e.quotaToken||e.apiKey;if(!o)return null;let s=Ud(e.baseUrl)||"api.minimaxi.com",a=s.endsWith(".minimax.io")||s==="minimax.io"?"api.minimax.io":"api.minimaxi.com",c={method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${o.trim()}`},signal:AbortSignal.timeout(r)};if(n)try{let{ProxyAgent:l}=await import("undici");c.dispatcher=new l(new URL(n).toString())}catch{}try{let l=await fetch(`https://${a}/v1/api/openplatform/coding_plan/remains`,c);if(!l.ok)return null;let f=await l.json();if(f?.base_resp){let b=f.base_resp.status_code;if(b!==void 0&&b!==0)return null}let d=Array.isArray(f?.model_remains)?f.model_remains:[];if(d.length===0)return null;let p=d[0],C={},k=Ee(p.current_interval_total_count),_=Ee(p.current_interval_usage_count),y=Ee(p.end_time);k!==void 0&&_!==void 0&&(C.usedDailyBalance=Math.max(0,k-_),C.limitDaily=k),y&&(C.resetTime=new Date(y).toISOString());let g=Ee(p.current_weekly_total_count),m=Ee(p.current_weekly_usage_count),v=Ee(p.weekly_end_time);return g!==void 0&&m!==void 0&&(C.usedBalance=Math.max(0,g-m),C.remainingBalance=m,C.totalBalance=g),v&&!C.resetTime&&(C.resetTime=new Date(v).toISOString()),this.hasQuotaData(C)?C:null}catch{return null}}},XT=new Fd,ZT=new Pd,eD=new Id,tD=new Bd,rD=new Nd,nD=new Md,oD=new jd;function Ld(t){let e=Ud(t);return e?e==="kimi.com"||e.endsWith(".kimi.com")||e==="moonshot.cn"||e.endsWith(".moonshot.cn")?nD:e==="minimaxi.com"||e.endsWith(".minimaxi.com")||e==="minimax.io"||e.endsWith(".minimax.io")?oD:e==="deepseek.com"||e.endsWith(".deepseek.com")?XT:e==="openrouter.ai"||e.endsWith(".openrouter.ai")?ZT:e==="siliconflow.com"||e.endsWith(".siliconflow.com")||e==="siliconflow.cn"||e.endsWith(".siliconflow.cn")?eD:e==="bigmodel.cn"||e.endsWith(".bigmodel.cn")?tD:e==="dashscope.aliyuncs.com"||e.endsWith(".dashscope.aliyuncs.com")?rD:null:null}function sD(t){let e=Ud(t);return e?.endsWith(".siliconflow.cn")||e==="siliconflow.cn"?"https://api.siliconflow.cn/v1/user/info":"https://api.siliconflow.com/v1/user/info"}function Ud(t){try{return new URL(t).hostname.toLowerCase()}catch{return null}}function Ee(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 r=Number(e);return Number.isFinite(r)?r:void 0}var iD={enabled:!0,quotaProbeIntervalMinutes:10,probeTimeoutMs:15e3,initialDelayMs:5e3,excludeProviders:[]};function aD(t){try{let e=new URL(t),r=e.pathname;return r.endsWith("/v1/messages")?r=r.slice(0,-12):r.endsWith("/messages")?r=r.slice(0,-9):r.endsWith("/v1/chat/completions")?r=r.slice(0,-20):r.endsWith("/chat/completions")&&(r=r.slice(0,-17)),r.endsWith("/v1")||(r=r.endsWith("/")?`${r}v1`:`${r}/v1`),e.pathname=`${r}/models`,e.toString()}catch{return null}}function uD(t){try{let e=new URL(t).hostname.toLowerCase();return e.includes("moonshot")||e.includes("kimi")}catch{return!1}}async function $d(t,e,r){let n=aD(t.baseUrl);if(!n)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(r)try{let{ProxyAgent:c}=await import("undici");o.dispatcher=new c(new URL(r).toString())}catch{}let s=await fetch(n,o);if(s.headers&&Do(t.name,t.baseUrl,s.headers),s.ok)return{success:!0,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"}}}var Ka=class{config;quotaProbeTimer;healthProbeTimer;getProviders;getHttpsProxy;logger;running=!1;constructor(e,r,n,o){this.config={...iD,...r},this.getProviders=e,this.getHttpsProxy=n,this.logger=o}start(){!this.config.enabled||this.running||(this.running=!0,setTimeout(()=>{this.running&&(this.runQuotaProbe(),this.runHealthProbe())},this.config.initialDelayMs),this.quotaProbeTimer=setInterval(()=>this.runQuotaProbe(),this.config.quotaProbeIntervalMinutes*60*1e3),this.healthProbeTimer=setInterval(()=>this.runHealthProbe(),300*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.logger?.info("Active probe service stopped")}async runQuotaProbe(){let e=this.getProviders().filter(a=>a?.name&&!this.config.excludeProviders.includes(a.name)),r=this.getHttpsProxy?.(),n=it();if(e.length===0)return;let o=[];for(let a of e){let c=Ld(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,r).then(f=>{if(f){vd(a.name,f),this.logger?.debug?.(`Stored quota probe result for ${a.name}`);let d=f.limitDaily!==void 0&&f.usedDailyBalance!==void 0&&f.usedDailyBalance>=f.limitDaily,p=f.totalBalance!==void 0&&f.usedBalance!==void 0&&f.usedBalance>=f.totalBalance;if(d||p){let C=d?`Quota exhausted: 5h limit reached (${f.usedDailyBalance}/${f.limitDaily})`:`Quota exhausted: 7d balance depleted (${f.usedBalance}/${f.totalBalance})`;for(let k of l)n.forceOpen(a.name,k,C);this.logger?.warn?.(`${C} for ${a.name}, marked as unhealthy`)}}})}),uD(a.baseUrl)&&o.push({provider:a.name,models:l,type:"rate-limit-headers",promise:$d(a,this.config.probeTimeoutMs,r).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=it(),r=this.getProviders().filter(s=>s?.name&&!this.config.excludeProviders.includes(s.name)),n=this.getHttpsProxy?.();if(r.length===0)return;this.logger?.debug?.(`Running health probe for ${r.length} providers`);let o=await Promise.allSettled(r.map(s=>$d(s,this.config.probeTimeoutMs,n)));for(let s=0;s<r.length;s++){let a=r[s],c=o[s],l=Array.isArray(a.models)?a.models:[];if(c.status==="fulfilled"){let f=c.value;if(f.success){for(let d of l)e.recordSuccess(a.name,d);this.logger?.info?.(`Health probe succeeded for ${a.name}`)}else{for(let d of l)e.recordFailure(a.name,d,f.error);this.logger?.warn?.(`Health probe failed for ${a.name}: ${f.error}`)}}else{for(let f of l)e.recordFailure(a.name,f,c.reason?.message||"Probe error");this.logger?.warn?.(`Health probe error for ${a.name}: ${c.reason}`)}}}async probeProviderManually(e){let n=this.getProviders().find(c=>c.name===e);if(!n)return this.logger?.warn?.(`Provider ${e} not found for manual probe`),!1;let o=this.getHttpsProxy?.(),s=await $d(n,this.config.probeTimeoutMs,o),a=Array.isArray(n.models)?n.models:[];if(s.success)for(let c of a)it().recordSuccess(n.name,c);else for(let c of a)it().recordFailure(n.name,c,s.error);return s.success}},Qr=null;function m0(t,e,r,n){return Qr||(Qr=new Ka(t,e,r,n)),Qr}function qd(t,e,r,n){let o=m0(t,e,r,n);return o.start(),o}function zd(){Qr&&Qr.stop()}function cD(){Qr&&(Qr.stop(),Qr=null)}var Hd=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,r={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:r.enabled!==!1,options:r})}async enablePlugin(e,r){let n=this.plugins.get(e),o=this.pluginInstances.get(e);if(!n||!o)throw new Error(`Plugin ${e} not found`);n.enabled&&await r.register(o.register,n.options)}async enablePlugins(e){for(let[r,n]of this.plugins)if(n.enabled)try{await this.enablePlugin(r,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${r}: ${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,r){let n=this.plugins.get(e);n&&(n.enabled=r)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},g0=new Hd;var T0=jr(w0(),1);var mo=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,r)=>{this.buffer+=e;let n=this.buffer.split(`
|
|
345
345
|
`);this.buffer=n.pop()||"";for(let o of n){let s=this.processLine(o);s&&r.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let r=[];this.processLine(this.buffer.trim(),r),r.forEach(n=>e.enqueue(n))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,r){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let n={...this.currentEvent};return this.currentEvent={},r?(r.push(n),null):n}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let n=e.slice(5).trim();if(n==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(n)}catch{this.currentEvent.data={raw:n,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 Qa=class extends TransformStream{constructor(){super({transform:(e,r)=>{let n="";e.event&&(n+=`event: ${e.event}
|
|
346
346
|
`),e.id&&(n+=`id: ${e.id}
|
|
347
347
|
`),e.retry&&(n+=`retry: ${e.retry}
|
|
348
348
|
`),e.data&&(e.data.type==="done"?n+=`data: [DONE]
|
|
349
349
|
`:n+=`data: ${JSON.stringify(e.data)}
|
|
350
350
|
`),n+=`
|
|
351
|
-
`,r.enqueue(n)}})}};var E0=(t,e)=>{let r=t.getReader();return new ReadableStream({async start(n){try{for(;;){let{done:o,value:s}=await r.read();if(o){n.close();break}let a=await e(s,n);a!==void 0&&n.enqueue(a)}}catch(o){n.error(o)}finally{r.releaseLock()}}})};Jd();Vd();Kd();k0();var hs=new Map,Qd=new Map,bD=1,D0={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,T0.default)(async(t,e)=>{let r={reporter:["console","temp-file"],...e},n=Array.isArray(r.reporter)?r.reporter:[r.reporter];if(r.outputHandlers&&r.outputHandlers.length>0)go.registerHandlers(r.outputHandlers);else{let s=[];for(let a of n)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&&go.registerHandlers(s)}r.outputOptions&&go.setDefaultOptions(r.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,f=`${c}:${l}`;if(Qd.has(f))return Qd.get(f);let d=a.getTokenizerConfigForModel(c,l);if(!d)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await a.getTokenizer(d);return Qd.set(f,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 f=s.id||Date.now().toString(),d;try{let y=s.body?.metadata?.user_id;if(y&&typeof y=="string")try{let g=JSON.parse(y);g.session_id&&(d=g.session_id)}catch{let g=y.match(/_session_([a-f0-9-]+)/i);d=g?g[1]:void 0}}catch{}if(!d)return;let p=await o(s);if(c instanceof ReadableStream){hs.set(f,{requestId:f,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[y,g]=c.tee();return(async()=>{let v=null,
|
|
351
|
+
`,r.enqueue(n)}})}};var E0=(t,e)=>{let r=t.getReader();return new ReadableStream({async start(n){try{for(;;){let{done:o,value:s}=await r.read();if(o){n.close();break}let a=await e(s,n);a!==void 0&&n.enqueue(a)}}catch(o){n.error(o)}finally{r.releaseLock()}}})};Jd();Vd();Kd();k0();var hs=new Map,Qd=new Map,bD=1,D0={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,T0.default)(async(t,e)=>{let r={reporter:["console","temp-file"],...e},n=Array.isArray(r.reporter)?r.reporter:[r.reporter];if(r.outputHandlers&&r.outputHandlers.length>0)go.registerHandlers(r.outputHandlers);else{let s=[];for(let a of n)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&&go.registerHandlers(s)}r.outputOptions&&go.setDefaultOptions(r.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,f=`${c}:${l}`;if(Qd.has(f))return Qd.get(f);let d=a.getTokenizerConfigForModel(c,l);if(!d)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let p=await a.getTokenizer(d);return Qd.set(f,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 f=s.id||Date.now().toString(),d;try{let y=s.body?.metadata?.user_id;if(y&&typeof y=="string")try{let g=JSON.parse(y);g.session_id&&(d=g.session_id)}catch{let g=y.match(/_session_([a-f0-9-]+)/i);d=g?g[1]:void 0}}catch{}if(!d)return;let p=await o(s);if(c instanceof ReadableStream){hs.set(f,{requestId:f,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[y,g]=c.tee();return(async()=>{let v=null,b=async A=>{let D=hs.get(f);if(!D)return;let O=performance.now();if(A){let q=D.firstTokenTime?D.firstTokenTime-D.startTime:0,J=D.lastTokenTime-D.startTime;D.tokensPerSecond=S0(D.tokenCount,J,q)}else{let q=O-1e3;D.tokenTimestamps=D.tokenTimestamps.filter(J=>J>q),D.tokensPerSecond=D.tokenTimestamps.length}await v0(D,n,r.outputOptions,A).catch(q=>{t.log?.warn(`Failed to output streaming stats: ${q.message}`)})};try{let D=g.pipeThrough(new TextDecoderStream).pipeThrough(new mo).getReader();for(v=setInterval(async()=>{hs.get(f)&&await b(!1)},1e3);;){let{done:O,value:q}=await D.read();if(O)break;let J=q,B=hs.get(f);if(!B)continue;let Y=performance.now();if(!B.firstTokenTime&&(J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="text_block"||J.event==="content_block")&&(B.firstTokenTime=Y,B.timeToFirstToken=Math.round(Y-B.startTime)),J.event==="content_block_delta"&&J.data?.delta){let re=J.data.delta.type,ee="";if(re==="text_delta"?ee=J.data.delta.text||"":re==="input_json_delta"?ee=J.data.delta.partial_json||"":re==="thinking_delta"&&(ee=J.data.delta.thinking||""),ee){let ue=p&&p.encodeText?p.encodeText(ee).length:ps(ee);B.tokenCount+=ue,B.lastTokenTime=Y;for(let fe=0;fe<ue;fe++)B.tokenTimestamps.push(Y)}}J.event==="message_stop"&&(v&&(clearInterval(v),v=null),await b(!0),hs.delete(f))}}catch(A){v&&clearInterval(v),A.name!=="AbortError"&&A.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${A.message}`)}})().catch(v=>{console.log(v),t.log?.warn(`Background stats processing failed: ${v.message}`)}),y}let C=performance.now(),k=0,_=!1;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(typeof y.usage?.output_tokens=="number")k=y.usage.output_tokens,_=!0;else{let g=y.content??y.message?.content;if(g!==void 0)if(_=!0,p)Array.isArray(g)?k=g.reduce((m,v)=>{if(v.type==="text"){let b=v.text||"";return m+(p.encodeText?p.encodeText(b).length:ps(b))}return m},0):typeof g=="string"&&(k=p.encodeText?p.encodeText(g).length:ps(g));else{let m=Array.isArray(g)?g.map(v=>v.text).join(""):typeof g=="string"?g:"";k=ps(m)}}}catch{}if(_){let y=Math.round(C-l),g=C-l,m={requestId:f,sessionId:d,startTime:l,lastTokenTime:C,tokenCount:k,tokensPerSecond:S0(k,g),timeToFirstToken:y,stream:!1,tokenTimestamps:[]};await v0(m,n,r.outputOptions,!0)}return c})})};function S0(t,e,r=0){if(t<=0)return 0;let n=Math.max((e-r)/1e3,bD);return Math.round(t/n)}function ps(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,r=t.length-e;return Math.ceil(e/1.5+r/4)}async function v0(t,e,r,n=!1){let o=n?"[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},...r};for(let c of e)try{await go.outputToType(c,s,a)}catch(l){console.error(`[TokenSpeedPlugin] Failed to output to ${c}:`,l)}}In();function ED(t={}){let e=CD({bodyLimit:52428800,...t});return e.setErrorHandler(gh),e.register(wD),e}var Xd=class{app;configService;providerService;transformerService;tokenizerService;activeProbeService;recordUsage;constructor(e={}){let{initialConfig:r,...n}=e;this.app=ED({...n,logger:n.logger??!0}),this.configService=new Pn(e),this.transformerService=new ho(this.configService,this.app.log),this.tokenizerService=new po(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new Bn(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,r){await this.app.register(e,r)}addHook(e,r){this.app.addHook(e,r)}async registerNamespace(e,r){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,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Od(l,f,{configService:this.configService,tokenizerService:this.tokenizerService})}),await Lu(c)});return}if(!r)throw new Error("options is required");let n=new Pn({initialConfig:{providers:r.Providers,Router:r.Router}}),o=new ho(n,this.app.log);await o.initialize();let s=new Bn(n,o,this.app.log),a=new po(n,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",n),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.decorate("recordUsage",this.recordUsage||(()=>{})),c.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Od(l,f,{configService:n,tokenizerService:a})}),await Lu(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,o,s)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body){let c=n.body;n.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(n,o)=>{if(new URL(`http://127.0.0.1${n.url}`).pathname.endsWith("/v1/messages")&&n.body)try{let a=n.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let[c,...l]=a.model.split(",");a.model=l.join(","),n.provider=c,n.model=l;return}catch(a){return n.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{let n={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=qd(()=>this.providerService.getProviders(),n,()=>this.configService.getHttpsProxy(),this.app.log)}catch(n){this.app.log.warn?.(`Failed to start active probe service: ${n.message}`)}let r=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`);try{zd()}catch{}await this.app.close(),process.exit(0)};process.on("SIGINT",()=>r("SIGINT")),process.on("SIGTERM",()=>r("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},_B=Xd;export{Ka as ActiveProbeService,Pn as ConfigService,Vs as ProviderHealthStore,Bn as ProviderService,mo as SSEParserTransform,Qa as SSESerializerTransform,po as TokenizerService,ho as TransformerService,l0 as calculateTokenCount,_B as default,m0 as getActiveProbeService,zT as getAllQuotaResults,Bb as getAllRateLimitInfo,it as getHealthStore,Ld as getQuotaAdapter,Td as getQuotaResult,Ib as getRateLimitInfo,g0 as pluginManager,cD as resetActiveProbeService,E0 as rewriteStream,Od as router,p0 as searchProjectBySession,kd as sessionUsageCache,qd as startActiveProbe,zd as stopActiveProbe,vd as storeQuotaResult,D0 as tokenSpeedPlugin};
|
|
352
352
|
/*! Bundled license information:
|
|
353
353
|
|
|
354
354
|
web-streams-polyfill/dist/ponyfill.es2018.js:
|