@aventurevc/mcp-server 0.8.244 → 0.8.245
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{oauth-discovery-Bb2qdhKV.js → oauth-discovery-tQsVuWM3.js} +1 -1
- package/dist/chunks/{openapi-call-DlI-9oge.js → openapi-call-CaPg45Hn.js} +1 -1
- package/dist/chunks/{streamable-http-D7yAJ96S.js → streamable-http-DGKWgZ_h.js} +1 -1
- package/dist/mcp-server/index.js +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e}from"./env-CpA6E7ay.js";import{w as t}from"./tool-policy-NTXy68a8.js";import{a as n,o as r,t as i}from"./logging-BHp-5JwI.js";import{c as a,r as o}from"./openapi-call-
|
|
1
|
+
import{f as e}from"./env-CpA6E7ay.js";import{w as t}from"./tool-policy-NTXy68a8.js";import{a as n,o as r,t as i}from"./logging-BHp-5JwI.js";import{c as a,r as o}from"./openapi-call-CaPg45Hn.js";import{t as s}from"./provider-catalog-k5VPfOoO.js";var c=5e3;function l(){let e,t;return async()=>(e===void 0&&(e=await(t??=u().finally(()=>{t=void 0}))),e)}async function u(){let l=`getAuthProviderCatalog`,u=await a(e(),{method:`GET`,path:o(l,{}),headers:{},operationId:l,timeoutMs:c},s).catch(e=>{r({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:i(e),fields:{requestId:t()},error:e})});if(u===void 0)return;if(!u.ok||u.redirect){r({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:`the API did not return an OAuth provider catalog`,fields:{requestId:t()}});return}let d=u.data.oauthClient;if(d==null){r({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published no OAuth client; retrying on the next request that needs one`,fields:{requestId:t()}});return}let f=d.mcpResource;if(f==null){r({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an OAuth client without an MCP resource indicator, so this server has no resource to advertise or audience to verify; retrying on the next request that needs one`,fields:{requestId:t()}});return}if(!URL.canParse(f)){r({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an unusable MCP resource indicator: ${f}`,fields:{requestId:t()}});return}let p=new URL(f);return n({component:`aventure-mcp-server`,event:`oauth_discovery_ready`,fields:{requestId:t(),resource:p.href,authorizationServer:d.authorizationServer}}),{client:d,resourceUrl:p}}export{l as catalogOAuthDiscovery};
|
|
@@ -93,4 +93,4 @@ Content-Type: ${o.type||`application/octet-stream`}\r\n\r\n`);a.push(e,o,u),type
|
|
|
93
93
|
)
|
|
94
94
|
`)}close(){this.#n.close()}get(e){i(e);let t=this.#f(e);return t?{body:t.body?Buffer.from(t.body.buffer,t.body.byteOffset,t.body.byteLength):void 0,statusCode:t.statusCode,statusMessage:t.statusMessage,headers:t.headers?JSON.parse(t.headers):void 0,etag:t.etag?t.etag:void 0,vary:t.vary?JSON.parse(t.vary):void 0,cacheControlDirectives:t.cacheControlDirectives?JSON.parse(t.cacheControlDirectives):void 0,cachedAt:t.cachedAt,staleAt:t.staleAt,deleteAt:t.deleteAt}:void 0}set(e,t){i(e);let n=this.#d(e),r=Array.isArray(t.body)?Buffer.concat(t.body):t.body,a=r?.byteLength;if(a&&a>this.#e)return;let o=this.#f(e,!0);o?this.#i.run(r,t.deleteAt,t.statusCode,t.statusMessage,t.headers?JSON.stringify(t.headers):null,t.etag?t.etag:null,t.cacheControlDirectives?JSON.stringify(t.cacheControlDirectives):null,t.vary?JSON.stringify(t.vary):null,t.cachedAt,t.staleAt,o.id):(this.#a.run(n,e.method,r,t.deleteAt,t.statusCode,t.statusMessage,t.headers?JSON.stringify(t.headers):null,t.etag?t.etag:null,t.cacheControlDirectives?JSON.stringify(t.cacheControlDirectives):null,t.vary?JSON.stringify(t.vary):null,t.cachedAt,t.staleAt),this.#u())}createWriteStream(e,t){i(e),a(t);let n=0,o=[],s=this;return new r({decodeStrings:!0,write(e,t,r){n+=e.byteLength,n<=s.#e?o.push(e):this.destroy(),r()},final(n){s.set(e,{...t,body:o}),n()}})}delete(e){if(typeof e!=`object`)throw TypeError(`expected key to be object, got ${typeof e}`);this.#s.run(this.#d(e))}#u(){if(Number.isFinite(this.#t)&&this.size<=this.#t)return 0;{let e=this.#o.run(Date.now()).changes;if(e)return e}{let e=this.#l?.run(Math.max(Math.floor(this.#t*.1),1)).changes;if(e)return e}return 0}get size(){let{total:e}=this.#c.get();return e}#d(e){return`${e.origin}/${e.path}`}#f(e,t=!1){let n=this.#d(e),{headers:r,method:i}=e,a=this.#r.all(n,i);if(a.length===0)return;let o=Date.now();for(let e of a){if(o>=e.deleteAt&&!t)continue;let n=!0;if(e.vary){let t=JSON.parse(e.vary);for(let e in t)if(!l(r[e],t[e])){n=!1;break}}if(n)return e}}};function l(e,t){if(e==null&&t==null)return!0;if(e==null&&t!=null||e!=null&&t==null)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}return e===t}})),sn=t(((t,n)=>{var{kConstruct:r}=Z(),{kEnumerableProperty:i}=$(),{iteratorMixin:a,isValidHeaderName:o,isValidHeaderValue:s}=$e(),{webidl:c}=Qe(),l=e(`node:assert`),u=e(`node:util`);function d(e){return e===10||e===13||e===9||e===32}function f(e){let t=0,n=e.length;for(;n>t&&d(e.charCodeAt(n-1));)--n;for(;n>t&&d(e.charCodeAt(t));)++t;return t===0&&n===e.length?e:e.substring(t,n)}function p(e,t){if(Array.isArray(t))for(let n=0;n<t.length;++n){let r=t[n];if(r.length!==2)throw c.errors.exception({header:`Headers constructor`,message:`expected name/value pair to be length 2, found ${r.length}.`});m(e,r[0],r[1])}else if(typeof t==`object`&&t){let n=Object.keys(t);for(let r=0;r<n.length;++r)m(e,n[r],t[n[r]])}else throw c.errors.conversionFailed({prefix:`Headers constructor`,argument:`Argument 1`,types:[`sequence<sequence<ByteString>>`,`record<ByteString, ByteString>`]})}function m(e,t,n){if(n=f(n),!o(t))throw c.errors.invalidArgument({prefix:`Headers.append`,value:t,type:`header name`});if(!s(n))throw c.errors.invalidArgument({prefix:`Headers.append`,value:n,type:`header value`});if(v(e)===`immutable`)throw TypeError(`immutable`);return b(e).append(t,n,!1)}function h(e){let t=b(e);if(!t)return[];if(t.sortedMap)return t.sortedMap;let n=[],r=t.toSortedArray(),i=t.cookies;if(i===null||i.length===1)return t.sortedMap=r;for(let e=0;e<r.length;++e){let{0:t,1:a}=r[e];if(t===`set-cookie`)for(let e=0;e<i.length;++e)n.push([t,i[e]]);else n.push([t,a])}return t.sortedMap=n}function g(e,t){return e[0]<t[0]?-1:1}var _=class e{cookies=null;sortedMap;headersMap;constructor(t){t instanceof e?(this.headersMap=new Map(t.headersMap),this.sortedMap=t.sortedMap,this.cookies=t.cookies===null?null:[...t.cookies]):(this.headersMap=new Map(t),this.sortedMap=null)}contains(e,t){return this.headersMap.has(t?e:e.toLowerCase())}clear(){this.headersMap.clear(),this.sortedMap=null,this.cookies=null}append(e,t,n){this.sortedMap=null;let r=n?e:e.toLowerCase(),i=this.headersMap.get(r);if(i){let e=r===`cookie`?`; `:`, `;this.headersMap.set(r,{name:i.name,value:`${i.value}${e}${t}`})}else this.headersMap.set(r,{name:e,value:t});r===`set-cookie`&&(this.cookies??=[]).push(t)}set(e,t,n){this.sortedMap=null;let r=n?e:e.toLowerCase();r===`set-cookie`&&(this.cookies=[t]),this.headersMap.set(r,{name:e,value:t})}delete(e,t){this.sortedMap=null,t||(e=e.toLowerCase()),e===`set-cookie`&&(this.cookies=null),this.headersMap.delete(e)}get(e,t){return this.headersMap.get(t?e:e.toLowerCase())?.value??null}*[Symbol.iterator](){for(let{0:e,1:{value:t}}of this.headersMap)yield[e,t]}get entries(){let e={};if(this.headersMap.size!==0)for(let{name:t,value:n}of this.headersMap.values())e[t]=n;return e}rawValues(){return this.headersMap.values()}get entriesList(){let e=[];if(this.headersMap.size!==0)for(let{0:t,1:{name:n,value:r}}of this.headersMap)if(t===`set-cookie`)for(let t of this.cookies)e.push([n,t]);else e.push([n,r]);return e}toSortedArray(){let e=this.headersMap.size,t=Array(e);if(e<=32){if(e===0)return t;let n=this.headersMap[Symbol.iterator](),r=n.next().value;t[0]=[r[0],r[1].value],l(r[1].value!==null);for(let r=1,i=0,a=0,o=0,s=0,c,u;r<e;++r){for(u=n.next().value,c=t[r]=[u[0],u[1].value],l(c[1]!==null),o=0,a=r;o<a;)s=o+(a-o>>1),t[s][0]<=c[0]?o=s+1:a=s;if(r!==s){for(i=r;i>o;)t[i]=t[--i];t[o]=c}}if(!n.next().done)throw TypeError(`Unreachable`);return t}{let e=0;for(let{0:n,1:{value:r}}of this.headersMap)t[e++]=[n,r],l(r!==null);return t.sort(g)}}},v,y,b,x,S=class{#e;#t;constructor(e=void 0){c.util.markAsUncloneable(this),e!==r&&(this.#t=new _,this.#e=`none`,e!==void 0&&(e=c.converters.HeadersInit(e,`Headers constructor`,`init`),p(this,e)))}append(e,t){c.brandCheck(this,c.is.Headers),c.argumentLengthCheck(arguments,2,`Headers.append`);let n=`Headers.append`;return e=c.converters.ByteString(e,n,`name`),t=c.converters.ByteString(t,n,`value`),m(this,e,t)}delete(e){if(c.brandCheck(this,c.is.Headers),c.argumentLengthCheck(arguments,1,`Headers.delete`),e=c.converters.ByteString(e,`Headers.delete`,`name`),!o(e))throw c.errors.invalidArgument({prefix:`Headers.delete`,value:e,type:`header name`});if(this.#e===`immutable`)throw TypeError(`immutable`);this.#t.contains(e,!1)&&this.#t.delete(e,!1)}get(e){c.brandCheck(this,c.is.Headers),c.argumentLengthCheck(arguments,1,`Headers.get`);let t=`Headers.get`;if(e=c.converters.ByteString(e,t,`name`),!o(e))throw c.errors.invalidArgument({prefix:t,value:e,type:`header name`});return this.#t.get(e,!1)}has(e){c.brandCheck(this,c.is.Headers),c.argumentLengthCheck(arguments,1,`Headers.has`);let t=`Headers.has`;if(e=c.converters.ByteString(e,t,`name`),!o(e))throw c.errors.invalidArgument({prefix:t,value:e,type:`header name`});return this.#t.contains(e,!1)}set(e,t){c.brandCheck(this,c.is.Headers),c.argumentLengthCheck(arguments,2,`Headers.set`);let n=`Headers.set`;if(e=c.converters.ByteString(e,n,`name`),t=c.converters.ByteString(t,n,`value`),t=f(t),!o(e))throw c.errors.invalidArgument({prefix:n,value:e,type:`header name`});if(!s(t))throw c.errors.invalidArgument({prefix:n,value:t,type:`header value`});if(this.#e===`immutable`)throw TypeError(`immutable`);this.#t.set(e,t,!1)}getSetCookie(){c.brandCheck(this,c.is.Headers);let e=this.#t.cookies;return e?[...e]:[]}[u.inspect.custom](e,t){return t.depth??=e,`Headers ${u.formatWithOptions(t,this.#t.entries)}`}static{v=e=>e.#e,y=(e,t)=>{e.#e=t},b=e=>e.#t,x=(e,t)=>{e.#t=t},c.is.Headers=e=>typeof e==`object`&&!!e&&#e in e}};a(`Headers`,S,h,0,1,c.is.Headers),Object.defineProperties(S.prototype,{append:i,delete:i,get:i,has:i,set:i,getSetCookie:i,[Symbol.toStringTag]:{value:`Headers`,configurable:!0},[u.inspect.custom]:{enumerable:!1}}),c.converters.HeadersInit=function(e,t,n){if(c.util.Type(e)===c.util.Types.OBJECT){let r=Reflect.get(e,Symbol.iterator);if(!u.types.isProxy(e)&&r===S.prototype.entries)try{return b(e).entriesList}catch{}return typeof r==`function`?c.converters[`sequence<sequence<ByteString>>`](e,t,n,r.bind(e)):c.converters[`record<ByteString, ByteString>`](e,t,n)}throw c.errors.conversionFailed({prefix:`Headers constructor`,argument:`Argument 1`,types:[`sequence<sequence<ByteString>>`,`record<ByteString, ByteString>`]})},n.exports={fill:p,compareHeaderName:g,Headers:S,HeadersList:_,getHeadersGuard:v,setHeadersGuard:y,setHeadersList:x,getHeadersList:b}})),cn=t(((t,n)=>{var{Headers:r,HeadersList:i,fill:a,getHeadersGuard:o,setHeadersGuard:s,setHeadersList:c}=sn(),{extractBody:l,cloneBody:u,mixinBody:d,streamRegistry:f,bodyUnusable:p}=rt(),m=$(),h=e(`node:util`),{kEnumerableProperty:g}=m,{isValidReasonPhrase:_,isCancelled:v,isAborted:y,isErrorLike:b,environmentSettingsObject:x}=$e(),{redirectStatusSet:S,nullBodyStatus:C}=qe(),{webidl:w}=Qe(),{URLSerializer:T}=Ze(),{kConstruct:E}=Z(),D=e(`node:assert`),{isomorphicEncode:O,serializeJavascriptValueToJSONString:k}=Xe(),A=new TextEncoder(`utf-8`),j,M,N,P,F=class{#e;#t;static error(){return H(R(),`immutable`)}static json(e,t=void 0){w.argumentLengthCheck(arguments,1,`Response.json`),t=w.converters.ResponseInit(t);let n=l(A.encode(k(e))),r=H(L({}),`response`);return te(r,t,{body:n[0],type:`application/json`}),r}static redirect(e,t=302){w.argumentLengthCheck(arguments,1,`Response.redirect`),e=w.converters.USVString(e),t=w.converters[`unsigned short`](t);let n;try{n=new URL(e,x.settingsObject.baseUrl)}catch(t){throw TypeError(`Failed to parse URL from ${e}`,{cause:t})}if(!S.has(t))throw RangeError(`Invalid status code ${t}`);let r=H(L({}),`immutable`);r.#t.status=t;let i=O(T(n));return r.#t.headersList.append(`location`,i,!0),r}constructor(e=null,t=void 0){if(w.util.markAsUncloneable(this),e===E)return;e!==null&&(e=w.converters.BodyInit(e,`Response`,`body`)),t=w.converters.ResponseInit(t),this.#t=L({}),this.#e=new r(E),s(this.#e,`response`),c(this.#e,this.#t.headersList);let n=null;if(e!=null){let[t,r]=l(e);n={body:t,type:r}}te(this,t,n)}get type(){return w.brandCheck(this,w.is.Response),this.#t.type}get url(){w.brandCheck(this,w.is.Response);let e=this.#t.urlList,t=e[e.length-1]??null;return t===null?``:T(t,!0)}get redirected(){return w.brandCheck(this,w.is.Response),this.#t.urlList.length>1}get status(){return w.brandCheck(this,w.is.Response),this.#t.status}get ok(){return w.brandCheck(this,w.is.Response),this.#t.status>=200&&this.#t.status<=299}get statusText(){return w.brandCheck(this,w.is.Response),this.#t.statusText}get headers(){return w.brandCheck(this,w.is.Response),this.#e}get body(){return w.brandCheck(this,w.is.Response),this.#t.body?this.#t.body.stream:null}get bodyUsed(){return w.brandCheck(this,w.is.Response),!!this.#t.body&&m.isDisturbed(this.#t.body.stream)}clone(){if(w.brandCheck(this,w.is.Response),p(this.#t))throw w.errors.exception({header:`Response.clone`,message:`Body has already been consumed.`});let e=I(this.#t);return this.#t.urlList.length!==0&&this.#t.body?.stream&&f.register(this,new WeakRef(this.#t.body.stream)),H(e,o(this.#e))}[h.inspect.custom](e,t){t.depth===null&&(t.depth=2),t.colors??=!0;let n={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${h.formatWithOptions(t,n)}`}static{j=e=>e.#e,M=(e,t)=>{e.#e=t},N=e=>e.#t,P=(e,t)=>{e.#t=t},w.is.Response=e=>typeof e==`object`&&!!e&&#t in e}};d(F,N,w.is.Response),Object.defineProperties(F.prototype,{type:g,url:g,status:g,ok:g,redirected:g,statusText:g,headers:g,clone:g,body:g,bodyUsed:g,[Symbol.toStringTag]:{value:`Response`,configurable:!0}}),Object.defineProperties(F,{json:g,redirect:g,error:g});function I(e){if(e.internalResponse)return V(I(e.internalResponse),e.type);let t=L({...e,body:null});return e.body!=null&&(t.body=u(e.body)),t}function L(e){return{aborted:!1,rangeRequested:!1,timingAllowPassed:!1,requestIncludesCredentials:!1,type:`default`,status:200,timingInfo:null,cacheState:``,statusText:``,...e,headersList:e?.headersList?new i(e?.headersList):new i,urlList:e?.urlList?[...e.urlList]:[]}}function R(e){return L({type:`error`,status:0,error:b(e)?e:Error(e&&String(e)),aborted:e&&e.name===`AbortError`})}function z(e){return e.type===`error`&&e.status===0}function B(e,t){return t={internalResponse:e,...t},new Proxy(e,{get(e,n){return n in t?t[n]:e[n]},set(e,n,r){return D(!(n in t)),e[n]=r,!0}})}function V(e,t){if(t===`basic`)return B(e,{type:`basic`,headersList:e.headersList});if(t===`cors`)return B(e,{type:`cors`,headersList:e.headersList});if(t===`opaque`)return B(e,{type:`opaque`,urlList:[],status:0,statusText:``,body:null});if(t===`opaqueredirect`)return B(e,{type:`opaqueredirect`,status:0,statusText:``,headersList:[],body:null});D(!1)}function ee(e,t=null){return D(v(e)),y(e)?R(Object.assign(new DOMException(`The operation was aborted.`,`AbortError`),{cause:t})):R(Object.assign(new DOMException(`Request was cancelled.`),{cause:t}))}function te(e,t,n){if(t.status!==null&&(t.status<200||t.status>599))throw RangeError(`init["status"] must be in the range of 200 to 599, inclusive.`);if(`statusText`in t&&t.statusText!=null&&!_(String(t.statusText)))throw TypeError(`Invalid statusText`);if(`status`in t&&t.status!=null&&(N(e).status=t.status),`statusText`in t&&t.statusText!=null&&(N(e).statusText=t.statusText),`headers`in t&&t.headers!=null&&a(j(e),t.headers),n){if(C.includes(e.status))throw w.errors.exception({header:`Response constructor`,message:`Invalid response status code ${e.status}`});N(e).body=n.body,n.type!=null&&!N(e).headersList.contains(`content-type`,!0)&&N(e).headersList.append(`content-type`,n.type,!0)}}function H(e,t){let n=new F(E);P(n,e);let i=new r(E);return M(n,i),c(i,e.headersList),s(i,t),e.urlList.length!==0&&e.body?.stream&&f.register(n,new WeakRef(e.body.stream)),n}w.converters.XMLHttpRequestBodyInit=function(e,t,n){return typeof e==`string`?w.converters.USVString(e,t,n):w.is.Blob(e)||w.is.BufferSource(e)||w.is.FormData(e)||w.is.URLSearchParams(e)?e:w.converters.DOMString(e,t,n)},w.converters.BodyInit=function(e,t,n){return w.is.ReadableStream(e)||e?.[Symbol.asyncIterator]?e:w.converters.XMLHttpRequestBodyInit(e,t,n)},w.converters.ResponseInit=w.dictionaryConverter([{key:`status`,converter:w.converters[`unsigned short`],defaultValue:()=>200},{key:`statusText`,converter:w.converters.ByteString,defaultValue:()=>``},{key:`headers`,converter:w.converters.HeadersInit}]),n.exports={isNetworkError:z,makeNetworkError:R,makeResponse:L,makeAppropriateNetworkError:ee,filterResponse:V,Response:F,cloneResponse:I,fromInnerResponse:H,getResponseState:N}})),ln=t(((t,n)=>{var{extractBody:r,mixinBody:i,cloneBody:a,bodyUnusable:o}=rt(),{Headers:s,fill:c,HeadersList:l,setHeadersGuard:u,getHeadersGuard:d,setHeadersList:f,getHeadersList:p}=sn(),m=$(),h=e(`node:util`),{isValidHTTPToken:g,sameOrigin:_,environmentSettingsObject:v}=$e(),{forbiddenMethodsSet:y,corsSafeListedMethodsSet:b,referrerPolicy:x,requestRedirect:S,requestMode:C,requestCredentials:w,requestCache:T,requestDuplex:E}=qe(),{kEnumerableProperty:D,normalizedMethodRecordsBase:O,normalizedMethodRecords:k}=m,{webidl:A}=Qe(),{URLSerializer:j}=Ze(),{kConstruct:M}=Z(),N=e(`node:assert`),{getMaxListeners:P,setMaxListeners:F,defaultMaxListeners:I}=e(`node:events`),L=Symbol(`abortController`),R=new FinalizationRegistry(({signal:e,abort:t})=>{e.removeEventListener(`abort`,t)}),z=new WeakMap,B;try{B=P(new AbortController().signal)>0}catch{B=!1}function V(e){return t;function t(){let n=e.deref();if(n!==void 0){R.unregister(t),this.removeEventListener(`abort`,t),n.abort(this.reason);let e=z.get(n.signal);if(e!==void 0){if(e.size!==0){for(let t of e){let e=t.deref();e!==void 0&&e.abort(this.reason)}e.clear()}z.delete(n.signal)}}}}var ee=!1,te,H,ne,U,W,G,K,q=class{#e;#t;#n;#r;#i=null;constructor(e,t=void 0){if(A.util.markAsUncloneable(this),e===M)return;A.argumentLengthCheck(arguments,1,`Request constructor`),e=A.converters.RequestInfo(e),t=A.converters.RequestInit(t);let n=null,i=null,a=v.settingsObject.baseUrl,d=null;if(typeof e==`string`){this.#t=t.dispatcher;let r;try{r=new URL(e,a)}catch(t){throw TypeError(`Failed to parse URL from `+e,{cause:t})}if(r.username||r.password)throw TypeError(`Request cannot be constructed from a URL that includes credentials: `+e);n=J({urlList:[r]}),i=`cors`}else N(A.is.Request(e)),n=e.#r,d=e.#e,this.#t=t.dispatcher||e.#t;let h=v.settingsObject.origin,x=`client`;if(n.window?.constructor?.name===`EnvironmentSettingsObject`&&_(n.window,h)&&(x=n.window),t.window!=null)throw TypeError(`'window' option '${x}' must be null`);`window`in t&&(x=`no-window`),n=J({method:n.method,headersList:n.headersList,unsafeRequest:n.unsafeRequest,client:v.settingsObject,window:x,priority:n.priority,origin:n.origin,referrer:n.referrer,referrerPolicy:n.referrerPolicy,mode:n.mode,credentials:n.credentials,cache:n.cache,redirect:n.redirect,integrity:n.integrity,keepalive:n.keepalive,reloadNavigation:n.reloadNavigation,historyNavigation:n.historyNavigation,urlList:[...n.urlList]});let S=Object.keys(t).length!==0;if(S&&(n.mode===`navigate`&&(n.mode=`same-origin`),n.reloadNavigation=!1,n.historyNavigation=!1,n.origin=`client`,n.referrer=`client`,n.referrerPolicy=``,n.url=n.urlList[n.urlList.length-1],n.urlList=[n.url]),t.referrer!==void 0){let e=t.referrer;if(e===``)n.referrer=`no-referrer`;else{let t;try{t=new URL(e,a)}catch(t){throw TypeError(`Referrer "${e}" is not a valid URL.`,{cause:t})}t.protocol===`about:`&&t.hostname===`client`||h&&!_(t,v.settingsObject.baseUrl)?n.referrer=`client`:n.referrer=t}}t.referrerPolicy!==void 0&&(n.referrerPolicy=t.referrerPolicy);let C;if(C=t.mode===void 0?i:t.mode,C===`navigate`)throw A.errors.exception({header:`Request constructor`,message:`invalid request mode navigate.`});if(C!=null&&(n.mode=C),t.credentials!==void 0&&(n.credentials=t.credentials),t.cache!==void 0&&(n.cache=t.cache),n.cache===`only-if-cached`&&n.mode!==`same-origin`)throw TypeError(`'only-if-cached' can be set only with 'same-origin' mode`);if(t.redirect!==void 0&&(n.redirect=t.redirect),t.integrity!=null&&(n.integrity=String(t.integrity)),t.keepalive!==void 0&&(n.keepalive=!!t.keepalive),t.method!==void 0){let e=t.method,r=k[e];if(r!==void 0)n.method=r;else{if(!g(e))throw TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(y.has(t))throw TypeError(`'${e}' HTTP method is unsupported.`);e=O[t]??e,n.method=e}!ee&&n.method===`patch`&&(process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:`UNDICI-FETCH-patch`}),ee=!0)}t.signal!==void 0&&(d=t.signal),this.#r=n;let w=new AbortController;if(this.#e=w.signal,d!=null){if(d.aborted)w.abort(d.reason);else{this[L]=w;let e=V(new WeakRef(w));B&&P(d)===I&&F(1500,d);let t=m.addAbortListener(d,e);R.register(w,{signal:d,abort:e},e),this.#i=()=>{R.unregister(e),t(),this.#i=null}}}if(this.#n=new s(M),f(this.#n,n.headersList),u(this.#n,`request`),C===`no-cors`){if(!b.has(n.method))throw TypeError(`'${n.method} is unsupported in no-cors mode.`);u(this.#n,`request-no-cors`)}if(S){let e=p(this.#n),n=t.headers===void 0?new l(e):t.headers;if(e.clear(),n instanceof l){for(let{name:t,value:r}of n.rawValues())e.append(t,r,!1);e.cookies=n.cookies}else c(this.#n,n)}let T=A.is.Request(e)?e.#r.body:null;if((t.body!=null||T!=null)&&(n.method===`GET`||n.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);let E=null;if(t.body!=null){let[e,i]=r(t.body,n.keepalive);E=e,i&&!p(this.#n).contains(`content-type`,!0)&&this.#n.append(`content-type`,i,!0)}let D=E??T;if(D!=null&&D.source==null){if(E!=null&&t.duplex==null)throw TypeError(`RequestInit: duplex option is required when sending a body.`);if(n.mode!==`same-origin`&&n.mode!==`cors`)throw TypeError(`If request is made from ReadableStream, mode should be "same-origin" or "cors"`);n.useCORSPreflightFlag=!0}let j=D;if(E==null&&T!=null){if(o(e.#r))throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);let t=new TransformStream;T.stream.pipeThrough(t),j={source:T.source,length:T.length,stream:t.readable}}this.#r.body=j}get method(){return A.brandCheck(this,A.is.Request),this.#r.method}get url(){return A.brandCheck(this,A.is.Request),j(this.#r.url)}get headers(){return A.brandCheck(this,A.is.Request),this.#n}get destination(){return A.brandCheck(this,A.is.Request),this.#r.destination}get referrer(){return A.brandCheck(this,A.is.Request),this.#r.referrer===`no-referrer`?``:this.#r.referrer===`client`?`about:client`:this.#r.referrer.toString()}get referrerPolicy(){return A.brandCheck(this,A.is.Request),this.#r.referrerPolicy}get mode(){return A.brandCheck(this,A.is.Request),this.#r.mode}get credentials(){return A.brandCheck(this,A.is.Request),this.#r.credentials}get cache(){return A.brandCheck(this,A.is.Request),this.#r.cache}get redirect(){return A.brandCheck(this,A.is.Request),this.#r.redirect}get integrity(){return A.brandCheck(this,A.is.Request),this.#r.integrity}get keepalive(){return A.brandCheck(this,A.is.Request),this.#r.keepalive}get isReloadNavigation(){return A.brandCheck(this,A.is.Request),this.#r.reloadNavigation}get isHistoryNavigation(){return A.brandCheck(this,A.is.Request),this.#r.historyNavigation}get signal(){return A.brandCheck(this,A.is.Request),this.#e}get body(){return A.brandCheck(this,A.is.Request),this.#r.body?this.#r.body.stream:null}get bodyUsed(){return A.brandCheck(this,A.is.Request),!!this.#r.body&&m.isDisturbed(this.#r.body.stream)}get duplex(){return A.brandCheck(this,A.is.Request),`half`}clone(){if(A.brandCheck(this,A.is.Request),o(this.#r))throw TypeError(`unusable`);let e=re(this.#r),t=new AbortController;if(this.signal.aborted)t.abort(this.signal.reason);else{let e=z.get(this.signal);e===void 0&&(e=new Set,z.set(this.signal,e));let n=new WeakRef(t);e.add(n),m.addAbortListener(t.signal,V(n))}return ie(e,this.#t,t.signal,d(this.#n))}[h.inspect.custom](e,t){t.depth===null&&(t.depth=2),t.colors??=!0;let n={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${h.formatWithOptions(t,n)}`}static{te=(e,t)=>{e.#e=t},H=e=>e.#t,ne=(e,t)=>{e.#t=t},U=(e,t)=>{e.#n=t},W=e=>e.#r,G=(e,t)=>{e.#r=t},K=e=>{e.#i?.()},A.is.Request=e=>typeof e==`object`&&!!e&&#r in e}};i(q,W,A.is.Request);function J(e){return{method:e.method??`GET`,localURLsOnly:e.localURLsOnly??!1,unsafeRequest:e.unsafeRequest??!1,body:e.body??null,client:e.client??null,reservedClient:e.reservedClient??null,replacesClientId:e.replacesClientId??``,window:e.window??`client`,keepalive:e.keepalive??!1,serviceWorkers:e.serviceWorkers??`all`,initiator:e.initiator??``,destination:e.destination??``,priority:e.priority??`auto`,origin:e.origin??`client`,policyContainer:e.policyContainer??`client`,referrer:e.referrer??`client`,referrerPolicy:e.referrerPolicy??``,mode:e.mode??`no-cors`,useCORSPreflightFlag:e.useCORSPreflightFlag??!1,credentials:e.credentials??`same-origin`,useCredentials:e.useCredentials??!1,cache:e.cache??`default`,redirect:e.redirect??`follow`,integrity:e.integrity??``,cryptoGraphicsNonceMetadata:e.cryptoGraphicsNonceMetadata??``,parserMetadata:e.parserMetadata??``,reloadNavigation:e.reloadNavigation??!1,historyNavigation:e.historyNavigation??!1,userActivation:e.userActivation??!1,taintedOrigin:e.taintedOrigin??!1,redirectCount:e.redirectCount??0,responseTainting:e.responseTainting??`basic`,preventNoCacheCacheControlHeaderModification:e.preventNoCacheCacheControlHeaderModification??!1,done:e.done??!1,timingAllowFailed:e.timingAllowFailed??!1,useURLCredentials:e.useURLCredentials??void 0,traversableForUserPrompts:e.traversableForUserPrompts??`client`,urlList:e.urlList,url:e.urlList[0],headersList:e.headersList?new l(e.headersList):new l}}function re(e){let t=J({...e,body:null});return e.body!=null&&(t.body=a(e.body)),t}function ie(e,t,n,r){let i=new q(M);G(i,e),ne(i,t),te(i,n);let a=new s(M);return U(i,a),f(a,e.headersList),u(a,r),i}Object.defineProperties(q.prototype,{method:D,url:D,headers:D,redirect:D,clone:D,signal:D,duplex:D,destination:D,body:D,bodyUsed:D,isHistoryNavigation:D,isReloadNavigation:D,keepalive:D,integrity:D,cache:D,credentials:D,attribute:D,referrerPolicy:D,referrer:D,mode:D,[Symbol.toStringTag]:{value:`Request`,configurable:!0}}),A.converters.RequestInfo=function(e){return typeof e==`string`?A.converters.USVString(e):A.is.Request(e)?e:A.converters.USVString(e)},A.converters.RequestInit=A.dictionaryConverter([{key:`method`,converter:A.converters.ByteString},{key:`headers`,converter:A.converters.HeadersInit},{key:`body`,converter:A.nullableConverter(A.converters.BodyInit)},{key:`referrer`,converter:A.converters.USVString},{key:`referrerPolicy`,converter:A.converters.DOMString,allowedValues:x},{key:`mode`,converter:A.converters.DOMString,allowedValues:C},{key:`credentials`,converter:A.converters.DOMString,allowedValues:w},{key:`cache`,converter:A.converters.DOMString,allowedValues:T},{key:`redirect`,converter:A.converters.DOMString,allowedValues:S},{key:`integrity`,converter:A.converters.DOMString},{key:`keepalive`,converter:A.converters.boolean},{key:`signal`,converter:A.nullableConverter(e=>A.converters.AbortSignal(e,`RequestInit`,`signal`))},{key:`window`,converter:A.converters.any},{key:`duplex`,converter:A.converters.DOMString,allowedValues:E},{key:`dispatcher`,converter:A.converters.any},{key:`priority`,converter:A.converters.DOMString,allowedValues:[`high`,`low`,`auto`]}]),n.exports={Request:q,makeRequest:J,fromInnerRequest:ie,cloneRequest:re,getRequestDispatcher:H,getRequestState:W,removeRequestAbortListener:K}})),un=t(((t,n)=>{var r=e(`node:assert`),{runtimeFeatures:i}=et(),a=new Map([[`sha256`,0],[`sha384`,1],[`sha512`,2]]),o;if(i.has(`crypto`)){o=e(`node:crypto`);let t=o.getHashes();t.length===0&&a.clear();for(let e of a.keys())t.includes(e)===!1&&a.delete(e)}else a.clear();var s=Map.prototype.get.bind(a),c=Map.prototype.has.bind(a),l=i.has(`crypto`)===!1||a.size===0?()=>!0:(e,t)=>{let n=d(t);if(n.length===0)return!0;let r=u(n);for(let t of r){let n=t.alg,r=t.val;if(p(f(n,e),r))return!0}return!1};function u(e){let t=[],n=null;for(let i of e){if(r(c(i.alg),`Invalid SRI hash algorithm token`),t.length===0){t.push(i),n=i;continue}let e=n.alg,a=s(e),o=i.alg,l=s(o);l<a||(l>a?(n=i,t[0]=i,t.length=1):t.push(i))}return t}function d(e){let t=[];for(let n of e.split(` `)){let e=n.split(`?`,1)[0],r=``,i=[e.slice(0,6),e.slice(7)],a=i[0];if(!c(a))continue;i[1]&&(r=i[1]);let o={alg:a,val:r};t.push(o)}return t}var f=(e,t)=>o.hash(e,t,`base64`);function p(e,t){let n=e.length;n!==0&&e[n-1]===`=`&&--n,n!==0&&e[n-1]===`=`&&--n;let r=t.length;if(r!==0&&t[r-1]===`=`&&--r,r!==0&&t[r-1]===`=`&&--r,n!==r)return!1;for(let r=0;r<n;++r)if(!(e[r]===t[r]||e[r]===`+`&&t[r]===`-`||e[r]===`/`&&t[r]===`_`))return!1;return!0}n.exports={applyAlgorithmToBytes:f,bytesMatch:l,caseSensitiveMatch:p,isValidSRIHashAlgorithm:c,getStrongestMetadata:u,parseMetadata:d}})),dn=t(((t,n)=>{var{makeNetworkError:r,makeAppropriateNetworkError:i,filterResponse:a,makeResponse:o,fromInnerResponse:s,getResponseState:c}=cn(),{HeadersList:l}=sn(),{Request:u,cloneRequest:d,getRequestDispatcher:f,getRequestState:p,removeRequestAbortListener:m}=ln(),h=e(`node:zlib`),{makePolicyContainer:g,clonePolicyContainer:_,requestBadPort:v,TAOCheck:y,appendRequestOriginHeader:b,responseLocationURL:x,requestCurrentURL:S,setRequestReferrerPolicyOnRedirect:C,tryUpgradeRequestToAPotentiallyTrustworthyURL:w,createOpaqueTimingInfo:T,appendFetchMetadata:E,corsCheck:D,crossOriginResourcePolicyCheck:O,determineRequestsReferrer:k,coarsenedSharedCurrentTime:A,sameOrigin:j,isCancelled:M,isAborted:N,isErrorLike:P,fullyReadBody:F,readableStreamClose:I,urlIsLocal:L,urlIsHttpHttpsScheme:R,urlHasHttpsScheme:z,clampAndCoarsenConnectionTimingInfo:B,simpleRangeHeaderValue:V,buildContentRange:ee,createInflate:te,extractMimeType:H,hasAuthenticationEntry:ne,includesCredentials:U,isTraversableNavigable:W}=$e(),G=e(`node:assert`),{safelyExtractBody:K,extractBody:q}=rt(),{redirectStatusSet:J,nullBodyStatus:re,safeMethodsSet:ie,requestBodyHeader:ae,subresourceSet:oe}=qe(),se=e(`node:events`),{Readable:ce,pipeline:le,finished:ue,isErrored:de,isReadable:Y}=e(`node:stream`),{addAbortListener:fe,bufferToLowerCasedHeaderName:pe}=$(),{SocketError:X}=Q(),{dataURLProcessor:me,serializeAMimeType:he,minimizeSupportedMimeType:ge}=Ze(),{getGlobalDispatcher:_e}=Ht(),{webidl:ve}=Qe(),{STATUS_CODES:ye}=e(`node:http`),{bytesMatch:be}=un(),{isomorphicEncode:xe}=Xe(),Se=[`GET`,`HEAD`],Ce=typeof __UNDICI_IS_NODE__<`u`||typeof esbuildDetection<`u`?`node`:`undici`,we;function Te(e,t,n){if(Array.isArray(n))for(let t=0;t<n.length;t+=2){let r=pe(n[t]),i=n[t+1];if(Array.isArray(i)&&!Buffer.isBuffer(i))for(let t of i)e.append(r,t.toString(`latin1`),!0);else e.append(r,i.toString(`latin1`),!0)}else for(let[n,r]of Object.entries(t??{}))if(Array.isArray(r))for(let t of r)e.append(n,`${t}`,!0);else e.append(n,`${r}`,!0)}var Ee=class extends se{constructor(e){super(),this.dispatcher=e,this.connection=null,this.dump=!1,this.state=`ongoing`}terminate(e){this.state===`ongoing`&&(this.state=`terminated`,this.connection?.destroy(e),this.emit(`terminated`,e))}abort(e){this.state===`ongoing`&&(this.state=`aborted`,e||=new DOMException(`The operation was aborted.`,`AbortError`),this.serializedAbortReason=e,this.connection?.destroy(e),this.emit(`terminated`,e))}};function De(e){ke(e,`fetch`)}function Oe(e,t=void 0){ve.argumentLengthCheck(arguments,1,`globalThis.fetch`);let n=Promise.withResolvers(),r;try{r=new u(e,t)}catch(e){return n.reject(e),n.promise}let i=p(r);if(r.signal.aborted)return je(n,i,null,r.signal.reason,null),n.promise;i.client.globalObject?.constructor?.name===`ServiceWorkerGlobalScope`&&(i.serviceWorkers=`none`);let a=null,o=!1,c=null,l=fe(r.signal,()=>{o=!0,G(c!=null),c.abort(r.signal.reason);let e=a?.deref();je(n,i,e,r.signal.reason,c.controller)}),d=()=>{l(),m(r)};return c=Me({request:i,processResponseEndOfBody:e=>{De(e),d()},processResponse:e=>{o||(e.aborted?(je(n,i,a,c.serializedAbortReason,c.controller),d()):e.type===`error`?(n.reject(TypeError(`fetch failed`,{cause:e.error})),d()):(a=new WeakRef(s(e,`immutable`)),n.resolve(a.deref()),n=null))},dispatcher:f(r),requestObject:r}),n.promise}function ke(e,t=`other`){if(e.type===`error`&&e.aborted||!e.urlList?.length)return;let n=e.urlList[0],r=e.timingInfo,i=e.cacheState;R(n)&&r!==null&&(e.timingAllowPassed||(r=T({startTime:r.startTime}),i=``),r.endTime=A(),e.timingInfo=r,Ae(r,n.href,t,globalThis,i,``,e.status))}var Ae=performance.markResourceTiming;function je(e,t,n,r,i){if(e&&e.reject(r),t.body?.stream!=null&&Y(t.body.stream)&&t.body.stream.cancel(r).catch(e=>{if(e.code!==`ERR_INVALID_STATE`)throw e}),n==null)return;let a=c(n);a.body?.stream!=null&&Y(a.body.stream)&&i.error(r)}function Me({request:e,processRequestBodyChunkLength:t,processRequestEndOfBody:n,processResponse:r,processResponseEndOfBody:i,processResponseConsumeBody:a,useParallelQueue:o=!1,dispatcher:s=_e(),requestObject:c=null}){G(s);let l=null,u=!1;e.client!=null&&(l=e.client.globalObject,u=e.client.crossOriginIsolatedCapability);let d=T({startTime:A(u)}),f={controller:new Ee(s),request:e,timingInfo:d,processRequestBodyChunkLength:t,processRequestEndOfBody:n,processResponse:r,processResponseConsumeBody:a,processResponseEndOfBody:i,taskDestination:l,crossOriginIsolatedCapability:u,requestObject:c};return G(!e.body||e.body.stream),e.window===`client`&&(e.window=e.client?.globalObject?.constructor?.name===`Window`?e.client:`no-window`),e.origin===`client`&&(e.origin=e.client.origin),e.policyContainer===`client`&&(e.policyContainer=e.client==null?g():_(e.client.policyContainer)),e.headersList.contains(`accept`,!0)||e.headersList.append(`accept`,`*/*`,!0),e.headersList.contains(`accept-language`,!0)||e.headersList.append(`accept-language`,`*`,!0),e.priority,oe.has(e.destination),Ne(f,!1),f.controller}async function Ne(e,t){try{let n=e.request,i=null;if(n.localURLsOnly&&!L(S(n))&&(i=r(`local URLs only`)),w(n),v(n)===`blocked`&&(i=r(`bad port`)),n.referrerPolicy===``&&(n.referrerPolicy=n.policyContainer.referrerPolicy),n.referrer!==`no-referrer`&&(n.referrer=k(n)),i===null){let t=S(n);j(t,n.url)&&n.responseTainting===`basic`||t.protocol===`data:`||n.mode===`navigate`||n.mode===`websocket`?(n.responseTainting=`basic`,i=await Z(e)):n.mode===`same-origin`?i=r(`request mode cannot be "same-origin"`):n.mode===`no-cors`?n.redirect===`follow`?(n.responseTainting=`opaque`,i=await Z(e)):i=r(`redirect mode cannot be "follow" for "no-cors" request`):R(S(n))?(n.responseTainting=`cors`,i=await Ie(e)):i=r(`URL scheme must be a HTTP(S) scheme`)}if(t)return i;i.status!==0&&!i.internalResponse&&(n.responseTainting,n.responseTainting===`basic`?i=a(i,`basic`):n.responseTainting===`cors`?i=a(i,`cors`):n.responseTainting===`opaque`?i=a(i,`opaque`):G(!1));let o=i.status===0?i:i.internalResponse;if(o.urlList.length===0&&o.urlList.push(...n.urlList),n.timingAllowFailed||(i.timingAllowPassed=!0),i.type===`opaque`&&o.status===206&&o.rangeRequested&&!n.headers.contains(`range`,!0)&&(i=o=r()),i.status!==0&&(n.method===`HEAD`||n.method===`CONNECT`||re.includes(o.status))&&(o.body=null,e.controller.dump=!0),n.integrity){let t=t=>Fe(e,r(t));if(n.responseTainting===`opaque`||i.body==null){t(i.error);return}F(i.body,r=>{be(r,n.integrity)?(i.body=K(r)[0],Fe(e,i)):t(`integrity mismatch`)},t)}else Fe(e,i)}catch(t){e.controller.terminate(t)}}function Z(t){if(M(t))return Promise.resolve(i(t));let{request:n}=t,{protocol:a}=S(n);switch(a){case`about:`:return Promise.resolve(r(`about scheme is not supported`));case`blob:`:{we||=e(`node:buffer`).resolveObjectURL;let t=S(n);if(t.search.length!==0)return Promise.resolve(r(`NetworkError when attempting to fetch resource.`));let i=we(t.toString());if(n.method!==`GET`||!ve.is.Blob(i))return Promise.resolve(r(`invalid method`));let a=o(),s=i.size,c=xe(`${s}`),l=i.type;if(n.headersList.contains(`range`,!0)){a.rangeRequested=!0;let e=V(n.headersList.get(`range`,!0),!0);if(e===`failure`)return Promise.resolve(r(`failed to fetch the data URL`));let{rangeStartValue:t,rangeEndValue:o}=e;if(t===null)t=s-o,o=t+o-1;else{if(t>=s)return Promise.resolve(r(`Range start is greater than the blob's size.`));(o===null||o>=s)&&(o=s-1)}let c=i.slice(t,o+1,l);a.body=q(c)[0];let u=xe(`${c.size}`),d=ee(t,o,s);a.status=206,a.statusText=`Partial Content`,a.headersList.set(`content-length`,u,!0),a.headersList.set(`content-type`,l,!0),a.headersList.set(`content-range`,d,!0)}else{let e=q(i);a.statusText=`OK`,a.body=e[0],a.headersList.set(`content-length`,c,!0),a.headersList.set(`content-type`,l,!0)}return Promise.resolve(a)}case`data:`:{let e=me(S(n));if(e===`failure`)return Promise.resolve(r(`failed to fetch the data URL`));let t=he(e.mimeType);return Promise.resolve(o({statusText:`OK`,headersList:[[`content-type`,{name:`Content-Type`,value:t}]],body:K(e.body)[0]}))}case`file:`:return Promise.resolve(r(`not implemented... yet...`));case`http:`:case`https:`:return Ie(t).catch(e=>r(e));default:return Promise.resolve(r(`unknown scheme`))}}function Pe(e,t){e.request.done=!0,e.processResponseDone!=null&&queueMicrotask(()=>e.processResponseDone(t))}function Fe(e,t){let n=e.timingInfo;e.request.destination===`document`&&(e.controller.fullTimingInfo=n);let r=()=>{let r=Date.now();e.controller.reportTimingSteps=()=>{if(!R(e.request.url))return;n.endTime=r;let i=t.cacheState,a=t.bodyInfo;t.timingAllowPassed||(n=T(n),i=``);let o=0;if(e.request.mode!==`navigate`||!t.hasCrossOriginRedirects){o=t.status;let e=H(t.headersList);e!==`failure`&&(a.contentType=ge(e))}e.request.initiatorType!=null&&Ae(n,e.request.url.href,e.request.initiatorType,globalThis,i,a,o)};let i=()=>{e.request.done=!0,e.processResponseEndOfBody!=null&&queueMicrotask(()=>e.processResponseEndOfBody(t)),e.request.initiatorType!=null&&e.controller.reportTimingSteps()};queueMicrotask(()=>i())};e.processResponse!=null&&queueMicrotask(()=>{e.processResponse(t),e.processResponse=null});let i=t.type===`error`?t:t.internalResponse??t;if(i.body==null?r():ue(i.body.stream,()=>{r()}),e.processResponseConsumeBody!=null){let n=n=>e.processResponseConsumeBody(t,n);i.body==null?queueMicrotask(()=>n(null)):F(i.body,n,()=>e.processResponseConsumeBody(t,`failure`))}}async function Ie(e){let t=e.request,n=null,i=null,a=e.timingInfo;if(t.serviceWorkers,n===null){if(t.redirect===`follow`&&(t.serviceWorkers=`none`),i=n=await Re(e),t.responseTainting===`cors`&&D(t,n)===`failure`)return r(`cors failure`);y(t,n)===`failure`&&(t.timingAllowFailed=!0)}return(t.responseTainting===`opaque`||n.type===`opaque`)&&O(t.origin,t.client,t.destination,i)===`blocked`?r(`blocked`):(J.has(i.status)&&(t.redirect!==`manual`&&e.controller.connection.destroy(),t.redirect===`error`?n=r(`unexpected redirect`):t.redirect===`manual`?n=i:t.redirect===`follow`?n=await Le(e,n):G(!1)),n.timingInfo=a,n)}function Le(e,t){let n=e.request,i=t.internalResponse?t.internalResponse:t,a;try{if(a=x(i,S(n).hash),a==null)return t}catch(e){return Promise.resolve(r(e))}if(!R(a))return Promise.resolve(r(`URL scheme must be a HTTP(S) scheme`));if(n.redirectCount===20)return Promise.resolve(r(`redirect count exceeded`));if(n.redirectCount+=1,n.mode===`cors`&&(a.username||a.password)&&!j(n,a))return Promise.resolve(r(`cross origin not allowed for request mode "cors"`));if(n.responseTainting===`cors`&&(a.username||a.password))return Promise.resolve(r(`URL cannot contain credentials for request mode "cors"`));if(i.status!==303&&n.body!=null&&n.body.source==null)return Promise.resolve(r());if([301,302].includes(i.status)&&n.method===`POST`||i.status===303&&!Se.includes(n.method)){n.method=`GET`,n.body=null;for(let e of ae)n.headersList.delete(e)}j(S(n),a)||(n.headersList.delete(`authorization`,!0),n.headersList.delete(`proxy-authorization`,!0),n.headersList.delete(`cookie`,!0),n.headersList.delete(`host`,!0)),n.body!=null&&(G(n.body.source!=null),n.body=K(n.body.source)[0]);let o=e.timingInfo;return o.redirectEndTime=o.postRedirectStartTime=A(e.crossOriginIsolatedCapability),o.redirectStartTime===0&&(o.redirectStartTime=o.startTime),n.urlList.push(a),C(n,i),Ne(e,!0)}async function Re(e,t=!1,n=!1){let a=e.request,o=null,s=null,c=null;a.window===`no-window`&&a.redirect===`error`?(o=e,s=a):(a.body?.source==null?(s=d({...a,body:null}),s.body=a.body):s=d(a),o={...e},o.request=s);let l=a.credentials===`include`||a.credentials===`same-origin`&&a.responseTainting===`basic`,u=s.body?s.body.length:null,f=null;if(s.body==null&&[`POST`,`PUT`].includes(s.method)&&(f=`0`),u!=null&&(f=xe(`${u}`)),f!=null&&!s.headersList.contains(`content-length`,!0)&&s.headersList.append(`content-length`,f,!0),u!=null&&s.keepalive,ve.is.URL(s.referrer)&&s.headersList.append(`referer`,xe(s.referrer.href),!0),b(s),E(s),s.headersList.contains(`user-agent`,!0)||s.headersList.append(`user-agent`,Ce,!0),s.cache==="default"&&(s.headersList.contains(`if-modified-since`,!0)||s.headersList.contains(`if-none-match`,!0)||s.headersList.contains(`if-unmodified-since`,!0)||s.headersList.contains(`if-match`,!0)||s.headersList.contains(`if-range`,!0))&&(s.cache=`no-store`),s.cache===`no-cache`&&!s.preventNoCacheCacheControlHeaderModification&&!s.headersList.contains(`cache-control`,!0)&&s.headersList.append(`cache-control`,`max-age=0`,!0),(s.cache===`no-store`||s.cache===`reload`)&&(s.headersList.contains(`pragma`,!0)||s.headersList.append(`pragma`,`no-cache`,!0),s.headersList.contains(`cache-control`,!0)||s.headersList.append(`cache-control`,`no-cache`,!0)),s.headersList.contains(`range`,!0)&&s.headersList.append(`accept-encoding`,`identity`,!0),s.headersList.contains(`accept-encoding`,!0)||(z(S(s))?s.headersList.append(`accept-encoding`,`br, gzip, deflate, zstd`,!0):s.headersList.append(`accept-encoding`,`gzip, deflate`,!0)),s.headersList.delete(`host`,!0),l&&!s.headersList.contains(`authorization`,!0)){let e=null;if((!ne(s)||s.useURLCredentials!==void 0&&U(S(s)))&&U(S(s))&&t){let{username:t,password:n}=S(s);e=`Basic ${Buffer.from(`${t}:${n}`).toString(`base64`)}`}e!==null&&s.headersList.append(`Authorization`,e,!1)}if(s.cache=`no-store`,s.cache!==`no-store`&&s.cache,c==null){if(s.cache===`only-if-cached`)return r(`only if cached`);let e=await ze(o,l,n);!ie.has(s.method)&&e.status>=200&&e.status,c??=e}if(c.urlList=[...s.urlList],s.headersList.contains(`range`,!0)&&(c.rangeRequested=!0),c.requestIncludesCredentials=l,c.status===401&&s.responseTainting!==`cors`&&l&&(a.useURLCredentials!==void 0||W(a.traversableForUserPrompts))){if(a.body!=null){if(a.body.source==null)return c;a.body=K(a.body.source)[0]}if(a.useURLCredentials===void 0||t)return M(e)?i(e):c;e.controller.connection.destroy(),c=await Re(e,!0)}if(c.status===407)return a.window===`no-window`?r():M(e)?i(e):r(`proxy authentication required`);if(c.status===421&&!n&&(a.body==null||a.body.source!=null)){if(M(e))return i(e);e.controller.connection.destroy(),c=await Re(e,t,!0)}return c}async function ze(e,t=!1,n=!1){G(!e.controller.connection||e.controller.connection.destroyed),e.controller.connection={abort:null,destroyed:!1,destroy(e){this.destroyed||(this.destroyed=!0,this.abort?.(e??new DOMException(`The operation was aborted.`,`AbortError`)))}};let a=e.request,s=null,c=e.timingInfo;a.cache=`no-store`,a.mode;let u=null;if(a.body==null&&e.processRequestEndOfBody)queueMicrotask(()=>e.processRequestEndOfBody());else if(a.body!=null){let t=async function*(t){M(e)||(yield t,e.processRequestBodyChunkLength?.(t.byteLength))},n=()=>{M(e)||e.processRequestEndOfBody&&e.processRequestEndOfBody()},r=t=>{M(e)||(t.name===`AbortError`?e.controller.abort():e.controller.terminate(t))};u=(async function*(){try{for await(let e of a.body.stream)yield*t(e);n()}catch(e){r(e)}})()}try{let{body:t,status:n,statusText:r,headersList:i,socket:a}=await p({body:u});if(a)s=o({status:n,statusText:r,headersList:i,socket:a});else{let a=t[Symbol.asyncIterator]();e.controller.next=()=>a.next(),s=o({status:n,statusText:r,headersList:i})}}catch(t){return t.name===`AbortError`?(e.controller.connection.destroy(),i(e,t)):r(t)}let d=new ReadableStream({start(t){e.controller.controller=t},pull:()=>e.controller.resume(),cancel:t=>{M(e)||e.controller.abort(t)},type:`bytes`});s.body={stream:d,source:null,length:null},e.controller.resume||e.controller.on(`terminated`,f),e.controller.resume=async()=>{for(;;){let t,n;try{let{done:n,value:r}=await e.controller.next();if(N(e))break;t=n?void 0:r}catch(r){e.controller.ended&&!c.encodedBodySize?t=void 0:(t=r,n=!0)}if(t===void 0){I(e.controller.controller),Pe(e,s);return}if(c.decodedBodySize+=t?.byteLength??0,n){e.controller.terminate(t);return}let r=new Uint8Array(t);if(r.byteLength&&e.controller.controller.enqueue(r),de(d)){e.controller.terminate();return}if(e.controller.controller.desiredSize<=0)return}};function f(t){N(e)?(s.aborted=!0,Y(d)&&e.controller.controller.error(e.controller.serializedAbortReason)):Y(d)&&e.controller.controller.error(TypeError(`terminated`,{cause:P(t)?t:void 0})),e.controller.connection.destroy()}return s;function p({body:t}){let n=S(a),r=e.controller.dispatcher,i=n.pathname+n.search,o=n.search.length===0&&n.href[n.href.length-n.hash.length-1]===`?`;return s(t);function s(t,u){return new Promise((d,f)=>r.dispatch({path:o?`${i}?`:i,origin:n.origin,method:a.method,body:r.isMockActive?a.body&&(a.body.source||a.body.stream):t,__mockAgentBodyForDispatch:t,headers:a.headersList.entries,maxRedirections:0,upgrade:a.mode===`websocket`?`websocket`:void 0,...u===!1?{allowH2:u}:null},{body:null,abort:null,onRequestStart(t){let{connection:n}=e.controller;c.finalConnectionTimingInfo=B(void 0,c.postRedirectStartTime,e.crossOriginIsolatedCapability);let r=e=>t.abort(e);n.destroyed?r(new DOMException(`The operation was aborted.`,`AbortError`)):(e.controller.on(`terminated`,r),this.abort=n.abort=r),c.finalNetworkRequestStartTime=A(e.crossOriginIsolatedCapability)},onResponseStarted(){c.finalNetworkResponseStartTime=A(e.crossOriginIsolatedCapability)},onResponseStart(e,t,n,r){if(t<200)return;let i=e?.rawHeaders??[],o=new l;Te(o,n,i);let s=o.get(`location`,!0);this.body=new ce({read:()=>e.resume()});let c=s&&a.redirect===`follow`&&J.has(t),u=[];if(a.method!==`HEAD`&&a.method!==`CONNECT`&&!re.includes(t)&&!c){let e=o.get(`content-encoding`,!0),t=e?e.toLowerCase().split(`,`):[];if(t.length>5){f(Error(`too many content-encodings in response: ${t.length}, maximum allowed is 5`));return}for(let e=t.length-1;e>=0;--e){let n=t[e].trim();if(n===`x-gzip`||n===`gzip`)u.push(h.createGunzip({flush:h.constants.Z_SYNC_FLUSH,finishFlush:h.constants.Z_SYNC_FLUSH}));else if(n===`deflate`)u.push(te({flush:h.constants.Z_SYNC_FLUSH,finishFlush:h.constants.Z_SYNC_FLUSH}));else if(n===`br`)u.push(h.createBrotliDecompress({flush:h.constants.BROTLI_OPERATION_FLUSH,finishFlush:h.constants.BROTLI_OPERATION_FLUSH}));else if(n===`zstd`)u.push(h.createZstdDecompress({flush:h.constants.ZSTD_e_continue,finishFlush:h.constants.ZSTD_e_end}));else{u.length=0;break}}}let p=t=>this.onResponseError(e,t);d({status:t,statusText:r,headersList:o,body:u.length?le(this.body,...u,t=>{t&&this.onResponseError(e,t)}).on(`error`,p):this.body.on(`error`,p)})},onResponseData(t,n){if(e.controller.dump)return;let r=n;c.encodedBodySize+=r.byteLength,this.body.push(r)===!1&&t.pause()},onResponseEnd(){this.abort&&e.controller.off(`terminated`,this.abort),e.controller.ended=!0,this.body?.push(null)},onResponseError(n,r){this.abort&&e.controller.off(`terminated`,this.abort),a.mode===`websocket`&&u!==!1&&r?.code===`UND_ERR_INFO`&&r?.message===`HTTP/2: Extended CONNECT protocol not supported by server`?d(s(t,!1)):(this.body?.destroy(r),n?.aborted||e.controller.terminate(r),f(r))},onRequestUpgrade(e,t,n,r){if(r.session!=null&&t!==200||r.session==null&&t!==101)return r.session!=null&&e.abort(new X(`bad upgrade`,null)),!1;let i=e?.rawHeaders??[],a=new l;return Te(a,n,i),d({status:t,statusText:ye[t],headersList:a,socket:r}),!0}}))}}}n.exports={fetch:Oe,Fetch:Ee,fetching:Me,finalizeAndReportTiming:ke}})),fn=t(((t,n)=>{var r=e(`node:assert`),{URLSerializer:i}=Ze(),{isValidHeaderName:a}=$e();function o(e,t,n=!1){return i(e,n)===i(t,n)}function s(e){r(e!==null);let t=[];for(let n of e.split(`,`))n=n.trim(),a(n)&&t.push(n);return t}n.exports={urlEquals:o,getFieldValues:s}})),pn=t(((t,n)=>{var r=e(`node:assert`),{kConstruct:i}=Z(),{urlEquals:a,getFieldValues:o}=fn(),{kEnumerableProperty:s,isDisturbed:c}=$(),{webidl:l}=Qe(),{cloneResponse:u,fromInnerResponse:d,getResponseState:f}=cn(),{Request:p,fromInnerRequest:m,getRequestState:h}=ln(),{fetching:g}=dn(),{urlIsHttpHttpsScheme:_,readAllBytes:v}=$e(),y=class{#e;constructor(){arguments[0]!==i&&l.illegalConstructor(),l.util.markAsUncloneable(this),this.#e=arguments[1]}async match(e,t={}){l.brandCheck(this,l.is.Cache);let n=`Cache.match`;l.argumentLengthCheck(arguments,1,n),e=l.converters.RequestInfo(e),t=l.converters.CacheQueryOptions(t,n,`options`);let r=this.#i(e,t,1);if(r.length!==0)return r[0]}async matchAll(e=void 0,t={}){return l.brandCheck(this,l.is.Cache),e!==void 0&&(e=l.converters.RequestInfo(e)),t=l.converters.CacheQueryOptions(t,`Cache.matchAll`,`options`),this.#i(e,t)}async add(e){l.brandCheck(this,l.is.Cache),l.argumentLengthCheck(arguments,1,`Cache.add`),e=l.converters.RequestInfo(e);let t=[e];return await this.addAll(t)}async addAll(e){l.brandCheck(this,l.is.Cache);let t=`Cache.addAll`;l.argumentLengthCheck(arguments,1,t);let n=[],r=[];for(let n of e){if(n===void 0)throw l.errors.conversionFailed({prefix:t,argument:`Argument 1`,types:[`undefined is not allowed`]});if(n=l.converters.RequestInfo(n),typeof n==`string`)continue;let e=h(n);if(!_(e.url)||e.method!==`GET`)throw l.errors.exception({header:t,message:`Expected http/s scheme when method is not GET.`})}let i=[];for(let a of e){let e=h(new p(a));if(!_(e.url))throw l.errors.exception({header:t,message:`Expected http/s scheme.`});e.initiator=`fetch`,e.destination=`subresource`,r.push(e);let s=Promise.withResolvers();i.push(g({request:e,processResponse(e){if(e.type===`error`||e.status===206||e.status<200||e.status>299)s.reject(l.errors.exception({header:`Cache.addAll`,message:`Received an invalid status code or the request failed.`}));else if(e.headersList.contains(`vary`)){let t=o(e.headersList.get(`vary`));for(let e of t)if(e===`*`){s.reject(l.errors.exception({header:`Cache.addAll`,message:`invalid vary field value`}));for(let e of i)e.abort();return}}},processResponseConsumeBody(e){e.aborted?s.reject(new DOMException(`aborted`,`AbortError`)):s.resolve(e)}})),n.push(s.promise)}let a=await Promise.all(n),s=[],c=0;for(let e of a){let t={type:`put`,request:r[c],response:e};s.push(t),c++}let u=Promise.withResolvers(),d=null;try{this.#t(s)}catch(e){d=e}return queueMicrotask(()=>{d===null?u.resolve(void 0):u.reject(d)}),u.promise}async put(e,t){l.brandCheck(this,l.is.Cache);let n=`Cache.put`;l.argumentLengthCheck(arguments,2,n),e=l.converters.RequestInfo(e),t=l.converters.Response(t,n,`response`);let r=null;if(r=l.is.Request(e)?h(e):h(new p(e)),!_(r.url)||r.method!==`GET`)throw l.errors.exception({header:n,message:`Expected an http/s scheme when method is not GET`});let i=f(t);if(i.status===206)throw l.errors.exception({header:n,message:`Got 206 status`});if(i.headersList.contains(`vary`)){let e=o(i.headersList.get(`vary`));for(let t of e)if(t===`*`)throw l.errors.exception({header:n,message:`Got * vary field value`})}if(i.body&&(c(i.body.stream)||i.body.stream.locked))throw l.errors.exception({header:n,message:`Response body is locked or disturbed`});let a=u(i),s=Promise.withResolvers();i.body==null?s.resolve(void 0):v(i.body.stream.getReader(),s.resolve,s.reject);let d=[],m={type:`put`,request:r,response:a};d.push(m);let g=await s.promise;a.body!=null&&(a.body.source=g);let y=Promise.withResolvers(),b=null;try{this.#t(d)}catch(e){b=e}return queueMicrotask(()=>{b===null?y.resolve():y.reject(b)}),y.promise}async delete(e,t={}){l.brandCheck(this,l.is.Cache);let n=`Cache.delete`;l.argumentLengthCheck(arguments,1,n),e=l.converters.RequestInfo(e),t=l.converters.CacheQueryOptions(t,n,`options`);let i=null;if(l.is.Request(e)){if(i=h(e),i.method!==`GET`&&!t.ignoreMethod)return!1}else r(typeof e==`string`),i=h(new p(e));let a=[],o={type:`delete`,request:i,options:t};a.push(o);let s=Promise.withResolvers(),c=null,u;try{u=this.#t(a)}catch(e){c=e}return queueMicrotask(()=>{c===null?s.resolve(!!u?.length):s.reject(c)}),s.promise}async keys(e=void 0,t={}){l.brandCheck(this,l.is.Cache),e!==void 0&&(e=l.converters.RequestInfo(e)),t=l.converters.CacheQueryOptions(t,`Cache.keys`,`options`);let n=null;if(e!==void 0){if(l.is.Request(e)){if(n=h(e),n.method!==`GET`&&!t.ignoreMethod)return[]}else typeof e==`string`&&(n=h(new p(e)))}let r=Promise.withResolvers(),i=[];if(e===void 0)for(let e of this.#e)i.push(e[0]);else{let e=this.#n(n,t);for(let t of e)i.push(t[0])}return queueMicrotask(()=>{let e=[];for(let t of i){let n=m(t,void 0,new AbortController().signal,`immutable`);e.push(n)}r.resolve(Object.freeze(e))}),r.promise}#t(e){let t=this.#e,n=[...t],i=[],a=[];try{for(let n of e){if(n.type!==`delete`&&n.type!==`put`)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`operation type does not match "delete" or "put"`});if(n.type===`delete`&&n.response!=null)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`delete operation should not have an associated response`});if(this.#n(n.request,n.options,i).length)throw new DOMException(`???`,`InvalidStateError`);let e;if(n.type===`delete`){if(e=this.#n(n.request,n.options),e.length===0)return[];for(let n of e){let e=t.indexOf(n);r(e!==-1),t.splice(e,1)}}else if(n.type===`put`){if(n.response==null)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`put operation should have an associated response`});let a=n.request;if(!_(a.url))throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`expected http or https scheme`});if(a.method!==`GET`)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`not get method`});if(n.options!=null)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`options must not be defined`});e=this.#n(n.request);for(let n of e){let e=t.indexOf(n);r(e!==-1),t.splice(e,1)}t.push([n.request,n.response]),i.push([n.request,n.response])}a.push([n.request,n.response])}return a}catch(e){throw this.#e.length=0,this.#e=n,e}}#n(e,t,n){let r=[],i=n??this.#e;for(let n of i){let[i,a]=n;this.#r(e,i,a,t)&&r.push(n)}return r}#r(e,t,n=null,r){let i=new URL(e.url),s=new URL(t.url);if(r?.ignoreSearch&&(s.search=``,i.search=``),!a(i,s,!0))return!1;if(n==null||r?.ignoreVary||!n.headersList.contains(`vary`))return!0;let c=o(n.headersList.get(`vary`));for(let n of c)if(n===`*`||t.headersList.get(n)!==e.headersList.get(n))return!1;return!0}#i(e,t,n=1/0){let r=null;if(e!==void 0){if(l.is.Request(e)){if(r=h(e),r.method!==`GET`&&!t.ignoreMethod)return[]}else typeof e==`string`&&(r=h(new p(e)))}let i=[];if(e===void 0)for(let e of this.#e)i.push(e[1]);else{let e=this.#n(r,t);for(let t of e)i.push(t[1])}let a=[];for(let e of i){let t=d(u(e),`immutable`);if(a.push(t),a.length>=n)break}return Object.freeze(a)}static{l.is.Cache=e=>typeof e==`object`&&!!e&&#e in e}};Object.defineProperties(y.prototype,{[Symbol.toStringTag]:{value:`Cache`,configurable:!0},match:s,matchAll:s,add:s,addAll:s,put:s,delete:s,keys:s});var b=[{key:`ignoreSearch`,converter:l.converters.boolean,defaultValue:()=>!1},{key:`ignoreMethod`,converter:l.converters.boolean,defaultValue:()=>!1},{key:`ignoreVary`,converter:l.converters.boolean,defaultValue:()=>!1}];l.converters.CacheQueryOptions=l.dictionaryConverter(b),l.converters.MultiCacheQueryOptions=l.dictionaryConverter([...b,{key:`cacheName`,converter:l.converters.DOMString}]),l.converters.Response=l.interfaceConverter(l.is.Response,`Response`),l.converters[`sequence<RequestInfo>`]=l.sequenceConverter(l.converters.RequestInfo),n.exports={Cache:y}})),mn=t(((e,t)=>{var{Cache:n}=pn(),{webidl:r}=Qe(),{kEnumerableProperty:i}=$(),{kConstruct:a}=Z(),o=class{#e=new Map;constructor(){arguments[0]!==a&&r.illegalConstructor(),r.util.markAsUncloneable(this)}async match(e,t={}){if(r.brandCheck(this,r.is.CacheStorage),r.argumentLengthCheck(arguments,1,`CacheStorage.match`),e=r.converters.RequestInfo(e),t=r.converters.MultiCacheQueryOptions(t),t.cacheName!=null){if(this.#e.has(t.cacheName))return await new n(a,this.#e.get(t.cacheName)).match(e,t)}else for(let r of this.#e.values()){let i=await new n(a,r).match(e,t);if(i!==void 0)return i}}async has(e){r.brandCheck(this,r.is.CacheStorage);let t=`CacheStorage.has`;return r.argumentLengthCheck(arguments,1,t),e=r.converters.DOMString(e,t,`cacheName`),this.#e.has(e)}async open(e){r.brandCheck(this,r.is.CacheStorage);let t=`CacheStorage.open`;if(r.argumentLengthCheck(arguments,1,t),e=r.converters.DOMString(e,t,`cacheName`),this.#e.has(e))return new n(a,this.#e.get(e));let i=[];return this.#e.set(e,i),new n(a,i)}async delete(e){r.brandCheck(this,r.is.CacheStorage);let t=`CacheStorage.delete`;return r.argumentLengthCheck(arguments,1,t),e=r.converters.DOMString(e,t,`cacheName`),this.#e.delete(e)}async keys(){return r.brandCheck(this,r.is.CacheStorage),[...this.#e.keys()]}static{r.is.CacheStorage=e=>typeof e==`object`&&!!e&&#e in e}};Object.defineProperties(o.prototype,{[Symbol.toStringTag]:{value:`CacheStorage`,configurable:!0},match:i,has:i,open:i,delete:i,keys:i}),t.exports={CacheStorage:o}})),hn=t(((e,t)=>{t.exports={maxAttributeValueSize:1024,maxNameValuePairSize:4096}})),gn=t(((e,t)=>{function n(e){for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n>=0&&n<=8||n>=10&&n<=31||n===127)return!0}return!1}function r(e){for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n<33||n>126||n===34||n===40||n===41||n===60||n===62||n===64||n===44||n===59||n===58||n===92||n===47||n===91||n===93||n===63||n===61||n===123||n===125)throw Error(`Invalid cookie name`)}}function i(e){let t=e.length,n=0;if(e[0]===`"`){if(t===1||e[t-1]!==`"`)throw Error(`Invalid cookie value`);--t,++n}for(;n<t;){let t=e.charCodeAt(n++);if(t<33||t>126||t===34||t===44||t===59||t===92)throw Error(`Invalid cookie value`)}}function a(e){for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n<32||n>126||n===59)throw Error(`Invalid cookie path`)}}function o(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function s(e){if(e===` `)return;if(e.length>255)throw Error(`Invalid cookie domain`);let t=0;for(let n=0;n<e.length;++n){let r=e.charCodeAt(n);if(r===46){if(t===0||e.charCodeAt(n-1)===45)throw Error(`Invalid cookie domain`);t=0}else if(t===0&&!o(r)||!o(r)&&r!==45||++t>63)throw Error(`Invalid cookie domain`)}if(t===0||e.charCodeAt(e.length-1)===45)throw Error(`Invalid cookie domain`)}var c=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],l=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],u=Array(61).fill(0).map((e,t)=>t.toString().padStart(2,`0`));function d(e){return typeof e==`number`&&(e=new Date(e)),`${c[e.getUTCDay()]}, ${u[e.getUTCDate()]} ${l[e.getUTCMonth()]} ${e.getUTCFullYear()} ${u[e.getUTCHours()]}:${u[e.getUTCMinutes()]}:${u[e.getUTCSeconds()]} GMT`}function f(e){if(e<0)throw Error(`Invalid cookie max-age`)}function p(e){if(e.name.length===0)return null;r(e.name),i(e.value);let t=[`${e.name}=${e.value}`];e.name.startsWith(`__Secure-`)&&(e.secure=!0),e.name.startsWith(`__Host-`)&&(e.secure=!0,e.domain=null,e.path=`/`),e.secure&&t.push(`Secure`),e.httpOnly&&t.push(`HttpOnly`),typeof e.maxAge==`number`&&(f(e.maxAge),t.push(`Max-Age=${e.maxAge}`)),e.domain&&(s(e.domain),t.push(`Domain=${e.domain}`)),e.path&&(a(e.path),t.push(`Path=${e.path}`)),e.expires!=null&&e.expires.toString()!==`Invalid Date`&&t.push(`Expires=${d(e.expires)}`),e.sameSite&&t.push(`SameSite=${e.sameSite}`);for(let n of e.unparsed){if(!n.includes(`=`))throw Error(`Invalid unparsed`);let[e,...a]=n.split(`=`),o=e.trim(),s=a.join(`=`);r(o),i(s),t.push(`${o}=${s}`)}return t.join(`; `)}t.exports={isCTLExcludingHtab:n,validateCookieName:r,validateCookiePath:a,validateCookieValue:i,toIMFDate:d,stringify:p}})),_n=t(((t,n)=>{var{collectASequenceOfCodePointsFast:r}=Xe(),{maxNameValuePairSize:i,maxAttributeValueSize:a}=hn(),{isCTLExcludingHtab:o}=gn(),s=e(`node:assert`);function c(e){if(o(e))return null;let t=``,n=``,a=``,s=``;if(e.includes(`;`)){let i={position:0};t=r(`;`,e,i),n=e.slice(i.position)}else t=e;if(!t.includes(`=`))s=t;else{let e={position:0};a=r(`=`,t,e),s=t.slice(e.position+1)}return a=a.trim(),s=s.trim(),a.length+s.length>i?null:{name:a,value:s,...l(n)}}function l(e,t={}){for(;;){if(e.length===0)return t;s(e[0]===`;`),e=e.slice(1);let n=``;e.includes(`;`)?(n=r(`;`,e,{position:0}),e=e.slice(n.length)):(n=e,e=``);let i=``,o=``;if(n.includes(`=`)){let e={position:0};i=r(`=`,n,e),o=n.slice(e.position+1)}else i=n;if(i=i.trim(),o=o.trim(),o.length>a)continue;let c=i.toLowerCase();if(c===`expires`){let e=new Date(o);Number.isNaN(e.getTime())||(t.expires=e)}else if(c===`max-age`){let e=o.charCodeAt(0),n=e>=48&&e<=57,r=o[0]===`-`&&o.length>1;if(!n&&!r||/[^\d]/.test(o.slice(1)))continue;t.maxAge=Number(o)}else if(c===`domain`){let e=o;e[0]===`.`&&(e=e.slice(1)),e=e.toLowerCase(),t.domain=e}else if(c===`path`){let e=``;e=o.length===0||o[0]!==`/`?`/`:o,t.path=e}else if(c===`secure`)t.secure=!0;else if(c===`httponly`)t.httpOnly=!0;else if(c===`samesite`){let e=o.toLowerCase();e===`none`?t.sameSite=`None`:e===`strict`?t.sameSite=`Strict`:e===`lax`&&(t.sameSite=`Lax`)}else t.unparsed??=[],t.unparsed.push(`${i}=${o}`)}}n.exports={parseSetCookie:c,parseUnparsedAttributes:l}})),vn=t(((e,t)=>{var{parseSetCookie:n}=_n(),{stringify:r}=gn(),{webidl:i}=Qe(),a=e=>i.brandCheck(e,i.util.MakeTypeAssertion(globalThis.Headers)),o=e=>i.brandCheck(e,i.is.Headers);function s(e){try{o(e);return}catch{}a(e)}function c(e){i.argumentLengthCheck(arguments,1,`getCookies`),s(e);let t=e.get(`cookie`),n={__proto__:null};if(!t)return n;for(let e of t.split(`;`)){let[t,...r]=e.split(`=`);n[t.trim()]=r.join(`=`)}return n}function l(e,t,n){s(e);let r=`deleteCookie`;i.argumentLengthCheck(arguments,2,r),t=i.converters.DOMString(t,r,`name`),n=i.converters.DeleteCookieAttributes(n),f(e,{name:t,value:``,expires:new Date(0),...n})}function u(e){i.argumentLengthCheck(arguments,1,`getSetCookies`),s(e);let t=e.getSetCookie();return t?t.map(e=>n(e)):[]}function d(e){return e=i.converters.DOMString(e),n(e)}function f(e,t){i.argumentLengthCheck(arguments,2,`setCookie`),s(e),t=i.converters.Cookie(t);let n=r(t);n&&e.append(`set-cookie`,n,!0)}i.converters.DeleteCookieAttributes=i.dictionaryConverter([{converter:i.nullableConverter(i.converters.DOMString),key:`path`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.DOMString),key:`domain`,defaultValue:()=>null}]),i.converters.Cookie=i.dictionaryConverter([{converter:i.converters.DOMString,key:`name`},{converter:i.converters.DOMString,key:`value`},{converter:i.nullableConverter(e=>typeof e==`number`?i.converters[`unsigned long long`](e):new Date(e)),key:`expires`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters[`long long`]),key:`maxAge`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.DOMString),key:`domain`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.DOMString),key:`path`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.boolean),key:`secure`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.boolean),key:`httpOnly`,defaultValue:()=>null},{converter:i.converters.USVString,key:`sameSite`,allowedValues:[`Strict`,`Lax`,`None`]},{converter:i.sequenceConverter(i.converters.DOMString),key:`unparsed`,defaultValue:()=>[]}]),t.exports={getCookies:c,deleteCookie:l,getSetCookies:u,setCookie:f,parseCookie:d}})),yn=t(((e,t)=>{var{webidl:n}=Qe(),{kEnumerableProperty:r}=$(),{kConstruct:i}=Z(),a,o=class e extends Event{#e;constructor(e,t={}){if(e===i){super(arguments[1],arguments[2]),n.util.markAsUncloneable(this);return}let r=`MessageEvent constructor`;n.argumentLengthCheck(arguments,1,r),e=n.converters.DOMString(e,r,`type`),t=n.converters.MessageEventInit(t,r,`eventInitDict`),super(e,t),this.#e=t,n.util.markAsUncloneable(this)}get data(){return n.brandCheck(this,n.is.MessageEvent),this.#e.data}get origin(){return n.brandCheck(this,n.is.MessageEvent),this.#e.origin}get lastEventId(){return n.brandCheck(this,n.is.MessageEvent),this.#e.lastEventId}get source(){return n.brandCheck(this,n.is.MessageEvent),this.#e.source}get ports(){return n.brandCheck(this,n.is.MessageEvent),Object.isFrozen(this.#e.ports)||Object.freeze(this.#e.ports),this.#e.ports}initMessageEvent(t,r=!1,i=!1,a=null,o=``,s=``,c=null,l=[]){return n.brandCheck(this,n.is.MessageEvent),n.argumentLengthCheck(arguments,1,`MessageEvent.initMessageEvent`),new e(t,{bubbles:r,cancelable:i,data:a,origin:o,lastEventId:s,source:c,ports:l})}static{a=(t,n)=>{let r=new e(i,t,n);return r.#e=n,r.#e.data??=null,r.#e.origin??=``,r.#e.lastEventId??=``,r.#e.source??=null,r.#e.ports??=[],r},n.is.MessageEvent=e=>typeof e==`object`&&!!e&&#e in e}},s=class extends Event{#e;constructor(e,t={}){let r=`CloseEvent constructor`;n.argumentLengthCheck(arguments,1,r),e=n.converters.DOMString(e,r,`type`),t=n.converters.CloseEventInit(t),super(e,t),this.#e=t,n.util.markAsUncloneable(this)}get wasClean(){return n.brandCheck(this,n.is.CloseEvent),this.#e.wasClean}get code(){return n.brandCheck(this,n.is.CloseEvent),this.#e.code}get reason(){return n.brandCheck(this,n.is.CloseEvent),this.#e.reason}static{n.is.CloseEvent=e=>typeof e==`object`&&!!e&&#e in e}},c=class extends Event{#e;constructor(e,t){let r=`ErrorEvent constructor`;n.argumentLengthCheck(arguments,1,r),super(e,t),n.util.markAsUncloneable(this),e=n.converters.DOMString(e,r,`type`),t=n.converters.ErrorEventInit(t??{}),this.#e=t}get message(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.message}get filename(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.filename}get lineno(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.lineno}get colno(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.colno}get error(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.error}static{n.is.ErrorEvent=e=>typeof e==`object`&&!!e&&#e in e}};Object.defineProperties(o.prototype,{[Symbol.toStringTag]:{value:`MessageEvent`,configurable:!0},data:r,origin:r,lastEventId:r,source:r,ports:r,initMessageEvent:r}),Object.defineProperties(s.prototype,{[Symbol.toStringTag]:{value:`CloseEvent`,configurable:!0},reason:r,code:r,wasClean:r}),Object.defineProperties(c.prototype,{[Symbol.toStringTag]:{value:`ErrorEvent`,configurable:!0},message:r,filename:r,lineno:r,colno:r,error:r}),n.converters.MessagePort=n.interfaceConverter(n.is.MessagePort,`MessagePort`),n.converters[`sequence<MessagePort>`]=n.sequenceConverter(n.converters.MessagePort);var l=[{key:`bubbles`,converter:n.converters.boolean,defaultValue:()=>!1},{key:`cancelable`,converter:n.converters.boolean,defaultValue:()=>!1},{key:`composed`,converter:n.converters.boolean,defaultValue:()=>!1}];n.converters.MessageEventInit=n.dictionaryConverter([...l,{key:`data`,converter:n.converters.any,defaultValue:()=>null},{key:`origin`,converter:n.converters.USVString,defaultValue:()=>``},{key:`lastEventId`,converter:n.converters.DOMString,defaultValue:()=>``},{key:`source`,converter:n.nullableConverter(n.converters.MessagePort),defaultValue:()=>null},{key:`ports`,converter:n.converters[`sequence<MessagePort>`],defaultValue:()=>[]}]),n.converters.CloseEventInit=n.dictionaryConverter([...l,{key:`wasClean`,converter:n.converters.boolean,defaultValue:()=>!1},{key:`code`,converter:n.converters[`unsigned short`],defaultValue:()=>0},{key:`reason`,converter:n.converters.USVString,defaultValue:()=>``}]),n.converters.ErrorEventInit=n.dictionaryConverter([...l,{key:`message`,converter:n.converters.DOMString,defaultValue:()=>``},{key:`filename`,converter:n.converters.USVString,defaultValue:()=>``},{key:`lineno`,converter:n.converters[`unsigned long`],defaultValue:()=>0},{key:`colno`,converter:n.converters[`unsigned long`],defaultValue:()=>0},{key:`error`,converter:n.converters.any}]),t.exports={MessageEvent:o,CloseEvent:s,ErrorEvent:c,createFastMessageEvent:a}})),bn=t(((e,t)=>{t.exports={uid:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,sentCloseFrameState:{SENT:1,RECEIVED:2},staticPropertyDescriptors:{enumerable:!0,writable:!1,configurable:!1},states:{CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},opcodes:{CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10},maxUnsigned16Bit:65535,parserStates:{INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4},emptyBuffer:Buffer.allocUnsafe(0),sendHints:{text:1,typedArray:2,arrayBuffer:3,blob:4}}})),xn=t(((t,n)=>{var{states:r,opcodes:i}=bn(),{isUtf8:a}=e(`node:buffer`),{removeHTTPWhitespace:o}=Ze(),{collectASequenceOfCodePointsFast:s}=Xe();function c(e){return e===r.CONNECTING}function l(e){return e===r.OPEN}function u(e){return e===r.CLOSING}function d(e){return e===r.CLOSED}function f(e,t,n=(e,t)=>new Event(e,t),r={}){let i=n(e,r);t.dispatchEvent(i)}function p(e,t,n){e.onMessage(t,n)}function m(e){return e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function h(e){if(e.length===0)return!1;for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n<33||n>126||n===34||n===40||n===41||n===44||n===47||n===58||n===59||n===60||n===61||n===62||n===63||n===64||n===91||n===92||n===93||n===123||n===125)return!1}return!0}function g(e){return e>=1e3&&e<1015?e!==1004&&e!==1005&&e!==1006:e>=3e3&&e<=4999}function _(e){return e===i.CLOSE||e===i.PING||e===i.PONG}function v(e){return e===i.CONTINUATION}function y(e){return e===i.TEXT||e===i.BINARY}function b(e){return y(e)||v(e)||_(e)}function x(e){let t={position:0},n=new Map;for(;t.position<e.length;){let[r,i=``]=s(`;`,e,t).split(`=`,2);n.set(o(r,!0,!1),o(i,!1,!0)),t.position++}return n}function S(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}let t=Number.parseInt(e,10);return t>=8&&t<=15}function C(e,t){let n;try{n=new URL(e,t)}catch(e){throw new DOMException(e,`SyntaxError`)}if(n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`),n.protocol!==`ws:`&&n.protocol!==`wss:`)throw new DOMException(`expected a ws: or wss: url`,`SyntaxError`);if(n.hash.length||n.href.endsWith(`#`))throw new DOMException(`hash`,`SyntaxError`);return n}function w(e,t){if(e!==null&&e!==1e3&&(e<3e3||e>4999))throw new DOMException(`invalid code`,`InvalidAccessError`);if(t!==null){let e=Buffer.byteLength(t);if(e>123)throw new DOMException(`Reason must be less than 123 bytes; received ${e}`,`SyntaxError`)}}n.exports={isConnecting:c,isEstablished:l,isClosing:u,isClosed:d,fireEvent:f,isValidSubprotocol:h,isValidStatusCode:g,websocketMessageReceived:p,utf8Decode:(()=>{if(typeof process.versions.icu==`string`){let e=new TextDecoder(`utf-8`,{fatal:!0});return e.decode.bind(e)}return function(e){if(a(e))return e.toString(`utf-8`);throw TypeError(`Invalid utf-8 received.`)}})(),isControlFrame:_,isContinuationFrame:v,isTextBinaryFrame:y,isValidOpcode:b,parseExtensions:x,isValidClientWindowBits:S,toArrayBuffer:m,getURLRecord:C,validateCloseCodeAndReason:w}})),Sn=t(((t,n)=>{var{runtimeFeatures:r}=et(),{maxUnsigned16Bit:i,opcodes:a}=bn(),o=8192,s=null,c=o,l=r.has(`crypto`)?e(`node:crypto`).randomFillSync:null;function u(){return c===o&&(c=0,l(s??=Buffer.allocUnsafeSlow(o),0,o)),[s[c++],s[c++],s[c++],s[c++]]}n.exports={WebsocketFrameSend:class{constructor(e){this.frameData=e}createFrame(e){let t=this.frameData,n=u(),r=t?.byteLength??0,a=r,o=6;r>i?(o+=8,a=127):r>125&&(o+=2,a=126);let s=Buffer.allocUnsafe(r+o);s[0]=s[1]=0,s[0]|=128,s[0]=(s[0]&240)+e,s[o-4]=n[0],s[o-3]=n[1],s[o-2]=n[2],s[o-1]=n[3],s[1]=a,a===126?s.writeUInt16BE(r,2):a===127&&(s[2]=s[3]=0,s.writeUIntBE(r,4,6)),s[1]|=128;for(let e=0;e<r;++e)s[o+e]=t[e]^n[e&3];return s}static createFastTextFrame(e){let t=u(),n=e.length;for(let r=0;r<n;++r)e[r]^=t[r&3];let r=n,o=6;n>i?(o+=8,r=127):n>125&&(o+=2,r=126);let s=Buffer.allocUnsafeSlow(o);return s[0]=128|a.TEXT,s[1]=r|128,s[o-4]=t[0],s[o-3]=t[1],s[o-2]=t[2],s[o-1]=t[3],r===126?s.writeUInt16BE(n,2):r===127&&(s[2]=s[3]=0,s.writeUIntBE(n,4,6)),[s,e]}},generateMask:u}})),Cn=t(((t,n)=>{var{uid:r,states:i,sentCloseFrameState:a,emptyBuffer:o,opcodes:s}=bn(),{parseExtensions:c,isClosed:l,isClosing:u,isEstablished:d,isConnecting:f,validateCloseCodeAndReason:p}=xn(),{makeRequest:m}=ln(),{fetching:h}=dn(),{Headers:g,getHeadersList:_}=sn(),{getDecodeSplit:v}=$e(),{WebsocketFrameSend:y}=Sn(),b=e(`node:assert`),{runtimeFeatures:x}=et(),S=x.has(`crypto`)?e(`node:crypto`):null,C=!1;function w(e,t,n,i,a){let o=e;o.protocol=e.protocol===`ws:`?`http:`:`https:`;let s=m({urlList:[o],client:n,serviceWorkers:`none`,referrer:`no-referrer`,mode:`websocket`,credentials:`include`,cache:`no-store`,redirect:`error`,useURLCredentials:!0});a.headers&&(s.headersList=_(new g(a.headers)));let l=S.randomBytes(16).toString(`base64`);s.headersList.append(`sec-websocket-key`,l,!0),s.headersList.append(`sec-websocket-version`,`13`,!0);for(let e of t)s.headersList.append(`sec-websocket-protocol`,e,!0);return s.headersList.append(`sec-websocket-extensions`,`permessage-deflate; client_max_window_bits`,!0),h({request:s,useParallelQueue:!0,dispatcher:a.dispatcher,processResponse(e){if(e.type===`error`||e.status!==101){if(e.socket?.session==null){E(i,e,1002,`Received network error or non-101 status code.`,e.error);return}if(e.status!==200){E(i,e,1002,`Received network error or non-200 status code.`,e.error);return}}if(C===!1&&e.socket?.session!=null&&(process.emitWarning(`WebSocket over HTTP2 is experimental, and subject to change.`,`ExperimentalWarning`),C=!0),t.length!==0&&!e.headersList.get(`Sec-WebSocket-Protocol`)){E(i,e,1002,`Server did not respond with sent protocols.`);return}if(e.socket.session==null&&e.headersList.get(`Upgrade`)?.toLowerCase()!==`websocket`){E(i,e,1002,`Server did not set Upgrade header to "websocket".`);return}if(e.socket.session==null&&e.headersList.get(`Connection`)?.toLowerCase()!==`upgrade`){E(i,e,1002,`Server did not set Connection header to "upgrade".`);return}if(e.socket.session==null&&e.headersList.get(`Sec-WebSocket-Accept`)!==S.hash(`sha1`,l+r,`base64`)){E(i,e,1002,`Incorrect hash received in Sec-WebSocket-Accept header.`);return}let n=e.headersList.get(`Sec-WebSocket-Extensions`),a;if(n!==null&&(a=c(n),!a.has(`permessage-deflate`))){E(i,e,1002,`Sec-WebSocket-Extensions header does not match.`);return}let o=e.headersList.get(`Sec-WebSocket-Protocol`);if(o!==null){let t=v(`sec-websocket-protocol`,s.headersList);if(t===null||!t.includes(o)){E(i,e,1002,`Protocol was not set in the opening handshake.`);return}}e.socket.session!=null&&(e.socket.allowHalfOpen=!1),e.socket.on(`data`,i.onSocketData),e.socket.on(`close`,i.onSocketClose),e.socket.on(`error`,i.onSocketError),i.wasEverConnected=!0,i.onConnectionEstablished(e,a)}})}function T(e,t,n,r=!1){if(t??=null,n??=``,r&&p(t,n),!(l(e.readyState)||u(e.readyState))){if(!d(e.readyState))D(e),e.readyState=i.CLOSING;else if(!e.closeState.has(a.SENT)&&!e.closeState.has(a.RECEIVED)){let r=new y;n.length!==0&&t===null&&(t=1e3),b(t===null||Number.isInteger(t)),t===null&&n.length===0?r.frameData=o:t!==null&&n===null?(r.frameData=Buffer.allocUnsafe(2),r.frameData.writeUInt16BE(t,0)):t!==null&&n!==null?(r.frameData=Buffer.allocUnsafe(2+Buffer.byteLength(n)),r.frameData.writeUInt16BE(t,0),r.frameData.write(n,2,`utf-8`)):r.frameData=o,e.socket.write(r.createFrame(s.CLOSE)),e.closeState.add(a.SENT),e.readyState=i.CLOSING}else e.readyState=i.CLOSING}}function E(e,t,n,r,i){t.socket?.session!=null&&!t.socket.destroyed&&t.socket.destroy(),D(e,n,r,i)}function D(e,t,n,r){d(e.readyState)&&T(e,t,n,!1),e.controller.abort(),f(e.readyState)?e.onSocketClose():e.socket?.destroyed===!1&&e.socket.destroy()}n.exports={establishWebSocketConnection:w,failWebsocketConnection:D,closeWebSocketConnection:T}})),wn=t(((t,n)=>{var{createInflateRaw:r,Z_DEFAULT_WINDOWBITS:i}=e(`node:zlib`),{isValidClientWindowBits:a}=xn(),{MessageSizeExceededError:o}=Q(),s=Buffer.from([0,0,255,255]),c=Symbol(`kBuffer`),l=Symbol(`kLength`);n.exports={PerMessageDeflate:class{#e;#t={};#n=0;constructor(e,t){this.#t.serverNoContextTakeover=e.has(`server_no_context_takeover`),this.#t.serverMaxWindowBits=e.get(`server_max_window_bits`),this.#n=t.maxPayloadSize}decompress(e,t,n){if(!this.#e){let e=i;if(this.#t.serverMaxWindowBits){if(!a(this.#t.serverMaxWindowBits)){n(Error(`Invalid server_max_window_bits`));return}e=Number.parseInt(this.#t.serverMaxWindowBits)}try{this.#e=r({windowBits:e})}catch(e){n(e);return}this.#e[c]=[],this.#e[l]=0,this.#e.on(`data`,e=>{this.#e[l]+=e.length,this.#n>0&&this.#e[l]>this.#n?(n(new o),this.#e.removeAllListeners(),this.#e.destroy(),this.#e=null):this.#e[c].push(e)}),this.#e.on(`error`,e=>{this.#e=null,n(e)})}this.#e.write(e),t&&this.#e.write(s),this.#e.flush(()=>{if(!this.#e)return;let e=Buffer.concat(this.#e[c],this.#e[l]);this.#e[c].length=0,this.#e[l]=0,n(null,e)})}}}})),Tn=t(((t,n)=>{var{Writable:r}=e(`node:stream`),i=e(`node:assert`),{parserStates:a,opcodes:o,states:s,emptyBuffer:c,sentCloseFrameState:l}=bn(),{isValidStatusCode:u,isValidOpcode:d,websocketMessageReceived:f,utf8Decode:p,isControlFrame:m,isTextBinaryFrame:h,isContinuationFrame:g}=xn(),{failWebsocketConnection:_}=Cn(),{WebsocketFrameSend:v}=Sn(),{PerMessageDeflate:y}=wn(),{MessageSizeExceededError:b}=Q();n.exports={ByteParser:class extends r{#e=[];#t=0;#n=0;#r=!1;#i=a.INFO;#a={};#o=[];#s;#c;#l;#u;constructor(e,t,n={}){super(),this.#c=e,this.#s=t??new Map,this.#l=n.maxFragments??0,this.#u=n.maxPayloadSize??0,this.#s.has(`permessage-deflate`)&&this.#s.set(`permessage-deflate`,new y(t,n))}_write(e,t,n){this.#e.push(e),this.#n+=e.length,this.#r=!0,this.run(n)}#d(){return this.#u>0&&!m(this.#a.opcode)&&this.#a.payloadLength+this.#t>this.#u?(_(this.#c,1009,`Payload size exceeds maximum allowed size`),!1):!0}run(e){for(;this.#r;)if(this.#i===a.INFO){if(this.#n<2)return e();let t=this.consume(2),n=!!(t[0]&128),r=t[0]&15,i=(t[1]&128)==128,s=!n&&r!==o.CONTINUATION,c=t[1]&127,l=t[0]&64,u=t[0]&32,f=t[0]&16;if(!d(r))return _(this.#c,1002,`Invalid opcode received`),e();if(i)return _(this.#c,1002,`Frame cannot be masked`),e();if(l!==0&&!this.#s.has(`permessage-deflate`)){_(this.#c,1002,`Expected RSV1 to be clear.`);return}if(u!==0||f!==0){_(this.#c,1002,`RSV1, RSV2, RSV3 must be clear`);return}if(s&&!h(r)){_(this.#c,1002,`Invalid frame type was fragmented.`);return}if(h(r)&&this.#o.length>0){_(this.#c,1002,`Expected continuation frame`);return}if(this.#a.fragmented&&s){_(this.#c,1002,`Fragmented frame exceeded 125 bytes.`);return}if((c>125||s)&&m(r)){_(this.#c,1002,`Control frame either too large or fragmented`);return}if(g(r)&&this.#o.length===0&&!this.#a.compressed){_(this.#c,1002,`Unexpected continuation frame`);return}if(c<=125){if(this.#a.payloadLength=c,this.#i=a.READ_DATA,!this.#d())return}else c===126?this.#i=a.PAYLOADLENGTH_16:c===127&&(this.#i=a.PAYLOADLENGTH_64);h(r)&&(this.#a.binaryType=r,this.#a.compressed=l!==0),this.#a.opcode=r,this.#a.masked=i,this.#a.fin=n,this.#a.fragmented=s}else if(this.#i===a.PAYLOADLENGTH_16){if(this.#n<2)return e();let t=this.consume(2);if(this.#a.payloadLength=t.readUInt16BE(0),this.#i=a.READ_DATA,!this.#d())return}else if(this.#i===a.PAYLOADLENGTH_64){if(this.#n<8)return e();let t=this.consume(8),n=t.readUInt32BE(0),r=t.readUInt32BE(4);if(n!==0||r>2**31-1){_(this.#c,1009,`Received payload length > 2^31 bytes.`);return}if(this.#a.payloadLength=r,this.#i=a.READ_DATA,!this.#d())return}else if(this.#i===a.READ_DATA){if(this.#n<this.#a.payloadLength)return e();let t=this.consume(this.#a.payloadLength);if(m(this.#a.opcode))this.#r=this.parseControlFrame(t),this.#i=a.INFO;else if(this.#a.compressed){this.#s.get(`permessage-deflate`).decompress(t,this.#a.fin,(t,n)=>{if(t){let e=t instanceof b?1009:1007;_(this.#c,e,t.message)}else this.writeFragments(n)&&(this.#u>0&&this.#t>this.#u?_(this.#c,1009,new b().message):this.#a.fin?(f(this.#c,this.#a.binaryType,this.consumeFragments()),this.#r=!0,this.#i=a.INFO,this.run(e)):(this.#i=a.INFO,this.#r=!0,this.run(e)))},this.#t),this.#r=!1;break}else{if(!this.writeFragments(t))return;!this.#a.fragmented&&this.#a.fin&&f(this.#c,this.#a.binaryType,this.consumeFragments()),this.#i=a.INFO}}}consume(e){if(e>this.#n)throw Error(`Called consume() before buffers satiated.`);if(e===0)return c;this.#n-=e;let t=this.#e[0];if(t.length>e)return this.#e[0]=t.subarray(e,t.length),t.subarray(0,e);if(t.length===e)return this.#e.shift();{let t=0,n=Buffer.allocUnsafeSlow(e);for(;t!==e;){let r=this.#e[0],i=r.length;if(i+t===e){n.set(this.#e.shift(),t);break}if(i+t>e){n.set(r.subarray(0,e-t),t),this.#e[0]=r.subarray(e-t);break}n.set(this.#e.shift(),t),t+=i}return n}}writeFragments(e){return this.#l>0&&this.#o.length===this.#l?(_(this.#c,1008,`Too many message fragments`),!1):(this.#t+=e.length,this.#o.push(e),!0)}consumeFragments(){let e=this.#o;if(this.#a.compressed=!1,e.length===1)return this.#t=0,e.shift();let t=0,n=Buffer.allocUnsafeSlow(this.#t);for(let r=0;r<e.length;++r){let i=e[r];n.set(i,t),t+=i.length}return this.#o=[],this.#t=0,n}parseCloseBody(e){i(e.length!==1);let t;if(e.length>=2&&(t=e.readUInt16BE(0)),t!==void 0&&!u(t))return{code:1002,reason:`Invalid status code`,error:!0};let n=e.subarray(2);n[0]===239&&n[1]===187&&n[2]===191&&(n=n.subarray(3));try{n=p(n)}catch{return{code:1007,reason:`Invalid UTF-8`,error:!0}}return{code:t,reason:n,error:!1}}parseControlFrame(e){let{opcode:t,payloadLength:n}=this.#a;if(t===o.CLOSE){if(n===1)return _(this.#c,1002,`Received close frame with a 1-byte body.`),!1;if(this.#a.closeInfo=this.parseCloseBody(e),this.#a.closeInfo.error){let{code:e,reason:t}=this.#a.closeInfo;return _(this.#c,e,t),!1}if(!this.#c.closeState.has(l.SENT)&&!this.#c.closeState.has(l.RECEIVED)){let e=c;this.#a.closeInfo.code&&(e=Buffer.allocUnsafe(2),e.writeUInt16BE(this.#a.closeInfo.code,0));let t=new v(e);this.#c.socket.write(t.createFrame(o.CLOSE)),this.#c.closeState.add(l.SENT)}return this.#c.readyState=s.CLOSING,this.#c.closeState.add(l.RECEIVED),!1}if(t===o.PING){if(!this.#c.closeState.has(l.RECEIVED)){let t=new v(e);this.#c.socket.write(t.createFrame(o.PONG)),this.#c.onPing(e)}}else t===o.PONG&&this.#c.onPong(e);return!0}get closingInfo(){return this.#a.closeInfo}}}})),En=t(((e,t)=>{var{WebsocketFrameSend:n}=Sn(),{opcodes:r,sendHints:i}=bn(),a=st(),o=class{#e=new a;#t=!1;#n;constructor(e){this.#n=e}add(e,t,r){if(r!==i.blob){if(this.#t){let n={promise:null,callback:t,frame:s(e,r)};this.#e.push(n)}else if(r===i.text){let{0:r,1:i}=n.createFastTextFrame(e);this.#n.cork(),this.#n.write(r),this.#n.write(i,t),this.#n.uncork()}else this.#n.write(s(e,r),t);return}let a={promise:e.arrayBuffer().then(e=>{a.promise=null,a.frame=s(e,r)}),callback:t,frame:null};this.#e.push(a),this.#t||this.#r()}async#r(){this.#t=!0;let e=this.#e;for(;!e.isEmpty();){let t=e.shift();t.promise!==null&&await t.promise,this.#n.write(t.frame,t.callback),t.callback=t.frame=null}this.#t=!1}};function s(e,t){return new n(c(e,t)).createFrame(t===i.text?r.TEXT:r.BINARY)}function c(e,t){switch(t){case i.text:case i.typedArray:return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);case i.arrayBuffer:case i.blob:return new Uint8Array(e)}}t.exports={SendQueue:o}})),Dn=t(((t,n)=>{var{isArrayBuffer:r}=e(`node:util/types`),{webidl:i}=Qe(),{URLSerializer:a}=Ze(),{environmentSettingsObject:o}=$e(),{staticPropertyDescriptors:s,states:c,sentCloseFrameState:l,sendHints:u,opcodes:d}=bn(),{isConnecting:f,isEstablished:p,isClosing:m,isClosed:h,isValidSubprotocol:g,fireEvent:_,utf8Decode:v,toArrayBuffer:y,getURLRecord:b}=xn(),{establishWebSocketConnection:x,closeWebSocketConnection:S,failWebsocketConnection:C}=Cn(),{ByteParser:w}=Tn(),{kEnumerableProperty:T}=$(),{getGlobalDispatcher:E}=Ht(),{ErrorEvent:D,CloseEvent:O,createFastMessageEvent:k}=yn(),{SendQueue:A}=En(),{WebsocketFrameSend:j}=Sn(),{channels:M}=Re(),N=Symbol.for(`nodejs.ref`),P=Symbol.for(`nodejs.unref`),F;function I(e){return typeof e?.address==`function`?e.address():typeof e?.session?.socket?.address==`function`?e.session.socket.address():null}var L=class e extends EventTarget{#e={open:null,error:null,close:null,message:null};#t=0;#n=``;#r=``;#i=!0;#a;#o={onConnectionEstablished:(e,t)=>this.#u(e,t),onMessage:(e,t)=>this.#d(e,t),onParserError:e=>C(this.#o,null,e.message),onParserDrain:()=>this.#f(),onSocketData:e=>{this.#l.write(e)||this.#o.socket.pause()},onSocketError:e=>{this.#o.readyState=c.CLOSING,M.socketError.hasSubscribers&&M.socketError.publish(e),this.#o.socket.destroy()},onSocketClose:()=>this.#p(),onPing:e=>{M.ping.hasSubscribers&&M.ping.publish({payload:e,websocket:this})},onPong:e=>{M.pong.hasSubscribers&&M.pong.publish({payload:e,websocket:this})},readyState:c.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#s;#c;#l;constructor(t,n=[]){super(),i.util.markAsUncloneable(this);let r=`WebSocket constructor`;i.argumentLengthCheck(arguments,1,r);let a=i.converters[`DOMString or sequence<DOMString> or WebSocketInit`](n,r,`options`);t=i.converters.USVString(t),n=a.protocols;let s=o.settingsObject.baseUrl,c=b(t,s);if(typeof n==`string`&&(n=[n]),n.length!==new Set(n.map(e=>e.toLowerCase())).size||n.length>0&&!n.every(e=>g(e)))throw new DOMException(`Invalid Sec-WebSocket-Protocol value`,`SyntaxError`);this.#s=new URL(c.href);let l=o.settingsObject;this.#o.controller=x(c,n,l,this.#o,a),this.#o.readyState=e.CONNECTING,this.#c=`blob`}[N](){this.#i=!0,this.#o.socket?.ref?.()}[P](){this.#i=!1,this.#o.socket?.unref?.()}close(e=void 0,t=void 0){i.brandCheck(this,i.is.WebSocket),e!==void 0&&(e=i.converters[`unsigned short`](e,`WebSocket.close`,`code`,i.attributes.Clamp)),t!==void 0&&(t=i.converters.USVString(t)),e??=null,t??=``,S(this.#o,e,t,!0)}send(e){i.brandCheck(this,i.is.WebSocket);let t=`WebSocket.send`;if(i.argumentLengthCheck(arguments,1,t),e=i.converters.WebSocketSendData(e,t,`data`),f(this.#o.readyState))throw new DOMException(`Sent before connected.`,`InvalidStateError`);if(p(this.#o.readyState)&&!m(this.#o.readyState)){if(typeof e==`string`){let t=Buffer.from(e);this.#t+=t.byteLength,this.#a.add(t,()=>{this.#t-=t.byteLength},u.text)}else r(e)?(this.#t+=e.byteLength,this.#a.add(e,()=>{this.#t-=e.byteLength},u.arrayBuffer)):ArrayBuffer.isView(e)?(this.#t+=e.byteLength,this.#a.add(e,()=>{this.#t-=e.byteLength},u.typedArray)):i.is.Blob(e)&&(this.#t+=e.size,this.#a.add(e,()=>{this.#t-=e.size},u.blob))}}get readyState(){return i.brandCheck(this,i.is.WebSocket),this.#o.readyState}get bufferedAmount(){return i.brandCheck(this,i.is.WebSocket),this.#t}get url(){return i.brandCheck(this,i.is.WebSocket),a(this.#s)}get extensions(){return i.brandCheck(this,i.is.WebSocket),this.#r}get protocol(){return i.brandCheck(this,i.is.WebSocket),this.#n}get onopen(){return i.brandCheck(this,i.is.WebSocket),this.#e.open}set onopen(e){i.brandCheck(this,i.is.WebSocket),this.#e.open&&this.removeEventListener(`open`,this.#e.open);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.open=null:(this.addEventListener(`open`,t),this.#e.open=e)}get onerror(){return i.brandCheck(this,i.is.WebSocket),this.#e.error}set onerror(e){i.brandCheck(this,i.is.WebSocket),this.#e.error&&this.removeEventListener(`error`,this.#e.error);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.error=null:(this.addEventListener(`error`,t),this.#e.error=e)}get onclose(){return i.brandCheck(this,i.is.WebSocket),this.#e.close}set onclose(e){i.brandCheck(this,i.is.WebSocket),this.#e.close&&this.removeEventListener(`close`,this.#e.close);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.close=null:(this.addEventListener(`close`,t),this.#e.close=e)}get onmessage(){return i.brandCheck(this,i.is.WebSocket),this.#e.message}set onmessage(e){i.brandCheck(this,i.is.WebSocket),this.#e.message&&this.removeEventListener(`message`,this.#e.message);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.message=null:(this.addEventListener(`message`,t),this.#e.message=e)}get binaryType(){return i.brandCheck(this,i.is.WebSocket),this.#c}set binaryType(e){i.brandCheck(this,i.is.WebSocket),this.#c=e!==`blob`&&e!==`arraybuffer`?`blob`:e}#u(e,t){this.#o.socket=e.socket,this.#i||this.#o.socket.unref?.();let n=this.#o.controller.dispatcher?.webSocketOptions?.maxFragments,r=this.#o.controller.dispatcher?.webSocketOptions?.maxPayloadSize,i=new w(this.#o,t,{maxFragments:n,maxPayloadSize:r});i.on(`drain`,()=>this.#o.onParserDrain()),i.on(`error`,e=>this.#o.onParserError(e)),this.#l=i,this.#a=new A(e.socket),this.#o.readyState=c.OPEN;let a=e.headersList.get(`sec-websocket-extensions`);a!==null&&(this.#r=a);let o=e.headersList.get(`sec-websocket-protocol`);if(o!==null&&(this.#n=o),_(`open`,this),M.open.hasSubscribers){let t=e.headersList.entries;M.open.publish({address:I(e.socket),protocol:this.#n,extensions:this.#r,websocket:this,handshakeResponse:{status:e.status,statusText:e.statusText,headers:t}})}}#d(e,t){if(this.#o.readyState!==c.OPEN)return;let n;if(e===d.TEXT)try{n=v(t)}catch{C(this.#o,1007,`Received invalid UTF-8 in text frame.`);return}else e===d.BINARY&&(n=this.#c===`blob`?new Blob([t]):y(t));_(`message`,this,k,{origin:this.#s.origin,data:n})}#f(){this.#o.socket.resume()}#p(){let e=this.#o.closeState.has(l.SENT)&&this.#o.closeState.has(l.RECEIVED),t=1005,n=``,r=this.#l?.closingInfo;r&&!r.error&&(t=r.code??1005,n=r.reason),this.#o.readyState=c.CLOSED,this.#o.closeState.has(l.RECEIVED)||(t=1006,_(`error`,this,(e,t)=>new D(e,t),{error:TypeError(n)})),_(`close`,this,(e,t)=>new O(e,t),{wasClean:e,code:t,reason:n}),M.close.hasSubscribers&&M.close.publish({websocket:this,code:t,reason:n})}static{F=(e,t)=>{if(Buffer.isBuffer(t)){if(t.length>125)throw TypeError(`A PING frame cannot have a body larger than 125 bytes.`)}else if(t!==void 0)throw TypeError(`Expected buffer payload`);let n=e.#o.readyState;if(p(n)&&!m(n)&&!h(n)){let n=new j(t);e.#o.socket.write(n.createFrame(d.PING))}},i.is.WebSocket=e=>typeof e==`object`&&!!e&&#o in e}};L.CONNECTING=L.prototype.CONNECTING=c.CONNECTING,L.OPEN=L.prototype.OPEN=c.OPEN,L.CLOSING=L.prototype.CLOSING=c.CLOSING,L.CLOSED=L.prototype.CLOSED=c.CLOSED,Object.defineProperties(L.prototype,{CONNECTING:s,OPEN:s,CLOSING:s,CLOSED:s,url:T,readyState:T,bufferedAmount:T,onopen:T,onerror:T,onclose:T,close:T,onmessage:T,binaryType:T,send:T,extensions:T,protocol:T,[Symbol.toStringTag]:{value:`WebSocket`,writable:!1,enumerable:!1,configurable:!0}}),Object.defineProperties(L,{CONNECTING:s,OPEN:s,CLOSING:s,CLOSED:s}),i.converters[`sequence<DOMString>`]=i.sequenceConverter(i.converters.DOMString),i.converters[`DOMString or sequence<DOMString>`]=function(e,t,n){return i.util.Type(e)===i.util.Types.OBJECT&&Symbol.iterator in e?i.converters[`sequence<DOMString>`](e):i.converters.DOMString(e,t,n)},i.converters.WebSocketInit=i.dictionaryConverter([{key:`protocols`,converter:i.converters[`DOMString or sequence<DOMString>`],defaultValue:()=>[]},{key:`dispatcher`,converter:i.converters.any,defaultValue:()=>E()},{key:`headers`,converter:i.nullableConverter(i.converters.HeadersInit)}]),i.converters[`DOMString or sequence<DOMString> or WebSocketInit`]=function(e){return i.util.Type(e)===i.util.Types.OBJECT&&!(Symbol.iterator in e)?i.converters.WebSocketInit(e):{protocols:i.converters[`DOMString or sequence<DOMString>`](e)}},i.converters.WebSocketSendData=function(e){return i.util.Type(e)===i.util.Types.OBJECT&&(i.is.Blob(e)||i.is.BufferSource(e))?e:i.converters.USVString(e)},n.exports={WebSocket:L,ping:F}})),On=t(((e,t)=>{var{webidl:n}=Qe(),{validateCloseCodeAndReason:r}=xn(),{kConstruct:i}=Z(),{kEnumerableProperty:a}=$();function o(){class e extends DOMException{get reason(){return``}}return new e().reason===void 0?new Proxy(DOMException,{construct(e,t,n){let r=Reflect.construct(e,t,e);return Object.setPrototypeOf(r,n.prototype),r}}):DOMException}var s,c=class e extends o(){#e;#t;constructor(e=``,t=void 0){if(e=n.converters.DOMString(e,`WebSocketError`,`message`),super(e,`WebSocketError`),t===i)return;t!==null&&(t=n.converters.WebSocketCloseInfo(t));let a=t.closeCode??null,o=t.reason??``;r(a,o),o.length!==0&&a===null&&(a=1e3),this.#e=a,this.#t=o}get closeCode(){return this.#e}get reason(){return this.#t}static{s=(t,n,r)=>{let a=new e(t,i);return a.#e=n,a.#t=r,a},n.is.WebSocketError=e=>typeof e==`object`&&!!e&&#t in e}};Object.defineProperties(c.prototype,{closeCode:a,reason:a,[Symbol.toStringTag]:{value:`WebSocketError`,writable:!1,enumerable:!1,configurable:!0}}),t.exports={WebSocketError:c,createUnvalidatedWebSocketError:s}})),kn=t(((t,n)=>{var{addAbortListener:r}=e(`node:events`),{environmentSettingsObject:i,readableStreamClose:a}=$e(),{states:o,opcodes:s,sentCloseFrameState:c}=bn(),{webidl:l}=Qe(),{getURLRecord:u,isValidSubprotocol:d,isEstablished:f,utf8Decode:p}=xn(),{establishWebSocketConnection:m,failWebsocketConnection:h,closeWebSocketConnection:g}=Cn(),{channels:_}=Re(),{WebsocketFrameSend:v}=Sn(),{ByteParser:y}=Tn(),{WebSocketError:b,createUnvalidatedWebSocketError:x}=On(),{kEnumerableProperty:S}=$(),{utf8DecodeBytes:C}=Ye(),w=!1,T=class{#e;#t;#n;#r;#i;#a;#o=!1;#s={onConnectionEstablished:(e,t)=>this.#u(e,t),onMessage:(e,t)=>this.#d(e,t),onParserError:e=>h(this.#s,null,e.message),onParserDrain:()=>this.#s.socket.resume(),onSocketData:e=>{this.#c.write(e)||this.#s.socket.pause()},onSocketError:e=>{this.#s.readyState=o.CLOSING,_.socketError.hasSubscribers&&_.socketError.publish(e),this.#s.socket.destroy()},onSocketClose:()=>queueMicrotask(()=>this.#f()),onPing:()=>{},onPong:()=>{},readyState:o.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#c;constructor(e,t=void 0){w||=(process.emitWarning(`WebSocketStream is experimental! Expect it to change at any time.`,{code:`UNDICI-WSS`}),!0),l.argumentLengthCheck(arguments,1,`WebSocket`),e=l.converters.USVString(e),t!==null&&(t=l.converters.WebSocketStreamOptions(t));let n=i.settingsObject.baseUrl,a=u(e,n),s=t.protocols;if(s.length!==new Set(s.map(e=>e.toLowerCase())).size||s.length>0&&!s.every(e=>d(e)))throw new DOMException(`Invalid Sec-WebSocket-Protocol value`,`SyntaxError`);if(this.#e=a.toString(),this.#t=Promise.withResolvers(),this.#n=Promise.withResolvers(),t.signal!=null){let e=t.signal;if(e.aborted){this.#t.reject(e.reason),this.#n.reject(e.reason);return}r(e,()=>{f(this.#s.readyState)||(h(this.#s),this.#s.readyState=o.CLOSING,this.#t.reject(e.reason),this.#n.reject(e.reason),this.#o=!0)})}let c=i.settingsObject;this.#s.controller=m(a,s,c,this.#s,t)}get url(){return this.#e.toString()}get opened(){return this.#t.promise}get closed(){return this.#n.promise}close(e=void 0){e!==null&&(e=l.converters.WebSocketCloseInfo(e));let t=e.closeCode??null,n=e.reason;g(this.#s,t,n,!0)}#l(e){e=l.converters.WebSocketStreamWrite(e);let t=Promise.withResolvers(),n=null,r=null;if(l.is.BufferSource(e))n=new Uint8Array(ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice()),r=s.BINARY;else{let i;try{i=l.converters.DOMString(e)}catch(e){return t.reject(e),t.promise}n=new TextEncoder().encode(i),r=s.TEXT}if(!this.#s.closeState.has(c.SENT)&&!this.#s.closeState.has(c.RECEIVED)){let e=new v(n);this.#s.socket.write(e.createFrame(r),()=>{t.resolve(void 0)})}else t.resolve(void 0);return t.promise}#u(e,t){this.#s.socket=e.socket;let n=this.#s.controller.dispatcher?.webSocketOptions?.maxFragments,r=this.#s.controller.dispatcher?.webSocketOptions?.maxPayloadSize,i=new y(this.#s,t,{maxFragments:n,maxPayloadSize:r});i.on(`drain`,()=>this.#s.onParserDrain()),i.on(`error`,e=>this.#s.onParserError(e)),this.#c=i,this.#s.readyState=o.OPEN;let a=e.headersList.get(`sec-websocket-extensions`)??``,s=e.headersList.get(`sec-websocket-protocol`)??``,c=new ReadableStream({start:e=>{this.#i=e},pull:()=>this.#m(),cancel:e=>this.#h(e)}),l=new WritableStream({start:e=>{this.#a=e},write:e=>this.#l(e),close:()=>g(this.#s,null,null),abort:e=>this.#p(e)});this.#r=c,this.#t.resolve({extensions:a,protocol:s,readable:c,writable:l})}#d(e,t){if(this.#s.readyState!==o.OPEN)return;let n;if(e===s.TEXT)try{n=p(t)}catch{h(this.#s,1007,`Received invalid UTF-8 in text frame.`);return}else e===s.BINARY&&(n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength));this.#i.enqueue(n),this.#i.desiredSize<=0&&this.#s.socket.pause()}#f(){let e=this.#s.closeState.has(c.SENT)&&this.#s.closeState.has(c.RECEIVED);if(this.#s.readyState=o.CLOSED,this.#o)return;this.#s.wasEverConnected||this.#t.reject(new b(`Socket never opened`));let t=this.#c?.closingInfo,n=t?.code??1005;this.#s.closeState.has(c.RECEIVED)||(n=1006);let r=t?.reason==null?``:C(Buffer.from(t.reason));if(e)a(this.#i),this.#a.error(new DOMException(`A closed WebSocketStream cannot be written to`,`InvalidStateError`)),this.#n.resolve({closeCode:n,reason:r});else{let e=x(`unclean close`,n,r);this.#i?.error(e),this.#a?.error(e),this.#n.reject(e)}}#p(e){let t=null,n=``;l.is.WebSocketError(e)&&(t=e.closeCode,n=e.reason),g(this.#s,t,n)}#m(){this.#s.socket.resume()}#h(e){this.#p(e)}};Object.defineProperties(T.prototype,{url:S,opened:S,closed:S,close:S,[Symbol.toStringTag]:{value:`WebSocketStream`,writable:!1,enumerable:!1,configurable:!0}}),l.converters.WebSocketStreamOptions=l.dictionaryConverter([{key:`protocols`,converter:l.sequenceConverter(l.converters.USVString),defaultValue:()=>[]},{key:`signal`,converter:l.nullableConverter(l.converters.AbortSignal),defaultValue:()=>null}]),l.converters.WebSocketCloseInfo=l.dictionaryConverter([{key:`closeCode`,converter:e=>l.converters[`unsigned short`](e,l.attributes.EnforceRange)},{key:`reason`,converter:l.converters.USVString,defaultValue:()=>``}]),l.converters.WebSocketStreamWrite=function(e){return typeof e==`string`?l.converters.USVString(e):l.converters.BufferSource(e)},n.exports={WebSocketStream:T}})),An=t(((e,t)=>{var{makeRequest:n}=ln();function r(e){return e.indexOf(`\0`)===-1}function i(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<48||e.charCodeAt(t)>57)return!1;return!0}function a(e,t,r,i){let a=r===`no cors`?`no-cors`:`cors`;i&&a===`no-cors`&&(a=`same-origin`);let o=`include`;return r===`anonymous`&&(o=`same-origin`),n({urlList:[e],destination:t,mode:a,credentials:o,useURLCredentials:!0})}t.exports={isValidLastEventId:r,isASCIINumber:i,createPotentialCORSRequest:a}})),jn=t(((t,n)=>{var r=e(`node:buffer`),{Transform:i}=e(`node:stream`),{isASCIINumber:a,isValidLastEventId:o}=An(),s=[239,187,191],c=10,l=13,u=58,d=32,f=r.kStringMaxLength,p=Buffer.from(`data`),m=Buffer.from(`event`),h=Buffer.from(`id`),g=Buffer.from(`retry`);function _(e,t){if(t>=e.length)return!1;for(let n=t;n<e.length;n++)if(e[n]<48||e[n]>57)return!1;return!0}function v(e,t){for(let n=t;n<e.length;n++)if(e[n]===0)return!1;return!0}function y(e,t,n){if(t!==n.length)return!1;for(let r=0;r<t;r++)if(e[r]!==n[r])return!1;return!0}function b(){let e=Error(`EventSource message size exceeded`);return e.aborted=!1,e}n.exports={EventSourceStream:class extends i{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;eventDataSize=0;maxEventSize;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(e={}){e.readableObjectMode=!0,super(e),this.state=e.eventSourceSettings||{},this.maxEventSize=e.maxEventSize??f,e.push&&(this.push=e.push)}_transform(e,t,n){if(e.length===0)n();else if(this.chunks.push(e),this.checkBOM&&this.handleBOM())n();else{for(;this.hasCurrentByte();){let e=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(e===c){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(e===c||e===l){e===l&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1}else if(e===c||e===l){e===l&&(this.crlfCheck=!0);try{this.parseLine(this.readLine(),this.event)}catch(e){n(e);return}this.consumeCurrentByte(),this.eventEndCheck=!0}else this.advanceCursor()}n()}}parseLine(e,t){if(e.length===0)return;let n=e.indexOf(u);if(n===0)return;let r=e.length,i=e.length;if(n!==-1&&(r=n,i=n+1,e[i]===d&&++i),y(e,r,p)){let n=e.length-i,r=this.eventDataSize+(t.data===void 0?0:1)+n;if(this.maxEventSize>0&&r>this.maxEventSize)throw b();let a=e.toString(`utf8`,i);t.data===void 0?t.data=a:t.data+=`\n${a}`,this.eventDataSize=r}else if(y(e,r,g))_(e,i)&&(t.retry=e.toString(`utf8`,i));else if(y(e,r,h))v(e,i)&&(t.id=e.toString(`utf8`,i));else if(y(e,r,m)){let n=e.toString(`utf8`,i);n.length>0&&(t.event=n)}}processEvent(e){e.retry&&a(e.retry)&&(this.state.reconnectionTime=parseInt(e.retry,10)),e.id!==void 0&&o(e.id)&&(this.state.lastEventId=e.id),e.data!==void 0&&this.push({type:e.event||`message`,options:{data:e.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event.data=void 0,this.event.event=void 0,this.event.id=void 0,this.event.retry=void 0,this.eventDataSize=0}hasPendingEvent(){return this.event.data!==void 0||this.event.event!==void 0||this.event.id!==void 0||this.event.retry!==void 0}hasCurrentByte(){return this.chunkIndex<this.chunks.length&&this.pos<this.chunks[this.chunkIndex].length}currentByte(){return this.chunks[this.chunkIndex][this.pos]}consumeCurrentByte(){this.advanceCursor(),this.syncLineStartToCursor()}advanceCursor(){for(this.pos++;this.chunkIndex<this.chunks.length&&this.pos>=this.chunks[this.chunkIndex].length;)this.chunkIndex++,this.pos=0}syncLineStartToCursor(){this.lineChunkIndex=this.chunkIndex,this.linePos=this.pos,this.dropConsumedChunks()}dropConsumedChunks(){for(;this.lineChunkIndex>0;)this.chunks.shift(),this.lineChunkIndex--,this.chunkIndex--;this.chunkIndex===this.chunks.length&&(this.chunks.length=0,this.chunkIndex=0,this.pos=0,this.lineChunkIndex=0,this.linePos=0)}readLine(){if(this.lineChunkIndex===this.chunkIndex)return this.chunks[this.chunkIndex].subarray(this.linePos,this.pos);let e=[],t=0;for(let n=this.lineChunkIndex;n<=this.chunkIndex;n++){let r=this.chunks[n],i=n===this.lineChunkIndex?this.linePos:0,a=n===this.chunkIndex?this.pos:r.length,o=r.subarray(i,a);t+=o.length,e.push(o)}return Buffer.concat(e,t)}peekBufferedByte(e){let t=this.lineChunkIndex,n=this.linePos;for(;t<this.chunks.length;){let r=this.chunks[t],i=r.length-n;if(e<i)return r[n+e];e-=i,t++,n=0}}discardLeadingBytes(e){for(;e>0&&this.lineChunkIndex<this.chunks.length;){let t=this.chunks[this.lineChunkIndex].length-this.linePos;e<t?(this.linePos+=e,e=0):(e-=t,this.lineChunkIndex++,this.linePos=0)}this.chunkIndex=this.lineChunkIndex,this.pos=this.linePos,this.dropConsumedChunks()}handleBOM(){let e=this.peekBufferedByte(0),t=this.peekBufferedByte(1),n=this.peekBufferedByte(2);return t===void 0?(e===s[0]||(this.checkBOM=!1),!0):n===void 0?e===s[0]&&t===s[1]||(this.checkBOM=!1,!1):(e===s[0]&&t===s[1]&&n===s[2]&&this.discardLeadingBytes(3),this.checkBOM=!1,!this.hasCurrentByte())}}}})),Mn=t(((t,n)=>{var{pipeline:r}=e(`node:stream`),{fetching:i}=dn(),{webidl:a}=Qe(),{EventSourceStream:o}=jn(),{parseMIMEType:s}=Ze(),{createFastMessageEvent:c}=yn(),{isNetworkError:l}=cn(),{isValidHeaderValue:u,kEnumerableProperty:d}=$(),{environmentSettingsObject:f}=$e(),{createPotentialCORSRequest:p}=An(),{getGlobalDispatcher:m}=Ht(),{isomorphicDecode:h}=Xe(),g=new TextEncoder,_=!1,v=3e3,y=0,b=1,x=2,S=`anonymous`,C=`use-credentials`,w=class extends EventTarget{#e={open:null,error:null,message:null};#t;#n=!1;#r=y;#i=null;#a=null;#o;#s;constructor(e,t={}){super(),a.util.markAsUncloneable(this);let n=`EventSource constructor`;a.argumentLengthCheck(arguments,1,n),_||(_=!0,process.emitWarning(`EventSource is experimental, expect them to change at any time.`,{code:`UNDICI-ES`})),e=a.converters.USVString(e),t=a.converters.EventSourceInitDict(t,n,`eventSourceInitDict`),this.#o=t.node.dispatcher||t.dispatcher,this.#s={lastEventId:``,reconnectionTime:t.node.reconnectionTime};let r=f,i;try{i=new URL(e,r.settingsObject.baseUrl),this.#s.origin=i.origin}catch(e){throw new DOMException(e,`SyntaxError`)}this.#t=i.href;let o=S;t.withCredentials===!0&&(o=C,this.#n=!0);let s=p(i,``,o);s.client=f.settingsObject,s.headersList.set(`Accept`,`text/event-stream`),s.cache=`no-store`,s.initiator=`other`,this.#i=s,this.#c()}get readyState(){return a.brandCheck(this,a.is.EventSource),this.#r}get url(){return a.brandCheck(this,a.is.EventSource),this.#t}get withCredentials(){return a.brandCheck(this,a.is.EventSource),this.#n}#c(){if(this.#r===x)return;this.#r=y;let e={request:this.#i,dispatcher:this.#o};e.processResponseEndOfBody=e=>{if(!l(e))return this.#l()},e.processResponse=e=>{if(l(e)){if(e.aborted){this.close(),this.dispatchEvent(new Event(`error`));return}this.#l();return}let t=e.headersList.get(`content-type`,!0),n=t===null?`failure`:s(t),i=n!==`failure`&&n.essence===`text/event-stream`;if(e.status!==200||i===!1){this.close(),this.dispatchEvent(new Event(`error`));return}this.#r=b,this.dispatchEvent(new Event(`open`)),this.#s.origin=e.urlList[e.urlList.length-1].origin;let a=new o({eventSourceSettings:this.#s,maxEventSize:this.#o.eventSourceOptions?.maxEventSize,push:e=>{this.dispatchEvent(c(e.type,e.options))}});r(e.body.stream,a,e=>{e?.aborted===!1&&(this.close(),this.dispatchEvent(new Event(`error`)))})},this.#a=i(e)}#l(){this.#r!==x&&(this.#r=y,this.dispatchEvent(new Event(`error`)),setTimeout(()=>{if(this.#r===y){if(this.#i.headersList.delete(`last-event-id`,!0),this.#s.lastEventId.length){let e=h(g.encode(this.#s.lastEventId));u(e)&&this.#i.headersList.set(`last-event-id`,e,!0)}this.#c()}},this.#s.reconnectionTime)?.unref())}close(){a.brandCheck(this,a.is.EventSource),this.#r!==x&&(this.#r=x,this.#a.abort(),this.#i=null)}get onopen(){return a.brandCheck(this,a.is.EventSource),this.#e.open}set onopen(e){a.brandCheck(this,a.is.EventSource),this.#e.open&&this.removeEventListener(`open`,this.#e.open);let t=a.converters.EventHandlerNonNull(e);t===null?this.#e.open=null:(this.addEventListener(`open`,t),this.#e.open=e)}get onmessage(){return a.brandCheck(this,a.is.EventSource),this.#e.message}set onmessage(e){a.brandCheck(this,a.is.EventSource),this.#e.message&&this.removeEventListener(`message`,this.#e.message);let t=a.converters.EventHandlerNonNull(e);t===null?this.#e.message=null:(this.addEventListener(`message`,t),this.#e.message=e)}get onerror(){return a.brandCheck(this,a.is.EventSource),this.#e.error}set onerror(e){a.brandCheck(this,a.is.EventSource),this.#e.error&&this.removeEventListener(`error`,this.#e.error);let t=a.converters.EventHandlerNonNull(e);t===null?this.#e.error=null:(this.addEventListener(`error`,t),this.#e.error=e)}static{a.is.EventSource=e=>typeof e==`object`&&!!e&&#e in e}},T={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:y,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:b,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:x,writable:!1}};Object.defineProperties(w,T),Object.defineProperties(w.prototype,T),Object.defineProperties(w.prototype,{close:d,onerror:d,onmessage:d,onopen:d,readyState:d,url:d,withCredentials:d}),a.converters.EventSourceInitDict=a.dictionaryConverter([{key:`withCredentials`,converter:a.converters.boolean,defaultValue:()=>!1},{key:`dispatcher`,converter:a.converters.any,defaultValue:()=>m()},{key:`node`,converter:a.dictionaryConverter([{key:`reconnectionTime`,converter:a.converters[`unsigned long`],defaultValue:()=>v},{key:`dispatcher`,converter:a.converters.any}]),defaultValue:()=>({})}]),n.exports={EventSource:w,defaultReconnectionTime:v}})),Nn=t(((e,t)=>{var n=ot(),r=Be(),i=lt(),a=ut(),o=dt(),s=ft(),c=pt(),l=_t(),u=gt(),d=vt(),f=bt(),p=xt(),m=Q(),h=$(),{InvalidArgumentError:g}=m,_=kt(),v=He(),y=Pt(),{MockCallHistory:b,MockCallHistoryLog:x}=Ft(),S=Rt(),C=It(),w=Vt(),T=At(),E=yt(),{getGlobalDispatcher:D,setGlobalDispatcher:O}=Ht(),k=Ut(),A=Wt();Object.assign(r.prototype,_),t.exports.Dispatcher=r,t.exports.Client=n,t.exports.Pool=i,t.exports.BalancedPool=a,t.exports.RoundRobinPool=o,t.exports.Agent=s,t.exports.Dispatcher1Wrapper=c,t.exports.ProxyAgent=l,t.exports.Socks5ProxyAgent=u,t.exports.EnvHttpProxyAgent=d,t.exports.RetryAgent=f,t.exports.H2CClient=p,t.exports.RetryHandler=E,t.exports.DecoratorHandler=k,t.exports.RedirectHandler=A,t.exports.interceptors={redirect:Gt(),responseError:Kt(),retry:qt(),dump:Jt(),dns:Yt(),cache:tn(),decompress:nn(),deduplicate:an()},t.exports.cacheStores={MemoryCacheStore:$t()};var j=on();t.exports.cacheStores.SqliteCacheStore=j,t.exports.buildConnector=v,t.exports.errors=m,t.exports.util={parseHeaders:h.parseHeaders,headerNameToString:h.headerNameToString};function M(e){return(t,n,r)=>{if(typeof n==`function`&&(r=n,n=null),!t||typeof t!=`string`&&typeof t!=`object`&&!(t instanceof URL))throw new g(`invalid url`);if(n!=null&&typeof n!=`object`)throw new g(`invalid opts`);if(n&&n.path!=null){if(typeof n.path!=`string`)throw new g(`invalid opts.path`);let e=n.path;n.path.startsWith(`/`)||(e=`/${e}`),t=new URL(h.parseOrigin(t).origin+e)}else n||=typeof t==`object`?t:{},t=h.parseURL(t);let{agent:i,dispatcher:a=D(),...o}=n;if(i)throw new g(`unsupported opts.agent. Did you mean opts.client?`);return e.call(a,{...o,origin:t.origin,path:t.search?`${t.pathname}${t.search}`:t.pathname,method:n.method||(n.body?`PUT`:`GET`)},r)}}t.exports.setGlobalDispatcher=O,t.exports.getGlobalDispatcher=D;var N=dn().fetch,P=typeof __filename<`u`?__filename:void 0;function F(e,t){if(!e||typeof e!=`object`)return;let n=typeof e.stack==`string`?e.stack:``,r=t.replace(/\\/g,`/`);if(n&&(n.includes(t)||n.includes(r)))return;let i={};if(Error.captureStackTrace(i,F),!i.stack)return;let a=i.stack.split(`
|
|
95
95
|
`).slice(1).join(`
|
|
96
|
-
`);e.stack=n?`${n}\n${a}`:i.stack}t.exports.fetch=function(e,n=void 0){return N(e,n).catch(e=>{throw P?F(e,P):e&&typeof e==`object`&&Error.captureStackTrace(e,t.exports.fetch),e})},t.exports.Headers=sn().Headers,t.exports.Response=cn().Response,t.exports.Request=ln().Request,t.exports.FormData=tt().FormData;var{setGlobalOrigin:I,getGlobalOrigin:L}=Je();t.exports.setGlobalOrigin=I,t.exports.getGlobalOrigin=L;var{CacheStorage:R}=mn(),{kConstruct:z}=Z();t.exports.caches=new R(z);var{deleteCookie:B,getCookies:V,getSetCookies:ee,setCookie:te,parseCookie:H}=vn();t.exports.deleteCookie=B,t.exports.getCookies=V,t.exports.getSetCookies=ee,t.exports.setCookie=te,t.exports.parseCookie=H;var{parseMIMEType:ne,serializeAMimeType:U}=Ze();t.exports.parseMIMEType=ne,t.exports.serializeAMimeType=U;var{CloseEvent:W,ErrorEvent:G,MessageEvent:K}=yn(),{WebSocket:q,ping:J}=Dn();t.exports.WebSocket=q,t.exports.CloseEvent=W,t.exports.ErrorEvent=G,t.exports.MessageEvent=K,t.exports.ping=J,t.exports.WebSocketStream=kn().WebSocketStream,t.exports.WebSocketError=On().WebSocketError,t.exports.request=M(_.request),t.exports.stream=M(_.stream),t.exports.pipeline=M(_.pipeline),t.exports.connect=M(_.connect),t.exports.upgrade=M(_.upgrade),t.exports.MockClient=y,t.exports.MockCallHistory=b,t.exports.MockCallHistoryLog=x,t.exports.MockPool=C,t.exports.MockAgent=S,t.exports.SnapshotAgent=w,t.exports.mockErrors=T;var{EventSource:re}=Mn();t.exports.EventSource=re;function ie(){globalThis.fetch=t.exports.fetch,globalThis.Headers=t.exports.Headers,globalThis.Response=t.exports.Response,globalThis.Request=t.exports.Request,globalThis.FormData=t.exports.FormData,globalThis.WebSocket=t.exports.WebSocket,globalThis.CloseEvent=t.exports.CloseEvent,globalThis.ErrorEvent=t.exports.ErrorEvent,globalThis.MessageEvent=t.exports.MessageEvent,globalThis.EventSource=t.exports.EventSource}t.exports.install=ie}))(),Pn=11e4,Fn=8,In=67108864,Ln=new Set([`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`]),Rn=new Map;function zn(){let e=process.env.AVENTURE_API_SOCKET_PATH,t={headersTimeout:0,bodyTimeout:0},n=Rn.get(e??``)??new Nn.Dispatcher1Wrapper(e?new Nn.Agent({...t,connect:(t,n)=>(0,Nn.buildConnector)({socketPath:e,timeout:Pn})({...t,protocol:`http:`},n)}):new Nn.EnvHttpProxyAgent({...t,proxyTunnel:!0}));return Rn.set(e??``,n),n}async function Bn(e,t,n){let r=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),i=t.timeoutMs??(Number.isInteger(r)&&r>0?r:Pn),a=Date.now()+i,o={...t,headers:{...t.headers,[y]:I()??crypto.randomUUID()},unconfirmedWriteAdvice:t.method===`GET`||t.idempotent===!0?t.unconfirmedWriteAdvice:`no response arrived, so this write may or may not have been stored; read it back`+(t.readbackOperationId===void 0?``:` with ${t.readbackOperationId}`)+` before resending it`},s=t.followRollover===!0?o:{...o,headers:{Prefer:`respond-async`,...o.headers}},c=(t,r={waitMs:0,deadline:a})=>Vn(e,t,n,i,r.deadline,r.waitMs),l=await c(s);if(!l.ok&&l.headers!==void 0){let{idempotent:n,replayRateLimit:r}=t,i=ce(l.status,l.problem,n===!0,r);i!==void 0&&Date.now()+i<a&&(ee({component:`aventure-api-client`,event:`request_retry`,fields:{...Jn(o,e.host,o.headers[y]),retryKind:`http_refusal`,status:l.status,waitMs:Math.round(i)}}),l=await c({...s,idempotent:!1},{waitMs:i,deadline:a}))}let u=t.followRollover!==!0&&we(l)!==void 0;if(t.followRollover!==!0&&!u)return l;let d=!u&&!l.ok&&l.problem.code===`search_still_running`&&Date.now()<a?await c({...o,headers:{...o.headers,Prefer:`respond-async`}}):l,f=!d.ok&&d.problem.code===`async_lookup_sign_in_required`?l:d;if(!f.ok&&!u)return f;let p={...o.headers,Accept:`application/json`};return De(f,{origin:new URL(Gn(e.host,`/`)).origin,deadline:a,signal:t.signal,rollsOver:t.followRollover===!0},(e,n)=>c({method:`GET`,path:e,headers:p,signal:t.signal},{waitMs:0,deadline:Date.now()+n}))}async function Vn(e,t,r,i,a,o=0){let c=Gn(e.host,t.path,t.searchParams),l=t.headers[y],u=Jn(t,e.host,l),d={Accept:`application/json`,"User-Agent":n(),...t.headers,...x()},f=t.body instanceof FormData?t.body:JSON.stringify(t.body);f!==void 0&&t.contentType!==void 0&&(d[`Content-Type`]=t.contentType);let p=performance.now();B({component:`aventure-api-client`,event:`request`,fields:{...u,hasBody:t.body!==void 0}});let m=``,h,g=`neutral`,_,v=`network`,b=e=>{let n=t.signal?.aborted?t.signal.reason:e,r=n instanceof Error&&n.name===`TimeoutError`?`deadline`:t.signal?.aborted?`caller_abort`:e instanceof SyntaxError||e instanceof RangeError?`body`:v;return B({component:`aventure-api-client`,event:`request_failed`,message:te(e),fields:{...u,status:_?.status,timeoutMs:i,failureKind:r,durationMs:Math.round(performance.now()-p),...V(e)},error:e}),r},S=()=>(h=T(new URL(c).origin,A),m=t.unconfirmedWriteAdvice===void 0?``:`; ${t.unconfirmedWriteAdvice}`,h);try{o>0&&await pe(o,void 0,{signal:t.signal}),_=await Wn(c,t,d,f,i,a,S),g=[502,503,504].includes(_.status)?`failure`:`success`,v=`body`;let e={status:_.status,headers:Object.fromEntries(_.headers)},n={...u,status:_.status},s=_.headers.get(`location`),l=qn.has(_.status)&&s!==null;l&&await _.body?.cancel().catch(()=>ee({component:`aventure-api-client`,event:`redirect_body_cleanup_failed`,message:`Redirect body cleanup failed after headers were received`,fields:n}));let h=l?``:await Hn(_,t.responseBytes===!0).catch(e=>{if(_?.ok&&e instanceof RangeError)return e;if(_?.ok||e instanceof RangeError)throw e;return b(e),`Response body read failed: ${te(e)}`});v=`schema`;let y=l||h instanceof Uint8Array||h instanceof RangeError?h:Yn(h,_.headers.get(`content-type`),_.ok?r:void 0,n,m),x=y instanceof SyntaxError||y instanceof RangeError;x&&b(y);let C=Math.round(performance.now()-p);if(_.ok&&!x||l)return B({component:`aventure-api-client`,event:`response`,fields:{...n,durationMs:C}}),l?{ok:!0,redirect:!0,...e,location:s,data:void 0}:{ok:!0,...e,data:y};let w=x?y.message:y??h,T=re(se(J(_.status,w,d),_.headers),d),E=T.code===`search_still_running`&&(t.followRollover===!0||_.headers.has(`location`));return(E?B:ee)({component:`aventure-api-client`,event:E?`following_job`:`problem_response`,fields:{...u,durationMs:C,...oe(T,d)}}),{ok:!1,...e,problem:T}}catch(e){let t=b(e);if(e instanceof L)return{ok:!1,status:503,problem:J(503,{title:`API is ${e.reason===`capacity`?`overloaded`:`unavailable`}; retry later`})};if(v===`schema`)throw e;g!==`failure`&&!(e instanceof RangeError)&&(g=t===`caller_abort`?`neutral`:`failure`);let n=te(e),r=V(e).causeChain,i=r===void 0?``:`: ${String(r)}`;throw Error(v===`body`?`Response body read from ${s()} failed: ${n}${m}`:`request to ${s()} failed: ${n}${i}${m}`,{cause:e})}finally{h?.finish(g)}}async function Hn(e,t){let n=e.body?.getReader();if(!n)return e.ok&&t?new Uint8Array:``;let r=[],i=0;try{for(let e=await n.read();!e.done;e=await n.read()){if(i+=e.value.byteLength,i>In){let e=RangeError(`API response exceeded ${In} bytes`);throw await n.cancel(e),e}r.push(e.value)}}finally{n.releaseLock()}let a=Buffer.concat(r,i),o=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);return e.ok&&t?o:new TextDecoder().decode(o)}function Un(e){for(let t=0;t<Fn&&e instanceof Error;t+=1){if(`code`in e&&typeof e.code==`string`)return Ln.has(e.code);if(e.name===`TimeoutError`||e.message===`socket hang up`)return!0;e=e.cause}return!1}async function Wn(e,t,n,r,i,a,o){if(t.method===`GET`&&r!==void 0)throw TypeError(`GET requests cannot have a body`);let s=new Headers(n).get(`X-Client-Request-Id`)??void 0,c=zn(),l=t.method===`GET`||t.idempotent===!0?2:1;for(let u=1;;u+=1){let d=a-Date.now();if(d<=0)throw Object.assign(Error(`request deadline exceeded`),{name:`TimeoutError`});let f=AbortSignal.any([AbortSignal.timeout(Math.min(i,d)),...t.signal?[t.signal]:[]]),p;try{return u>1&&await pe(ue(),void 0,{signal:f}),f.throwIfAborted(),p=o(),await fetch(e,{method:t.method,headers:n,body:r??null,signal:f,dispatcher:c,redirect:`manual`})}catch(n){if(n instanceof L)throw n;let r=f.aborted?f.reason:n;if(u>=l||t.signal?.aborted===!0||Date.now()>=a||!Un(r))throw r;p?.finish(`failure`),ee({component:`aventure-api-client`,event:`request_retry`,message:te(n),fields:{...Jn(t,new URL(e).host,s),retryKind:`transport`,attempt:u,...V(n)},error:n})}}}function Gn(e,t,n){let r=new URL(t,e.startsWith(`http`)?e:`https://${e}`);for(let[e,t]of Object.entries(n??{}))t!==void 0&&r.searchParams.set(e,String(t));return r.toString()}var Kn=new Set([202,204,205]),qn=new Set([301,302,303,307,308]);function Jn(e,t,n){let{method:r,path:i,operationId:a}=e;return{method:r,host:t,path:w(i),requestId:n,operationId:a}}function Yn(e,t,n,r,i){let a=t?.includes(`json`)===!0,o=e.length===0?void 0:e;if(e.length>0&&(a||[`{`,`[`].includes(e.trimStart().slice(0,1))))try{o=JSON.parse(e)}catch{if(ee({component:`aventure-api-client`,event:`response_json_parse_failed`,message:`API response declared JSON but did not parse`,fields:{...r}}),n!==void 0&&a)return SyntaxError(`API response declared JSON but did not parse${i}`)}if(n===void 0||o===void 0&&Kn.has(r.status))return o;let s=n.safeParse(o);if(s.success)return s.data;throw Error(`API response failed canonical schema validation${i}`,{cause:s.error})}function Xn(e,t,n,r,i){let a=r(Zn(e,t,n,!1));return h(a,i)?a:r(Zn(e,t,n,!0))}function Zn(e,t,n,r){let i=n.redirect?void 0:n.rolloverJob;if(i?.running===!0)return{ids:i.jobId===void 0?[]:[i.jobId],references:[`${e}${i.statusUrl}`]};let{data:a}=n,o=[`${e}${t}`],s=er(a)?a.sourceDocumentId:void 0;return typeof s==`string`?{ids:[s],references:[...o,`${e}/v1/research/source-documents/${s}/body`]}:{ids:r?$n(a):[],references:o}}var Qn=2;function $n(e,t=0){let n=t===0&&Array.isArray(e)?e:er(e)&&Array.isArray(e.content)?e.content:void 0;return n===void 0?!er(e)||t>=Qn?[]:Object.values(e).flatMap(e=>$n(e,t+1)):n.flatMap(e=>{if(!er(e))return[];let t=er(e.entity)?e.entity:e.person,n=er(t)&&er(t.core)?t.core.id:void 0,r=er(e.core)?e.core.id:e.id??n;return typeof r==`string`||typeof r==`number`?[String(r)]:[]})}var er=e=>typeof e==`object`&&!!e&&!Array.isArray(e),tr=`actorType`,nr=`agentChassis`,rr=`agentModel`,ir=[tr,nr,rr],ar=`AVENTURE_AGENT_CHASSIS`,or=`AVENTURE_AGENT_MODEL`,sr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_HOME`,`GROK_MANAGED_BY_NPM`,`GROK_MANAGED_BY_INTERNAL`]},{chassis:`claude-code`,envNames:[`CLAUDECODE`,`CLAUDE_CODE`]},{chassis:`pi-cli`,envNames:[`PI_CODING_AGENT`]},{chassis:`codex-cli`,envNames:[`CODEX_MANAGED_BY_NPM`,`CODEX_SANDBOX`,`CODEX_THREAD_ID`,`CODEX_HOME`]},{chassis:`opencode`,envNames:[`OPENCODE_TERMINAL`]}],cr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_MODEL`,`XAI_MODEL`]},{chassis:`pi-cli`,envNames:[`PI_MODEL`]}],lr=[`OLLAMA_MODEL`,`OLLAMA_LAUNCH_MODEL`],ur=[`claude-code`,`claude-agent-sdk`],dr=`codex-cli`,fr=`opencode`;function pr(e){let t=Cr(e);return t.has(tr)||t.has(nr)&&t.has(rr)}function mr({operation:e,searchParams:t,env:n=process.env,clientInfo:r}){if(!pr(e)){if(ir.some(e=>t?.[e]!==void 0)){let e={...t};for(let t of ir)delete e[t];return p(`Agent provenance not applicable`,e)}return p(`Agent provenance unchanged`,t)}let i=Dr(t?.[tr]),a=i?.toLowerCase();if(i&&a!==`agent`&&a!==`employee`)return g(`${e.operationId} has unknown provenance actorType.`,[`Use actorType=agent or actorType=employee. actorType is optional only at the API boundary when a complete agent pair or employee JWT lets the resolver infer it before domain and write-lane enforcement.`]);let o=Dr(t?.[nr]),s=Dr(t?.[rr]),c=vr(n,r);if(a===`employee`)return o||s||c.status!==`missing`?g(`${e.operationId} has mixed employee and agent provenance.`,[`An agent runtime cannot claim employee attribution; use the runtime's agent provenance carrier.`]):p(`Employee provenance explicit`,{...t,actorType:`employee`});let l=Er(n,ar),u=Er(n,or);if(o&&l&&o!==l)return g(gr(e,`chassis`),[_r({param:nr,flag:`--agent-chassis`,envName:ar,envValue:l,explicitValue:o})]);if(s&&u&&s!==u)return g(gr(e,`model`),[_r({param:rr,flag:`--agent-model`,envName:or,envValue:u,explicitValue:s})]);if(o&&s){if(c.status===`partial`){let i=yr(n,r);return o!==Sr(r?.name)&&o===dr?g(`${e.operationId} rejected: ${dr} binds its pair through its PreToolUse hook.`,[c.warning,`Run the CLI directly without --agent-chassis or --agent-model.`]):l===void 0&&u===void 0&&i.includes(o)?p(`Agent provenance explicit`,{...t,actorType:`agent`}):g(`${e.operationId} rejected: --agent-chassis ${o} is not this runtime.`,[c.warning,i.length===0?`Set ${ar} and ${or} together.`:`This shell shows ${i.join(` and `)}. If that is you, pass --agent-chassis ${i.join(` or `)} --agent-model <your current model>; a different runtime launched from it sets ${ar} and ${or} to its own pair.`])}let i=l===void 0&&o!==dr&&yr(n,r).includes(o);return c.status===`complete`&&!i&&(o!==c.pair.agentChassis||s!==c.pair.agentModel)?g(`${e.operationId} rejected: explicit agent provenance disagrees with the runtime environment.`,[`Detected ${c.pair.agentChassis}/${c.pair.agentModel} from runtime signals.`,`You passed --agent-chassis ${o} --agent-model ${s}.`,`Omit both flags, or set AVENTURE_AGENT_CHASSIS and AVENTURE_AGENT_MODEL after verifying the session.`]):p(`Agent provenance explicit`,{...t,actorType:`agent`})}return o||s?g(hr(e),[`Pass both agentChassis and agentModel, or omit both so the API can infer an employee actor from an authenticated user JWT session or this caller can auto-fill a verified local agent pair.`]):c.status===`missing`?a===`agent`?g(hr(e),[`actorType=agent requires agentChassis and agentModel before the API can build the enforced domain actor.`]):p(`Provenance left for API-boundary actor inference`,t):c.status===`partial`?g(hr(e),[c.warning,`Pass agentChassis and agentModel together, or neither.`]):p(`Agent provenance auto-filled`,{...t,actorType:`agent`,agentChassis:c.pair.agentChassis,agentModel:c.pair.agentModel})}function hr(e){return`${e.operationId} requires complete agent provenance.`}function gr(e,t){return`${e.operationId} rejected: explicit agent ${t} disagrees with the runtime environment.`}function _r(e){return[`Your runtime environment declares ${e.envName}=${e.envValue}, but you passed ${e.flag} ${e.explicitValue} (query param ${e.param}).`,`The environment value comes from the container/runtime you are executing inside and is almost always correct.`,`If you (the LLM agent) believe the environment is wrong, investigate the container configuration first — do not override with a guess.`,`Otherwise, omit ${e.flag} entirely and the CLI will auto-fill from ${e.envName} (and ${or} for the model). LLM agents hallucinate provenance frequently; stop providing false parameters.`].join(` `)}function vr(e,t){let n=Er(e,ar),r=Er(e,or);if(n&&r)return{status:`complete`,pair:{agentChassis:n,agentModel:r}};if(n||r)return{status:`partial`,warning:`${ar} and ${or} must be set together.`};let i=yr(e,t),a=i.flatMap(t=>{let n=br(e,t);return n?[{agentChassis:t,agentModel:n}]:[]});if(a[0])return{status:`complete`,pair:a[0]};let o=i.filter(e=>e!==fr),s=o.length===1?o[0]:i.length===1?i[0]:void 0,c=s===fr||o.some(e=>e===`codex-cli`||xr(e))?void 0:wr(e,...lr);return s&&c?{status:`complete`,pair:{agentChassis:s,agentModel:c}}:i.length>0?{status:`partial`,warning:`${i.join(` and `)} ${i.length===1?`was`:`were`} detected, but no verified model source was present.`}:c?{status:`partial`,warning:`A model was detected, but no verified agent chassis source was present.`}:{status:`missing`,warning:`No verified local agent chassis/model pair was present.`}}function yr(e,t){let n=Sr(t?.name);return n?[n]:sr.filter(t=>t.envNames.some(t=>Tr(e,t))).map(e=>e.chassis)}function br(e,t){let n=cr.find(e=>e.chassis===t);return n?wr(e,...n.envNames):void 0}function xr(e){return e!==void 0&&ur.some(t=>t===e)}function Sr(e){let t=e?.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim();if(t){if(t.includes(`claude`)&&t.includes(`sdk`))return`claude-agent-sdk`;if(t===`claude code`||t.includes(`claude code`))return`claude-code`;if(t===`codex`||t.includes(`codex`))return`codex-cli`;if(t===`kimi`||t.includes(`kimi`))return`kimi-cli`;if(t.includes(`hermes`))return`hermes-cli`;if(t.includes(`grok`))return`grok-build-cli`;if(t.includes(`mistral vibe`))return`mistral-vibe-cli`;if(t===`pi`||t===`pi cli`)return`pi-cli`}}var Cr=e=>new Set((e.parameters??[]).filter(e=>e.in===`query`).map(e=>e.name)),wr=(e,...t)=>t.map(t=>Er(e,t)).find(e=>e!==void 0);function Tr(e,t){let n=Er(e,t)?.toLowerCase();return n!==void 0&&n!==`0`&&n!==`false`&&n!==`no`}function Er(e,t){return e[t]?.trim()||void 0}function Dr(e){if(e===void 0)return;let t=typeof e==`object`?e[0]:e;return t===void 0?void 0:String(t).trim()||void 0}var Or={AVENTURE_JOB_NAME:`X-Job-Name`,AVENTURE_TIER:`X-Tier`},kr=/^[A-Za-z0-9._:-]{1,120}$/;function Ar(){return Object.fromEntries(Object.entries(Or).flatMap(([e,t])=>{let n=process.env[e]?.trim();return n&&kr.test(n)?[[t,n]]:[]}))}function jr(e,t,n,r){let i=e.responses[String(t)]?.content;return n===void 0?n:Mr(n,i?.[`application/json`]?.schema,r).value}function Mr(e,t,n){let r=Br(t,n);if(r===void 0||typeof e!=`object`||!e)return{value:e,dropped:0};let i=[...r.oneOf??[],...r.anyOf??[]].filter(t=>Pr(Br(t,n),e));if(r.properties===void 0&&i.length>0)return i.map(t=>Mr(e,t,n)).reduce((e,t)=>t.dropped<e.dropped?t:e);if(Array.isArray(e))return Nr(e,r,n);let a=Fr(r,n);if(a===void 0)return{value:e,dropped:0};let o=0,s=Object.entries(e).flatMap(([e,t])=>{if(t===void 0)return[];let r=a.properties.get(e)??a.additionalProperties;if(r===void 0)return o+=1,[];let i=r===!0?{value:t,dropped:0}:Mr(t,r,n);return o+=i.dropped,[[e,i.value]]});return{value:Object.fromEntries(s),dropped:o}}function Nr(e,t,n){let r=t.items??(t.allOf??[]).find(e=>e.items!==void 0)?.items,i=e.map(e=>Mr(e,r,n));return{value:i.map(e=>e.value),dropped:i.reduce((e,t)=>e+t.dropped,0)}}function Pr(e,t){return e===void 0?!1:Array.isArray(t)?e.items!==void 0||Rr(e).includes(`array`):e.type===void 0&&e.properties===void 0||zr(e)||Lr(e).length>0}function Fr(e,t){let n=new Map,r;return Ir(e,t,n,new Set,e=>{r??=e})&&n.size>0?{properties:n,additionalProperties:r}:void 0}function Ir(e,t,n,r,i){let a=e.$ref;if(a!==void 0){if(r.has(a))return!0;r.add(a)}let o=Br(e,t);if(o===void 0)return!1;(o.additionalProperties===!0||typeof o.additionalProperties==`object`)&&i(o.additionalProperties);for(let[e,t]of Object.entries(o.properties??{}))n.has(e)||n.set(e,t);let s=Lr(o);return o.properties===void 0&&s.length===0?o.type!==void 0&&!zr(o):s.every(e=>Ir(e,t,n,r,i))}function Lr(e){return[...e.allOf??[],...e.oneOf??[],...e.anyOf??[]]}function Rr(e){return e.type===void 0?[]:[e.type].flat()}function zr(e){return e.properties!==void 0||Rr(e).includes(`object`)}function Br(e,t){let n=S(e);return n===void 0?e:t[n]}var Vr=class extends Error{problem;constructor(e){let{status:t,title:n,detail:r,code:i,retryAfterSeconds:a}=e;super(`OAuth bearer verification ${t===429?`was rate limited`:`is unavailable`}: ${t} ${n}${r?` — ${r}`:``}`+(typeof i==`string`?` [code: ${i}]`:``)+(typeof a==`number`?` [retry after ${a} seconds]`:``)),this.problem=e,this.name=`BearerVerificationUnavailableError`}};async function Hr(e,t,n=[],r){let i=`authorizeOperations`,a=await Bn(Yr(c()),{method:`POST`,path:Gr(i,{}),headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`},body:{operation:[...n]},operationId:i,idempotent:!0,replayRateLimit:!1,timeoutMs:r},ye);if(a.ok&&a.redirect)throw new Vr(J(a.status,`Unexpected authorization redirect`));if(!a.ok&&a.status!==401&&a.status!==403)throw new Vr(a.problem);if(!a.ok)return a.status===403?`forbidden`:null;if(!e.includes(`.`))return a.data;try{let{typ:t}=W(e);if(t!==`at+jwt`&&t!==`application/at+jwt`)return a.data}catch{return a.data}let{aud:o}=G(e);if(o===void 0)return a.data;if(t===void 0)throw Error(`OAuth bearer verification is unavailable`);let s=Array.isArray(o)?o:[o];return s.length===1&&s[0]===t.href?a.data:null}var Ur=`MCP transport credential is read-only; refused an authenticated upstream call.`,Wr=11e4;function Gr(e,t){let n=D(H().paths,e);if(!n)throw Error(`OpenAPI operationId not found: ${e}`);return z(n.template,v(n.operation,t,e),e)}function Kr(e){let t=e.pathParams??{};try{if(e.operationId!==void 0){let n=D(H().paths,e.operationId);if(n===null)return g(`OpenAPI operationId not found: ${e.operationId}`);let r=Gr(e.operationId,t);return p(`Resolved ${e.operationId}`,{...n,path:r})}if(e.method===void 0||e.path===void 0)return g(`Pass operationId or method+path.`);let n=C(e.method),r=e.path;H().paths[r]?.[n]===void 0&&r.includes(`{`)&&(r=Object.entries(H().paths).find(([t,r])=>{let i=r[n];return i!==void 0&&(i.parameters??[]).reduce((e,t)=>{let n=t[`x-aventure-legacy-name`]?.name;return n===void 0?e:e.replaceAll(`{${t.name}}`,`{${n}}`)},t)===e.path})?.[0]??e.path);let i=H().paths[r]?.[n],a=z(r,i===void 0?t:v(i,t,e.path),e.path),o=O(H().paths,n,a);return o===null?g(`OpenAPI operation not found for ${e.method} ${w(a)}`):(i===void 0&&v(o.operation,t,e.path),p(`Resolved ${o.operation.operationId}`,{...o,path:a}))}catch(e){return g(e instanceof Error?e.message:String(e))}}async function qr(e){let t=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),n=Date.now()+(Number.isInteger(t)&&t>0?t:Wr),r=O(H().paths,C(e.method),e.path);if(!r)return g(`OpenAPI operation not found for ${e.method} ${w(e.path)}`,[`Use a path in this package's OpenAPI contract; undocumented routes are not supported.`]);let i=r.operation,a=k(i.requestBody?.content),o=R(a,e.contentType);if(!o.ok||o.data===null)return g(o.summary,o.warnings);let c=X(i,e.headers);if(!c.ok||c.data===null)return g(c.summary,c.warnings);let l=e.requesterScope??`write`,h=e.auth===`auto`?(i.security?.length??0)>0?`bearer`:`none`:e.auth,v=b();if(l===`read`&&v===void 0&&(h===`write`||h===`bearer`))return g(Ur,[`Resolved upstream auth=${h} for ${e.method} ${e.path}.`,`Pass auth='read' explicitly for POST read endpoints, or sign in with an account that permits the call.`]);let y=M(e.body);if(!y.ok)return g(y.summary,y.warnings);if(F(o.data,H().components.schemas)&&y.data!==void 0&&!Array.isArray(y.data))return g(`${i.operationId} requires a JSON array body.`);let x=i.operationId,S=e.responseBytes===!0&&P(i),T=S?`*/*`:Zr(e.responseFormat??`auto`,i),D=e.preparedAuth===void 0?v===void 0?Xr(h,i,{searchParams:e.searchParams,body:y.data}):d(`none`):p(`reused prepared auth`,e.preparedAuth);if(!D.ok||!D.data)return g(D.summary,D.warnings);let A=e.preparedAuth===void 0&&v!==void 0?{...D.data,credential:u.authToken,headers:{Authorization:`Bearer ${v}`}}:D.data;e.onAuthPrepared?.(A);let I=mr({operation:i,searchParams:fe(i,e.searchParams,y.data,`Authorization`in A.headers),clientInfo:e.clientInfo});if(!I.ok)return g(I.summary,I.warnings);let L=I.data??void 0,z=Qr(e.path,L),B=Ee(i)&&e.method===`GET`&&w(z)===`/v1/web/page`&&!z.includes(`include=anchors`),V=Yr(D.data.env),ee=Yr({...V,host:s()}).host,te={method:e.method,endpoint:z,operationId:x},W=await j(i,y.data,e.contentType,{deadline:n,signal:e.signal,defaultContentType:e.method===`PATCH`?`application/merge-patch+json`:e.method===`POST`||e.method===`PUT`?`application/json`:void 0});if(!W.ok||W.data===null)return g(W.summary,W.warnings,{httpStatus:W.httpStatus});if(e.signal?.aborted||Date.now()>=n)return g(`Request canceled or invocation deadline exceeded before upload.`);let G=N({method:e.method,path:r.template,operation:i,includeBinary:!0}),K={method:e.method,path:z,headers:{...c.data,...A.headers,...B?{Prefer:`respond-async`}:{},...Ar(),Accept:T},body:W.data.body,contentType:W.data.contentType,operationId:x,readbackOperationId:i[`x-aventure-mutation-readback`]?.readOperationId,idempotent:e.method===`POST`&&G?.scope===`read`&&G.mutates!==!0&&i[`x-aventure-mutation-readback`]===void 0,followRollover:Ee(i),signal:AbortSignal.any([AbortSignal.timeout(Math.max(1,n-Date.now())),...e.signal?[e.signal]:[]])},q=S?await Bn(V,{...K,responseBytes:!0}):await Bn(V,K,m),J=x??e.method;if(!q.ok)return ie(`${J} failed`,q.problem,[`endpoint=${z}`]);if(q.data instanceof Uint8Array)return ne(p(`${J} succeeded`,q.data));let re=!q.redirect&&q.rolloverJob?.running===!0&&K.followRollover,oe=re&&e.pendingResult!==void 0?void 0:je(J,q,K.followRollover),se={...te,httpStatus:q.status},ce=f(q.data),le=T===`text/plain`&&typeof q.data==`string`?q.data:{...se,...a.length>1&&o.data!==void 0?{contentType:o.data.contentType}:{},...q.redirect?{location:q.location}:{},summary:i.summary,...q.headers[`x-next-cursor`]?{nextCursor:q.headers[`x-next-cursor`]}:{},response:jr(Jr(i,q.redirect?void 0:q.rolloverJob?.answeredPath),q.status,q.data,H().components.schemas)};if(oe!==void 0)return q.redirect||q.rolloverJob?.running===!0?oe:{...oe,data:le};let ue=Xn(ee,z,q,e=>p(Me(J,q),le,{...se,format:q.redirect||q.rolloverJob||T!==`text/plain`?`json`:`text`,count:_(q.data,ce),page:ce,filters:E(i,L),...ae(q.headers),...e}),e.responseFormat===`json`?U:void 0);return(re?e.pendingResult?.(ue,q):void 0)??ue}function Jr(e,t){if(t===void 0)return e;let n=O(H().paths,`get`,t);if(n===null)throw Error(`No bundled operation serves the polled job route GET ${t}`);return n.operation}function Yr(e){let t=e.host.trim();return/^https?:\/\//i.test(t)?t===e.host?e:{...e,host:t}:{...e,host:`${l(t)?`http`:`https`}://${t}`}}function Xr(e,t,n){if(e!==`none`)return d(e);let r=d(`none`);return!r.ok||!r.data?r:Y(t,n.searchParams,n.body)===`required`||r.data.env.userBearerToken?d(`bearer`):r}function Zr(e,t){return e===`json`?`application/json`:Object.entries(t.responses).some(([e,t])=>e.startsWith(`2`)&&`text/plain`in(t.content??{}))?`text/plain`:`application/json`}function Qr(e,t){let n=new URL(e,`https://placeholder.invalid`);for(let[e,r]of Object.entries(t??{}))if(r!==void 0){if(Array.isArray(r))for(let t of r)n.searchParams.append(e,String(t));else n.searchParams.set(e,String(r))}return`${n.pathname}${n.search}`}export{qr as a,Bn as c,Kr as i,ye as l,Zr as n,Hr as o,Gr as r,ir as s,Vr as t,me as u};
|
|
96
|
+
`);e.stack=n?`${n}\n${a}`:i.stack}t.exports.fetch=function(e,n=void 0){return N(e,n).catch(e=>{throw P?F(e,P):e&&typeof e==`object`&&Error.captureStackTrace(e,t.exports.fetch),e})},t.exports.Headers=sn().Headers,t.exports.Response=cn().Response,t.exports.Request=ln().Request,t.exports.FormData=tt().FormData;var{setGlobalOrigin:I,getGlobalOrigin:L}=Je();t.exports.setGlobalOrigin=I,t.exports.getGlobalOrigin=L;var{CacheStorage:R}=mn(),{kConstruct:z}=Z();t.exports.caches=new R(z);var{deleteCookie:B,getCookies:V,getSetCookies:ee,setCookie:te,parseCookie:H}=vn();t.exports.deleteCookie=B,t.exports.getCookies=V,t.exports.getSetCookies=ee,t.exports.setCookie=te,t.exports.parseCookie=H;var{parseMIMEType:ne,serializeAMimeType:U}=Ze();t.exports.parseMIMEType=ne,t.exports.serializeAMimeType=U;var{CloseEvent:W,ErrorEvent:G,MessageEvent:K}=yn(),{WebSocket:q,ping:J}=Dn();t.exports.WebSocket=q,t.exports.CloseEvent=W,t.exports.ErrorEvent=G,t.exports.MessageEvent=K,t.exports.ping=J,t.exports.WebSocketStream=kn().WebSocketStream,t.exports.WebSocketError=On().WebSocketError,t.exports.request=M(_.request),t.exports.stream=M(_.stream),t.exports.pipeline=M(_.pipeline),t.exports.connect=M(_.connect),t.exports.upgrade=M(_.upgrade),t.exports.MockClient=y,t.exports.MockCallHistory=b,t.exports.MockCallHistoryLog=x,t.exports.MockPool=C,t.exports.MockAgent=S,t.exports.SnapshotAgent=w,t.exports.mockErrors=T;var{EventSource:re}=Mn();t.exports.EventSource=re;function ie(){globalThis.fetch=t.exports.fetch,globalThis.Headers=t.exports.Headers,globalThis.Response=t.exports.Response,globalThis.Request=t.exports.Request,globalThis.FormData=t.exports.FormData,globalThis.WebSocket=t.exports.WebSocket,globalThis.CloseEvent=t.exports.CloseEvent,globalThis.ErrorEvent=t.exports.ErrorEvent,globalThis.MessageEvent=t.exports.MessageEvent,globalThis.EventSource=t.exports.EventSource}t.exports.install=ie}))(),Pn=11e4,Fn=8,In=67108864,Ln=new Set([`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`]),Rn=new Map;function zn(){let e=process.env.AVENTURE_API_SOCKET_PATH,t={headersTimeout:0,bodyTimeout:0},n=Rn.get(e??``)??new Nn.Dispatcher1Wrapper(e?new Nn.Agent({...t,connect:(t,n)=>(0,Nn.buildConnector)({socketPath:e,timeout:Pn})({...t,protocol:`http:`},n)}):new Nn.EnvHttpProxyAgent({...t,proxyTunnel:!0}));return Rn.set(e??``,n),n}async function Bn(e,t,n){let r=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),i=t.timeoutMs??(Number.isInteger(r)&&r>0?r:Pn),a=Date.now()+i,o={...t,headers:{...t.headers,[y]:I()??crypto.randomUUID()},unconfirmedWriteAdvice:t.method===`GET`||t.idempotent===!0?t.unconfirmedWriteAdvice:`no response arrived, so this write may or may not have been stored; read it back`+(t.readbackOperationId===void 0?``:` with ${t.readbackOperationId}`)+` before resending it`},s=t.followRollover===!0,c=s?o:{...o,headers:{Prefer:`respond-async`,...o.headers}},l=(t,r={waitMs:0,deadline:a})=>Vn(e,t,n,i,r.deadline,r.waitMs),u=await l(c),d=we(u);if(!u.ok&&u.headers!==void 0&&d===void 0){let{idempotent:n,replayRateLimit:r}=t,i=ce(u.status,u.problem,n===!0,r);i!==void 0&&Date.now()+i<a&&(ee({component:`aventure-api-client`,event:`request_retry`,fields:{...Jn(o,e.host,o.headers[y]),retryKind:`http_refusal`,status:u.status,waitMs:Math.round(i)}}),u=await l({...c,idempotent:!1},{waitMs:i,deadline:a}))}let f=(!s||t.idempotent===!0)&&we(u)!==void 0;if(!s&&!f)return u;let p=!f&&!u.ok&&u.problem.code===`search_still_running`&&Date.now()<a?await l({...o,headers:{...o.headers,Prefer:`respond-async`}}):u,m=!p.ok&&p.problem.code===`async_lookup_sign_in_required`?u:p;if(!m.ok&&!f)return m;let h={...o.headers,Accept:`application/json`};return De(m,{origin:new URL(Gn(e.host,`/`)).origin,deadline:a,signal:t.signal,rollsOver:s},(e,n)=>l({method:`GET`,path:e,headers:h,signal:t.signal},{waitMs:0,deadline:Date.now()+n}))}async function Vn(e,t,r,i,a,o=0){let c=Gn(e.host,t.path,t.searchParams),l=t.headers[y],u=Jn(t,e.host,l),d={Accept:`application/json`,"User-Agent":n(),...t.headers,...x()},f=t.body instanceof FormData?t.body:JSON.stringify(t.body);f!==void 0&&t.contentType!==void 0&&(d[`Content-Type`]=t.contentType);let p=performance.now();B({component:`aventure-api-client`,event:`request`,fields:{...u,hasBody:t.body!==void 0}});let m=``,h,g=`neutral`,_,v=`network`,b=e=>{let n=t.signal?.aborted?t.signal.reason:e,r=n instanceof Error&&n.name===`TimeoutError`?`deadline`:t.signal?.aborted?`caller_abort`:e instanceof SyntaxError||e instanceof RangeError?`body`:v;return B({component:`aventure-api-client`,event:`request_failed`,message:te(e),fields:{...u,status:_?.status,timeoutMs:i,failureKind:r,durationMs:Math.round(performance.now()-p),...V(e)},error:e}),r},S=()=>(h=T(new URL(c).origin,A),m=t.unconfirmedWriteAdvice===void 0?``:`; ${t.unconfirmedWriteAdvice}`,h);try{o>0&&await pe(o,void 0,{signal:t.signal}),_=await Wn(c,t,d,f,i,a,S),g=[502,503,504].includes(_.status)?`failure`:`success`,v=`body`;let e={status:_.status,headers:Object.fromEntries(_.headers)},n={...u,status:_.status},s=_.headers.get(`location`),l=qn.has(_.status)&&s!==null;l&&await _.body?.cancel().catch(()=>ee({component:`aventure-api-client`,event:`redirect_body_cleanup_failed`,message:`Redirect body cleanup failed after headers were received`,fields:n}));let h=l?``:await Hn(_,t.responseBytes===!0).catch(e=>{if(_?.ok&&e instanceof RangeError)return e;if(_?.ok||e instanceof RangeError)throw e;return b(e),`Response body read failed: ${te(e)}`});v=`schema`;let y=l||h instanceof Uint8Array||h instanceof RangeError?h:Yn(h,_.headers.get(`content-type`),_.ok?r:void 0,n,m),x=y instanceof SyntaxError||y instanceof RangeError;x&&b(y);let C=Math.round(performance.now()-p);if(_.ok&&!x||l)return B({component:`aventure-api-client`,event:`response`,fields:{...n,durationMs:C}}),l?{ok:!0,redirect:!0,...e,location:s,data:void 0}:{ok:!0,...e,data:y};let w=x?y.message:y??h,T=re(se(J(_.status,w,d),_.headers),d),E=T.code===`search_still_running`&&(t.followRollover===!0||_.headers.has(`location`));return E&&(g=`success`),(E?B:ee)({component:`aventure-api-client`,event:E?`following_job`:`problem_response`,fields:{...u,durationMs:C,...oe(T,d)}}),{ok:!1,...e,problem:T}}catch(e){let t=b(e);if(e instanceof L)return{ok:!1,status:503,problem:J(503,{title:`API is ${e.reason===`capacity`?`overloaded`:`unavailable`}; retry later`})};if(v===`schema`)throw e;g!==`failure`&&!(e instanceof RangeError)&&(g=t===`caller_abort`?`neutral`:`failure`);let n=te(e),r=V(e).causeChain,i=r===void 0?``:`: ${String(r)}`;throw Error(v===`body`?`Response body read from ${s()} failed: ${n}${m}`:`request to ${s()} failed: ${n}${i}${m}`,{cause:e})}finally{h?.finish(g)}}async function Hn(e,t){let n=e.body?.getReader();if(!n)return e.ok&&t?new Uint8Array:``;let r=[],i=0;try{for(let e=await n.read();!e.done;e=await n.read()){if(i+=e.value.byteLength,i>In){let e=RangeError(`API response exceeded ${In} bytes`);throw await n.cancel(e),e}r.push(e.value)}}finally{n.releaseLock()}let a=Buffer.concat(r,i),o=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);return e.ok&&t?o:new TextDecoder().decode(o)}function Un(e){for(let t=0;t<Fn&&e instanceof Error;t+=1){if(`code`in e&&typeof e.code==`string`)return Ln.has(e.code);if(e.name===`TimeoutError`||e.message===`socket hang up`)return!0;e=e.cause}return!1}async function Wn(e,t,n,r,i,a,o){if(t.method===`GET`&&r!==void 0)throw TypeError(`GET requests cannot have a body`);let s=new Headers(n).get(`X-Client-Request-Id`)??void 0,c=zn(),l=t.method===`GET`||t.idempotent===!0?2:1;for(let u=1;;u+=1){let d=a-Date.now();if(d<=0)throw Object.assign(Error(`request deadline exceeded`),{name:`TimeoutError`});let f=AbortSignal.any([AbortSignal.timeout(Math.min(i,d)),...t.signal?[t.signal]:[]]),p;try{return u>1&&await pe(ue(),void 0,{signal:f}),f.throwIfAborted(),p=o(),await fetch(e,{method:t.method,headers:n,body:r??null,signal:f,dispatcher:c,redirect:`manual`})}catch(n){if(n instanceof L)throw n;let r=f.aborted?f.reason:n;if(u>=l||t.signal?.aborted===!0||Date.now()>=a||!Un(r))throw r;p?.finish(`failure`),ee({component:`aventure-api-client`,event:`request_retry`,message:te(n),fields:{...Jn(t,new URL(e).host,s),retryKind:`transport`,attempt:u,...V(n)},error:n})}}}function Gn(e,t,n){let r=new URL(t,e.startsWith(`http`)?e:`https://${e}`);for(let[e,t]of Object.entries(n??{}))t!==void 0&&r.searchParams.set(e,String(t));return r.toString()}var Kn=new Set([202,204,205]),qn=new Set([301,302,303,307,308]);function Jn(e,t,n){let{method:r,path:i,operationId:a}=e;return{method:r,host:t,path:w(i),requestId:n,operationId:a}}function Yn(e,t,n,r,i){let a=t?.includes(`json`)===!0,o=e.length===0?void 0:e;if(e.length>0&&(a||[`{`,`[`].includes(e.trimStart().slice(0,1))))try{o=JSON.parse(e)}catch{if(ee({component:`aventure-api-client`,event:`response_json_parse_failed`,message:`API response declared JSON but did not parse`,fields:{...r}}),n!==void 0&&a)return SyntaxError(`API response declared JSON but did not parse${i}`)}if(n===void 0||o===void 0&&Kn.has(r.status))return o;let s=n.safeParse(o);if(s.success)return s.data;throw Error(`API response failed canonical schema validation${i}`,{cause:s.error})}function Xn(e,t,n,r,i){let a=r(Zn(e,t,n,!1));return h(a,i)?a:r(Zn(e,t,n,!0))}function Zn(e,t,n,r){let i=n.redirect?void 0:n.rolloverJob;if(i?.running===!0)return{ids:i.jobId===void 0?[]:[i.jobId],references:[`${e}${i.statusUrl}`]};let{data:a}=n,o=[`${e}${t}`],s=er(a)?a.sourceDocumentId:void 0;return typeof s==`string`?{ids:[s],references:[...o,`${e}/v1/research/source-documents/${s}/body`]}:{ids:r?$n(a):[],references:o}}var Qn=2;function $n(e,t=0){let n=t===0&&Array.isArray(e)?e:er(e)&&Array.isArray(e.content)?e.content:void 0;return n===void 0?!er(e)||t>=Qn?[]:Object.values(e).flatMap(e=>$n(e,t+1)):n.flatMap(e=>{if(!er(e))return[];let t=er(e.entity)?e.entity:e.person,n=er(t)&&er(t.core)?t.core.id:void 0,r=er(e.core)?e.core.id:e.id??n;return typeof r==`string`||typeof r==`number`?[String(r)]:[]})}var er=e=>typeof e==`object`&&!!e&&!Array.isArray(e),tr=`actorType`,nr=`agentChassis`,rr=`agentModel`,ir=[tr,nr,rr],ar=`AVENTURE_AGENT_CHASSIS`,or=`AVENTURE_AGENT_MODEL`,sr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_HOME`,`GROK_MANAGED_BY_NPM`,`GROK_MANAGED_BY_INTERNAL`]},{chassis:`claude-code`,envNames:[`CLAUDECODE`,`CLAUDE_CODE`]},{chassis:`pi-cli`,envNames:[`PI_CODING_AGENT`]},{chassis:`codex-cli`,envNames:[`CODEX_MANAGED_BY_NPM`,`CODEX_SANDBOX`,`CODEX_THREAD_ID`,`CODEX_HOME`]},{chassis:`opencode`,envNames:[`OPENCODE_TERMINAL`]}],cr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_MODEL`,`XAI_MODEL`]},{chassis:`pi-cli`,envNames:[`PI_MODEL`]}],lr=[`OLLAMA_MODEL`,`OLLAMA_LAUNCH_MODEL`],ur=[`claude-code`,`claude-agent-sdk`],dr=`codex-cli`,fr=`opencode`;function pr(e){let t=Cr(e);return t.has(tr)||t.has(nr)&&t.has(rr)}function mr({operation:e,searchParams:t,env:n=process.env,clientInfo:r}){if(!pr(e)){if(ir.some(e=>t?.[e]!==void 0)){let e={...t};for(let t of ir)delete e[t];return p(`Agent provenance not applicable`,e)}return p(`Agent provenance unchanged`,t)}let i=Dr(t?.[tr]),a=i?.toLowerCase();if(i&&a!==`agent`&&a!==`employee`)return g(`${e.operationId} has unknown provenance actorType.`,[`Use actorType=agent or actorType=employee. actorType is optional only at the API boundary when a complete agent pair or employee JWT lets the resolver infer it before domain and write-lane enforcement.`]);let o=Dr(t?.[nr]),s=Dr(t?.[rr]),c=vr(n,r);if(a===`employee`)return o||s||c.status!==`missing`?g(`${e.operationId} has mixed employee and agent provenance.`,[`An agent runtime cannot claim employee attribution; use the runtime's agent provenance carrier.`]):p(`Employee provenance explicit`,{...t,actorType:`employee`});let l=Er(n,ar),u=Er(n,or);if(o&&l&&o!==l)return g(gr(e,`chassis`),[_r({param:nr,flag:`--agent-chassis`,envName:ar,envValue:l,explicitValue:o})]);if(s&&u&&s!==u)return g(gr(e,`model`),[_r({param:rr,flag:`--agent-model`,envName:or,envValue:u,explicitValue:s})]);if(o&&s){if(c.status===`partial`){let i=yr(n,r);return o!==Sr(r?.name)&&o===dr?g(`${e.operationId} rejected: ${dr} binds its pair through its PreToolUse hook.`,[c.warning,`Run the CLI directly without --agent-chassis or --agent-model.`]):l===void 0&&u===void 0&&i.includes(o)?p(`Agent provenance explicit`,{...t,actorType:`agent`}):g(`${e.operationId} rejected: --agent-chassis ${o} is not this runtime.`,[c.warning,i.length===0?`Set ${ar} and ${or} together.`:`This shell shows ${i.join(` and `)}. If that is you, pass --agent-chassis ${i.join(` or `)} --agent-model <your current model>; a different runtime launched from it sets ${ar} and ${or} to its own pair.`])}let i=l===void 0&&o!==dr&&yr(n,r).includes(o);return c.status===`complete`&&!i&&(o!==c.pair.agentChassis||s!==c.pair.agentModel)?g(`${e.operationId} rejected: explicit agent provenance disagrees with the runtime environment.`,[`Detected ${c.pair.agentChassis}/${c.pair.agentModel} from runtime signals.`,`You passed --agent-chassis ${o} --agent-model ${s}.`,`Omit both flags, or set AVENTURE_AGENT_CHASSIS and AVENTURE_AGENT_MODEL after verifying the session.`]):p(`Agent provenance explicit`,{...t,actorType:`agent`})}return o||s?g(hr(e),[`Pass both agentChassis and agentModel, or omit both so the API can infer an employee actor from an authenticated user JWT session or this caller can auto-fill a verified local agent pair.`]):c.status===`missing`?a===`agent`?g(hr(e),[`actorType=agent requires agentChassis and agentModel before the API can build the enforced domain actor.`]):p(`Provenance left for API-boundary actor inference`,t):c.status===`partial`?g(hr(e),[c.warning,`Pass agentChassis and agentModel together, or neither.`]):p(`Agent provenance auto-filled`,{...t,actorType:`agent`,agentChassis:c.pair.agentChassis,agentModel:c.pair.agentModel})}function hr(e){return`${e.operationId} requires complete agent provenance.`}function gr(e,t){return`${e.operationId} rejected: explicit agent ${t} disagrees with the runtime environment.`}function _r(e){return[`Your runtime environment declares ${e.envName}=${e.envValue}, but you passed ${e.flag} ${e.explicitValue} (query param ${e.param}).`,`The environment value comes from the container/runtime you are executing inside and is almost always correct.`,`If you (the LLM agent) believe the environment is wrong, investigate the container configuration first — do not override with a guess.`,`Otherwise, omit ${e.flag} entirely and the CLI will auto-fill from ${e.envName} (and ${or} for the model). LLM agents hallucinate provenance frequently; stop providing false parameters.`].join(` `)}function vr(e,t){let n=Er(e,ar),r=Er(e,or);if(n&&r)return{status:`complete`,pair:{agentChassis:n,agentModel:r}};if(n||r)return{status:`partial`,warning:`${ar} and ${or} must be set together.`};let i=yr(e,t),a=i.flatMap(t=>{let n=br(e,t);return n?[{agentChassis:t,agentModel:n}]:[]});if(a[0])return{status:`complete`,pair:a[0]};let o=i.filter(e=>e!==fr),s=o.length===1?o[0]:i.length===1?i[0]:void 0,c=s===fr||o.some(e=>e===`codex-cli`||xr(e))?void 0:wr(e,...lr);return s&&c?{status:`complete`,pair:{agentChassis:s,agentModel:c}}:i.length>0?{status:`partial`,warning:`${i.join(` and `)} ${i.length===1?`was`:`were`} detected, but no verified model source was present.`}:c?{status:`partial`,warning:`A model was detected, but no verified agent chassis source was present.`}:{status:`missing`,warning:`No verified local agent chassis/model pair was present.`}}function yr(e,t){let n=Sr(t?.name);return n?[n]:sr.filter(t=>t.envNames.some(t=>Tr(e,t))).map(e=>e.chassis)}function br(e,t){let n=cr.find(e=>e.chassis===t);return n?wr(e,...n.envNames):void 0}function xr(e){return e!==void 0&&ur.some(t=>t===e)}function Sr(e){let t=e?.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim();if(t){if(t.includes(`claude`)&&t.includes(`sdk`))return`claude-agent-sdk`;if(t===`claude code`||t.includes(`claude code`))return`claude-code`;if(t===`codex`||t.includes(`codex`))return`codex-cli`;if(t===`kimi`||t.includes(`kimi`))return`kimi-cli`;if(t.includes(`hermes`))return`hermes-cli`;if(t.includes(`grok`))return`grok-build-cli`;if(t.includes(`mistral vibe`))return`mistral-vibe-cli`;if(t===`pi`||t===`pi cli`)return`pi-cli`}}var Cr=e=>new Set((e.parameters??[]).filter(e=>e.in===`query`).map(e=>e.name)),wr=(e,...t)=>t.map(t=>Er(e,t)).find(e=>e!==void 0);function Tr(e,t){let n=Er(e,t)?.toLowerCase();return n!==void 0&&n!==`0`&&n!==`false`&&n!==`no`}function Er(e,t){return e[t]?.trim()||void 0}function Dr(e){if(e===void 0)return;let t=typeof e==`object`?e[0]:e;return t===void 0?void 0:String(t).trim()||void 0}var Or={AVENTURE_JOB_NAME:`X-Job-Name`,AVENTURE_TIER:`X-Tier`},kr=/^[A-Za-z0-9._:-]{1,120}$/;function Ar(){return Object.fromEntries(Object.entries(Or).flatMap(([e,t])=>{let n=process.env[e]?.trim();return n&&kr.test(n)?[[t,n]]:[]}))}function jr(e,t,n,r){let i=e.responses[String(t)]?.content;return n===void 0?n:Mr(n,i?.[`application/json`]?.schema,r).value}function Mr(e,t,n){let r=Br(t,n);if(r===void 0||typeof e!=`object`||!e)return{value:e,dropped:0};let i=[...r.oneOf??[],...r.anyOf??[]].filter(t=>Pr(Br(t,n),e));if(r.properties===void 0&&i.length>0)return i.map(t=>Mr(e,t,n)).reduce((e,t)=>t.dropped<e.dropped?t:e);if(Array.isArray(e))return Nr(e,r,n);let a=Fr(r,n);if(a===void 0)return{value:e,dropped:0};let o=0,s=Object.entries(e).flatMap(([e,t])=>{if(t===void 0)return[];let r=a.properties.get(e)??a.additionalProperties;if(r===void 0)return o+=1,[];let i=r===!0?{value:t,dropped:0}:Mr(t,r,n);return o+=i.dropped,[[e,i.value]]});return{value:Object.fromEntries(s),dropped:o}}function Nr(e,t,n){let r=t.items??(t.allOf??[]).find(e=>e.items!==void 0)?.items,i=e.map(e=>Mr(e,r,n));return{value:i.map(e=>e.value),dropped:i.reduce((e,t)=>e+t.dropped,0)}}function Pr(e,t){return e===void 0?!1:Array.isArray(t)?e.items!==void 0||Rr(e).includes(`array`):e.type===void 0&&e.properties===void 0||zr(e)||Lr(e).length>0}function Fr(e,t){let n=new Map,r;return Ir(e,t,n,new Set,e=>{r??=e})&&n.size>0?{properties:n,additionalProperties:r}:void 0}function Ir(e,t,n,r,i){let a=e.$ref;if(a!==void 0){if(r.has(a))return!0;r.add(a)}let o=Br(e,t);if(o===void 0)return!1;(o.additionalProperties===!0||typeof o.additionalProperties==`object`)&&i(o.additionalProperties);for(let[e,t]of Object.entries(o.properties??{}))n.has(e)||n.set(e,t);let s=Lr(o);return o.properties===void 0&&s.length===0?o.type!==void 0&&!zr(o):s.every(e=>Ir(e,t,n,r,i))}function Lr(e){return[...e.allOf??[],...e.oneOf??[],...e.anyOf??[]]}function Rr(e){return e.type===void 0?[]:[e.type].flat()}function zr(e){return e.properties!==void 0||Rr(e).includes(`object`)}function Br(e,t){let n=S(e);return n===void 0?e:t[n]}var Vr=class extends Error{problem;constructor(e){let{status:t,title:n,detail:r,code:i,retryAfterSeconds:a}=e;super(`OAuth bearer verification ${t===429?`was rate limited`:`is unavailable`}: ${t} ${n}${r?` — ${r}`:``}`+(typeof i==`string`?` [code: ${i}]`:``)+(typeof a==`number`?` [retry after ${a} seconds]`:``)),this.problem=e,this.name=`BearerVerificationUnavailableError`}};async function Hr(e,t,n=[],r){let i=`authorizeOperations`,a=await Bn(Yr(c()),{method:`POST`,path:Gr(i,{}),headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`},body:{operation:[...n]},operationId:i,idempotent:!0,replayRateLimit:!1,timeoutMs:r},ye);if(a.ok&&a.redirect)throw new Vr(J(a.status,`Unexpected authorization redirect`));if(!a.ok&&a.status!==401&&a.status!==403)throw new Vr(a.problem);if(!a.ok)return a.status===403?`forbidden`:null;if(!e.includes(`.`))return a.data;try{let{typ:t}=W(e);if(t!==`at+jwt`&&t!==`application/at+jwt`)return a.data}catch{return a.data}let{aud:o}=G(e);if(o===void 0)return a.data;if(t===void 0)throw Error(`OAuth bearer verification is unavailable`);let s=Array.isArray(o)?o:[o];return s.length===1&&s[0]===t.href?a.data:null}var Ur=`MCP transport credential is read-only; refused an authenticated upstream call.`,Wr=11e4;function Gr(e,t){let n=D(H().paths,e);if(!n)throw Error(`OpenAPI operationId not found: ${e}`);return z(n.template,v(n.operation,t,e),e)}function Kr(e){let t=e.pathParams??{};try{if(e.operationId!==void 0){let n=D(H().paths,e.operationId);if(n===null)return g(`OpenAPI operationId not found: ${e.operationId}`);let r=Gr(e.operationId,t);return p(`Resolved ${e.operationId}`,{...n,path:r})}if(e.method===void 0||e.path===void 0)return g(`Pass operationId or method+path.`);let n=C(e.method),r=e.path;H().paths[r]?.[n]===void 0&&r.includes(`{`)&&(r=Object.entries(H().paths).find(([t,r])=>{let i=r[n];return i!==void 0&&(i.parameters??[]).reduce((e,t)=>{let n=t[`x-aventure-legacy-name`]?.name;return n===void 0?e:e.replaceAll(`{${t.name}}`,`{${n}}`)},t)===e.path})?.[0]??e.path);let i=H().paths[r]?.[n],a=z(r,i===void 0?t:v(i,t,e.path),e.path),o=O(H().paths,n,a);return o===null?g(`OpenAPI operation not found for ${e.method} ${w(a)}`):(i===void 0&&v(o.operation,t,e.path),p(`Resolved ${o.operation.operationId}`,{...o,path:a}))}catch(e){return g(e instanceof Error?e.message:String(e))}}async function qr(e){let t=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),n=Date.now()+(Number.isInteger(t)&&t>0?t:Wr),r=O(H().paths,C(e.method),e.path);if(!r)return g(`OpenAPI operation not found for ${e.method} ${w(e.path)}`,[`Use a path in this package's OpenAPI contract; undocumented routes are not supported.`]);let i=r.operation,a=k(i.requestBody?.content),o=R(a,e.contentType);if(!o.ok||o.data===null)return g(o.summary,o.warnings);let c=X(i,e.headers);if(!c.ok||c.data===null)return g(c.summary,c.warnings);let l=e.requesterScope??`write`,h=e.auth===`auto`?(i.security?.length??0)>0?`bearer`:`none`:e.auth,v=b();if(l===`read`&&v===void 0&&(h===`write`||h===`bearer`))return g(Ur,[`Resolved upstream auth=${h} for ${e.method} ${e.path}.`,`Pass auth='read' explicitly for POST read endpoints, or sign in with an account that permits the call.`]);let y=M(e.body);if(!y.ok)return g(y.summary,y.warnings);if(F(o.data,H().components.schemas)&&y.data!==void 0&&!Array.isArray(y.data))return g(`${i.operationId} requires a JSON array body.`);let x=i.operationId,S=e.responseBytes===!0&&P(i),T=S?`*/*`:Zr(e.responseFormat??`auto`,i),D=e.preparedAuth===void 0?v===void 0?Xr(h,i,{searchParams:e.searchParams,body:y.data}):d(`none`):p(`reused prepared auth`,e.preparedAuth);if(!D.ok||!D.data)return g(D.summary,D.warnings);let A=e.preparedAuth===void 0&&v!==void 0?{...D.data,credential:u.authToken,headers:{Authorization:`Bearer ${v}`}}:D.data;e.onAuthPrepared?.(A);let I=mr({operation:i,searchParams:fe(i,e.searchParams,y.data,`Authorization`in A.headers),clientInfo:e.clientInfo});if(!I.ok)return g(I.summary,I.warnings);let L=I.data??void 0,z=Qr(e.path,L),B=Ee(i)&&e.method===`GET`&&w(z)===`/v1/web/page`&&!z.includes(`include=anchors`),V=Yr(D.data.env),ee=Yr({...V,host:s()}).host,te={method:e.method,endpoint:z,operationId:x},W=await j(i,y.data,e.contentType,{deadline:n,signal:e.signal,defaultContentType:e.method===`PATCH`?`application/merge-patch+json`:e.method===`POST`||e.method===`PUT`?`application/json`:void 0});if(!W.ok||W.data===null)return g(W.summary,W.warnings,{httpStatus:W.httpStatus});if(e.signal?.aborted||Date.now()>=n)return g(`Request canceled or invocation deadline exceeded before upload.`);let G=N({method:e.method,path:r.template,operation:i,includeBinary:!0}),K={method:e.method,path:z,headers:{...c.data,...A.headers,...B?{Prefer:`respond-async`}:{},...Ar(),Accept:T},body:W.data.body,contentType:W.data.contentType,operationId:x,readbackOperationId:i[`x-aventure-mutation-readback`]?.readOperationId,idempotent:e.method===`POST`&&G?.scope===`read`&&G.mutates!==!0&&i[`x-aventure-mutation-readback`]===void 0,followRollover:Ee(i),signal:AbortSignal.any([AbortSignal.timeout(Math.max(1,n-Date.now())),...e.signal?[e.signal]:[]])},q=S?await Bn(V,{...K,responseBytes:!0}):await Bn(V,K,m),J=x??e.method;if(!q.ok)return ie(`${J} failed`,q.problem,[`endpoint=${z}`]);if(q.data instanceof Uint8Array)return ne(p(`${J} succeeded`,q.data));let re=!q.redirect&&q.rolloverJob?.running===!0&&K.followRollover,oe=re&&e.pendingResult!==void 0?void 0:je(J,q,K.followRollover),se={...te,httpStatus:q.status},ce=f(q.data),le=T===`text/plain`&&typeof q.data==`string`?q.data:{...se,...a.length>1&&o.data!==void 0?{contentType:o.data.contentType}:{},...q.redirect?{location:q.location}:{},summary:i.summary,...q.headers[`x-next-cursor`]?{nextCursor:q.headers[`x-next-cursor`]}:{},response:jr(Jr(i,q.redirect?void 0:q.rolloverJob?.answeredPath),q.status,q.data,H().components.schemas)};if(oe!==void 0)return q.redirect||q.rolloverJob?.running===!0?oe:{...oe,data:le};let ue=Xn(ee,z,q,e=>p(Me(J,q),le,{...se,format:q.redirect||q.rolloverJob||T!==`text/plain`?`json`:`text`,count:_(q.data,ce),page:ce,filters:E(i,L),...ae(q.headers),...e}),e.responseFormat===`json`?U:void 0);return(re?e.pendingResult?.(ue,q):void 0)??ue}function Jr(e,t){if(t===void 0)return e;let n=O(H().paths,`get`,t);if(n===null)throw Error(`No bundled operation serves the polled job route GET ${t}`);return n.operation}function Yr(e){let t=e.host.trim();return/^https?:\/\//i.test(t)?t===e.host?e:{...e,host:t}:{...e,host:`${l(t)?`http`:`https`}://${t}`}}function Xr(e,t,n){if(e!==`none`)return d(e);let r=d(`none`);return!r.ok||!r.data?r:Y(t,n.searchParams,n.body)===`required`||r.data.env.userBearerToken?d(`bearer`):r}function Zr(e,t){return e===`json`?`application/json`:Object.entries(t.responses).some(([e,t])=>e.startsWith(`2`)&&`text/plain`in(t.content??{}))?`text/plain`:`application/json`}function Qr(e,t){let n=new URL(e,`https://placeholder.invalid`);for(let[e,r]of Object.entries(t??{}))if(r!==void 0){if(Array.isArray(r))for(let t of r)n.searchParams.append(e,String(t));else n.searchParams.set(e,String(r))}return`${n.pathname}${n.search}`}export{qr as a,Bn as c,Kr as i,ye as l,Zr as n,Hr as o,Gr as r,ir as s,Vr as t,me as u};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-B09viugM.js";import{a as o}from"./package-CZBWjlYb.js";import{C as s,D as c,O as l,S as u,T as d,_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,l as x,m as S,n as C,o as w,p as T,s as E,t as D,u as O,v as k,w as A,x as j,y as M}from"./iso-l1vOidnb.js";import{$ as N,$n as P,$t as F,A as I,An as L,At as R,B as z,Bn as ee,Bt as B,C as te,Cn as ne,Cr as re,Ct as ie,D as ae,Dn as V,Dr as oe,Dt as se,E as ce,En as le,Er as H,Et as ue,F as de,Fn as fe,Ft as pe,G as me,Gn as he,Gt as ge,H as _e,Hn as ve,Ht as ye,I as be,In as xe,It as Se,J as Ce,Jn as we,Jt as Te,K as Ee,Kn as De,Kt as Oe,L as ke,Ln as Ae,Lt as je,Mn as Me,Mt as Ne,N as Pe,Nn as Fe,Nt as Ie,O as Le,On as Re,Ot as ze,P as Be,Pn as Ve,Pt as He,Q as Ue,Qn as We,Qt as Ge,R as Ke,Rn as qe,Rt as Je,S as Ye,Sn as Xe,Sr as Ze,St as Qe,T as $e,Tn as et,Tr as tt,Tt as nt,U as rt,Un as it,Ut as at,V as ot,Vn as st,Vt as ct,W as lt,Wn as ut,Wt as dt,X as ft,Xn as pt,Xt as mt,Y as ht,Yn as gt,Yt as _t,Z as vt,Zn as yt,Zt as bt,_ as xt,_n as St,_r as Ct,_t as wt,a as Tt,an as Et,ar as Dt,at as Ot,b as kt,bn as At,br as jt,bt as Mt,c as Nt,cn as Pt,cr as Ft,ct as It,d as Lt,dn as Rt,dr as zt,dt as Bt,en as Vt,er as Ht,et as Ut,f as Wt,fn as Gt,fr as Kt,ft as qt,g as Jt,gn as Yt,gr as Xt,h as Zt,hn as Qt,hr as $t,ht as en,i as tn,in as nn,ir as rn,it as an,j as on,jn as sn,jt as cn,k as ln,kn as un,kt as dn,l as fn,ln as pn,lr as mn,lt as hn,m as gn,mn as _n,mr as vn,mt as yn,n as bn,nn as xn,nr as Sn,nt as Cn,o as wn,on as Tn,or as En,ot as Dn,p as On,pr as kn,pt as An,q as jn,qn as Mn,qt as Nn,r as Pn,rn as Fn,rr as In,rt as Ln,s as Rn,sn as zn,sr as Bn,st as Vn,t as Hn,tn as Un,tr as Wn,tt as Gn,u as Kn,un as qn,ur as Jn,ut as Yn,v as Xn,vn as Zn,vr as Qn,vt as $n,w as er,wn as tr,wr as nr,wt as rr,x as ir,xn as ar,xr as or,xt as sr,y as cr,yn as lr,yr as ur,yt as dr,z as fr,zn as pr,zt as mr}from"./auth-BNDyLTqp-GYAzJXBe.js";import{a as hr,l as gr,n as _r}from"./env-CpA6E7ay.js";import{c as vr,f as yr,l as br,n as xr,o as Sr,r as Cr,u as wr}from"./result-envelope-DXFbrrkt.js";import{A as Tr,D as Er,F as Dr,G as Or,H as kr,I as Ar,M as jr,N as Mr,O as Nr,P as Pr,R as Fr,T as Ir,V as Lr,j as Rr,k as zr,w as Br,y as Vr,z as Hr}from"./tool-policy-NTXy68a8.js";import{E as Ur,O as Wr,c as Gr,d as Kr,l as U,n as qr,t as Jr}from"./esm-lPyPa01D.js";import{C as Yr,F as Xr,H as Zr,M as Qr,N as $r,P as ei,Q as ti,S as ni,U as ri,X as ii,_ as ai,a as oi,d as si,f as ci,g as li,h as ui,i as di,k as fi,m as pi,o as mi,ot as hi,p as gi,s as _i,t as vi,v as yi,w as bi,x as xi,y as Si,z as Ci}from"./logging-BHp-5JwI.js";import{t as wi}from"./openapi-snapshot-BH6bggk_.js";import{a as Ti,i as Ei,o as Di,r as Oi,s as ki,t as Ai}from"./openapi-call-DlI-9oge.js";import{c as ji,l as Mi,t as Ni}from"./human-text-cap-BcNmIPQA.js";import{R as Pi,i as Fi}from"./webapi-B2JTupyg.js";import{l as Ii}from"./response-problem-D7yaxq6L.js";import{n as Li,t as Ri}from"./request-replay-BFjYWNP9.js";import{r as zi}from"./contract-parameter-DRNxhCKs.js";import{t as Bi}from"./contract-BoQqQVwP.js";import"./dist-DaW7WEqw.js";import"./internal-DaW7WEqw.js";import{n as Vi,t as Hi}from"./http-credentials-BUPEQD7v.js";import{E as Ui,T as Wi,s as Gi,w as Ki}from"./help-catalog-tM-2mFr2.js";import{i as qi,n as Ji,r as Yi,t as Xi}from"./help-intent-DYxEva6T.js";import{i as Zi,t as Qi}from"./text-response-BI4rEuhL.js";import{t as $i}from"./sentry-BDcmqXAw.js";import{n as ea,t as ta}from"./mcp-generation-contract-BJbKgq5e.js";import{existsSync as na,readFileSync as ra}from"node:fs";import{Buffer as ia}from"node:buffer";import aa from"crypto";import{Readable as oa}from"stream";import{BlockList as sa,isIP as ca,isIPv4 as la,isIPv6 as ua}from"node:net";import{createHash as da,randomUUID as fa,timingSafeEqual as pa}from"node:crypto";var ma={name:`metric_data_point`,countItems:e=>{let t=0;for(let n of e.scopeMetrics)for(let e of n.metrics)t+=e.dataPoints.length;return t}},ha,ga=n((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(ha||={})})),W,_a,va=n((()=>{(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(W||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(_a||={})}));function ya(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function ba(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function xa(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new Ta(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function Sa(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Ca(e,t){let n=0,r=e.length-1,i=e.length;for(;r>=n;){let a=n+Math.trunc((r-n)/2);e[a]<t?n=a+1:(i=a,r=a-1)}return i}function wa(e,t){return e.toLowerCase()===t.toLowerCase()}var Ta,Ea=n((()=>{Ta=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),Da,Oa=n((()=>{(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(Da||={})})),ka,Aa=n((()=>{Oa(),ka=class{kind=Da.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function ja(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Ma,Na,Pa=n((()=>{Oa(),va(),Ea(),Ma=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=ja(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=r}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=Ca(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Na=class{kind=Da.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new Ma(e,this._boundaries,this._recordMinMax)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]+a[e];let s=1/0,c=-1/0;return this._recordMinMax&&(n.hasMinMax&&r.hasMinMax?(s=Math.min(n.min,r.min),c=Math.max(n.max,r.max)):n.hasMinMax?(s=n.min,c=n.max):r.hasMinMax&&(s=r.min,c=r.max)),new Ma(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:n.count+r.count,sum:n.sum+r.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||r.hasMinMax),min:s,max:c})}diff(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=a[e]-i[e];return new Ma(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:r.count-n.count,sum:r.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_a.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===W.GAUGE||e.type===W.UP_DOWN_COUNTER||e.type===W.OBSERVABLE_GAUGE||e.type===W.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}})),Fa,Ia,La=n((()=>{Fa=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new Ia,t=0,n=0,r=0){this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=r}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,n=1<<e,r=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let a=e%n;a<0&&(a+=n);for(let o=a;o<n&&r<t;o++)this._relocateBucket(i,r),r++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}},Ia=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,n){let r=Array(e).fill(0);r.splice(n,this._counts.length-t,...this._counts.slice(t)),r.splice(0,t,...this._counts.slice(0,t)),this._counts=r}reverse(e,t){let n=Math.floor((e+t)/2)-e;for(let r=0;r<n;r++){let n=this._counts[e+r];this._counts[e+r]=this._counts[t-r-1],this._counts[t-r-1]=n}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}}));function Ra(e){return qa.setFloat64(0,e),{hi:qa.getUint32(0),lo:qa.getUint32(4)}}function za(e){let{hi:t}=Ra(e);return((t&Va)>>20)-Ua}function Ba(e){let{hi:t,lo:n}=Ra(e);return(t&Ha)===0&&n===0}var Va,Ha,Ua,Wa,Ga,Ka,qa,Ja=n((()=>{Va=2146435072,Ha=1048575,Ua=1023,Wa=-1022,Ga=Ua,Ka=2**-1022,qa=new DataView(new ArrayBuffer(8))}));function Ya(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function Xa(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var Za=n((()=>{})),Qa,$a=n((()=>{Qa=class extends Error{}})),eo,to=n((()=>{Ja(),Za(),$a(),eo=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<Ka?this._minNormalLowerBoundaryIndex():za(e)+(Ba(e)?-1:0)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Qa(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Qa(`overflow: ${e} is > maximum lower boundary: ${n}`);return Ya(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=Wa>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return Ga>>this._shift}}})),no,ro=n((()=>{Ja(),Za(),$a(),no=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=Ya(Math.LOG2E,e),this._inverseFactor=Ya(Math.LN2,-e)}mapToIndex(e){if(e<=Ka)return this._minNormalLowerBoundaryIndex()-1;if(Ba(e))return(za(e)<<this._scale)-1;let t=Math.floor(Math.log(e)*this._scaleFactor),n=this._maxNormalLowerBoundaryIndex();return t>=n?n:t}lowerBoundary(e){let t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Qa(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ka;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Qa(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Wa<<this._scale}_maxNormalLowerBoundaryIndex(){return(Ga+1<<this._scale)-1}}}));function io(e){if(e>oo||e<ao)throw new Qa(`expected scale >= ${ao} && <= ${oo}, got: ${e}`);return so[e+10]}var ao,oo,so,co=n((()=>{to(),ro(),$a(),ao=-10,oo=20,so=Array.from({length:31},(e,t)=>t>10?new no(t-10):new eo(t-10))})),lo,uo,fo,po,mo,ho,go=n((()=>{Oa(),va(),qr(),La(),co(),Za(),lo=class e{static combine(t,n){return new e(Math.min(t.low,n.low),Math.max(t.high,n.high))}low;high;constructor(e,t){this.low=e,this.high=t}},uo=20,fo=160,po=2,mo=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=fo,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new Fa,l=new Fa,u=io(uo)){this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=r,this._count=i,this._zeroCount=a,this._min=o,this._max=s,this._positive=c,this._negative=l,this._mapping=u,this._maxSize<po&&(U.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-B09viugM.js";import{a as o}from"./package-CZBWjlYb.js";import{C as s,D as c,O as l,S as u,T as d,_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,l as x,m as S,n as C,o as w,p as T,s as E,t as D,u as O,v as k,w as A,x as j,y as M}from"./iso-l1vOidnb.js";import{$ as N,$n as P,$t as F,A as I,An as L,At as R,B as z,Bn as ee,Bt as B,C as te,Cn as ne,Cr as re,Ct as ie,D as ae,Dn as V,Dr as oe,Dt as se,E as ce,En as le,Er as H,Et as ue,F as de,Fn as fe,Ft as pe,G as me,Gn as he,Gt as ge,H as _e,Hn as ve,Ht as ye,I as be,In as xe,It as Se,J as Ce,Jn as we,Jt as Te,K as Ee,Kn as De,Kt as Oe,L as ke,Ln as Ae,Lt as je,Mn as Me,Mt as Ne,N as Pe,Nn as Fe,Nt as Ie,O as Le,On as Re,Ot as ze,P as Be,Pn as Ve,Pt as He,Q as Ue,Qn as We,Qt as Ge,R as Ke,Rn as qe,Rt as Je,S as Ye,Sn as Xe,Sr as Ze,St as Qe,T as $e,Tn as et,Tr as tt,Tt as nt,U as rt,Un as it,Ut as at,V as ot,Vn as st,Vt as ct,W as lt,Wn as ut,Wt as dt,X as ft,Xn as pt,Xt as mt,Y as ht,Yn as gt,Yt as _t,Z as vt,Zn as yt,Zt as bt,_ as xt,_n as St,_r as Ct,_t as wt,a as Tt,an as Et,ar as Dt,at as Ot,b as kt,bn as At,br as jt,bt as Mt,c as Nt,cn as Pt,cr as Ft,ct as It,d as Lt,dn as Rt,dr as zt,dt as Bt,en as Vt,er as Ht,et as Ut,f as Wt,fn as Gt,fr as Kt,ft as qt,g as Jt,gn as Yt,gr as Xt,h as Zt,hn as Qt,hr as $t,ht as en,i as tn,in as nn,ir as rn,it as an,j as on,jn as sn,jt as cn,k as ln,kn as un,kt as dn,l as fn,ln as pn,lr as mn,lt as hn,m as gn,mn as _n,mr as vn,mt as yn,n as bn,nn as xn,nr as Sn,nt as Cn,o as wn,on as Tn,or as En,ot as Dn,p as On,pr as kn,pt as An,q as jn,qn as Mn,qt as Nn,r as Pn,rn as Fn,rr as In,rt as Ln,s as Rn,sn as zn,sr as Bn,st as Vn,t as Hn,tn as Un,tr as Wn,tt as Gn,u as Kn,un as qn,ur as Jn,ut as Yn,v as Xn,vn as Zn,vr as Qn,vt as $n,w as er,wn as tr,wr as nr,wt as rr,x as ir,xn as ar,xr as or,xt as sr,y as cr,yn as lr,yr as ur,yt as dr,z as fr,zn as pr,zt as mr}from"./auth-BNDyLTqp-GYAzJXBe.js";import{a as hr,l as gr,n as _r}from"./env-CpA6E7ay.js";import{c as vr,f as yr,l as br,n as xr,o as Sr,r as Cr,u as wr}from"./result-envelope-DXFbrrkt.js";import{A as Tr,D as Er,F as Dr,G as Or,H as kr,I as Ar,M as jr,N as Mr,O as Nr,P as Pr,R as Fr,T as Ir,V as Lr,j as Rr,k as zr,w as Br,y as Vr,z as Hr}from"./tool-policy-NTXy68a8.js";import{E as Ur,O as Wr,c as Gr,d as Kr,l as U,n as qr,t as Jr}from"./esm-lPyPa01D.js";import{C as Yr,F as Xr,H as Zr,M as Qr,N as $r,P as ei,Q as ti,S as ni,U as ri,X as ii,_ as ai,a as oi,d as si,f as ci,g as li,h as ui,i as di,k as fi,m as pi,o as mi,ot as hi,p as gi,s as _i,t as vi,v as yi,w as bi,x as xi,y as Si,z as Ci}from"./logging-BHp-5JwI.js";import{t as wi}from"./openapi-snapshot-BH6bggk_.js";import{a as Ti,i as Ei,o as Di,r as Oi,s as ki,t as Ai}from"./openapi-call-CaPg45Hn.js";import{c as ji,l as Mi,t as Ni}from"./human-text-cap-BcNmIPQA.js";import{R as Pi,i as Fi}from"./webapi-B2JTupyg.js";import{l as Ii}from"./response-problem-D7yaxq6L.js";import{n as Li,t as Ri}from"./request-replay-BFjYWNP9.js";import{r as zi}from"./contract-parameter-DRNxhCKs.js";import{t as Bi}from"./contract-BoQqQVwP.js";import"./dist-DaW7WEqw.js";import"./internal-DaW7WEqw.js";import{n as Vi,t as Hi}from"./http-credentials-BUPEQD7v.js";import{E as Ui,T as Wi,s as Gi,w as Ki}from"./help-catalog-tM-2mFr2.js";import{i as qi,n as Ji,r as Yi,t as Xi}from"./help-intent-DYxEva6T.js";import{i as Zi,t as Qi}from"./text-response-BI4rEuhL.js";import{t as $i}from"./sentry-BDcmqXAw.js";import{n as ea,t as ta}from"./mcp-generation-contract-BJbKgq5e.js";import{existsSync as na,readFileSync as ra}from"node:fs";import{Buffer as ia}from"node:buffer";import aa from"crypto";import{Readable as oa}from"stream";import{BlockList as sa,isIP as ca,isIPv4 as la,isIPv6 as ua}from"node:net";import{createHash as da,randomUUID as fa,timingSafeEqual as pa}from"node:crypto";var ma={name:`metric_data_point`,countItems:e=>{let t=0;for(let n of e.scopeMetrics)for(let e of n.metrics)t+=e.dataPoints.length;return t}},ha,ga=n((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(ha||={})})),W,_a,va=n((()=>{(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(W||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(_a||={})}));function ya(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function ba(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function xa(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new Ta(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function Sa(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Ca(e,t){let n=0,r=e.length-1,i=e.length;for(;r>=n;){let a=n+Math.trunc((r-n)/2);e[a]<t?n=a+1:(i=a,r=a-1)}return i}function wa(e,t){return e.toLowerCase()===t.toLowerCase()}var Ta,Ea=n((()=>{Ta=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),Da,Oa=n((()=>{(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(Da||={})})),ka,Aa=n((()=>{Oa(),ka=class{kind=Da.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function ja(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Ma,Na,Pa=n((()=>{Oa(),va(),Ea(),Ma=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=ja(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=r}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=Ca(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Na=class{kind=Da.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new Ma(e,this._boundaries,this._recordMinMax)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=i[e]+a[e];let s=1/0,c=-1/0;return this._recordMinMax&&(n.hasMinMax&&r.hasMinMax?(s=Math.min(n.min,r.min),c=Math.max(n.max,r.max)):n.hasMinMax?(s=n.min,c=n.max):r.hasMinMax&&(s=r.min,c=r.max)),new Ma(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:n.count+r.count,sum:n.sum+r.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||r.hasMinMax),min:s,max:c})}diff(e,t){let n=e.toPointValue(),r=t.toPointValue(),i=n.buckets.counts,a=r.buckets.counts,o=Array(i.length);for(let e=0;e<i.length;e++)o[e]=a[e]-i[e];return new Ma(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:o},count:r.count-n.count,sum:r.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_a.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===W.GAUGE||e.type===W.UP_DOWN_COUNTER||e.type===W.OBSERVABLE_GAUGE||e.type===W.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}})),Fa,Ia,La=n((()=>{Fa=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new Ia,t=0,n=0,r=0){this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=r}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,n=1<<e,r=0,i=0;for(let e=this.indexStart;e<=this.indexEnd;){let a=e%n;a<0&&(a+=n);for(let o=a;o<n&&r<t;o++)this._relocateBucket(i,r),r++,e++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}},Ia=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,n){let r=Array(e).fill(0);r.splice(n,this._counts.length-t,...this._counts.slice(t)),r.splice(0,t,...this._counts.slice(0,t)),this._counts=r}reverse(e,t){let n=Math.floor((e+t)/2)-e;for(let r=0;r<n;r++){let n=this._counts[e+r];this._counts[e+r]=this._counts[t-r-1],this._counts[t-r-1]=n}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}}));function Ra(e){return qa.setFloat64(0,e),{hi:qa.getUint32(0),lo:qa.getUint32(4)}}function za(e){let{hi:t}=Ra(e);return((t&Va)>>20)-Ua}function Ba(e){let{hi:t,lo:n}=Ra(e);return(t&Ha)===0&&n===0}var Va,Ha,Ua,Wa,Ga,Ka,qa,Ja=n((()=>{Va=2146435072,Ha=1048575,Ua=1023,Wa=-1022,Ga=Ua,Ka=2**-1022,qa=new DataView(new ArrayBuffer(8))}));function Ya(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function Xa(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var Za=n((()=>{})),Qa,$a=n((()=>{Qa=class extends Error{}})),eo,to=n((()=>{Ja(),Za(),$a(),eo=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<Ka?this._minNormalLowerBoundaryIndex():za(e)+(Ba(e)?-1:0)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Qa(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Qa(`overflow: ${e} is > maximum lower boundary: ${n}`);return Ya(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=Wa>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return Ga>>this._shift}}})),no,ro=n((()=>{Ja(),Za(),$a(),no=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=Ya(Math.LOG2E,e),this._inverseFactor=Ya(Math.LN2,-e)}mapToIndex(e){if(e<=Ka)return this._minNormalLowerBoundaryIndex()-1;if(Ba(e))return(za(e)<<this._scale)-1;let t=Math.floor(Math.log(e)*this._scaleFactor),n=this._maxNormalLowerBoundaryIndex();return t>=n?n:t}lowerBoundary(e){let t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new Qa(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ka;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Qa(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Wa<<this._scale}_maxNormalLowerBoundaryIndex(){return(Ga+1<<this._scale)-1}}}));function io(e){if(e>oo||e<ao)throw new Qa(`expected scale >= ${ao} && <= ${oo}, got: ${e}`);return so[e+10]}var ao,oo,so,co=n((()=>{to(),ro(),$a(),ao=-10,oo=20,so=Array.from({length:31},(e,t)=>t>10?new no(t-10):new eo(t-10))})),lo,uo,fo,po,mo,ho,go=n((()=>{Oa(),va(),qr(),La(),co(),Za(),lo=class e{static combine(t,n){return new e(Math.min(t.low,n.low),Math.max(t.high,n.high))}low;high;constructor(e,t){this.low=e,this.high=t}},uo=20,fo=160,po=2,mo=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=fo,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new Fa,l=new Fa,u=io(uo)){this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=r,this._count=i,this._zeroCount=a,this._min=o,this._max=s,this._positive=c,this._negative=l,this._mapping=u,this._maxSize<po&&(U.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
|
|
2
2
|
changing to the minimum size of: ${po}`),this._maxSize=po)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){Number.isFinite(e)&&(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0?this._zeroCount+=t:(this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)))}merge(e){this._count===0?(this._min=e.min,this._max=e.max):e.count!==0&&(e.min<this.min&&(this._min=e.min),e.max>this.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;let t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new e(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,n){let r=this._mapping.mapToIndex(t),i=!1,a=0,o=0;if(e.length===0?(e.indexStart=r,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):r<e.indexStart&&e.indexEnd-r>=this._maxSize?(i=!0,o=r,a=e.indexEnd):r>e.indexEnd&&r-e.indexStart>=this._maxSize&&(i=!0,o=e.indexStart,a=r),i){let e=this._changeScale(a,o);this._downscale(e),r=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,r,n)}_incrementIndexBy(e,t,n){if(n===0)return;if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){let n=e.indexEnd-t;n>=e.backing.length&&this._grow(e,n+1),e.indexStart=t}else if(t>e.indexEnd){let n=t-e.indexStart;n>=e.backing.length&&this._grow(e,n+1),e.indexEnd=t}let r=t-e.indexBase;r<0&&(r+=e.backing.length),e.incrementBucket(r,n)}_grow(e,t){let n=e.backing.length,r=e.indexBase-e.indexStart,i=n-r,a=Xa(t);a>this._maxSize&&(a=this._maxSize);let o=a-r;e.backing.growTo(a,i,o)}_changeScale(e,t){let n=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n}_downscale(e){if(e===0)return;if(e<0)throw Error(`impossible change of scale: ${this.scale}`);let t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=io(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=lo.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=lo.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(r.high,r.low))}_highLowAtScale(e,t,n){if(e.length===0)return new lo(0,-1);let r=t-n;return new lo(e.indexStart>>r,e.indexEnd>>r)}_mergeBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++)this._incrementIndexBy(e,i+t>>a,n.at(t))}_diffBuckets(e,t,n,r){let i=n.offset,a=t.scale-r;for(let t=0;t<n.length;t++){let r=(i+t>>a)-e.indexBase;r<0&&(r+=e.backing.length),e.decrementBucket(r,n.at(t))}e.trim()}},ho=class{kind=Da.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new mo(e,this._maxSize,this._recordMinMax)}merge(e,t){let n=t.clone();return n.merge(e),n}diff(e,t){let n=t.clone();return n.diff(e),n}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_a.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===W.GAUGE||e.type===W.UP_DOWN_COUNTER||e.type===W.OBSERVABLE_GAUGE||e.type===W.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:n.startTime,endTime:r,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:a?void 0:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},count:i.count,scale:i.scale,zeroCount:i.zeroCount}}})}}}})),_o,vo,yo=n((()=>{Oa(),Yr(),va(),_o=class{startTime;_current;sampleTime;constructor(e,t=0,n=[0,0]){this.startTime=e,this._current=t,this.sampleTime=n}record(e){this._current=e,this.sampleTime=Ci(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},vo=class{kind=Da.LAST_VALUE;createAccumulation(e){return new _o(e)}merge(e,t){let n=ei(t.sampleTime)>=ei(e.sampleTime)?t:e;return new _o(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,t){let n=ei(t.sampleTime)>=ei(e.sampleTime)?t:e;return new _o(t.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_a.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()}))}}}})),bo,xo,So=n((()=>{Oa(),va(),bo=class{startTime;monotonic;_current;reset;constructor(e,t,n=0,r=!1){this.startTime=e,this.monotonic=t,this._current=n,this.reset=r}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},xo=class{kind=Da.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new bo(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue();return t.reset?new bo(t.startTime,this.monotonic,r,t.reset):new bo(e.startTime,this.monotonic,n+r)}diff(e,t){let n=e.toPointValue(),r=t.toPointValue();return this.monotonic&&n>r?new bo(t.startTime,this.monotonic,r,!0):new bo(t.startTime,this.monotonic,r-n)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_a.SUM,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),Co=n((()=>{Aa(),Pa(),go(),yo(),So()})),wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io=n((()=>{qr(),Co(),va(),wo=class e{static DEFAULT_INSTANCE=new ka;createAggregator(t){return e.DEFAULT_INSTANCE}},To=class e{static MONOTONIC_INSTANCE=new xo(!0);static NON_MONOTONIC_INSTANCE=new xo(!1);createAggregator(t){switch(t.type){case W.COUNTER:case W.OBSERVABLE_COUNTER:case W.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}},Eo=class e{static DEFAULT_INSTANCE=new vo;createAggregator(t){return e.DEFAULT_INSTANCE}},Do=class e{static DEFAULT_INSTANCE=new Na([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(t){return e.DEFAULT_INSTANCE}},Oo=class{_boundaries;_recordMinMax;constructor(e,t=!0){if(e==null)throw Error(`ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array`);e=e.concat(),e=e.sort((e,t)=>e-t);let n=e.lastIndexOf(-1/0),r=e.indexOf(1/0);r===-1&&(r=void 0),this._boundaries=e.slice(n+1,r),this._recordMinMax=t}createAggregator(e){return new Na(this._boundaries,this._recordMinMax)}},ko=class{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new ho(this._maxSize,this._recordMinMax)}},Ao=class{_resolve(e){switch(e.type){case W.COUNTER:case W.UP_DOWN_COUNTER:case W.OBSERVABLE_COUNTER:case W.OBSERVABLE_UP_DOWN_COUNTER:return Mo;case W.GAUGE:case W.OBSERVABLE_GAUGE:return No;case W.HISTOGRAM:return e.advice.explicitBucketBoundaries?new Oo(e.advice.explicitBucketBoundaries):Po}return U.warn(`Unable to recognize instrument type: ${e.type}`),jo}createAggregator(e){return this._resolve(e).createAggregator(e)}},jo=new wo,Mo=new To,No=new Eo,Po=new Do,new ko,Fo=new Ao}));function Lo(e){switch(e.type){case Ro.DEFAULT:return Fo;case Ro.DROP:return jo;case Ro.SUM:return Mo;case Ro.LAST_VALUE:return No;case Ro.EXPONENTIAL_HISTOGRAM:{let t=e;return new ko(t.options?.maxSize,t.options?.recordMinMax)}case Ro.EXPLICIT_BUCKET_HISTOGRAM:{let t=e;return t.options==null?Po:new Oo(t.options?.boundaries,t.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}var Ro,zo=n((()=>{Io(),(function(e){e[e.DEFAULT=0]=`DEFAULT`,e[e.DROP=1]=`DROP`,e[e.SUM=2]=`SUM`,e[e.LAST_VALUE=3]=`LAST_VALUE`,e[e.EXPLICIT_BUCKET_HISTOGRAM=4]=`EXPLICIT_BUCKET_HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=5]=`EXPONENTIAL_HISTOGRAM`})(Ro||={})})),Bo,Vo,Ho=n((()=>{ga(),zo(),Bo=e=>({type:Ro.DEFAULT}),Vo=e=>ha.CUMULATIVE})),Uo,Wo,Go,Ko,qo,Jo=n((()=>{Uo=`otel.component.name`,Wo=`otel.component.type`,Go=`periodic_metric_reader`,Ko=`otel.sdk.metric_reader.collection.duration`,qo=`error.type`})),Yo,Xo,Zo=n((()=>{Jo(),Yo=new Map,Xo=class{collectionDuration;standardAttrs;constructor(e,t){let n=Yo.get(e)??0;Yo.set(e,n+1),this.standardAttrs={[Wo]:e,[Uo]:`${e}/${n}`},this.collectionDuration=t.createHistogram(Ko,{unit:`s`,description:`The duration of the collect operation of the metric reader.`,advice:{explicitBucketBoundaries:[]}})}recordCollection(e,t){let n=t?{...this.standardAttrs,[qo]:t}:this.standardAttrs;this.collectionDuration.record(e,n)}}})),Qo,$o=n((()=>{Qo=`2.11.0`})),es,ts=n((()=>{qr(),Ea(),Ho(),Zo(),$o(),Yr(),es=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_selfObsMetrics;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;_otelComponentType;constructor(e){this._aggregationSelector=e?.aggregationSelector??Bo,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??Vo,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector,this._otelComponentType=e?.otelComponentType??this.constructor.name,this._selfObsMetrics=new Xo(this._otelComponentType,Wr())}setMetricProducer(e){if(this._sdkMetricProducer)throw Error(`MetricReader can not be bound to a MeterProvider again.`);this._sdkMetricProducer=e,this.onInitialized()}_setSelfObsMeterProvider(e){let t=e.getMeter(`@opentelemetry/sdk-metrics`,Qo);this._selfObsMetrics=new Xo(this._otelComponentType,t)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(this._sdkMetricProducer===void 0)throw Error(`MetricReader is not bound to a MetricProducer`);if(this._shutdown)throw Error(`MetricReader is shutdown`);let t=Qr(),[n,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),i=Qr(),a=n.errors.concat(r.flatMap(e=>e.errors)),o=Xr($r(t,i));return this._selfObsMetrics.recordCollection(o,a.length>0?a[0].name??`collect_error`:void 0),{resourceMetrics:{resource:n.resourceMetrics.resource,scopeMetrics:n.resourceMetrics.scopeMetrics.concat(r.flatMap(e=>e.resourceMetrics.scopeMetrics))},errors:a}}async shutdown(e){this._shutdown?U.error(`Cannot call shutdown twice.`):(e?.timeoutMillis==null?await this.onShutdown():await xa(this.onShutdown(),e.timeoutMillis),this._shutdown=!0)}async forceFlush(e){this._shutdown?U.warn(`Cannot forceFlush on already shutdown MetricReader.`):e?.timeoutMillis==null?await this.onForceFlush():await xa(this.onForceFlush(),e.timeoutMillis)}}}));function ns(e,t){if(!Number.isInteger(t)||t<=0)throw Error(`maxExportBatchSize must be a positive integer`);let n=[],r=0,i=[];function a(){i.length>0&&(n.push({resource:e.resource,scopeMetrics:i}),i=[],r=0)}for(let n of e.scopeMetrics){let e=null;for(let o of n.metrics){let s=o.dataPoints;if(s.length===0){e||(e={scope:n.scope,metrics:[]},i.push(e)),e.metrics.push(o);continue}let c=0;for(;c<s.length;){let l=t-r,u=Math.min(l,s.length-c);e||(e={scope:n.scope,metrics:[]},i.push(e));let d={...o,dataPoints:s.slice(c,c+u)};e.metrics.push(d),c+=u,r+=u,r===t&&(a(),e=null)}}}return a(),n}var rs=n((()=>{})),is,as=n((()=>{qr(),Yr(),ts(),Ea(),va(),rs(),Jo(),is=class extends es{_interval;_exporter;_exportInterval;_exportTimeout;_maxExportBatchSize;_ongoingExportPromise=null;constructor(e){let{exporter:t,exportIntervalMillis:n=6e4,metricProducers:r,cardinalityLimits:i,maxExportBatchSize:a}=e,{exportTimeoutMillis:o=3e4}=e;if(super({aggregationSelector:t.selectAggregation?.bind(t),aggregationTemporalitySelector:t.selectAggregationTemporality?.bind(t),otelComponentType:Go,metricProducers:r,cardinalitySelector:e=>{let t={default:2e3,...i};switch(e){case W.COUNTER:return t.counter??t.default;case W.GAUGE:return t.gauge??t.default;case W.HISTOGRAM:return t.histogram??t.default;case W.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case W.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case W.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case W.UP_DOWN_COUNTER:return t.upDownCounter??t.default;default:return t.default}}}),n<=0)throw Error(`exportIntervalMillis must be greater than 0`);if(o<=0)throw Error(`exportTimeoutMillis must be greater than 0`);if(a!==void 0&&(!Number.isInteger(a)||a<=0))throw Error(`maxExportBatchSize must be a positive integer`);if(n<o){if(`exportIntervalMillis`in e&&`exportTimeoutMillis`in e)throw Error(`exportIntervalMillis must be greater than or equal to exportTimeoutMillis`);U.info(`Timeout of ${o} exceeds the interval of ${n}. Clamping timeout to interval duration.`),o=n}this._exportInterval=n,this._exportTimeout=o,this._exporter=t,this._maxExportBatchSize=a}async _runOnce(){try{await this._doRun()}catch(e){ti(e)}}async _doRun(){if(this._ongoingExportPromise){U.debug(`PeriodicExportingMetricReader: export already in progress, skipping`);return}let e=async()=>{let{resourceMetrics:e,errors:t}=await this.collect({timeoutMillis:this._exportTimeout});if(t.length>0&&U.error(`PeriodicExportingMetricReader: metrics collection errors`,...t),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){U.debug(`Error while resolving async portion of resource: `,e),ti(e)}if(e.scopeMetrics.length===0)return;let n=this._maxExportBatchSize?ns(e,this._maxExportBatchSize):[e],r=null;for(let e of n)try{let t=await xa(bi._export(this._exporter,e),this._exportTimeout);t.code!==fi.SUCCESS&&(r=Error(`PeriodicExportingMetricReader: metrics export failed (error ${t.error})`))}catch(e){if(e instanceof Ta){U.error(`PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`);break}U.error(`PeriodicExportingMetricReader: metrics export threw error`,e),r=e instanceof Error?e:Error(String(e))}if(r)throw r};this._ongoingExportPromise=e();try{await this._ongoingExportPromise}finally{this._ongoingExportPromise=null}}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),typeof this._interval!=`number`&&this._interval.unref()}async onForceFlush(){await this._awaitOngoingExport(),this._ongoingExportPromise?await this._awaitOngoingExport():await this._runOnce(),await this._exporter.forceFlush()}async _awaitOngoingExport(){if(this._ongoingExportPromise){U.debug(`PeriodicExportingMetricReader: export already in progress, awaiting ongoing export`);try{await this._ongoingExportPromise}catch{}}}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}})),os,ss=n((()=>{Yr(),os=class{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){this._shutdown?setTimeout(()=>t({code:fi.FAILED}),0):(this._metrics.push(e),setTimeout(()=>t({code:fi.SUCCESS}),0))}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}})),cs,ls=n((()=>{Yr(),Ho(),cs=class e{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??Vo}export(t,n){if(this._shutdown)n({code:fi.FAILED});else return e._sendMetrics(t,n)}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,t){for(let t of e.scopeMetrics)for(let e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});t({code:fi.SUCCESS})}}})),us,ds=n((()=>{us=class{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(n=>this._matchInstrument(n.instrumentSelector,e)&&this._matchMeter(n.meterSelector,t))}_matchInstrument(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))}}}));function fs(e,t,n){return hs(e)||U.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:n?.description??``,unit:n?.unit??``,valueType:n?.valueType??Ur.DOUBLE,advice:n?.advice??{}}}function ps(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}function ms(e,t){return wa(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}function hs(e){return gs.test(e)}var gs,_s=n((()=>{qr(),Ea(),gs=/^[a-z][a-z0-9_.\-/]{0,254}$/i}));function vs(e){return e instanceof ws}var ys,bs,xs,Ss,Cs,ws,Ts,Es,Ds,Os=n((()=>{qr(),ys=class{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},n){typeof e==`number`?this._descriptor.valueType===Ur.INT&&!Number.isInteger(e)&&(U.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._writableMetricStorage.record(e,t,n,Date.now()):U.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`)}},bs=class extends ys{add(e,t,n){this._record(e,t,n)}},xs=class extends ys{add(e,t,n){e<0?U.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`):this._record(e,t,n)}},Ss=class extends ys{record(e,t,n){this._record(e,t,n)}},Cs=class extends ys{record(e,t,n){e<0?U.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`):this._record(e,t,n)}},ws=class{_metricStorages;_descriptor;_observableRegistry;constructor(e,t,n){this._descriptor=e,this._metricStorages=t,this._observableRegistry=n}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}},Ts=class extends ws{},Es=class extends ws{},Ds=class extends ws{}})),ks,As=n((()=>{_s(),Os(),va(),ks=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){let n=fs(e,W.GAUGE,t),r=this._meterSharedState.registerMetricStorage(n);return new Ss(r,n)}createHistogram(e,t){let n=fs(e,W.HISTOGRAM,t),r=this._meterSharedState.registerMetricStorage(n);return new Cs(r,n)}createCounter(e,t){let n=fs(e,W.COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new xs(r,n)}createUpDownCounter(e,t){let n=fs(e,W.UP_DOWN_COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new bs(r,n)}createObservableGauge(e,t){let n=fs(e,W.OBSERVABLE_GAUGE,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Es(n,r,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){let n=fs(e,W.OBSERVABLE_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Ts(n,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){let n=fs(e,W.OBSERVABLE_UP_DOWN_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Ds(n,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),js,Ms=n((()=>{_s(),js=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=fs(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),Ns,Ps,Fs=n((()=>{Ea(),Ns=class{_valueMap=new Map;_keyMap=new Map;_hash;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){let n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);let r=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,r),r}set(e,t,n){n??=this._hash(e),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){let e=this._keyMap.entries(),t=e.next();for(;t.done!==!0;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){let e=this._valueMap.entries(),t=e.next();for(;t.done!==!0;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}},Ps=class extends Ns{constructor(){super(ya)}}})),Is,Ls=n((()=>{Yr(),Ea(),Fs(),Is=class{_activeCollectionStorage=new Ps;_cumulativeMemoStorage=new Ps;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=ya(this._overflowAttributes)}record(e,t,n){let r=this._activeCollectionStorage.get(t);if(!r){let i=Ci(n);if(this._activeCollectionStorage.size>=this._cardinalityLimit){this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(i))?.record(e);return}r=this._aggregator.createAccumulation(i),this._activeCollectionStorage.set(t,r)}r?.record(e)}batchCumulate(e,t){for(let[n,r,i]of e.entries()){let e=n,a=i,o=this._aggregator.createAccumulation(t);o?.record(r);let s=o;if(this._cumulativeMemoStorage.has(e,a)){let t=this._cumulativeMemoStorage.get(e,a);s=this._aggregator.diff(t,o)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,a=this._overflowHashCode,this._cumulativeMemoStorage.has(e,a))){let t=this._cumulativeMemoStorage.get(e,a);s=this._aggregator.diff(t,o)}if(this._activeCollectionStorage.has(e,a)){let t=this._activeCollectionStorage.get(e,a);s=this._aggregator.merge(t,s)}this._cumulativeMemoStorage.set(e,o,a),this._activeCollectionStorage.set(e,s,a)}}collect(){let e=this._activeCollectionStorage;return this._activeCollectionStorage=new Ps,e}}}));function Rs(e){return Array.from(e.entries())}var zs,Bs=n((()=>{ga(),Fs(),zs=class e{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(t,n,r,i){this._stashAccumulations(r);let a=this._getMergedUnreportedAccumulations(t),o=a,s;if(this._reportHistory.has(t)){let n=this._reportHistory.get(t),r=n.collectionTime;s=n.aggregationTemporality,o=s===ha.CUMULATIVE?e.merge(n.accumulations,a,this._aggregator):e.calibrateStartTime(n.accumulations,a,r)}else s=t.selectAggregationTemporality(n.type);this._reportHistory.set(t,{accumulations:o,collectionTime:i,aggregationTemporality:s});let c=Rs(o);if(c.length!==0)return this._aggregator.toMetricData(n,s,c,i)}_stashAccumulations(e){let t=this._unreportedAccumulations.keys();for(let n of t){let t=this._unreportedAccumulations.get(n);t===void 0&&(t=[],this._unreportedAccumulations.set(n,t)),t.push(e)}}_getMergedUnreportedAccumulations(t){let n=new Ps,r=this._unreportedAccumulations.get(t);if(this._unreportedAccumulations.set(t,[]),r===void 0)return n;for(let t of r)n=e.merge(n,t,this._aggregator);return n}static merge(e,t,n){let r=e,i=t.entries(),a=i.next();for(;a.done!==!0;){let[t,o,s]=a.value;if(e.has(t,s)){let i=e.get(t,s),a=n.merge(i,o);r.set(t,a,s)}else r.set(t,o,s);a=i.next()}return r}static calibrateStartTime(e,t,n){for(let[r,i]of e.keys())t.get(r,i)?.setStartTime(n);return t}}})),Vs,Hs=n((()=>{Ms(),Ls(),Bs(),Fs(),Vs=class extends js{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new Is(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new zs(t,r),this._attributesProcessor=n}record(e,t){if(this._attributesProcessor===void 0){this._deltaMetricStorage.batchCumulate(e,t);return}let n=new Ps;for(let[t,r]of e.entries())n.set(this._attributesProcessor.process(t),r);this._deltaMetricStorage.batchCumulate(n,t)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}}));function Us(e,t){let n=``;return e.unit!==t.unit&&(n+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(n+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(n+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(n+=`\t- Description '${e.description}' does not match '${t.description}'\n`),n}function Ws(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function Gs(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function Ks(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'`}function qs(e,t){let n={name:t.name,type:t.type,unit:t.unit},r=JSON.stringify(n);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${r}'
|
|
3
3
|
\t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${r}
|
|
4
4
|
\t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${r}`}function Js(e,t){return e.valueType===t.valueType?e.unit===t.unit?e.type===t.type?e.description===t.description?``:qs(e,t):Ks(e,t):Gs(e,t):Ws(e,t)}var Ys=n((()=>{})),Xs,Zs=n((()=>{_s(),qr(),Ys(),Xs=class e{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new e}getStorages(e){let t=[];for(let e of this._sharedRegistry.values())t=t.concat(e);let n=this._perCollectorRegistry.get(e);if(n!=null)for(let e of n.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let n=this._perCollectorRegistry.get(e);n??(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)}findOrUpdateCompatibleStorage(e){let t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){let n=this._perCollectorRegistry.get(e);if(n===void 0)return null;let r=n.get(t.name);return r===void 0?null:this._findOrUpdateCompatibleStorage(t,r)}_registerStorage(e,t){let n=e.getInstrumentDescriptor(),r=t.get(n.name);r===void 0?t.set(n.name,[e]):r.push(e)}_findOrUpdateCompatibleStorage(e,t){let n=null;for(let r of t){let t=r.getInstrumentDescriptor();ms(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&r.updateDescription(e.description),U.warn(`A view or instrument with the name `,e.name,` has already been registered, but has a different description and is incompatible with another registered view.
|
package/dist/mcp-server/index.js
CHANGED
|
@@ -11,4 +11,4 @@ Environment:
|
|
|
11
11
|
AVENTURE_MCP_PORT Select the HTTP listening port.
|
|
12
12
|
AVENTURE_MCP_PATH Select the MCP route.
|
|
13
13
|
AVENTURE_MCP_JSON_LIMIT Limit request body size.
|
|
14
|
-
`).parseAsync()).opts(),[{describeError:o,logError:s,logInfo:c,shutdownLogging:l,useServerProcessLogging:u},{AUTH_SECRET_NAME:d},{metricsScrapeSecretFromEnvironment:f},{catalogOAuthDiscovery:p},{captureSentryException:m,initializeSentry:h,shutdownSentry:g},{HOSTED_REQUEST_DEADLINE_MS:_,startStreamableHttpServer:v}]=await Promise.all([import(`../chunks/logging-CgYAFXRk.js`),import(`../chunks/env-INx_D4Zq.js`),import(`../chunks/private-telemetry-credential-DbamSREI.js`),import(`../chunks/oauth-discovery-
|
|
14
|
+
`).parseAsync()).opts(),[{describeError:o,logError:s,logInfo:c,shutdownLogging:l,useServerProcessLogging:u},{AUTH_SECRET_NAME:d},{metricsScrapeSecretFromEnvironment:f},{catalogOAuthDiscovery:p},{captureSentryException:m,initializeSentry:h,shutdownSentry:g},{HOSTED_REQUEST_DEADLINE_MS:_,startStreamableHttpServer:v}]=await Promise.all([import(`../chunks/logging-CgYAFXRk.js`),import(`../chunks/env-INx_D4Zq.js`),import(`../chunks/private-telemetry-credential-DbamSREI.js`),import(`../chunks/oauth-discovery-tQsVuWM3.js`),import(`../chunks/sentry-BbZQYSQu.js`),import(`../chunks/streamable-http-DGKWgZ_h.js`)]),y=_+5e3;u(),await h(),delete process.env[d.authToken];var b=E(),x=process.env.AVENTURE_MCP_PATH??`/mcp`,S=process.env.AVENTURE_MCP_JSON_LIMIT??`10mb`,C=f()||void 0,w=!1;function T(e){Promise.allSettled([l(),g()]).then(e=>{for(let t of e){if(t.status!==`rejected`)continue;let e=o(t.reason);process.stderr.write(`${i.bin[0]} telemetry shutdown failed: ${e}\n`)}}).catch(e=>{let t=o(e);process.stderr.write(`${i.bin[0]} telemetry shutdown failed: ${t}\n`)}).finally(()=>process.exit(e))}v({port:b,host:a,path:x,resolveOAuthDiscovery:p(),jsonBodyLimit:S,metricsScrapeSecret:C}).then(e=>{c({component:`aventure-mcp-server`,event:`server_listening`,fields:{port:b,path:x}}),process.stdout.write(`${i.bin[0]} listening at http://localhost:${b}${x}\n`);let t=t=>{if(w)return;w=!0,c({component:`aventure-mcp-server`,event:`server_shutdown_started`,fields:{signal:t}});let n=setTimeout(()=>{s({component:`aventure-mcp-server`,event:`server_shutdown_timeout`,message:`MCP server did not drain before the platform forced-shutdown window`,fields:{signal:t,forceExitMs:y}}),T(1)},y);n.unref(),e.close().then(()=>{clearTimeout(n),c({component:`aventure-mcp-server`,event:`server_shutdown_completed`,fields:{signal:t}}),T(0)}).catch(e=>{let r=o(e);clearTimeout(n),s({component:`aventure-mcp-server`,event:`server_shutdown_failed`,message:r,fields:{signal:t},error:e}),T(1)})};for(let e of[`SIGTERM`,`SIGINT`])process.on(e,t)},async e=>{let t=o(e);m(e,`server_start_failed`),s({component:`aventure-mcp-server`,event:`server_start_failed`,message:t,error:e}),process.stderr.write(`${i.bin[0]} failed to start: ${t}\n`),T(1)});function E(){let e=process.env.AVENTURE_MCP_PORT??process.env.PORT??`3333`,t=Number(e);if(!Number.isInteger(t)||t<1||t>r)throw Error(`Invalid MCP server port: ${e}`);return t}export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aventurevc/mcp-server",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.245",
|
|
4
4
|
"mcpName": "io.github.aventurevc/aventure-mcp",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "MCP server that gives AI assistants access to aVenture research data on companies, people, funding, and news.",
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
},
|
|
30
30
|
"aventurePublicApi": {
|
|
31
31
|
"repository": "aventurevc/aventure-docs",
|
|
32
|
-
"commit": "
|
|
32
|
+
"commit": "aa6aa608507359928aa26caf4efcd8569ed6a312",
|
|
33
33
|
"openapiPath": "openapi/openapi.json",
|
|
34
|
-
"openapiSha256": "
|
|
34
|
+
"openapiSha256": "d53aa19fc6d5b9ef11c8a657d1af7e3c2c6bca0918e63affeda3d1c0a1026cf2"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {}
|
|
37
37
|
}
|