@aventurevc/mcp-server 0.8.96 → 0.8.100

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{A as e,M as t,N as n,O as r,_ as i,c as a,d as o,j as s,k as c,l,n as u,t as d,y as f}from"../chunks/esm-kgyHmk-Q.js";import{$ as p,$n as m,$r as h,$t as g,A as _,Ai as v,An as y,Ar as b,At as x,B as S,Bi as C,Bn as w,Br as T,Bt as E,Cn as D,Cr as O,Ct as k,D as A,Di as j,Dn as ee,Dr as te,Dt as M,En as N,Er as ne,Et as re,F as ie,Fi as ae,Fn as oe,Fr as se,Ft as ce,G as le,Gi as ue,Gn as de,Gr as fe,Gt as pe,H as me,Hn as he,Hr as ge,Ht as _e,I as ve,Ii as ye,In as be,Ir as xe,It as Se,J as Ce,Jn as we,Jr as Te,Jt as Ee,K as De,Ki as Oe,Kn as ke,Kr as Ae,Kt as je,L as Me,Li as Ne,Ln as Pe,Lr as Fe,Lt as Ie,M as Le,Mi as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Ni as Ue,Nn as We,Nr as Ge,Nt as Ke,O as qe,On as Je,Or as Ye,Ot as Xe,P as Ze,Pi as Qe,Pn as $e,Pr as et,Pt as tt,Q as nt,Qi as rt,Qn as it,Qr as at,Qt as ot,R as st,Ri as ct,Rn as lt,Rr as ut,Rt as dt,Sn as ft,Sr as pt,St as mt,Tn as ht,Tr as gt,Tt as _t,U as vt,Ui as yt,Un as bt,Ur as xt,Ut as St,V as Ct,Vi as wt,Vn as Tt,Vr as Et,Vt as Dt,W as Ot,Wi as kt,Wn as At,Wr as jt,Wt as Mt,X as Nt,Xi as Pt,Xn as Ft,Xr as It,Xt as Lt,Y as Rt,Yi as zt,Yn as Bt,Yr as Vt,Z as Ht,Zi as Ut,Zn as Wt,Zr as Gt,Zt as Kt,_ as qt,_n as Jt,_r as Yt,_t as Xt,a as Zt,aa as Qt,ai as $t,an as en,ar as tn,at as nn,bi as rn,bn as an,br as on,bt as sn,ca as cn,ci as ln,cn as un,cr as dn,ct as fn,dn as pn,dr as mn,ea as hn,ei as gn,en as _n,er as vn,et as yn,fi as bn,fn as xn,fr as Sn,ft as Cn,g as wn,gn as Tn,gr as En,gt as Dn,h as On,hn as kn,hr as An,ht as jn,ii as Mn,in as Nn,ir as Pn,it as Fn,j as In,ji as Ln,jn as Rn,jr as zn,jt as Bn,k as Vn,ki as Hn,kn as Un,kr as Wn,kt as Gn,li as Kn,ln as qn,lr as Jn,lt as Yn,m as Xn,mi as Zn,mn as Qn,mr as $n,mt as er,n as tr,na as nr,ni as rr,nn as ir,nr as ar,nt as or,o as sr,on as cr,or as lr,ot as ur,pi as dr,pn as fr,pr,pt as mr,q as hr,qi as gr,qn as _r,qr as vr,qt as yr,r as br,ra as xr,ri as Sr,rn as Cr,rr as wr,rt as Tr,s as Er,sa as Dr,si as Or,sn as kr,sr as Ar,st as jr,ta as Mr,ti as Nr,tn as Pr,tr as Fr,tt as Ir,u as Lr,ui as Rr,un as zr,ur as Br,ut as Vr,vi as Hr,vn as Ur,vr as Wr,vt as Gr,wn as Kr,wr as qr,wt as Jr,xi as Yr,xn as Xr,xr as Zr,xt as Qr,yn as $r,yr as ei,yt as ti,z as ni,zi as ri,zn as ii,zr as ai,zt as oi}from"../chunks/dist-YS55N1Pw.js";import{A as si,D as ci,E as P,S as F,T as I,_ as L,b as R,c as li,d as ui,f as di,g as z,h as fi,i as pi,k as mi,l as B,m as hi,o as V,p as gi,r as _i,s as vi,u as H,v as U,w as W,x as yi,y as G}from"../chunks/person-owner-BJgNYLKX.js";import{o as bi}from"../chunks/text-field-DNipvpqK.js";import{t as xi}from"../chunks/provider-catalog-cUfqcR8V.js";import{f as Si,p as Ci,t as wi,u as Ti}from"../chunks/text-response-tgiK3hHI.js";import Ei from"crypto";import{Readable as Di}from"stream";import{Buffer as Oi}from"node:buffer";import{fileURLToPath as ki}from"node:url";import{isIP as Ai,isIPv4 as ji,isIPv6 as Mi}from"node:net";import{createHash as Ni,randomUUID as Pi,timingSafeEqual as Fi}from"node:crypto";var Ii={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}},Li,Ri=c((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(Li||={})})),K,zi,Bi=c((()=>{(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`})(K||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(zi||={})}));function Vi(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function Hi(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function Ui(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new qi(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function Wi(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Gi(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 Ki(e,t){return e.toLowerCase()===t.toLowerCase()}var qi,Ji=c((()=>{qi=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),Yi,Xi=c((()=>{(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`})(Yi||={})})),Zi,Qi=c((()=>{Xi(),Zi=class{kind=Yi.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function $i(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 ea,ta,na=c((()=>{Xi(),Bi(),Ji(),ea=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=$i(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=Gi(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},ta=class{kind=Yi.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new ea(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 ea(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 ea(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:zi.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===K.GAUGE||e.type===K.UP_DOWN_COUNTER||e.type===K.OBSERVABLE_GAUGE||e.type===K.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}}})}}}})),ra,ia,aa=c((()=>{ra=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 oa(e){return ha.setFloat64(0,e),{hi:ha.getUint32(0),lo:ha.getUint32(4)}}function sa(e){let{hi:t}=oa(e);return((t&la)>>20)-da}function ca(e){let{hi:t,lo:n}=oa(e);return(t&ua)===0&&n===0}var la,ua,da,fa,pa,ma,ha,ga=c((()=>{la=2146435072,ua=1048575,da=1023,fa=-1022,pa=da,ma=2**-1022,ha=new DataView(new ArrayBuffer(8))}));function _a(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function va(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var ya=c((()=>{})),ba,xa=c((()=>{ba=class extends Error{}})),Sa,Ca=c((()=>{ga(),ya(),xa(),Sa=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<ma?this._minNormalLowerBoundaryIndex():sa(e)+(ca(e)?-1:0)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new ba(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new ba(`overflow: ${e} is > maximum lower boundary: ${n}`);return _a(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=fa>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return pa>>this._shift}}})),wa,Ta=c((()=>{ga(),ya(),xa(),wa=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=_a(Math.LOG2E,e),this._inverseFactor=_a(Math.LN2,-e)}mapToIndex(e){if(e<=ma)return this._minNormalLowerBoundaryIndex()-1;if(ca(e))return(sa(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 ba(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ma;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new ba(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return fa<<this._scale}_maxNormalLowerBoundaryIndex(){return(pa+1<<this._scale)-1}}}));function Ea(e){if(e>Oa||e<Da)throw new ba(`expected scale >= ${Da} && <= ${Oa}, got: ${e}`);return ka[e+10]}var Da,Oa,ka,Aa=c((()=>{Ca(),Ta(),xa(),Da=-10,Oa=20,ka=Array.from({length:31},(e,t)=>t>10?new wa(t-10):new Sa(t-10))})),ja,Ma,Na,Pa,Fa,Ia,La=c((()=>{Xi(),Bi(),u(),aa(),Aa(),ya(),ja=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}},Ma=20,Na=160,Pa=2,Fa=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=Na,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new ra,u=new ra,d=Ea(Ma)){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=u,this._mapping=d,this._maxSize<Pa&&(l.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
2
+ import{A as e,M as t,N as n,O as r,_ as i,c as a,d as o,j as s,k as c,l,n as u,t as d,y as f}from"../chunks/esm-kgyHmk-Q.js";import{$ as p,$n as m,$r as h,$t as g,A as _,Ai as v,An as y,Ar as b,At as x,B as S,Bi as C,Bn as w,Br as T,Bt as E,Cn as D,Cr as O,Ct as k,D as A,Di as j,Dn as ee,Dr as te,Dt as M,En as N,Er as ne,Et as re,F as ie,Fi as ae,Fn as oe,Fr as se,Ft as ce,G as le,Gi as ue,Gn as de,Gr as fe,Gt as pe,H as me,Hn as he,Hr as ge,Ht as _e,I as ve,Ii as ye,In as be,Ir as xe,It as Se,J as Ce,Jn as we,Jr as Te,Jt as Ee,K as De,Ki as Oe,Kn as ke,Kr as Ae,Kt as je,L as Me,Li as Ne,Ln as Pe,Lr as Fe,Lt as Ie,M as Le,Mi as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Ni as Ue,Nn as We,Nr as Ge,Nt as Ke,O as qe,On as Je,Or as Ye,Ot as Xe,P as Ze,Pi as Qe,Pn as $e,Pr as et,Pt as tt,Q as nt,Qi as rt,Qn as it,Qr as at,Qt as ot,R as st,Ri as ct,Rn as lt,Rr as ut,Rt as dt,Sn as ft,Sr as pt,St as mt,Tn as ht,Tr as gt,Tt as _t,U as vt,Ui as yt,Un as bt,Ur as xt,Ut as St,V as Ct,Vi as wt,Vn as Tt,Vr as Et,Vt as Dt,W as Ot,Wi as kt,Wn as At,Wr as jt,Wt as Mt,X as Nt,Xi as Pt,Xn as Ft,Xr as It,Xt as Lt,Y as Rt,Yi as zt,Yn as Bt,Yr as Vt,Z as Ht,Zi as Ut,Zn as Wt,Zr as Gt,Zt as Kt,_ as qt,_n as Jt,_r as Yt,_t as Xt,a as Zt,aa as Qt,ai as $t,an as en,ar as tn,at as nn,bi as rn,bn as an,br as on,bt as sn,ca as cn,ci as ln,cn as un,cr as dn,ct as fn,dn as pn,dr as mn,ea as hn,ei as gn,en as _n,er as vn,et as yn,fi as bn,fn as xn,fr as Sn,ft as Cn,g as wn,gn as Tn,gr as En,gt as Dn,h as On,hn as kn,hr as An,ht as jn,ii as Mn,in as Nn,ir as Pn,it as Fn,j as In,ji as Ln,jn as Rn,jr as zn,jt as Bn,k as Vn,ki as Hn,kn as Un,kr as Wn,kt as Gn,li as Kn,ln as qn,lr as Jn,lt as Yn,m as Xn,mi as Zn,mn as Qn,mr as $n,mt as er,n as tr,na as nr,ni as rr,nn as ir,nr as ar,nt as or,o as sr,on as cr,or as lr,ot as ur,pi as dr,pn as fr,pr,pt as mr,q as hr,qi as gr,qn as _r,qr as vr,qt as yr,r as br,ra as xr,ri as Sr,rn as Cr,rr as wr,rt as Tr,s as Er,sa as Dr,si as Or,sn as kr,sr as Ar,st as jr,ta as Mr,ti as Nr,tn as Pr,tr as Fr,tt as Ir,u as Lr,ui as Rr,un as zr,ur as Br,ut as Vr,vi as Hr,vn as Ur,vr as Wr,vt as Gr,wn as Kr,wr as qr,wt as Jr,xi as Yr,xn as Xr,xr as Zr,xt as Qr,yn as $r,yr as ei,yt as ti,z as ni,zi as ri,zn as ii,zr as ai,zt as oi}from"../chunks/dist-Ba5R_wLa.js";import{A as si,D as ci,E as P,S as F,T as I,_ as L,b as R,c as li,d as ui,f as di,g as z,h as fi,i as pi,k as mi,l as B,m as hi,o as V,p as gi,r as _i,s as vi,u as H,v as U,w as W,x as yi,y as G}from"../chunks/person-owner-BJgNYLKX.js";import{o as bi}from"../chunks/text-field-BzPZlAbX.js";import{t as xi}from"../chunks/provider-catalog-B21B8kCG.js";import{f as Si,p as Ci,t as wi,u as Ti}from"../chunks/text-response-CArYomyj.js";import Ei from"crypto";import{Readable as Di}from"stream";import{Buffer as Oi}from"node:buffer";import{fileURLToPath as ki}from"node:url";import{isIP as Ai,isIPv4 as ji,isIPv6 as Mi}from"node:net";import{createHash as Ni,randomUUID as Pi,timingSafeEqual as Fi}from"node:crypto";var Ii={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}},Li,Ri=c((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(Li||={})})),K,zi,Bi=c((()=>{(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`})(K||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(zi||={})}));function Vi(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function Hi(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function Ui(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new qi(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function Wi(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Gi(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 Ki(e,t){return e.toLowerCase()===t.toLowerCase()}var qi,Ji=c((()=>{qi=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),Yi,Xi=c((()=>{(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`})(Yi||={})})),Zi,Qi=c((()=>{Xi(),Zi=class{kind=Yi.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function $i(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 ea,ta,na=c((()=>{Xi(),Bi(),Ji(),ea=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=$i(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=Gi(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},ta=class{kind=Yi.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new ea(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 ea(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 ea(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:zi.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===K.GAUGE||e.type===K.UP_DOWN_COUNTER||e.type===K.OBSERVABLE_GAUGE||e.type===K.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}}})}}}})),ra,ia,aa=c((()=>{ra=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 oa(e){return ha.setFloat64(0,e),{hi:ha.getUint32(0),lo:ha.getUint32(4)}}function sa(e){let{hi:t}=oa(e);return((t&la)>>20)-da}function ca(e){let{hi:t,lo:n}=oa(e);return(t&ua)===0&&n===0}var la,ua,da,fa,pa,ma,ha,ga=c((()=>{la=2146435072,ua=1048575,da=1023,fa=-1022,pa=da,ma=2**-1022,ha=new DataView(new ArrayBuffer(8))}));function _a(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function va(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var ya=c((()=>{})),ba,xa=c((()=>{ba=class extends Error{}})),Sa,Ca=c((()=>{ga(),ya(),xa(),Sa=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<ma?this._minNormalLowerBoundaryIndex():sa(e)+(ca(e)?-1:0)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new ba(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new ba(`overflow: ${e} is > maximum lower boundary: ${n}`);return _a(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=fa>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return pa>>this._shift}}})),wa,Ta=c((()=>{ga(),ya(),xa(),wa=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=_a(Math.LOG2E,e),this._inverseFactor=_a(Math.LN2,-e)}mapToIndex(e){if(e<=ma)return this._minNormalLowerBoundaryIndex()-1;if(ca(e))return(sa(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 ba(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ma;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new ba(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return fa<<this._scale}_maxNormalLowerBoundaryIndex(){return(pa+1<<this._scale)-1}}}));function Ea(e){if(e>Oa||e<Da)throw new ba(`expected scale >= ${Da} && <= ${Oa}, got: ${e}`);return ka[e+10]}var Da,Oa,ka,Aa=c((()=>{Ca(),Ta(),xa(),Da=-10,Oa=20,ka=Array.from({length:31},(e,t)=>t>10?new wa(t-10):new Sa(t-10))})),ja,Ma,Na,Pa,Fa,Ia,La=c((()=>{Xi(),Bi(),u(),aa(),Aa(),ya(),ja=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}},Ma=20,Na=160,Pa=2,Fa=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=Na,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new ra,u=new ra,d=Ea(Ma)){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=u,this._mapping=d,this._maxSize<Pa&&(l.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
3
3
  changing to the minimum size of: ${Pa}`),this._maxSize=Pa)}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){if(Number.isFinite(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}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=va(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=Ea(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=ja.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=ja.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 ja(0,-1);let r=t-n;return new ja(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()}},Ia=class{kind=Yi.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new Fa(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:zi.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===K.GAUGE||e.type===K.UP_DOWN_COUNTER||e.type===K.OBSERVABLE_GAUGE||e.type===K.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}}})}}}})),Ra,za,Ba=c((()=>{Xi(),ue(),Bi(),Ra=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=hn(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},za=class{kind=Yi.LAST_VALUE;createAccumulation(e){return new Ra(e)}merge(e,t){let n=Ut(t.sampleTime)>=Ut(e.sampleTime)?t:e;return new Ra(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,t){let n=Ut(t.sampleTime)>=Ut(e.sampleTime)?t:e;return new Ra(t.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:zi.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()}))}}}})),Va,Ha,Ua=c((()=>{Xi(),Bi(),Va=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}},Ha=class{kind=Yi.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new Va(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue();return t.reset?new Va(t.startTime,this.monotonic,r,t.reset):new Va(e.startTime,this.monotonic,n+r)}diff(e,t){let n=e.toPointValue(),r=t.toPointValue();return this.monotonic&&n>r?new Va(t.startTime,this.monotonic,r,!0):new Va(t.startTime,this.monotonic,r-n)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:zi.SUM,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),Wa=c((()=>{Qi(),na(),La(),Ba(),Ua()})),Ga,Ka,qa,Ja,Ya,Xa,Za,Qa,$a,eo,to,no,ro=c((()=>{u(),Wa(),Bi(),Ga=class e{static DEFAULT_INSTANCE=new Zi;createAggregator(t){return e.DEFAULT_INSTANCE}},Ka=class e{static MONOTONIC_INSTANCE=new Ha(!0);static NON_MONOTONIC_INSTANCE=new Ha(!1);createAggregator(t){switch(t.type){case K.COUNTER:case K.OBSERVABLE_COUNTER:case K.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}},qa=class e{static DEFAULT_INSTANCE=new za;createAggregator(t){return e.DEFAULT_INSTANCE}},Ja=class e{static DEFAULT_INSTANCE=new ta([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(t){return e.DEFAULT_INSTANCE}},Ya=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 ta(this._boundaries,this._recordMinMax)}},Xa=class{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new Ia(this._maxSize,this._recordMinMax)}},Za=class{_resolve(e){switch(e.type){case K.COUNTER:case K.UP_DOWN_COUNTER:case K.OBSERVABLE_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:return $a;case K.GAUGE:case K.OBSERVABLE_GAUGE:return eo;case K.HISTOGRAM:return e.advice.explicitBucketBoundaries?new Ya(e.advice.explicitBucketBoundaries):to}return l.warn(`Unable to recognize instrument type: ${e.type}`),Qa}createAggregator(e){return this._resolve(e).createAggregator(e)}},Qa=new Ga,$a=new Ka,eo=new qa,to=new Ja,new Xa,no=new Za}));function io(e){switch(e.type){case ao.DEFAULT:return no;case ao.DROP:return Qa;case ao.SUM:return $a;case ao.LAST_VALUE:return eo;case ao.EXPONENTIAL_HISTOGRAM:{let t=e;return new Xa(t.options?.maxSize,t.options?.recordMinMax)}case ao.EXPLICIT_BUCKET_HISTOGRAM:{let t=e;return t.options==null?to:new Ya(t.options?.boundaries,t.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}var ao,oo=c((()=>{ro(),(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`})(ao||={})})),so,co,lo=c((()=>{Ri(),oo(),so=e=>({type:ao.DEFAULT}),co=e=>Li.CUMULATIVE})),uo,fo,po,mo,ho,go=c((()=>{uo=`otel.component.name`,fo=`otel.component.type`,po=`periodic_metric_reader`,mo=`otel.sdk.metric_reader.collection.duration`,ho=`error.type`})),_o,vo,yo=c((()=>{go(),_o=new Map,vo=class{collectionDuration;standardAttrs;constructor(e,t){let n=_o.get(e)??0;_o.set(e,n+1),this.standardAttrs={[fo]:e,[uo]:`${e}/${n}`},this.collectionDuration=t.createHistogram(mo,{unit:`s`,description:`The duration of the collect operation of the metric reader.`,advice:{explicitBucketBoundaries:[]}})}recordCollection(e,t){let n=t?{...this.standardAttrs,[ho]:t}:this.standardAttrs;this.collectionDuration.record(e,n)}}})),bo,xo=c((()=>{bo=`2.11.0`})),So,Co=c((()=>{u(),Ji(),lo(),yo(),xo(),ue(),So=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_selfObsMetrics;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;_otelComponentType;constructor(e){this._aggregationSelector=e?.aggregationSelector??so,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??co,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector,this._otelComponentType=e?.otelComponentType??this.constructor.name,this._selfObsMetrics=new vo(this._otelComponentType,f())}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`,bo);this._selfObsMetrics=new vo(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=zt(),[n,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),i=zt(),a=n.errors.concat(r.flatMap(e=>e.errors)),o=rt(Pt(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){if(this._shutdown){l.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await Ui(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){l.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await Ui(this.onForceFlush(),e.timeoutMillis)}}}));function wo(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 To=c((()=>{})),Eo,Do=c((()=>{u(),ue(),Co(),Ji(),Bi(),To(),go(),Eo=class extends So{_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:po,metricProducers:r,cardinalitySelector:e=>{let t={default:2e3,...i};switch(e){case K.COUNTER:return t.counter??t.default;case K.GAUGE:return t.gauge??t.default;case K.HISTOGRAM:return t.histogram??t.default;case K.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case K.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case K.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case K.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`);l.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){Qt(e)}}async _doRun(){if(this._ongoingExportPromise){l.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&&l.error(`PeriodicExportingMetricReader: metrics collection errors`,...t),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){l.debug(`Error while resolving async portion of resource: `,e),Qt(e)}if(e.scopeMetrics.length===0)return;let n=this._maxExportBatchSize?wo(e,this._maxExportBatchSize):[e],r=null;for(let e of n)try{let t=await Ui(Oe._export(this._exporter,e),this._exportTimeout);t.code!==gr.SUCCESS&&(r=Error(`PeriodicExportingMetricReader: metrics export failed (error ${t.error})`))}catch(e){if(e instanceof qi){l.error(`PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`);break}l.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){l.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()}}})),Oo,ko=c((()=>{ue(),Oo=class{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){if(this._shutdown){setTimeout(()=>t({code:gr.FAILED}),0);return}this._metrics.push(e),setTimeout(()=>t({code:gr.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()}}})),Ao,jo=c((()=>{ue(),lo(),Ao=class e{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??co}export(t,n){if(this._shutdown){n({code:gr.FAILED});return}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:gr.SUCCESS})}}})),Mo,No=c((()=>{Mo=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 Po(e,t,n){return Lo(e)||l.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??i.DOUBLE,advice:n?.advice??{}}}function Fo(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 Io(e,t){return Ki(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}function Lo(e){return Ro.test(e)}var Ro,zo=c((()=>{u(),Ji(),Ro=/^[a-z][a-z0-9_.\-/]{0,254}$/i}));function Bo(e){return e instanceof Ko}var Vo,Ho,Uo,Wo,Go,Ko,qo,Jo,Yo,Xo=c((()=>{u(),Vo=class{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},n){if(typeof e!=`number`){l.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===i.INT&&!Number.isInteger(e)&&(l.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())}},Ho=class extends Vo{add(e,t,n){this._record(e,t,n)}},Uo=class extends Vo{add(e,t,n){if(e<0){l.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},Wo=class extends Vo{record(e,t,n){this._record(e,t,n)}},Go=class extends Vo{record(e,t,n){if(e<0){l.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},Ko=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)}},qo=class extends Ko{},Jo=class extends Ko{},Yo=class extends Ko{}})),Zo,Qo=c((()=>{zo(),Xo(),Bi(),Zo=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){let n=Po(e,K.GAUGE,t),r=this._meterSharedState.registerMetricStorage(n);return new Wo(r,n)}createHistogram(e,t){let n=Po(e,K.HISTOGRAM,t),r=this._meterSharedState.registerMetricStorage(n);return new Go(r,n)}createCounter(e,t){let n=Po(e,K.COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new Uo(r,n)}createUpDownCounter(e,t){let n=Po(e,K.UP_DOWN_COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new Ho(r,n)}createObservableGauge(e,t){let n=Po(e,K.OBSERVABLE_GAUGE,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Jo(n,r,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){let n=Po(e,K.OBSERVABLE_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new qo(n,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){let n=Po(e,K.OBSERVABLE_UP_DOWN_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Yo(n,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),$o,es=c((()=>{zo(),$o=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=Po(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),ts,ns,rs=c((()=>{Ji(),ts=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}},ns=class extends ts{constructor(){super(Vi)}}})),is,as=c((()=>{ue(),Ji(),rs(),is=class{_activeCollectionStorage=new ns;_cumulativeMemoStorage=new ns;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Vi(this._overflowAttributes)}record(e,t,n){let r=this._activeCollectionStorage.get(t);if(!r){let i=hn(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 ns,e}}}));function os(e){return Array.from(e.entries())}var ss,cs=c((()=>{Ri(),rs(),ss=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===Li.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=os(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 ns,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}}})),ls,us=c((()=>{es(),as(),cs(),rs(),ls=class extends $o{_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 ss(t,r),this._attributesProcessor=n}record(e,t){if(this._attributesProcessor===void 0){this._deltaMetricStorage.batchCumulate(e,t);return}let n=new ns;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 ds(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 fs(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function ps(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function ms(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 hs(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}'
4
4
  \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${r}
5
5
  \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${r}`}function gs(e,t){return e.valueType===t.valueType?e.unit===t.unit?e.type===t.type?e.description===t.description?``:hs(e,t):ms(e,t):ps(e,t):fs(e,t)}var _s=c((()=>{})),vs,ys=c((()=>{zo(),u(),_s(),vs=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);if(r===void 0){t.set(n.name,[e]);return}r.push(e)}_findOrUpdateCompatibleStorage(e,t){let n=null;for(let r of t){let t=r.getInstrumentDescriptor();Io(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&r.updateDescription(e.description),l.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.
@@ -72,8 +72,8 @@ return fn.apply(this, arguments)
72
72
  `);this.writeFrame(`${t}\n\n`)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}this._deferredResponse!==void 0&&!this._deferredResponse.settled&&(this._deferredResponse.settled=!0,this._deferredResponse.reject(new Y(J.ConnectionClosed,`Connection closed before a response was produced`))),this.onclose?.()}}settleResponse(e){this._deferredResponse===void 0||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(e))}upgradeToSse(){let e,t=new ReadableStream({start:t=>{e=t},cancel:()=>{this.close()}});this._sse={controller:e,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=kv(this._keepAliveMs,()=>this.writeCommentFrame(`keepalive`)),this.settleResponse(new Response(t,{status:200,headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(e){this.writeFrame(`event: message\ndata: ${JSON.stringify(e)}\n\n`)}writeFrame(e){if(!(this._sse===void 0||this._sse.closed))try{this._sse.controller.enqueue(this._sse.encoder.encode(e))}catch(e){this.onerror?.(Error(`Failed to write to the response stream: ${e}`))}}};async function Dy(e,t,n){let r=new Ey({classification:n.classification,...n.responseMode!==void 0&&{responseMode:n.responseMode},...n.keepAliveMs!==void 0&&{keepAliveMs:n.keepAliveMs}});return await e.connect(r),r.handleMessage(t,{...n.request!==void 0&&{request:n.request},...n.authInfo!==void 0&&{authInfo:n.authInfo}})}var Oy=4194304,ky=100;function Ay(e){return`Payload Too Large: Request body must not exceed ${e} bytes`}function jy(e){if(e===void 0)return Oy;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}async function My(e,t=Oy){if(Number(e.headers.get(`content-length`))>t)return{tooLarge:!0};if(e.body===null)return{tooLarge:!1,text:``};let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{for(;;){let{done:e,value:o}=await n.read();if(e)break;if(i+=o.byteLength,i>t)return{tooLarge:!0};a+=r.decode(o,{stream:!0})}}finally{n.releaseLock()}return{tooLarge:!1,text:a+r.decode()}}var Ny=class{sessionIdGenerator;_started=!1;_hasHandledRequest=!1;_closed=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId=`_GET_stream`;_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;_keepAliveMs;_maxRequestBodySize;_scopeChallengeResolver;sessionId;onclose;onerror;onmessage;constructor(e={}){this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._supportedProtocolVersions=e.supportedProtocolVersions??An,this._keepAliveMs=e.keepAliveMs??15e3,this._maxRequestBodySize=jy(e.maxRequestBodySize)}startKeepAlive(e,t){if(this._closed)return;let n=kv(this._keepAliveMs,()=>{try{e.enqueue(t.encode(`: keepalive
73
73
 
74
74
  `))}catch{n!==void 0&&clearInterval(n)}});return n}setScopeChallengeResolver(e){this._scopeChallengeResolver=e}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}setSupportedProtocolVersions(e){this._supportedProtocolVersions=e}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),Response.json({jsonrpc:`2.0`,error:i,id:null},{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}async _checkScopeChallenge(e,t){if(!this._scopeChallengeResolver)return;let n=await Jv(e.filter(e=>Om(e)),t,this._scopeChallengeResolver);return n===void 0?void 0:Xv(n,Yv(t))}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}supportsEmptySSEData(e){return this._supportedProtocolVersions.includes(e)&&e>=`2025-11-25`}async writePrimingEvent(e,t,n,r){if(!this._eventStore||!this.supportsEmptySSEData(r))return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a,o=new ReadableStream({start:e=>{i=e},cancel:()=>{a!==void 0&&clearInterval(a),this._streamMapping.get(this._standaloneSseStreamId)?.controller===i&&this._streamMapping.delete(this._standaloneSseStreamId)}}),s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};return this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),a=this.startKeepAlive(i,r),new Response(o,{headers:s})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a,o=!1,s,c=new ReadableStream({start:e=>{i=e},cancel:()=>{o=!0,a!==void 0&&clearInterval(a),s!==void 0&&this._streamMapping.get(s)?.controller===i&&this._streamMapping.delete(s)}}),l=new Set;if(s=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(l.add(e),!this.writeSSEEvent(i,r,t,e))try{i.close()}catch{}}}),this._closed||o){try{i.close()}catch{}return this.createJsonErrorResponse(404,-32001,`Session not found`)}if(this._streamMapping.get(s)?.cleanup(),this._streamMapping.set(s,{controller:i,encoder:r,replayedEventIds:l,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(s);try{i.close()}catch{}}}),s!==this._standaloneSseStreamId&&![...this._requestToStreamMapping.values()].includes(s)){this._streamMapping.delete(s);try{i.close()}catch{}}return this._streamMapping.get(s)?.controller===i&&(a=this.startKeepAlive(i,r)),new Response(c,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
75
- `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);if(!_g(e.headers.get(`content-type`)))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=e,i;if(t?.parsedBody===void 0)try{let t=await My(e,this._maxRequestBodySize);if(t.tooLarge){let e=Ay(this._maxRequestBodySize);return this.onerror?.(Error(e)),this.createJsonErrorResponse(413,-32e3,e)}i=JSON.parse(t.text)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else i=t.parsedBody;if(Array.isArray(i)&&i.length>ky)return this.onerror?.(Error(`Invalid Request: Batch must not exceed ${ky} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${ky} messages`);let a;try{a=Array.isArray(i)?i.map(e=>St.parse(e)):[St.parse(i)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let o=a.some(e=>Nm(e));if(o){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(a.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!o){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let s;try{s=await this._checkScopeChallenge(a,t?.authInfo)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32603,`Internal server error`)}if(s)return s;if(!a.some(e=>Om(e))){for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=a.find(e=>Nm(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of a)Om(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r})});let d=new TextEncoder,f,p,m=new ReadableStream({start:e=>{f=e},cancel:()=>{p!==void 0&&clearInterval(p),this._streamMapping.get(c)?.controller===f&&this._streamMapping.delete(c)}}),h={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(h[`mcp-session-id`]=this.sessionId);for(let e of a)Om(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{p!==void 0&&clearInterval(p),this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of a){let n,i;Om(e)&&this._eventStore&&this.supportsEmptySSEData(u)&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:r,closeSSEStream:n,closeStandaloneSSEStream:i})}return this._streamMapping.get(c)?.controller===f&&(p=this.startKeepAlive(f,d)),new Response(m,{status:200,headers:h})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((Am(e)||jm(e))&&(n=e.id),n===void 0){if(Am(e)||jm(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&(t===void 0||!n.replayedEventIds?.has(t))&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e),i=this._streamMapping.get(r)),i?.controller&&i?.encoder&&(t===void 0||!i.replayedEventIds?.has(t))&&this.writeSSEEvent(i.controller,i.encoder,e,t)}if(Am(e)||jm(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e})),i.cleanup()}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}};function Py(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function Fy(e,t,n,r,i=null){return Response.json({jsonrpc:`2.0`,error:{code:t,message:n,...r!==void 0&&{data:r}},id:i},{status:e})}function Iy(e,t=null){return Fy(e.httpStatus,e.code,e.message,e.data,t)}function Ly(e){return e instanceof Error?e:Error(String(e))}function Ry(e=null){return Fy(500,-32603,`Internal server error`,void 0,e)}function zy(e){if(e.transport!==void 0)throw Error(`The factory returned an instance that is still serving another request. Return a new instance for each request.`)}function By(e,t,n,r){return async(i,a)=>{if(i.method.toUpperCase()!==`POST`)return Fy(405,-32e3,`Method not allowed.`);try{let t=await e({era:`legacy`,...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:i}),o=new Ny({sessionIdGenerator:void 0,...n!==void 0&&{keepAliveMs:n},...r!==void 0&&{maxRequestBodySize:r}});await t.connect(o);let s=()=>{o.close().catch(()=>{}),t.close().catch(()=>{})};i.signal?.addEventListener(`abort`,s,{once:!0});let c=await o.handleRequest(i,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(c.body===null||gg(c.headers.get(`content-type`))!==`text/event-stream`)return s(),c;let l=c.body.getReader(),u=!1,d=()=>{u||(u=!0,s())},f=new ReadableStream({pull:async e=>{try{let{done:t,value:n}=await l.read();if(t){d(),e.close();return}n!==void 0&&e.enqueue(n)}catch(t){d(),e.error(t)}},cancel:e=>(d(),l.cancel(e).catch(()=>{}))});return new Response(f,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(e){try{t?.(Ly(e))}catch{}return Ry(Py(a?.parsedBody))}}}function Vy(e){return{protocolVersionHeader:e.headers.get(`mcp-protocol-version`)??void 0,mcpMethodHeader:e.headers.get(`mcp-method`)??void 0,mcpNameHeader:e.headers.get(`mcp-name`)??void 0}}async function Hy(e,t,n=!0,r=Oy){let i=e.method.toUpperCase(),a,o=t,s=e,c=!1;if(i===`POST`){if(o===void 0){n&&(s=e.clone());let t;try{let n=await My(e,r);if(n.tooLarge)return{step:`body-too-large`};t=n.text}catch{return{step:`unreadable-body`}}try{a=t.length===0?void 0:JSON.parse(t)}catch{c=!0}!c&&a!==void 0&&(o=a)}else a=o;if(c||a===void 0)return{step:`no-json-body`,forwardRequest:s}}return{step:`classified`,outcome:hh({httpMethod:i,...Vy(e),...a!==void 0&&{body:a}}),body:a,parsedBody:o,forwardRequest:s}}function Uy(e,t={}){let{legacy:n,onerror:r,responseMode:i}=t,a=jy(t.maxRequestBodySize);if(typeof n==`function`)throw TypeError(`The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.`);let o=new Set,s=!1,c=e=>{try{r?.(e)}catch{}},l=t.bus??new Av(c),u=jv(l),d=Rv({bus:l,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:c});i===`json`&&console.warn(`responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.`);let f=n===`reject`?void 0:By(e,c,t.keepAliveMs,a);async function p(n,r,a){let s=n.classification.revision;if(s===void 0||!Wf.includes(s)){let e=new Fp({supported:[...Wf],requested:s??`unknown`});return c(e),Fy(400,e.code,e.message,e.data,Py(n.message))}let l=ch({httpMethod:r.method,...Vy(r)},n);if(l!==void 0)return c(Error(`Rejected inbound request (${l.cell}): ${l.message}`)),Iy(l,Py(n.message));let u=n.messageKind===`request`?Cm(n.message.params):void 0,f=u?.[S];if(n.messageKind===`request`){let e=Rf(n.message.method);if(e!==void 0){let t=Hf(e,f);if(t!==void 0){let e=new Ip({requiredCapabilities:t});return c(e),Fy(nh(e.code,`ladder`),e.code,e.message,e.data,n.message.id)}}}let p=await e({era:`modern`,...a!==void 0&&{authInfo:a},requestInfo:r}),m=p instanceof hy?p.server:p;if(zy(m),n.messageKind===`request`&&n.message.method===`subscriptions/listen`){let e=m.getCapabilities(),t=uy(m);return p.close().catch(c),d.serve(n.message,r.signal,e,t)}if(n.messageKind===`request`&&n.message.method===`tools/call`&&p instanceof hy){let e=n.message.params,t=typeof e?.name==`string`?e.name:void 0,i=t===void 0?void 0:p.toolInputSchemaJson(t);if(i!==void 0){let t=Bm(i);if(t.valid&&t.declarations.length>0){let i=Qm(t.declarations,e?.arguments,r.headers);if(i!==void 0)return p.close().catch(c),c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),Iy(i,n.message.id)}}}if(n.messageKind===`request`&&p instanceof hy)try{let e=await Jv([n.message],a,e=>p.resolveScopeChallenge(e));if(e!==void 0)return p.close().catch(c),Xv(e,Yv(a))}catch(e){return p.close().catch(c),c(Ly(e)),Ry(n.message.id)}zy(m),cg(m,s),ly(m,Wf),u!==void 0&&cy(m,{clientInfo:u[Ct],clientCapabilities:f});let h=m.onclose;o.add(m);let g=()=>{o.delete(m),m.onclose===g&&(m.onclose=h),h?.()};m.onclose=g;try{let e=await Dy(p,n.message,{classification:n.classification,request:r,...a!==void 0&&{authInfo:a},...i!==void 0&&{responseMode:i},...t.keepAliveMs!==void 0&&{keepAliveMs:t.keepAliveMs}});return n.messageKind===`notification`&&queueMicrotask(()=>void m.close().catch(()=>{})),e}catch(e){return e instanceof Y&&e.code===J.ConnectionClosed?new Response(null,{status:499}):(await m.close().catch(()=>{}),o.delete(m),c(Ly(e)),Ry(Py(n.message)))}}async function m(e,t,n,r){if(f!==void 0)return f(t,{...n!==void 0&&{authInfo:n},...r!==void 0&&{parsedBody:r}});let i=gh(e,Wf);return i===void 0?new Response(null,{status:202}):(c(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),Iy(i,Py(r)))}async function h(e,t){let n=t?.authInfo;if(e.method.toUpperCase()===`POST`&&!_g(e.headers.get(`content-type`)))return c(Error(`Unsupported Media Type: Content-Type must be application/json`)),Fy(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=await Hy(e,t?.parsedBody,!0,a);if(r.step===`unreadable-body`)return Fy(400,-32700,`Parse error: the request body could not be read`);if(r.step===`body-too-large`)return Fy(413,-32e3,Ay(a));if(r.step===`no-json-body`)return f===void 0?Fy(400,-32700,`Parse error: the request body is not valid JSON`):f(r.forwardRequest,{...n!==void 0&&{authInfo:n}});let{outcome:i,body:o,parsedBody:s,forwardRequest:l}=r;try{switch(i.kind){case`reject`:return c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),Iy(i,Py(o));case`modern`:return await p(i,e,n);case`legacy`:return await m(i,l,n,s)}}catch(e){return c(Ly(e)),Ry(Py(o))}}return{fetch:async(e,t)=>{if(s)throw Error(`This MCP handler has been closed`);try{return await h(e,t)}catch(e){return c(Ly(e)),Ry(Py(t?.parsedBody))}},notify:u,bus:l,close:async()=>{s=!0,d.closeAll();let e=[...o].map(e=>e.close().catch(()=>{}));o.clear(),await Promise.all(e)}}}var Wy=global.Request,Gy=class extends Wy{constructor(e,t){typeof e==`object`&&Yy in e&&(e=e[Yy]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Ky=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},qy=Symbol(`wrapBodyStream`),Jy=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Gy(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[qy]){let e;a.body=new ReadableStream({async pull(t){try{e||=Di.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Di.toWeb(r)}return new Gy(t,a)},Yy=Symbol(`getRequestCache`),Xy=Symbol(`requestCache`),Zy=Symbol(`incomingKey`),Qy=Symbol(`urlKey`),$y=Symbol(`headersKey`),eb=Symbol(`abortControllerKey`),tb={get method(){return this[Zy].method||`GET`},get url(){return this[Qy]},get headers(){return this[$y]||=Ky(this[Zy])},[Symbol(`getAbortController`)](){return this[Yy](),this[eb]},[Yy](){return this[eb]||=new AbortController,this[Xy]||=Jy(this.method,this[Qy],this.headers,this[Zy],this[eb])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(tb,e,{get(){return this[Yy]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(tb,e,{value:function(){return this[Yy]()[e]()}})}),Object.defineProperty(tb,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Xy]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(tb,Gy.prototype);var nb=Symbol(`responseCache`),rb=Symbol(`getResponseCache`),ib=Symbol(`cache`),ab=global.Response,ob=class e{#e;#t;[rb](){return delete this[ib],this[nb]||=new ab(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[nb];if(e){this.#t=e,this[rb]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[ib]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[ib];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[rb]().headers}get status(){return this[ib]?.[0]??this[rb]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(ob.prototype,e,{get(){return this[rb]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(ob.prototype,e,{value:function(){return this[rb]()[e]()}})}),Object.defineProperty(ob.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[nb]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(ob,ab),Object.setPrototypeOf(ob.prototype,ab.prototype),global.crypto===void 0&&(global.crypto=Ei);var sb=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name=`RequestBodyTooLargeError`}};function cb(e){if(e===void 0)return Oy;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function lb(e,t){let n=cb(t?.maxRequestBodySize);return async(r,i,a)=>{typeof a==`function`&&(a=void 0);let o=!1,s=new AbortController;i.on(`close`,()=>{o||s.abort()}),i.destroyed===!0&&s.abort();let c;try{let t=await db(r,a,{signal:s.signal,maxRequestBodySize:n});c=await e.fetch(t,{...r.auth!==void 0&&{authInfo:r.auth},...a!==void 0&&{parsedBody:a}})}catch(e){if(e instanceof sb)c=Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:`close`}});else{try{t?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}c=pb(fb(a))}}let l={};for(let[e,t]of c.headers)l[e]=t;if(i.writeHead(c.status,l),c.body===null){o=!0,i.end();return}let u;i.on(`drain`,()=>{u?.(),u=void 0});let d=new Promise(e=>{s.signal.addEventListener(`abort`,()=>e(),{once:!0})});try{for await(let e of c.body){if(s.signal.aborted)break;i.write(e)===!1&&await Promise.race([new Promise(e=>{u=e}),d])}}catch{}o=!0,i.end()}}function ub(e){return Array.isArray(e)?e[0]:e}async function db(e,t,n){let r=cb(n?.maxRequestBodySize),i=(e.method??`GET`).toUpperCase(),a=`http://${ub(e.headers.host)??ub(e.headers[`:authority`])??`localhost`}${e.url??`/`}`,o=new Headers;for(let[t,n]of Object.entries(e.headers))if(!(n===void 0||t.startsWith(`:`))){if(Array.isArray(n))for(let e of n)o.append(t,e);else o.set(t,n)}let s;if(i!==`GET`&&i!==`HEAD`){if(t===void 0){if(Number(ub(e.headers[`content-length`]))>r)throw new sb(r);let t=new TextDecoder,n=``,i=0;for await(let a of e){if(i+=typeof a==`string`?new TextEncoder().encode(a).byteLength:a.byteLength,i>r)throw new sb(r);n+=typeof a==`string`?a:t.decode(a,{stream:!0})}n+=t.decode(),n.length>0&&(s=n)}else{let e=JSON.stringify(t);o.delete(`content-encoding`),o.delete(`transfer-encoding`),e===void 0?o.delete(`content-length`):(s=e,o.set(`content-length`,String(new TextEncoder().encode(e).byteLength)))}}return new Request(a,{method:i,headers:o,...n?.signal!==void 0&&{signal:n.signal},...s!==void 0&&{body:s}})}function fb(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function pb(e){return Response.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:e},{status:500})}var mb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=void 0;var n=(u(),t(d)),r=(oc(),t(ac)),i=(ue(),t(kt)),a=(nr(),t(Mr)),o=`otel.scope.schema_url`;function s(e){return e.replace(/\\/g,`\\\\`).replace(/\n/g,`\\n`)}function c(e=``){return typeof e!=`string`&&(e=JSON.stringify(e)),s(e).replace(/"/g,`\\"`)}var l=/[^a-z0-9_]/gi,f=/_{2,}/g;function p(e){return e.replace(l,`_`).replace(f,`_`)}function m(e,t){return!e.endsWith(`_total`)&&t.dataPointType===r.DataPointType.SUM&&t.isMonotonic&&(e+=`_total`),e}function h(e){return e===1/0?`+Inf`:e===-1/0?`-Inf`:`${e}`}function g(e){switch(e.dataPointType){case r.DataPointType.SUM:return e.isMonotonic?`counter`:`gauge`;case r.DataPointType.GAUGE:return`gauge`;case r.DataPointType.HISTOGRAM:return`histogram`;default:return`untyped`}}function _(e,t,n,r,i){let a=!1,o=``;for(let[e,n]of Object.entries(t)){let t=p(e);a=!0,o+=`${o.length>0?`,`:``}${t}="${c(n)}"`}if(i)for(let[e,t]of Object.entries(i)){let n=p(e);a=!0,o+=`${o.length>0?`,`:``}${n}="${c(t)}"`}return a&&(e+=`{${o}}`),`${e} ${h(n)}${r===void 0?``:` `+String(r)}\n`}var v=`# no registered metrics`;e.PrometheusSerializer=class{_prefix;_appendTimestamp;_additionalAttributes;_withResourceConstantLabels;_withoutScopeInfo;_withoutTargetInfo;constructor(e,t=!1,n,r,i){e&&(this._prefix=e+`_`),this._appendTimestamp=t,this._withResourceConstantLabels=n,this._withoutScopeInfo=!!i,this._withoutTargetInfo=!!r}serialize(e){let t=``;this._additionalAttributes=this._filterResourceConstantLabels(e.resource.attributes,this._withResourceConstantLabels);for(let n of e.scopeMetrics)t+=this._serializeScopeMetrics(n);return t===``&&(t+=v),this._serializeResource(e.resource)+t}_filterResourceConstantLabels(e,t){if(t){let n={};for(let[r,i]of Object.entries(e))r.match(t)&&(n[r]=i);return n}}_serializeScopeMetrics(e){let t=``;for(let n of e.metrics){let r=this._serializeMetricData(n,e.scope);r&&(t+=r+`
76
- `)}return t}_serializeMetricData(e,t){let i=p(s(e.descriptor.name));if(this._prefix&&(i=`${this._prefix}${i}`),i===``)return n.diag.error(`Normalization for metric "${e.descriptor.name}" resulted in empty name`),``;if(i===`_`)return n.diag.error(`Normalization for metric "${e.descriptor.name}" resulted in an invalid name: "_"`),``;i[0]>=`0`&&i[0]<=`9`&&(i=`_${i}`);let c=e.dataPointType;i=m(i,e);let l=`# HELP ${i} ${s(e.descriptor.description||`description missing`)}`,u=e.descriptor.unit?`\n# UNIT ${i} ${s(e.descriptor.unit)}`:``,d=`# TYPE ${i} ${g(e)}`,f;if(this._withoutScopeInfo)f=this._additionalAttributes;else{let e={[a.ATTR_OTEL_SCOPE_NAME]:t.name};t.schemaUrl&&(e[o]=t.schemaUrl),t.version&&(e[a.ATTR_OTEL_SCOPE_VERSION]=t.version),f=Object.assign(e,this._additionalAttributes)}let h=``;switch(c){case r.DataPointType.SUM:case r.DataPointType.GAUGE:h=e.dataPoints.map(t=>this._serializeSingularDataPoint(i,e,t,f)).join(``);break;case r.DataPointType.HISTOGRAM:h=e.dataPoints.map(t=>this._serializeHistogramDataPoint(i,e,t,f)).join(``);break;default:n.diag.error(`Unrecognizable DataPointType: ${c} for metric "${i}"`)}return`${l}${u}\n${d}\n${h}`.trim()}_serializeSingularDataPoint(e,t,n,r){let a=``,{value:o,attributes:s}=n,c=(0,i.hrTimeToMilliseconds)(n.endTime);return a+=_(e,s,o,this._appendTimestamp?c:void 0,r),a}_serializeHistogramDataPoint(e,t,n,r){let a=``,o=n.attributes,s=n.value,c=(0,i.hrTimeToMilliseconds)(n.endTime);for(let t of[`count`,`sum`]){let n=s[t];n!=null&&(a+=_(e+`_`+t,o,n,this._appendTimestamp?c:void 0,r))}let l=0,u=s.buckets.counts.entries(),d=!1;for(let[t,n]of u){l+=n;let i=s.buckets.boundaries[t];if(i===void 0&&d)break;i===1/0&&(d=!0),a+=_(e+`_bucket`,o,l,this._appendTimestamp?c:void 0,Object.assign({},r,{le:i===void 0||i===1/0?`+Inf`:String(i)}))}return a}_serializeResource(e){if(this._withoutTargetInfo===!0)return``;let t=`target_info`;return`${`# HELP ${t} Target metadata`}\n${`# TYPE ${t} gauge`}\n${_(t,e.attributes,1).trim()}\n`}}})),hb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER=void 0,e.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER=`prometheus_http_text_metric_exporter`})),gb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusExporter=void 0;var n=(u(),t(d)),r=(ue(),t(kt)),i=(oc(),t(ac)),a=s(`http`),o=mb(),c=hb(),l=s(`url`);e.PrometheusExporter=class e extends i.MetricReader{static DEFAULT_OPTIONS={host:void 0,port:9464,endpoint:`/metrics`,prefix:``,appendTimestamp:!1,withResourceConstantLabels:void 0,withoutScopeInfo:!1,withoutTargetInfo:!1};_host;_port;_baseUrl;_endpoint;_server;_prefix;_appendTimestamp;_serializer;_startServerPromise;constructor(t={},r=()=>{}){super({aggregationSelector:e=>({type:i.AggregationType.DEFAULT}),aggregationTemporalitySelector:e=>i.AggregationTemporality.CUMULATIVE,otelComponentType:c.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER,metricProducers:t.metricProducers}),this._host=t.host||process.env.OTEL_EXPORTER_PROMETHEUS_HOST||e.DEFAULT_OPTIONS.host,this._port=t.port||Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT)||e.DEFAULT_OPTIONS.port,this._prefix=t.prefix||e.DEFAULT_OPTIONS.prefix,this._appendTimestamp=typeof t.appendTimestamp==`boolean`?t.appendTimestamp:e.DEFAULT_OPTIONS.appendTimestamp;let s=t.withResourceConstantLabels||e.DEFAULT_OPTIONS.withResourceConstantLabels,l=t.withoutScopeInfo||e.DEFAULT_OPTIONS.withoutScopeInfo,u=t.withoutTargetInfo||e.DEFAULT_OPTIONS.withoutTargetInfo;this._server=(0,a.createServer)(this._requestHandler).unref(),this._serializer=new o.PrometheusSerializer(this._prefix,this._appendTimestamp,s,u,l),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(t.endpoint||e.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,`/$1`),t.preventServerStart===!0?r&&queueMicrotask(r):this.startServer().then(r,e=>{n.diag.error(e),r(e)})}async onForceFlush(){}onShutdown(){return this.stopServer()}stopServer(){return this._server?new Promise(e=>{this._server.close(t=>{t?t.code!==`ERR_SERVER_NOT_RUNNING`&&(0,r.globalErrorHandler)(t):n.diag.debug(`Prometheus exporter was stopped`),e()})}):(n.diag.debug(`Prometheus stopServer() was called but server was never started.`),Promise.resolve())}startServer(){return this._startServerPromise??=new Promise((e,t)=>{this._server.once(`error`,t),this._server.listen({port:this._port,host:this._host},()=>{n.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`),e()})}),this._startServerPromise}getMetricsRequestHandler(e,t){this._exportMetrics(t)}_requestHandler=(e,t)=>{let n;try{e.url!=null&&(n=new l.URL(e.url,this._baseUrl).pathname)}catch{t.statusCode=400,t.end(`Bad Request`);return}n===this._endpoint?this._exportMetrics(t):this._notFound(t)};_exportMetrics=e=>{e.statusCode=200,e.setHeader(`content-type`,`text/plain`),this.collect().then(t=>{let{resourceMetrics:r,errors:i}=t;i.length&&n.diag.error(`PrometheusExporter: metrics collection errors`,...i),e.end(this._serializer.serialize(r))},t=>{e.end(`# failed to export metrics: ${t}`)})};_notFound=e=>{e.statusCode=404,e.end()}}})),_b=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=e.PrometheusExporter=void 0;var t=gb();Object.defineProperty(e,"PrometheusExporter",{enumerable:!0,get:function(){return t.PrometheusExporter}});var n=mb();Object.defineProperty(e,"PrometheusSerializer",{enumerable:!0,get:function(){return n.PrometheusSerializer}})})),vb;(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`,e[e.LOWMEMORY=2]=`LOWMEMORY`})(vb||={}),ue(),oc(),u();var yb=()=>Li.CUMULATIVE,bb=e=>{switch(e){case K.COUNTER:case K.OBSERVABLE_COUNTER:case K.GAUGE:case K.HISTOGRAM:case K.OBSERVABLE_GAUGE:return Li.DELTA;case K.UP_DOWN_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:return Li.CUMULATIVE}},xb=e=>{switch(e){case K.COUNTER:case K.HISTOGRAM:return Li.DELTA;case K.GAUGE:case K.UP_DOWN_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:case K.OBSERVABLE_COUNTER:case K.OBSERVABLE_GAUGE:return Li.CUMULATIVE}};function Sb(){let e=(xr(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`)??`cumulative`).toLowerCase();return e===`cumulative`?yb:e===`delta`?bb:e===`lowmemory`?xb:(l.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),yb)}function Cb(e){return e==null?Sb():e===vb.DELTA?bb:e===vb.LOWMEMORY?xb:yb}var wb=Object.freeze({type:ao.DEFAULT});function Tb(e){return e?.aggregationPreference??(()=>wb)}var Eb=class extends Dr{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=Tb(t),this._aggregationTemporalitySelector=Cb(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}},Db=`otlp_http_metric_exporter`,Ob=class extends Eb{_url;constructor(e){super(Qe(Ue(e??{},`METRICS`,`v1/metrics`,{"Content-Type":`application/json`}),_c,Db,Ii,e?.selfObsMeterProvider),e),this._url=e?.url}setSelfObsMeterProvider(e){this.setMetrics(ae(Db,Ii,this._url,e))}},kb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PACKAGE_NAME=e.PACKAGE_VERSION=void 0,e.PACKAGE_VERSION=`0.39.0`,e.PACKAGE_NAME=`@opentelemetry/host-metrics`})),Ab=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaseMetrics=void 0;var n=(u(),t(d)),r=kb(),i=r.PACKAGE_NAME;e.BaseMetrics=class{_meter;_name;_metricGroups;constructor(e){n.diag.warn(`@opentelemetry/host-metrics is deprecated. Use @opentelemetry/instrumentation-host-metrics instead.`),this._name=e?.name||i;let t=e?.meterProvider??n.metrics.getMeterProvider();this._meter=t.getMeter(this._name,r.PACKAGE_VERSION),this._metricGroups=e?.metricGroups}}})),jb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SYSTEM_MEMORY_STATE_VALUE_USED=e.SYSTEM_MEMORY_STATE_VALUE_FREE=e.SYSTEM_CPU_STATE_VALUE_USER=e.SYSTEM_CPU_STATE_VALUE_SYSTEM=e.SYSTEM_CPU_STATE_VALUE_NICE=e.SYSTEM_CPU_STATE_VALUE_INTERRUPT=e.SYSTEM_CPU_STATE_VALUE_IDLE=e.PROCESS_CPU_STATE_VALUE_USER=e.PROCESS_CPU_STATE_VALUE_SYSTEM=e.NETWORK_IO_DIRECTION_VALUE_TRANSMIT=e.NETWORK_IO_DIRECTION_VALUE_RECEIVE=e.METRIC_SYSTEM_NETWORK_IO=e.METRIC_SYSTEM_NETWORK_ERRORS=e.METRIC_SYSTEM_MEMORY_UTILIZATION=e.METRIC_SYSTEM_MEMORY_USAGE=e.METRIC_SYSTEM_CPU_UTILIZATION=e.METRIC_SYSTEM_CPU_TIME=e.METRIC_PROCESS_MEMORY_USAGE=e.METRIC_PROCESS_CPU_UTILIZATION=e.METRIC_PROCESS_CPU_TIME=e.ATTR_SYSTEM_MEMORY_STATE=e.ATTR_SYSTEM_DEVICE=e.ATTR_SYSTEM_CPU_STATE=e.ATTR_SYSTEM_CPU_LOGICAL_NUMBER=e.ATTR_PROCESS_CPU_STATE=e.ATTR_NETWORK_IO_DIRECTION=void 0,e.ATTR_NETWORK_IO_DIRECTION=`network.io.direction`,e.ATTR_PROCESS_CPU_STATE=`process.cpu.state`,e.ATTR_SYSTEM_CPU_LOGICAL_NUMBER=`system.cpu.logical_number`,e.ATTR_SYSTEM_CPU_STATE=`system.cpu.state`,e.ATTR_SYSTEM_DEVICE=`system.device`,e.ATTR_SYSTEM_MEMORY_STATE=`system.memory.state`,e.METRIC_PROCESS_CPU_TIME=`process.cpu.time`,e.METRIC_PROCESS_CPU_UTILIZATION=`process.cpu.utilization`,e.METRIC_PROCESS_MEMORY_USAGE=`process.memory.usage`,e.METRIC_SYSTEM_CPU_TIME=`system.cpu.time`,e.METRIC_SYSTEM_CPU_UTILIZATION=`system.cpu.utilization`,e.METRIC_SYSTEM_MEMORY_USAGE=`system.memory.usage`,e.METRIC_SYSTEM_MEMORY_UTILIZATION=`system.memory.utilization`,e.METRIC_SYSTEM_NETWORK_ERRORS=`system.network.errors`,e.METRIC_SYSTEM_NETWORK_IO=`system.network.io`,e.NETWORK_IO_DIRECTION_VALUE_RECEIVE=`receive`,e.NETWORK_IO_DIRECTION_VALUE_TRANSMIT=`transmit`,e.PROCESS_CPU_STATE_VALUE_SYSTEM=`system`,e.PROCESS_CPU_STATE_VALUE_USER=`user`,e.SYSTEM_CPU_STATE_VALUE_IDLE=`idle`,e.SYSTEM_CPU_STATE_VALUE_INTERRUPT=`interrupt`,e.SYSTEM_CPU_STATE_VALUE_NICE=`nice`,e.SYSTEM_CPU_STATE_VALUE_SYSTEM=`system`,e.SYSTEM_CPU_STATE_VALUE_USER=`user`,e.SYSTEM_MEMORY_STATE_VALUE_FREE=`free`,e.SYSTEM_MEMORY_STATE_VALUE_USED=`used`})),Mb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getProcessMemoryData=e.getMemoryData=e.getProcessCpuUsageData=e.getCpuUsageData=void 0;var t=s(`os`),n=1/1e3,r=1/1e6,i={time:Date.now(),cpus:(0,t.cpus)()};function a(){let e=Date.now(),r=e-i.time,a={time:e,cpus:(0,t.cpus)()},o=a.cpus.map((e,t)=>{let a=i.cpus[t].times,o=e.times,s=o.idle*n,c=o.user*n,l=o.sys*n,u=o.irq*n,d=o.nice*n,f=(o.idle-a.idle)/r,p=(o.user-a.user)/r,m=(o.sys-a.sys)/r,h=(o.irq-a.irq)/r,g=(o.nice-a.nice)/r;return{cpuNumber:String(t),idle:s,user:c,system:l,interrupt:u,nice:d,userP:p,systemP:m,idleP:f,interruptP:h,niceP:g}});return i=a,o}e.getCpuUsageData=a;var o={time:Date.now(),usage:process.cpuUsage()};function c(){let e=Date.now(),t=process.cpuUsage(),n=o.usage,a=(e-o.time)*1e3*i.cpus.length,s=t.user*r,c=t.system*r,l=(t.user-n.user)/a,u=(t.system-n.system)/a;return o={time:e,usage:t},{user:s,system:c,userP:l,systemP:u}}e.getProcessCpuUsageData=c;function l(){let e=(0,t.totalmem)(),n=(0,t.freemem)(),r=e-n,i=n/e;return{used:r,free:n,usedP:r/e,freeP:i}}e.getMemoryData=l;function u(){return process.memoryUsage.rss?process.memoryUsage.rss():process.memoryUsage().rss}e.getProcessMemoryData=u})),Nb=r((e=>{var t=s(`os`),n=s(`fs`),r=s(`path`),i=s(`child_process`).spawn,a=s(`child_process`).exec,o=s(`child_process`).execSync;s(`util`);var c=process.platform,l=c===`linux`||c===`android`,u=c===`darwin`,d=c===`win32`,f=c===`freebsd`,p=c===`openbsd`,m=c===`netbsd`,h=0,g=``,_=null,v=null,y=process.env.WINDIR||`C:\\Windows`,b,x=``,S=[],C=!1,w=``,T=`$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; `,E=`--###START###--`,D=`--ERROR--`,O=`--###ENDCMD###--`,k=`--##ID##--`,A={windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})},j={maxBuffer:104857600,encoding:`UTF-8`,stdio:[`pipe`,`pipe`,`ignore`]};function ee(e){let t=parseInt(e,10);return isNaN(t)&&(t=0),t}function te(e){let t=!1,n=``,r=``;for(let i of e)i>=`0`&&i<=`9`||t?(t=!0,n+=i):r+=i;return[r,n]}var M=new String,N=new String().replace,ne=new String().toLowerCase,re=new String().toString,ie=new String().substr,ae=new String().substring,oe=new String().trim,se=new String().startsWith,ce=Math.min;function le(e){return e&&{}.toString.call(e)===`[object Function]`}function ue(e){let t=[],n={};for(let r=0;r<e.length;r++){let i=Object.keys(e[r]);i.sort((e,t)=>e-t);let a=``;for(let t=0;t<i.length;t++)a+=JSON.stringify(i[t]),a+=JSON.stringify(e[r][i[t]]);({}).hasOwnProperty.call(n,a)||(t.push(e[r]),n[a]=!0)}return t}function de(e,t){return e.sort((e,n)=>{let r=``,i=``;return t.forEach(t=>{r+=e[t],i+=n[t]}),r<i?-1:+(r>i)})}function fe(){return h===0&&(h=t.cpus().length),h}function pe(e,t,n,r,i){n||=`:`,t=t.toLowerCase(),r||=!1,i||=!1;let a=``;return e.some(e=>{let o=e.toLowerCase().replace(/\t/g,``);if(r&&(o=o.trim()),o.startsWith(t)&&(!i||o.match(t+n)||o.match(t+` `+n))){let t=r?e.trim().split(n):e.split(n);if(t.length>=2)return t.shift(),a=t.join(n).trim(),!0}return!1}),a}function me(e,t){return t||=16,e.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],t))})}function he(e){let t=``,n=0;return e.split(``).forEach(e=>{e>=`0`&&e<=`9`?n===1&&n++:(n===0&&n++,n===1&&(t+=e))}),t}function ge(e,t){t||=``,e=e.toUpperCase();let n=0,r=0,i=he(e),a=e.split(i);if(a.length>=2){a[2]&&(a[1]+=a[2]);let e=(a[1]||``).toLowerCase(),i=e.indexOf(`pm`)>-1||e.indexOf(`p.m.`)>-1||e.indexOf(`p. m.`)>-1||e.indexOf(`n`)>-1||e.indexOf(`ch`)>-1||e.indexOf(`ös`)>-1||t&&e.indexOf(t)>-1;return n=parseInt(a[0],10),r=parseInt(a[1],10),n=i&&n<12?n+12:n,(`0`+n).substr(-2)+`:`+(`0`+r).substr(-2)}}function _e(e,t){let n={date:``,time:``};t||={};let r=(t.dateFormat||``).toLowerCase(),i=t.pmDesignator||``,a=e.split(` `);if(a[0]){if(a[0].indexOf(`/`)>=0){let t=a[0].split(`/`);t.length===3&&(n.date=t[0].length===4?t[0]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[2]).substr(-2):t[2].length===2?(r.indexOf(`/d/`)>-1||r.indexOf(`/dd/`),`20`+t[2]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[0]).substr(-2)):(e.toLowerCase().indexOf(`pm`)>-1||e.toLowerCase().indexOf(`p.m.`)>-1||e.toLowerCase().indexOf(`p. m.`)>-1||e.toLowerCase().indexOf(`am`)>-1||e.toLowerCase().indexOf(`a.m.`)>-1||e.toLowerCase().indexOf(`a. m.`)>-1||r.indexOf(`/d/`)>-1||r.indexOf(`/dd/`)>-1)&&r.indexOf(`dd/`)!==0?t[2]+`-`+(`0`+t[0]).substr(-2)+`-`+(`0`+t[1]).substr(-2):t[2]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[0]).substr(-2))}if(a[0].indexOf(`.`)>=0){let e=a[0].split(`.`);e.length===3&&(n.date=r.indexOf(`.d.`)>-1||r.indexOf(`.dd.`)>-1?e[2]+`-`+(`0`+e[0]).substr(-2)+`-`+(`0`+e[1]).substr(-2):e[2]+`-`+(`0`+e[1]).substr(-2)+`-`+(`0`+e[0]).substr(-2))}if(a[0].indexOf(`-`)>=0){let e=a[0].split(`-`);e.length===3&&(n.date=e[0]+`-`+(`0`+e[1]).substr(-2)+`-`+(`0`+e[2]).substr(-2))}}return a[1]&&(a.shift(),n.time=ge(a.join(` `),i)),n}function ve(e,t){let n=t>0,r=1,i=0,a=0,o=[];for(let s=0;s<e.length;s++)r<=t?(/\s/.test(e[s])&&!n&&(a=s-1,o.push({from:i,to:a+1,cap:e.substring(i,a+1)}),i=a+2,r++),n=e[s]===` `):(!/\s/.test(e[s])&&n&&(a=s-1,i<a&&o.push({from:i,to:a,cap:e.substring(i,a)}),i=a+1,r++),n=e[s]===` `);a=5e3,o.push({from:i,to:a,cap:e.substring(i,a)});let s=o.length;for(let e=0;e<s;e++)o[e].cap.replace(/\s/g,``).length===0&&e+1<s&&(o[e].to=o[e+1].to,o[e].cap=o[e].cap+o[e+1].cap,o.splice(e+1,1),--s);return o}function ye(e,t,n){for(let r=0;r<e.length;r++)if(e[r][t]===n)return r;return-1}function be(){if(w=`powershell.exe`,d){let e=`${y}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;n.existsSync(e)&&(w=e)}}function xe(){let e=(process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH||``).replace(/["%!^&|<>`$;\r\n]/g,``);return d?`"${e}\\VBoxManage.exe"`:`vboxmanage`}function Se(e){let t=``,n,r=``;if(e.indexOf(E)>=0){n=e.split(E);let r=n[1].split(k);t=r[0],r.length>1&&(e=r.slice(1).join(k))}e.indexOf(O)>=0&&(n=e.split(O),r=n[0]);let i=-1;for(let e=0;e<S.length;e++)S[e].id===t&&(i=e,S[e].callback(r));i>=0&&S.splice(i,1)}function Ce(){b||(b=i(w,[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-Command`,`-`],{stdio:`pipe`,windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})}),b&&b.pid&&(C=!0,b.stdout.on(`data`,e=>{x+=e.toString(`utf8`);let t=x.indexOf(O);for(;t>=0;){let e=t+16;Se(x.slice(0,e)),x=x.slice(e),t=x.indexOf(O)}}),b.stderr.on(`data`,()=>{Se(x+D)}),b.on(`error`,()=>{Se(x+D)}),b.on(`close`,()=>{b&&b.kill()})))}function we(){try{b&&(b.stdin.write(`exit`+t.EOL),b.stdin.end())}catch{b&&b.kill()}C=!1,b=null}function Te(e){if(C){let n=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function i(e){r(e)}S.push({id:n,cmd:e,callback:i,start:new Date});try{b&&b.pid&&b.stdin.write(T+`echo `+E+n+`--##ID##--; `+t.EOL+e+t.EOL+`echo --###ENDCMD###--`+t.EOL)}catch{r(``)}})})}{let n=``;return new Promise(r=>{process.nextTick(()=>{try{let a=t.release().split(`.`).map(Number),o=a[0]<10?[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,`-`]:[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,T+e],s=i(w,o,{stdio:`pipe`,windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})});if(s&&!s.pid&&s.on(`error`,()=>{r(n)}),s&&s.pid){if(s.stdout.on(`data`,e=>{n+=e.toString(`utf8`)}),s.stderr.on(`data`,()=>{s.kill(),r(n)}),s.on(`close`,()=>{s.kill(),r(n)}),s.on(`error`,()=>{s.kill(),r(n)}),a[0]<10)try{s.stdin.write(T+e+t.EOL),s.stdin.write(`exit`+t.EOL),s.stdin.end()}catch{s.kill(),r(n)}}else r(n)}catch{r(n)}})})}}function Ee(e,t,n){let r=``;return n||={},new Promise(a=>{process.nextTick(()=>{try{let o=i(e,t,n);o&&!o.pid&&o.on(`error`,()=>{a(r)}),o&&o.pid?(o.stdout.on(`data`,e=>{r+=e.toString()}),o.on(`close`,()=>{o.kill(),a(r)}),o.on(`error`,()=>{o.kill(),a(r)})):a(r)}catch{a(r)}})})}function De(){if(d){if(!g)try{let e=o(`chcp`,A).toString().split(`\r
75
+ `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);if(!_g(e.headers.get(`content-type`)))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=e,i;if(t?.parsedBody===void 0)try{let t=await My(e,this._maxRequestBodySize);if(t.tooLarge){let e=Ay(this._maxRequestBodySize);return this.onerror?.(Error(e)),this.createJsonErrorResponse(413,-32e3,e)}i=JSON.parse(t.text)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else i=t.parsedBody;if(Array.isArray(i)&&i.length>ky)return this.onerror?.(Error(`Invalid Request: Batch must not exceed ${ky} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${ky} messages`);let a;try{a=Array.isArray(i)?i.map(e=>St.parse(e)):[St.parse(i)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let o=a.some(e=>Nm(e));if(o){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(a.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!o){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(this._closed)return this.createJsonErrorResponse(404,-32001,`Session not found`);let s;try{s=await this._checkScopeChallenge(a,t?.authInfo)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32603,`Internal server error`)}if(s)return s;if(!a.some(e=>Om(e))){for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=a.find(e=>Nm(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of a)Om(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,request:r})});let d=new TextEncoder,f,p,m=new ReadableStream({start:e=>{f=e},cancel:()=>{p!==void 0&&clearInterval(p),this._streamMapping.get(c)?.controller===f&&this._streamMapping.delete(c)}}),h={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(h[`mcp-session-id`]=this.sessionId);for(let e of a)Om(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{p!==void 0&&clearInterval(p),this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of a){let n,i;Om(e)&&this._eventStore&&this.supportsEmptySSEData(u)&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:r,closeSSEStream:n,closeStandaloneSSEStream:i})}return this._streamMapping.get(c)?.controller===f&&(p=this.startKeepAlive(f,d)),new Response(m,{status:200,headers:h})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((Am(e)||jm(e))&&(n=e.id),n===void 0){if(Am(e)||jm(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&(t===void 0||!n.replayedEventIds?.has(t))&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e),i=this._streamMapping.get(r)),i?.controller&&i?.encoder&&(t===void 0||!i.replayedEventIds?.has(t))&&this.writeSSEEvent(i.controller,i.encoder,e,t)}if(Am(e)||jm(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e})),i.cleanup()}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}};function Py(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function Fy(e,t,n,r,i=null){return Response.json({jsonrpc:`2.0`,error:{code:t,message:n,...r!==void 0&&{data:r}},id:i},{status:e})}function Iy(e,t=null){return Fy(e.httpStatus,e.code,e.message,e.data,t)}function Ly(e){return e instanceof Error?e:Error(String(e))}function Ry(e=null){return Fy(500,-32603,`Internal server error`,void 0,e)}function zy(e){if(e.transport!==void 0)throw Error(`The factory returned an instance that is still serving another request. Return a new instance for each request.`)}function By(e,t,n,r){return async(i,a)=>{if(i.method.toUpperCase()!==`POST`)return Fy(405,-32e3,`Method not allowed.`);try{let t=await e({era:`legacy`,...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:i}),o=new Ny({sessionIdGenerator:void 0,...n!==void 0&&{keepAliveMs:n},...r!==void 0&&{maxRequestBodySize:r}});await t.connect(o);let s=()=>{o.close().catch(()=>{}),t.close().catch(()=>{})};i.signal?.addEventListener(`abort`,s,{once:!0});let c=await o.handleRequest(i,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(c.body===null||gg(c.headers.get(`content-type`))!==`text/event-stream`)return s(),c;let l=c.body.getReader(),u=!1,d=()=>{u||(u=!0,s())},f=new ReadableStream({pull:async e=>{try{let{done:t,value:n}=await l.read();if(t){d(),e.close();return}n!==void 0&&e.enqueue(n)}catch(t){d(),e.error(t)}},cancel:e=>(d(),l.cancel(e).catch(()=>{}))});return new Response(f,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(e){try{t?.(Ly(e))}catch{}return Ry(Py(a?.parsedBody))}}}function Vy(e){return{protocolVersionHeader:e.headers.get(`mcp-protocol-version`)??void 0,mcpMethodHeader:e.headers.get(`mcp-method`)??void 0,mcpNameHeader:e.headers.get(`mcp-name`)??void 0}}async function Hy(e,t,n=!0,r=Oy){let i=e.method.toUpperCase(),a,o=t,s=e,c=!1;if(i===`POST`){if(o===void 0){n&&(s=e.clone());let t;try{let n=await My(e,r);if(n.tooLarge)return{step:`body-too-large`};t=n.text}catch{return{step:`unreadable-body`}}try{a=t.length===0?void 0:JSON.parse(t)}catch{c=!0}!c&&a!==void 0&&(o=a)}else a=o;if(c||a===void 0)return{step:`no-json-body`,forwardRequest:s}}return{step:`classified`,outcome:hh({httpMethod:i,...Vy(e),...a!==void 0&&{body:a}}),body:a,parsedBody:o,forwardRequest:s}}function Uy(e,t={}){let{legacy:n,onerror:r,responseMode:i}=t,a=jy(t.maxRequestBodySize);if(typeof n==`function`)throw TypeError(`The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.`);let o=new Set,s=!1,c=e=>{try{r?.(e)}catch{}},l=t.bus??new Av(c),u=jv(l),d=Rv({bus:l,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:c});i===`json`&&console.warn(`responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.`);let f=n===`reject`?void 0:By(e,c,t.keepAliveMs,a);async function p(n,r,a){let s=n.classification.revision;if(s===void 0||!Wf.includes(s)){let e=new Fp({supported:[...Wf],requested:s??`unknown`});return c(e),Fy(400,e.code,e.message,e.data,Py(n.message))}let l=ch({httpMethod:r.method,...Vy(r)},n);if(l!==void 0)return c(Error(`Rejected inbound request (${l.cell}): ${l.message}`)),Iy(l,Py(n.message));let u=n.messageKind===`request`?Cm(n.message.params):void 0,f=u?.[S];if(n.messageKind===`request`){let e=Rf(n.message.method);if(e!==void 0){let t=Hf(e,f);if(t!==void 0){let e=new Ip({requiredCapabilities:t});return c(e),Fy(nh(e.code,`ladder`),e.code,e.message,e.data,n.message.id)}}}let p=await e({era:`modern`,...a!==void 0&&{authInfo:a},requestInfo:r}),m=p instanceof hy?p.server:p;if(zy(m),n.messageKind===`request`&&n.message.method===`subscriptions/listen`){let e=m.getCapabilities(),t=uy(m);return p.close().catch(c),d.serve(n.message,r.signal,e,t)}if(n.messageKind===`request`&&n.message.method===`tools/call`&&p instanceof hy){let e=n.message.params,t=typeof e?.name==`string`?e.name:void 0,i=t===void 0?void 0:p.toolInputSchemaJson(t);if(i!==void 0){let t=Bm(i);if(t.valid&&t.declarations.length>0){let i=Qm(t.declarations,e?.arguments,r.headers);if(i!==void 0)return p.close().catch(c),c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),Iy(i,n.message.id)}}}if(n.messageKind===`request`&&p instanceof hy)try{let e=await Jv([n.message],a,e=>p.resolveScopeChallenge(e));if(e!==void 0)return p.close().catch(c),Xv(e,Yv(a))}catch(e){return p.close().catch(c),c(Ly(e)),Ry(n.message.id)}zy(m),cg(m,s),ly(m,Wf),u!==void 0&&cy(m,{clientInfo:u[Ct],clientCapabilities:f});let h=m.onclose;o.add(m);let g=()=>{o.delete(m),m.onclose===g&&(m.onclose=h),h?.()};m.onclose=g;try{let e=await Dy(p,n.message,{classification:n.classification,request:r,...a!==void 0&&{authInfo:a},...i!==void 0&&{responseMode:i},...t.keepAliveMs!==void 0&&{keepAliveMs:t.keepAliveMs}});return n.messageKind===`notification`&&queueMicrotask(()=>void m.close().catch(()=>{})),e}catch(e){return e instanceof Y&&e.code===J.ConnectionClosed?new Response(null,{status:499}):(await m.close().catch(()=>{}),o.delete(m),c(Ly(e)),Ry(Py(n.message)))}}async function m(e,t,n,r){if(f!==void 0)return f(t,{...n!==void 0&&{authInfo:n},...r!==void 0&&{parsedBody:r}});let i=gh(e,Wf);return i===void 0?new Response(null,{status:202}):(c(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),Iy(i,Py(r)))}async function h(e,t){let n=t?.authInfo;if(e.method.toUpperCase()===`POST`&&!_g(e.headers.get(`content-type`)))return c(Error(`Unsupported Media Type: Content-Type must be application/json`)),Fy(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let r=await Hy(e,t?.parsedBody,!0,a);if(r.step===`unreadable-body`)return Fy(400,-32700,`Parse error: the request body could not be read`);if(r.step===`body-too-large`)return Fy(413,-32e3,Ay(a));if(r.step===`no-json-body`)return f===void 0?Fy(400,-32700,`Parse error: the request body is not valid JSON`):f(r.forwardRequest,{...n!==void 0&&{authInfo:n}});let{outcome:i,body:o,parsedBody:s,forwardRequest:l}=r;try{switch(i.kind){case`reject`:return c(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),Iy(i,Py(o));case`modern`:return await p(i,e,n);case`legacy`:return await m(i,l,n,s)}}catch(e){return c(Ly(e)),Ry(Py(o))}}return{fetch:async(e,t)=>{if(s)throw Error(`This MCP handler has been closed`);try{return await h(e,t)}catch(e){return c(Ly(e)),Ry(Py(t?.parsedBody))}},notify:u,bus:l,close:async()=>{s=!0,d.closeAll();let e=[...o].map(e=>e.close().catch(()=>{}));o.clear(),await Promise.all(e)}}}var Wy=global.Request,Gy=class extends Wy{constructor(e,t){typeof e==`object`&&Yy in e&&(e=e[Yy]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Ky=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},qy=Symbol(`wrapBodyStream`),Jy=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Gy(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[qy]){let e;a.body=new ReadableStream({async pull(t){try{e||=Di.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Di.toWeb(r)}return new Gy(t,a)},Yy=Symbol(`getRequestCache`),Xy=Symbol(`requestCache`),Zy=Symbol(`incomingKey`),Qy=Symbol(`urlKey`),$y=Symbol(`headersKey`),eb=Symbol(`abortControllerKey`),tb={get method(){return this[Zy].method||`GET`},get url(){return this[Qy]},get headers(){return this[$y]||=Ky(this[Zy])},[Symbol(`getAbortController`)](){return this[Yy](),this[eb]},[Yy](){return this[eb]||=new AbortController,this[Xy]||=Jy(this.method,this[Qy],this.headers,this[Zy],this[eb])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(tb,e,{get(){return this[Yy]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(tb,e,{value:function(){return this[Yy]()[e]()}})}),Object.defineProperty(tb,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Xy]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(tb,Gy.prototype);var nb=Symbol(`responseCache`),rb=Symbol(`getResponseCache`),ib=Symbol(`cache`),ab=global.Response,ob=class e{#e;#t;[rb](){return delete this[ib],this[nb]||=new ab(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[nb];if(e){this.#t=e,this[rb]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[ib]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[ib];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[rb]().headers}get status(){return this[ib]?.[0]??this[rb]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(ob.prototype,e,{get(){return this[rb]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(ob.prototype,e,{value:function(){return this[rb]()[e]()}})}),Object.defineProperty(ob.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[nb]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(ob,ab),Object.setPrototypeOf(ob.prototype,ab.prototype),global.crypto===void 0&&(global.crypto=Ei);var sb=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name=`RequestBodyTooLargeError`}};function cb(e){if(e===void 0)return Oy;if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function lb(e,t){let n=cb(t?.maxRequestBodySize);return async(r,i,a)=>{typeof a==`function`&&(a=void 0);let o=!1,s=new AbortController;i.on(`close`,()=>{o||s.abort()}),i.destroyed===!0&&s.abort();let c;try{let t=await db(r,a,{signal:s.signal,maxRequestBodySize:n});c=await e.fetch(t,{...r.auth!==void 0&&{authInfo:r.auth},...a!==void 0&&{parsedBody:a}})}catch(e){if(e instanceof sb)c=Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:`close`}});else{try{t?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}c=pb(fb(a))}}let l={};for(let[e,t]of c.headers)l[e]=t;if(i.writeHead(c.status,l),c.body===null){o=!0,i.end();return}let u;i.on(`drain`,()=>{u?.(),u=void 0});let d=new Promise(e=>{s.signal.addEventListener(`abort`,()=>e(),{once:!0})});try{for await(let e of c.body){if(s.signal.aborted)break;i.write(e)===!1&&await Promise.race([new Promise(e=>{u=e}),d])}}catch{}o=!0,i.end()}}function ub(e){return Array.isArray(e)?e[0]:e}async function db(e,t,n){let r=cb(n?.maxRequestBodySize),i=(e.method??`GET`).toUpperCase(),a=`http://${ub(e.headers.host)??ub(e.headers[`:authority`])??`localhost`}${e.url??`/`}`,o=new Headers;for(let[t,n]of Object.entries(e.headers))if(!(n===void 0||t.startsWith(`:`))){if(Array.isArray(n))for(let e of n)o.append(t,e);else o.set(t,n)}let s;if(i!==`GET`&&i!==`HEAD`){if(t===void 0){if(Number(ub(e.headers[`content-length`]))>r)throw new sb(r);let t=new TextDecoder,n=``,i=0;for await(let a of e){if(i+=typeof a==`string`?new TextEncoder().encode(a).byteLength:a.byteLength,i>r)throw new sb(r);n+=typeof a==`string`?a:t.decode(a,{stream:!0})}n+=t.decode(),n.length>0&&(s=n)}else{let e=JSON.stringify(t);o.delete(`content-encoding`),o.delete(`transfer-encoding`),e===void 0?o.delete(`content-length`):(s=e,o.set(`content-length`,String(new TextEncoder().encode(e).byteLength)))}}return new Request(a,{method:i,headers:o,...n?.signal!==void 0&&{signal:n.signal},...s!==void 0&&{body:s}})}function fb(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let{method:t,id:n}=e;return typeof t==`string`&&(typeof n==`string`||typeof n==`number`)?n:null}function pb(e){return Response.json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:e},{status:500})}var mb=`bearer `,hb=4096;function gb(e){if(e===void 0||e.length>hb||e.slice(0,7).toLowerCase()!==mb)return;let t=e.slice(7).trim();return t.length>0?t:void 0}var _b=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=void 0;var n=(u(),t(d)),r=(oc(),t(ac)),i=(ue(),t(kt)),a=(nr(),t(Mr)),o=`otel.scope.schema_url`;function s(e){return e.replace(/\\/g,`\\\\`).replace(/\n/g,`\\n`)}function c(e=``){return typeof e!=`string`&&(e=JSON.stringify(e)),s(e).replace(/"/g,`\\"`)}var l=/[^a-z0-9_]/gi,f=/_{2,}/g;function p(e){return e.replace(l,`_`).replace(f,`_`)}function m(e,t){return!e.endsWith(`_total`)&&t.dataPointType===r.DataPointType.SUM&&t.isMonotonic&&(e+=`_total`),e}function h(e){return e===1/0?`+Inf`:e===-1/0?`-Inf`:`${e}`}function g(e){switch(e.dataPointType){case r.DataPointType.SUM:return e.isMonotonic?`counter`:`gauge`;case r.DataPointType.GAUGE:return`gauge`;case r.DataPointType.HISTOGRAM:return`histogram`;default:return`untyped`}}function _(e,t,n,r,i){let a=!1,o=``;for(let[e,n]of Object.entries(t)){let t=p(e);a=!0,o+=`${o.length>0?`,`:``}${t}="${c(n)}"`}if(i)for(let[e,t]of Object.entries(i)){let n=p(e);a=!0,o+=`${o.length>0?`,`:``}${n}="${c(t)}"`}return a&&(e+=`{${o}}`),`${e} ${h(n)}${r===void 0?``:` `+String(r)}\n`}var v=`# no registered metrics`;e.PrometheusSerializer=class{_prefix;_appendTimestamp;_additionalAttributes;_withResourceConstantLabels;_withoutScopeInfo;_withoutTargetInfo;constructor(e,t=!1,n,r,i){e&&(this._prefix=e+`_`),this._appendTimestamp=t,this._withResourceConstantLabels=n,this._withoutScopeInfo=!!i,this._withoutTargetInfo=!!r}serialize(e){let t=``;this._additionalAttributes=this._filterResourceConstantLabels(e.resource.attributes,this._withResourceConstantLabels);for(let n of e.scopeMetrics)t+=this._serializeScopeMetrics(n);return t===``&&(t+=v),this._serializeResource(e.resource)+t}_filterResourceConstantLabels(e,t){if(t){let n={};for(let[r,i]of Object.entries(e))r.match(t)&&(n[r]=i);return n}}_serializeScopeMetrics(e){let t=``;for(let n of e.metrics){let r=this._serializeMetricData(n,e.scope);r&&(t+=r+`
76
+ `)}return t}_serializeMetricData(e,t){let i=p(s(e.descriptor.name));if(this._prefix&&(i=`${this._prefix}${i}`),i===``)return n.diag.error(`Normalization for metric "${e.descriptor.name}" resulted in empty name`),``;if(i===`_`)return n.diag.error(`Normalization for metric "${e.descriptor.name}" resulted in an invalid name: "_"`),``;i[0]>=`0`&&i[0]<=`9`&&(i=`_${i}`);let c=e.dataPointType;i=m(i,e);let l=`# HELP ${i} ${s(e.descriptor.description||`description missing`)}`,u=e.descriptor.unit?`\n# UNIT ${i} ${s(e.descriptor.unit)}`:``,d=`# TYPE ${i} ${g(e)}`,f;if(this._withoutScopeInfo)f=this._additionalAttributes;else{let e={[a.ATTR_OTEL_SCOPE_NAME]:t.name};t.schemaUrl&&(e[o]=t.schemaUrl),t.version&&(e[a.ATTR_OTEL_SCOPE_VERSION]=t.version),f=Object.assign(e,this._additionalAttributes)}let h=``;switch(c){case r.DataPointType.SUM:case r.DataPointType.GAUGE:h=e.dataPoints.map(t=>this._serializeSingularDataPoint(i,e,t,f)).join(``);break;case r.DataPointType.HISTOGRAM:h=e.dataPoints.map(t=>this._serializeHistogramDataPoint(i,e,t,f)).join(``);break;default:n.diag.error(`Unrecognizable DataPointType: ${c} for metric "${i}"`)}return`${l}${u}\n${d}\n${h}`.trim()}_serializeSingularDataPoint(e,t,n,r){let a=``,{value:o,attributes:s}=n,c=(0,i.hrTimeToMilliseconds)(n.endTime);return a+=_(e,s,o,this._appendTimestamp?c:void 0,r),a}_serializeHistogramDataPoint(e,t,n,r){let a=``,o=n.attributes,s=n.value,c=(0,i.hrTimeToMilliseconds)(n.endTime);for(let t of[`count`,`sum`]){let n=s[t];n!=null&&(a+=_(e+`_`+t,o,n,this._appendTimestamp?c:void 0,r))}let l=0,u=s.buckets.counts.entries(),d=!1;for(let[t,n]of u){l+=n;let i=s.buckets.boundaries[t];if(i===void 0&&d)break;i===1/0&&(d=!0),a+=_(e+`_bucket`,o,l,this._appendTimestamp?c:void 0,Object.assign({},r,{le:i===void 0||i===1/0?`+Inf`:String(i)}))}return a}_serializeResource(e){if(this._withoutTargetInfo===!0)return``;let t=`target_info`;return`${`# HELP ${t} Target metadata`}\n${`# TYPE ${t} gauge`}\n${_(t,e.attributes,1).trim()}\n`}}})),vb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER=void 0,e.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER=`prometheus_http_text_metric_exporter`})),yb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusExporter=void 0;var n=(u(),t(d)),r=(ue(),t(kt)),i=(oc(),t(ac)),a=s(`http`),o=_b(),c=vb(),l=s(`url`);e.PrometheusExporter=class e extends i.MetricReader{static DEFAULT_OPTIONS={host:void 0,port:9464,endpoint:`/metrics`,prefix:``,appendTimestamp:!1,withResourceConstantLabels:void 0,withoutScopeInfo:!1,withoutTargetInfo:!1};_host;_port;_baseUrl;_endpoint;_server;_prefix;_appendTimestamp;_serializer;_startServerPromise;constructor(t={},r=()=>{}){super({aggregationSelector:e=>({type:i.AggregationType.DEFAULT}),aggregationTemporalitySelector:e=>i.AggregationTemporality.CUMULATIVE,otelComponentType:c.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER,metricProducers:t.metricProducers}),this._host=t.host||process.env.OTEL_EXPORTER_PROMETHEUS_HOST||e.DEFAULT_OPTIONS.host,this._port=t.port||Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT)||e.DEFAULT_OPTIONS.port,this._prefix=t.prefix||e.DEFAULT_OPTIONS.prefix,this._appendTimestamp=typeof t.appendTimestamp==`boolean`?t.appendTimestamp:e.DEFAULT_OPTIONS.appendTimestamp;let s=t.withResourceConstantLabels||e.DEFAULT_OPTIONS.withResourceConstantLabels,l=t.withoutScopeInfo||e.DEFAULT_OPTIONS.withoutScopeInfo,u=t.withoutTargetInfo||e.DEFAULT_OPTIONS.withoutTargetInfo;this._server=(0,a.createServer)(this._requestHandler).unref(),this._serializer=new o.PrometheusSerializer(this._prefix,this._appendTimestamp,s,u,l),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(t.endpoint||e.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,`/$1`),t.preventServerStart===!0?r&&queueMicrotask(r):this.startServer().then(r,e=>{n.diag.error(e),r(e)})}async onForceFlush(){}onShutdown(){return this.stopServer()}stopServer(){return this._server?new Promise(e=>{this._server.close(t=>{t?t.code!==`ERR_SERVER_NOT_RUNNING`&&(0,r.globalErrorHandler)(t):n.diag.debug(`Prometheus exporter was stopped`),e()})}):(n.diag.debug(`Prometheus stopServer() was called but server was never started.`),Promise.resolve())}startServer(){return this._startServerPromise??=new Promise((e,t)=>{this._server.once(`error`,t),this._server.listen({port:this._port,host:this._host},()=>{n.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`),e()})}),this._startServerPromise}getMetricsRequestHandler(e,t){this._exportMetrics(t)}_requestHandler=(e,t)=>{let n;try{e.url!=null&&(n=new l.URL(e.url,this._baseUrl).pathname)}catch{t.statusCode=400,t.end(`Bad Request`);return}n===this._endpoint?this._exportMetrics(t):this._notFound(t)};_exportMetrics=e=>{e.statusCode=200,e.setHeader(`content-type`,`text/plain`),this.collect().then(t=>{let{resourceMetrics:r,errors:i}=t;i.length&&n.diag.error(`PrometheusExporter: metrics collection errors`,...i),e.end(this._serializer.serialize(r))},t=>{e.end(`# failed to export metrics: ${t}`)})};_notFound=e=>{e.statusCode=404,e.end()}}})),bb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=e.PrometheusExporter=void 0;var t=yb();Object.defineProperty(e,"PrometheusExporter",{enumerable:!0,get:function(){return t.PrometheusExporter}});var n=_b();Object.defineProperty(e,"PrometheusSerializer",{enumerable:!0,get:function(){return n.PrometheusSerializer}})})),xb;(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`,e[e.LOWMEMORY=2]=`LOWMEMORY`})(xb||={}),ue(),oc(),u();var Sb=()=>Li.CUMULATIVE,Cb=e=>{switch(e){case K.COUNTER:case K.OBSERVABLE_COUNTER:case K.GAUGE:case K.HISTOGRAM:case K.OBSERVABLE_GAUGE:return Li.DELTA;case K.UP_DOWN_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:return Li.CUMULATIVE}},wb=e=>{switch(e){case K.COUNTER:case K.HISTOGRAM:return Li.DELTA;case K.GAUGE:case K.UP_DOWN_COUNTER:case K.OBSERVABLE_UP_DOWN_COUNTER:case K.OBSERVABLE_COUNTER:case K.OBSERVABLE_GAUGE:return Li.CUMULATIVE}};function Tb(){let e=(xr(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`)??`cumulative`).toLowerCase();return e===`cumulative`?Sb:e===`delta`?Cb:e===`lowmemory`?wb:(l.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),Sb)}function Eb(e){return e==null?Tb():e===xb.DELTA?Cb:e===xb.LOWMEMORY?wb:Sb}var Db=Object.freeze({type:ao.DEFAULT});function Ob(e){return e?.aggregationPreference??(()=>Db)}var kb=class extends Dr{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=Ob(t),this._aggregationTemporalitySelector=Eb(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}},Ab=`otlp_http_metric_exporter`,jb=class extends kb{_url;constructor(e){super(Qe(Ue(e??{},`METRICS`,`v1/metrics`,{"Content-Type":`application/json`}),_c,Ab,Ii,e?.selfObsMeterProvider),e),this._url=e?.url}setSelfObsMeterProvider(e){this.setMetrics(ae(Ab,Ii,this._url,e))}},Mb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PACKAGE_NAME=e.PACKAGE_VERSION=void 0,e.PACKAGE_VERSION=`0.39.0`,e.PACKAGE_NAME=`@opentelemetry/host-metrics`})),Nb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaseMetrics=void 0;var n=(u(),t(d)),r=Mb(),i=r.PACKAGE_NAME;e.BaseMetrics=class{_meter;_name;_metricGroups;constructor(e){n.diag.warn(`@opentelemetry/host-metrics is deprecated. Use @opentelemetry/instrumentation-host-metrics instead.`),this._name=e?.name||i;let t=e?.meterProvider??n.metrics.getMeterProvider();this._meter=t.getMeter(this._name,r.PACKAGE_VERSION),this._metricGroups=e?.metricGroups}}})),Pb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SYSTEM_MEMORY_STATE_VALUE_USED=e.SYSTEM_MEMORY_STATE_VALUE_FREE=e.SYSTEM_CPU_STATE_VALUE_USER=e.SYSTEM_CPU_STATE_VALUE_SYSTEM=e.SYSTEM_CPU_STATE_VALUE_NICE=e.SYSTEM_CPU_STATE_VALUE_INTERRUPT=e.SYSTEM_CPU_STATE_VALUE_IDLE=e.PROCESS_CPU_STATE_VALUE_USER=e.PROCESS_CPU_STATE_VALUE_SYSTEM=e.NETWORK_IO_DIRECTION_VALUE_TRANSMIT=e.NETWORK_IO_DIRECTION_VALUE_RECEIVE=e.METRIC_SYSTEM_NETWORK_IO=e.METRIC_SYSTEM_NETWORK_ERRORS=e.METRIC_SYSTEM_MEMORY_UTILIZATION=e.METRIC_SYSTEM_MEMORY_USAGE=e.METRIC_SYSTEM_CPU_UTILIZATION=e.METRIC_SYSTEM_CPU_TIME=e.METRIC_PROCESS_MEMORY_USAGE=e.METRIC_PROCESS_CPU_UTILIZATION=e.METRIC_PROCESS_CPU_TIME=e.ATTR_SYSTEM_MEMORY_STATE=e.ATTR_SYSTEM_DEVICE=e.ATTR_SYSTEM_CPU_STATE=e.ATTR_SYSTEM_CPU_LOGICAL_NUMBER=e.ATTR_PROCESS_CPU_STATE=e.ATTR_NETWORK_IO_DIRECTION=void 0,e.ATTR_NETWORK_IO_DIRECTION=`network.io.direction`,e.ATTR_PROCESS_CPU_STATE=`process.cpu.state`,e.ATTR_SYSTEM_CPU_LOGICAL_NUMBER=`system.cpu.logical_number`,e.ATTR_SYSTEM_CPU_STATE=`system.cpu.state`,e.ATTR_SYSTEM_DEVICE=`system.device`,e.ATTR_SYSTEM_MEMORY_STATE=`system.memory.state`,e.METRIC_PROCESS_CPU_TIME=`process.cpu.time`,e.METRIC_PROCESS_CPU_UTILIZATION=`process.cpu.utilization`,e.METRIC_PROCESS_MEMORY_USAGE=`process.memory.usage`,e.METRIC_SYSTEM_CPU_TIME=`system.cpu.time`,e.METRIC_SYSTEM_CPU_UTILIZATION=`system.cpu.utilization`,e.METRIC_SYSTEM_MEMORY_USAGE=`system.memory.usage`,e.METRIC_SYSTEM_MEMORY_UTILIZATION=`system.memory.utilization`,e.METRIC_SYSTEM_NETWORK_ERRORS=`system.network.errors`,e.METRIC_SYSTEM_NETWORK_IO=`system.network.io`,e.NETWORK_IO_DIRECTION_VALUE_RECEIVE=`receive`,e.NETWORK_IO_DIRECTION_VALUE_TRANSMIT=`transmit`,e.PROCESS_CPU_STATE_VALUE_SYSTEM=`system`,e.PROCESS_CPU_STATE_VALUE_USER=`user`,e.SYSTEM_CPU_STATE_VALUE_IDLE=`idle`,e.SYSTEM_CPU_STATE_VALUE_INTERRUPT=`interrupt`,e.SYSTEM_CPU_STATE_VALUE_NICE=`nice`,e.SYSTEM_CPU_STATE_VALUE_SYSTEM=`system`,e.SYSTEM_CPU_STATE_VALUE_USER=`user`,e.SYSTEM_MEMORY_STATE_VALUE_FREE=`free`,e.SYSTEM_MEMORY_STATE_VALUE_USED=`used`})),Fb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getProcessMemoryData=e.getMemoryData=e.getProcessCpuUsageData=e.getCpuUsageData=void 0;var t=s(`os`),n=1/1e3,r=1/1e6,i={time:Date.now(),cpus:(0,t.cpus)()};function a(){let e=Date.now(),r=e-i.time,a={time:e,cpus:(0,t.cpus)()},o=a.cpus.map((e,t)=>{let a=i.cpus[t].times,o=e.times,s=o.idle*n,c=o.user*n,l=o.sys*n,u=o.irq*n,d=o.nice*n,f=(o.idle-a.idle)/r,p=(o.user-a.user)/r,m=(o.sys-a.sys)/r,h=(o.irq-a.irq)/r,g=(o.nice-a.nice)/r;return{cpuNumber:String(t),idle:s,user:c,system:l,interrupt:u,nice:d,userP:p,systemP:m,idleP:f,interruptP:h,niceP:g}});return i=a,o}e.getCpuUsageData=a;var o={time:Date.now(),usage:process.cpuUsage()};function c(){let e=Date.now(),t=process.cpuUsage(),n=o.usage,a=(e-o.time)*1e3*i.cpus.length,s=t.user*r,c=t.system*r,l=(t.user-n.user)/a,u=(t.system-n.system)/a;return o={time:e,usage:t},{user:s,system:c,userP:l,systemP:u}}e.getProcessCpuUsageData=c;function l(){let e=(0,t.totalmem)(),n=(0,t.freemem)(),r=e-n,i=n/e;return{used:r,free:n,usedP:r/e,freeP:i}}e.getMemoryData=l;function u(){return process.memoryUsage.rss?process.memoryUsage.rss():process.memoryUsage().rss}e.getProcessMemoryData=u})),Ib=r((e=>{var t=s(`os`),n=s(`fs`),r=s(`path`),i=s(`child_process`).spawn,a=s(`child_process`).exec,o=s(`child_process`).execSync;s(`util`);var c=process.platform,l=c===`linux`||c===`android`,u=c===`darwin`,d=c===`win32`,f=c===`freebsd`,p=c===`openbsd`,m=c===`netbsd`,h=0,g=``,_=null,v=null,y=process.env.WINDIR||`C:\\Windows`,b,x=``,S=[],C=!1,w=``,T=`$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; `,E=`--###START###--`,D=`--ERROR--`,O=`--###ENDCMD###--`,k=`--##ID##--`,A={windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})},j={maxBuffer:104857600,encoding:`UTF-8`,stdio:[`pipe`,`pipe`,`ignore`]};function ee(e){let t=parseInt(e,10);return isNaN(t)&&(t=0),t}function te(e){let t=!1,n=``,r=``;for(let i of e)i>=`0`&&i<=`9`||t?(t=!0,n+=i):r+=i;return[r,n]}var M=new String,N=new String().replace,ne=new String().toLowerCase,re=new String().toString,ie=new String().substr,ae=new String().substring,oe=new String().trim,se=new String().startsWith,ce=Math.min;function le(e){return e&&{}.toString.call(e)===`[object Function]`}function ue(e){let t=[],n={};for(let r=0;r<e.length;r++){let i=Object.keys(e[r]);i.sort((e,t)=>e-t);let a=``;for(let t=0;t<i.length;t++)a+=JSON.stringify(i[t]),a+=JSON.stringify(e[r][i[t]]);({}).hasOwnProperty.call(n,a)||(t.push(e[r]),n[a]=!0)}return t}function de(e,t){return e.sort((e,n)=>{let r=``,i=``;return t.forEach(t=>{r+=e[t],i+=n[t]}),r<i?-1:+(r>i)})}function fe(){return h===0&&(h=t.cpus().length),h}function pe(e,t,n,r,i){n||=`:`,t=t.toLowerCase(),r||=!1,i||=!1;let a=``;return e.some(e=>{let o=e.toLowerCase().replace(/\t/g,``);if(r&&(o=o.trim()),o.startsWith(t)&&(!i||o.match(t+n)||o.match(t+` `+n))){let t=r?e.trim().split(n):e.split(n);if(t.length>=2)return t.shift(),a=t.join(n).trim(),!0}return!1}),a}function me(e,t){return t||=16,e.replace(/\\x([0-9A-Fa-f]{2})/g,function(){return String.fromCharCode(parseInt(arguments[1],t))})}function he(e){let t=``,n=0;return e.split(``).forEach(e=>{e>=`0`&&e<=`9`?n===1&&n++:(n===0&&n++,n===1&&(t+=e))}),t}function ge(e,t){t||=``,e=e.toUpperCase();let n=0,r=0,i=he(e),a=e.split(i);if(a.length>=2){a[2]&&(a[1]+=a[2]);let e=(a[1]||``).toLowerCase(),i=e.indexOf(`pm`)>-1||e.indexOf(`p.m.`)>-1||e.indexOf(`p. m.`)>-1||e.indexOf(`n`)>-1||e.indexOf(`ch`)>-1||e.indexOf(`ös`)>-1||t&&e.indexOf(t)>-1;return n=parseInt(a[0],10),r=parseInt(a[1],10),n=i&&n<12?n+12:n,(`0`+n).substr(-2)+`:`+(`0`+r).substr(-2)}}function _e(e,t){let n={date:``,time:``};t||={};let r=(t.dateFormat||``).toLowerCase(),i=t.pmDesignator||``,a=e.split(` `);if(a[0]){if(a[0].indexOf(`/`)>=0){let t=a[0].split(`/`);t.length===3&&(n.date=t[0].length===4?t[0]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[2]).substr(-2):t[2].length===2?(r.indexOf(`/d/`)>-1||r.indexOf(`/dd/`),`20`+t[2]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[0]).substr(-2)):(e.toLowerCase().indexOf(`pm`)>-1||e.toLowerCase().indexOf(`p.m.`)>-1||e.toLowerCase().indexOf(`p. m.`)>-1||e.toLowerCase().indexOf(`am`)>-1||e.toLowerCase().indexOf(`a.m.`)>-1||e.toLowerCase().indexOf(`a. m.`)>-1||r.indexOf(`/d/`)>-1||r.indexOf(`/dd/`)>-1)&&r.indexOf(`dd/`)!==0?t[2]+`-`+(`0`+t[0]).substr(-2)+`-`+(`0`+t[1]).substr(-2):t[2]+`-`+(`0`+t[1]).substr(-2)+`-`+(`0`+t[0]).substr(-2))}if(a[0].indexOf(`.`)>=0){let e=a[0].split(`.`);e.length===3&&(n.date=r.indexOf(`.d.`)>-1||r.indexOf(`.dd.`)>-1?e[2]+`-`+(`0`+e[0]).substr(-2)+`-`+(`0`+e[1]).substr(-2):e[2]+`-`+(`0`+e[1]).substr(-2)+`-`+(`0`+e[0]).substr(-2))}if(a[0].indexOf(`-`)>=0){let e=a[0].split(`-`);e.length===3&&(n.date=e[0]+`-`+(`0`+e[1]).substr(-2)+`-`+(`0`+e[2]).substr(-2))}}return a[1]&&(a.shift(),n.time=ge(a.join(` `),i)),n}function ve(e,t){let n=t>0,r=1,i=0,a=0,o=[];for(let s=0;s<e.length;s++)r<=t?(/\s/.test(e[s])&&!n&&(a=s-1,o.push({from:i,to:a+1,cap:e.substring(i,a+1)}),i=a+2,r++),n=e[s]===` `):(!/\s/.test(e[s])&&n&&(a=s-1,i<a&&o.push({from:i,to:a,cap:e.substring(i,a)}),i=a+1,r++),n=e[s]===` `);a=5e3,o.push({from:i,to:a,cap:e.substring(i,a)});let s=o.length;for(let e=0;e<s;e++)o[e].cap.replace(/\s/g,``).length===0&&e+1<s&&(o[e].to=o[e+1].to,o[e].cap=o[e].cap+o[e+1].cap,o.splice(e+1,1),--s);return o}function ye(e,t,n){for(let r=0;r<e.length;r++)if(e[r][t]===n)return r;return-1}function be(){if(w=`powershell.exe`,d){let e=`${y}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;n.existsSync(e)&&(w=e)}}function xe(){let e=(process.env.VBOX_INSTALL_PATH||process.env.VBOX_MSI_INSTALL_PATH||``).replace(/["%!^&|<>`$;\r\n]/g,``);return d?`"${e}\\VBoxManage.exe"`:`vboxmanage`}function Se(e){let t=``,n,r=``;if(e.indexOf(E)>=0){n=e.split(E);let r=n[1].split(k);t=r[0],r.length>1&&(e=r.slice(1).join(k))}e.indexOf(O)>=0&&(n=e.split(O),r=n[0]);let i=-1;for(let e=0;e<S.length;e++)S[e].id===t&&(i=e,S[e].callback(r));i>=0&&S.splice(i,1)}function Ce(){b||(b=i(w,[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-Command`,`-`],{stdio:`pipe`,windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})}),b&&b.pid&&(C=!0,b.stdout.on(`data`,e=>{x+=e.toString(`utf8`);let t=x.indexOf(O);for(;t>=0;){let e=t+16;Se(x.slice(0,e)),x=x.slice(e),t=x.indexOf(O)}}),b.stderr.on(`data`,()=>{Se(x+D)}),b.on(`error`,()=>{Se(x+D)}),b.on(`close`,()=>{b&&b.kill()})))}function we(){try{b&&(b.stdin.write(`exit`+t.EOL),b.stdin.end())}catch{b&&b.kill()}C=!1,b=null}function Te(e){if(C){let n=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function i(e){r(e)}S.push({id:n,cmd:e,callback:i,start:new Date});try{b&&b.pid&&b.stdin.write(T+`echo `+E+n+`--##ID##--; `+t.EOL+e+t.EOL+`echo --###ENDCMD###--`+t.EOL)}catch{r(``)}})})}{let n=``;return new Promise(r=>{process.nextTick(()=>{try{let a=t.release().split(`.`).map(Number),o=a[0]<10?[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,`-`]:[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,T+e],s=i(w,o,{stdio:`pipe`,windowsHide:!0,maxBuffer:104857600,encoding:`UTF-8`,env:Object.assign({},process.env,{LANG:`en_US.UTF-8`})});if(s&&!s.pid&&s.on(`error`,()=>{r(n)}),s&&s.pid){if(s.stdout.on(`data`,e=>{n+=e.toString(`utf8`)}),s.stderr.on(`data`,()=>{s.kill(),r(n)}),s.on(`close`,()=>{s.kill(),r(n)}),s.on(`error`,()=>{s.kill(),r(n)}),a[0]<10)try{s.stdin.write(T+e+t.EOL),s.stdin.write(`exit`+t.EOL),s.stdin.end()}catch{s.kill(),r(n)}}else r(n)}catch{r(n)}})})}}function Ee(e,t,n){let r=``;return n||={},new Promise(a=>{process.nextTick(()=>{try{let o=i(e,t,n);o&&!o.pid&&o.on(`error`,()=>{a(r)}),o&&o.pid?(o.stdout.on(`data`,e=>{r+=e.toString()}),o.on(`close`,()=>{o.kill(),a(r)}),o.on(`error`,()=>{o.kill(),a(r)})):a(r)}catch{a(r)}})})}function De(){if(d){if(!g)try{let e=o(`chcp`,A).toString().split(`\r
77
77
  `)[0].split(`:`);g=e.length>1?e[1].replace(`.`,``).trim():``}catch{g=`437`}return g}if(l||u||f||p||m){if(!g)try{let e=o(`echo $LANG`,j).toString().split(`\r
78
78
  `)[0].split(`.`);g=e.length>1?e[1].trim():``,g||=`UTF-8`}catch{g=`UTF-8`}return g}}function Oe(){if(_!==null)return _;if(_=!1,d)try{let e=o(`WHERE smartctl 2>nul`,A).toString().split(`\r
79
79
  `);_=e&&e.length?e[0].indexOf(`:\\`)>=0:!1}catch{_=!1}if(l||u||f||p||m)try{_=o(`which smartctl 2>/dev/null`,j).toString().split(`\r
@@ -84,7 +84,7 @@ return fn.apply(this, arguments)
84
84
  `),v=e}catch{return!1}let t=We(e);return t.type===`4B`||t.type===`CM4`||t.type===`CM4S`||t.type===`400`?`VideoCore VI`:t.type===`5`||t.type===`500`?`VideoCore VII`:`VideoCore IV`}function Ke(e){let t=e.map(e=>new Promise(t=>{let n=[,,];e.then(e=>{n[0]=e}).catch(e=>{n[1]=e}).then(()=>{t(n)})})),n=[],r=[];return Promise.all(t).then(e=>(e.forEach(e=>{e[1]?(n.push(e[1]),r.push(null)):(n.push(null),r.push(e[0]))}),{errors:n,results:r}))}function qe(e){return function(){let t=Array.prototype.slice.call(arguments);return new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e.apply(null,t)})}}function Je(e){return function(){let t=Array.prototype.slice.call(arguments);return new Promise(n=>{t.push((e,t)=>{n(t)}),e.apply(null,t)})}}function Ye(){let e=``;if(l)try{e=o(`uname -v`,j).toString()}catch{e=``}return e}function Xe(e){let t=[`array`,`dict`,`key`,`string`,`integer`,`date`,`real`,`data`,`boolean`,`arrayEmpty`],n=e.indexOf(`<plist version`),r=e.length;for(;e[n]!==`>`&&n<r;)n++;let i=0,a=!1,o=!1,s=!1,c=[{tagStart:``,tagEnd:``,tagContent:``,key:``,data:null}],l=``,u=e[n];for(;n<r;)l=u,n+1<r&&(u=e[n+1]),l===`<`?(o=!1,u===`/`?s=!0:c[i].tagStart?(c[i].tagContent=``,c[i].data||(c[i].data=c[i].tagStart===`array`?[]:{}),i++,c.push({tagStart:``,tagEnd:``,tagContent:``,key:null,data:null}),a=!0,o=!1):a||=!0):l===`>`?(c[i].tagStart===`true/`&&(a=!1,s=!0,c[i].tagStart=``,c[i].tagEnd=`/boolean`,c[i].data=!0),c[i].tagStart===`false/`&&(a=!1,s=!0,c[i].tagStart=``,c[i].tagEnd=`/boolean`,c[i].data=!1),c[i].tagStart===`array/`&&(a=!1,s=!0,c[i].tagStart=``,c[i].tagEnd=`/arrayEmpty`,c[i].data=[]),o&&=!1,a&&(a=!1,o=!0,c[i].tagStart===`array`&&(c[i].data=[]),c[i].tagStart===`dict`&&(c[i].data={})),s&&(s=!1,c[i].tagEnd&&t.indexOf(c[i].tagEnd.substr(1))>=0&&(c[i].tagEnd===`/dict`||c[i].tagEnd===`/array`?(i>1&&c[i-2].tagStart===`array`&&c[i-2].data.push(c[i-1].data),i>1&&c[i-2].tagStart===`dict`&&!at(c[i-1].key)&&(c[i-2].data[c[i-1].key]=c[i-1].data),i--,c.pop(),c[i].tagContent=``,c[i].tagStart=``,c[i].tagEnd=``):(c[i].tagEnd===`/key`&&c[i].tagContent?c[i].key=c[i].tagContent:(c[i].tagEnd===`/real`&&c[i].tagContent&&(c[i].data=parseFloat(c[i].tagContent)||0),c[i].tagEnd===`/integer`&&c[i].tagContent&&(c[i].data=parseInt(c[i].tagContent)||0),c[i].tagEnd===`/string`&&c[i].tagContent&&(c[i].data=c[i].tagContent||``),c[i].tagEnd===`/boolean`&&(c[i].data=c[i].tagContent||!1),c[i].tagEnd===`/arrayEmpty`&&(c[i].data=c[i].tagContent||[]),i>0&&c[i-1].tagStart===`array`&&c[i-1].data.push(c[i].data),i>0&&c[i-1].tagStart===`dict`&&!at(c[i].key)&&(c[i-1].data[c[i].key]=c[i].data)),c[i].tagContent=``,c[i].tagStart=``,c[i].tagEnd=``)),c[i].tagEnd=``,a=!1,o=!1)):(a&&(c[i].tagStart+=l),s&&(c[i].tagEnd+=l),o&&(c[i].tagContent+=l)),n++;return c[0].data}function Ze(e){return typeof e==`string`&&!isNaN(e)&&!isNaN(parseFloat(e))}function Qe(e){let t=e.split(`
85
85
  `);for(let e=0;e<t.length;e++){if(t[e].indexOf(` = `)>=0){let n=t[e].split(` = `);if(n[0]=n[0].trim(),n[0].startsWith(`"`)||(n[0]=`"`+n[0]+`"`),n[1]=n[1].trim(),n[1].indexOf(`"`)===-1&&n[1].endsWith(`;`)){let e=n[1].substring(0,n[1].length-1);Ze(e)||(n[1]=`"${e}";`)}if(n[1].indexOf(`"`)>=0&&n[1].endsWith(`;`)){let e=n[1].substring(0,n[1].length-1).replace(/"/g,``);Ze(e)&&(n[1]=`${e};`)}t[e]=n.join(` : `)}t[e]=t[e].replace(/\(/g,`[`).replace(/\)/g,`]`).replace(/;/g,`,`).trim(),t[e].startsWith(`}`)&&t[e-1]&&t[e-1].endsWith(`,`)&&(t[e-1]=t[e-1].substring(0,t[e-1].length-1))}e=t.join(``);let n={};try{n=JSON.parse(e)}catch{}return n}function $e(e,t){let n=0,r=e.split(`.`).map(e=>parseInt(e,10)||0),i=t.split(`.`).map(e=>parseInt(e,10)||0);return r[0]<i[0]?n=1:r[0]>i[0]?n=-1:r[0]===i[0]&&r.length>=2&&i.length>=2&&(r[1]<i[1]?n=1:r[1]>i[1]?n=-1:r[1]===i[1]&&(r.length>=3&&i.length>=3?r[2]<i[2]?n=1:r[2]>i[2]&&(n=-1):i.length>=3&&(n=1))),n}function et(e){let t=[{key:`Mac17,9`,name:`MacBook Pro`,size:`14-inch`,processor:`M5 Pro`,year:`2026`,additional:``},{key:`Mac17,8`,name:`MacBook Pro`,size:`16-inch`,processor:`M5 Pro`,year:`2026`,additional:``},{key:`Mac17,7`,name:`MacBook Pro`,size:`14-inch`,processor:`M5 Max`,year:`2026`,additional:``},{key:`Mac17,6`,name:`MacBook Pro`,size:`16-inch`,processor:`M5 Max`,year:`2026`,additional:``},{key:`Mac17,5`,name:`MacBook Pro`,size:`16-inch`,processor:`M5 Pro`,year:`2026`,additional:``},{key:`Mac17,4`,name:`MacBook Pro`,size:`14-inch`,processor:`M5 Pro`,year:`2026`,additional:``},{key:`Mac17,1`,name:`MacBook Neo`,size:`14-inch`,processor:`A18 Pro`,year:`2026`,additional:``},{key:`Mac17,3`,name:`MacBook Pro`,size:`16-inch`,processor:`M5`,year:`2025`,additional:``},{key:`Mac17,2`,name:`MacBook Pro`,size:`14-inch`,processor:`M5`,year:`2025`,additional:``},{key:`Mac16,13`,name:`MacBook Air`,size:`15-inch`,processor:`M4`,year:`2025`,additional:``},{key:`Mac16,12`,name:`MacBook Air`,size:`13-inch`,processor:`M4`,year:`2025`,additional:``},{key:`Mac15,13`,name:`MacBook Air`,size:`15-inch`,processor:`M3`,year:`2024`,additional:``},{key:`Mac15,12`,name:`MacBook Air`,size:`13-inch`,processor:`M3`,year:`2024`,additional:``},{key:`Mac14,15`,name:`MacBook Air`,size:`15-inch`,processor:`M2`,year:`2024`,additional:``},{key:`Mac14,2`,name:`MacBook Air`,size:`13-inch`,processor:`M2`,year:`2022`,additional:``},{key:`MacBookAir10,1`,name:`MacBook Air`,size:`13-inch`,processor:`M1`,year:`2020`,additional:``},{key:`MacBookAir9,1`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`2020`,additional:``},{key:`MacBookAir8,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`2019`,additional:``},{key:`MacBookAir8,1`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`2018`,additional:``},{key:`MacBookAir7,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`2017`,additional:``},{key:`MacBookAir7,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`Early 2015`,additional:``},{key:`MacBookAir7,1`,name:`MacBook Air`,size:`11-inch`,processor:``,year:`Early 2015`,additional:``},{key:`MacBookAir6,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`Early 2014`,additional:``},{key:`MacBookAir6,1`,name:`MacBook Air`,size:`11-inch`,processor:``,year:`Early 2014`,additional:``},{key:`MacBookAir6,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`Mid 2013`,additional:``},{key:`MacBookAir6,1`,name:`MacBook Air`,size:`11-inch`,processor:``,year:`Mid 2013`,additional:``},{key:`MacBookAir5,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`Mid 2012`,additional:``},{key:`MacBookAir5,1`,name:`MacBook Air`,size:`11-inch`,processor:``,year:`Mid 2012`,additional:``},{key:`MacBookAir4,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`Mid 2011`,additional:``},{key:`MacBookAir4,1`,name:`MacBook Air`,size:`11-inch`,processor:``,year:`Mid 2011`,additional:``},{key:`MacBookAir3,2`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`Late 2010`,additional:``},{key:`MacBookAir3,1`,name:`MacBook Air`,size:`11-inch`,processor:``,year:`Late 2010`,additional:``},{key:`MacBookAir2,1`,name:`MacBook Air`,size:`13-inch`,processor:``,year:`Mid 2009`,additional:``},{key:`Mac16,1`,name:`MacBook Pro`,size:`14-inch`,processor:`M4`,year:`2024`,additional:``},{key:`Mac16,6`,name:`MacBook Pro`,size:`14-inch`,processor:`M4 Pro`,year:`2024`,additional:``},{key:`Mac16,8`,name:`MacBook Pro`,size:`14-inch`,processor:`M4 Max`,year:`2024`,additional:``},{key:`Mac16,5`,name:`MacBook Pro`,size:`16-inch`,processor:`M4 Pro`,year:`2024`,additional:``},{key:`Mac16,6`,name:`MacBook Pro`,size:`16-inch`,processor:`M4 Max`,year:`2024`,additional:``},{key:`Mac15,3`,name:`MacBook Pro`,size:`14-inch`,processor:`M3`,year:`Nov 2023`,additional:``},{key:`Mac15,6`,name:`MacBook Pro`,size:`14-inch`,processor:`M3 Pro`,year:`Nov 2023`,additional:``},{key:`Mac15,8`,name:`MacBook Pro`,size:`14-inch`,processor:`M3 Pro`,year:`Nov 2023`,additional:``},{key:`Mac15,10`,name:`MacBook Pro`,size:`14-inch`,processor:`M3 Max`,year:`Nov 2023`,additional:``},{key:`Mac15,7`,name:`MacBook Pro`,size:`16-inch`,processor:`M3 Pro`,year:`Nov 2023`,additional:``},{key:`Mac15,9`,name:`MacBook Pro`,size:`16-inch`,processor:`M3 Pro`,year:`Nov 2023`,additional:``},{key:`Mac15,11`,name:`MacBook Pro`,size:`16-inch`,processor:`M3 Max`,year:`Nov 2023`,additional:``},{key:`Mac14,5`,name:`MacBook Pro`,size:`14-inch`,processor:`M2 Max`,year:`2023`,additional:``},{key:`Mac14,9`,name:`MacBook Pro`,size:`14-inch`,processor:`M2 Max`,year:`2023`,additional:``},{key:`Mac14,6`,name:`MacBook Pro`,size:`16-inch`,processor:`M2 Max`,year:`2023`,additional:``},{key:`Mac14,10`,name:`MacBook Pro`,size:`16-inch`,processor:`M2 Max`,year:`2023`,additional:``},{key:`Mac14,7`,name:`MacBook Pro`,size:`13-inch`,processor:`M2`,year:`2022`,additional:``},{key:`MacBookPro18,3`,name:`MacBook Pro`,size:`14-inch`,processor:`M1 Pro`,year:`2021`,additional:``},{key:`MacBookPro18,4`,name:`MacBook Pro`,size:`14-inch`,processor:`M1 Max`,year:`2021`,additional:``},{key:`MacBookPro18,1`,name:`MacBook Pro`,size:`16-inch`,processor:`M1 Pro`,year:`2021`,additional:``},{key:`MacBookPro18,2`,name:`MacBook Pro`,size:`16-inch`,processor:`M1 Max`,year:`2021`,additional:``},{key:`MacBookPro17,1`,name:`MacBook Pro`,size:`13-inch`,processor:`M1`,year:`2020`,additional:``},{key:`MacBookPro16,3`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2020`,additional:`Two Thunderbolt 3 ports`},{key:`MacBookPro16,2`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2020`,additional:`Four Thunderbolt 3 ports`},{key:`MacBookPro16,1`,name:`MacBook Pro`,size:`16-inch`,processor:``,year:`2019`,additional:``},{key:`MacBookPro16,4`,name:`MacBook Pro`,size:`16-inch`,processor:``,year:`2019`,additional:``},{key:`MacBookPro15,3`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`2019`,additional:``},{key:`MacBookPro15,2`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2019`,additional:``},{key:`MacBookPro15,1`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`2019`,additional:``},{key:`MacBookPro15,4`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2019`,additional:`Two Thunderbolt 3 ports`},{key:`MacBookPro15,1`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`2018`,additional:``},{key:`MacBookPro15,2`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2018`,additional:`Four Thunderbolt 3 ports`},{key:`MacBookPro14,1`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2017`,additional:`Two Thunderbolt 3 ports`},{key:`MacBookPro14,2`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2017`,additional:`Four Thunderbolt 3 ports`},{key:`MacBookPro14,3`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`2017`,additional:``},{key:`MacBookPro13,1`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2016`,additional:`Two Thunderbolt 3 ports`},{key:`MacBookPro13,2`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`2016`,additional:`Four Thunderbolt 3 ports`},{key:`MacBookPro13,3`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`2016`,additional:``},{key:`MacBookPro11,4`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Mid 2015`,additional:``},{key:`MacBookPro11,5`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Mid 2015`,additional:``},{key:`MacBookPro12,1`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`Early 2015`,additional:``},{key:`MacBookPro11,2`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Late 2013`,additional:``},{key:`MacBookPro11,3`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Late 2013`,additional:``},{key:`MacBookPro11,1`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`Late 2013`,additional:``},{key:`MacBookPro10,1`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Mid 2012`,additional:``},{key:`MacBookPro10,2`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`Late 2012`,additional:``},{key:`MacBookPro9,1`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Mid 2012`,additional:``},{key:`MacBookPro9,2`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`Mid 2012`,additional:``},{key:`MacBookPro8,3`,name:`MacBook Pro`,size:`17-inch`,processor:``,year:`Early 2011`,additional:``},{key:`MacBookPro8,2`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Early 2011`,additional:``},{key:`MacBookPro8,1`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`Early 2011`,additional:``},{key:`MacBookPro6,1`,name:`MacBook Pro`,size:`17-inch`,processor:``,year:`Mid 2010`,additional:``},{key:`MacBookPro6,2`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Mid 2010`,additional:``},{key:`MacBookPro7,1`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`Mid 2010`,additional:``},{key:`MacBookPro5,2`,name:`MacBook Pro`,size:`17-inch`,processor:``,year:`Early 2009`,additional:``},{key:`MacBookPro5,3`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Mid 2009`,additional:``},{key:`MacBookPro5,5`,name:`MacBook Pro`,size:`13-inch`,processor:``,year:`Mid 2009`,additional:``},{key:`MacBookPro5,1`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Late 2008`,additional:``},{key:`MacBookPro4,1`,name:`MacBook Pro`,size:`15-inch`,processor:``,year:`Early 2008`,additional:``},{key:`MacBook10,1`,name:`MacBook`,size:`12-inch`,processor:``,year:`2017`,additional:``},{key:`MacBook9,1`,name:`MacBook`,size:`12-inch`,processor:``,year:`Early 2016`,additional:``},{key:`MacBook8,1`,name:`MacBook`,size:`12-inch`,processor:``,year:`Early 2015`,additional:``},{key:`MacBook7,1`,name:`MacBook`,size:`13-inch`,processor:``,year:`Mid 2010`,additional:``},{key:`MacBook6,1`,name:`MacBook`,size:`13-inch`,processor:``,year:`Late 2009`,additional:``},{key:`MacBook5,2`,name:`MacBook`,size:`13-inch`,processor:``,year:`Early 2009`,additional:``},{key:`Mac14,13`,name:`Mac Studio`,size:``,processor:`M2 Max`,year:`2023`,additional:``},{key:`Mac14,14`,name:`Mac Studio`,size:``,processor:`M2 Ultra`,year:`2023`,additional:``},{key:`Mac15,14`,name:`Mac Studio`,size:``,processor:`M3 Ultra`,year:`2025`,additional:``},{key:`Mac16,9`,name:`Mac Studio`,size:``,processor:`M4 Max`,year:`2025`,additional:``},{key:`Mac13,1`,name:`Mac Studio`,size:``,processor:`M1 Max`,year:`2022`,additional:``},{key:`Mac13,2`,name:`Mac Studio`,size:``,processor:`M1 Ultra`,year:`2022`,additional:``},{key:`Mac16,11`,name:`Mac mini`,size:``,processor:`M4 Pro`,year:`2024`,additional:``},{key:`Mac16,10`,name:`Mac mini`,size:``,processor:`M4`,year:`2024`,additional:``},{key:`Mac14,3`,name:`Mac mini`,size:``,processor:`M2`,year:`2023`,additional:``},{key:`Mac14,12`,name:`Mac mini`,size:``,processor:`M2 Pro`,year:`2023`,additional:``},{key:`Macmini9,1`,name:`Mac mini`,size:``,processor:`M1`,year:`2020`,additional:``},{key:`Macmini8,1`,name:`Mac mini`,size:``,processor:``,year:`Late 2018`,additional:``},{key:`Macmini7,1`,name:`Mac mini`,size:``,processor:``,year:`Late 2014`,additional:``},{key:`Macmini6,1`,name:`Mac mini`,size:``,processor:``,year:`Late 2012`,additional:``},{key:`Macmini6,2`,name:`Mac mini`,size:``,processor:``,year:`Late 2012`,additional:``},{key:`Macmini5,1`,name:`Mac mini`,size:``,processor:``,year:`Mid 2011`,additional:``},{key:`Macmini5,2`,name:`Mac mini`,size:``,processor:``,year:`Mid 2011`,additional:``},{key:`Macmini4,1`,name:`Mac mini`,size:``,processor:``,year:`Mid 2010`,additional:``},{key:`Macmini3,1`,name:`Mac mini`,size:``,processor:``,year:`Early 2009`,additional:``},{key:`Mac16,3`,name:`iMac`,size:`24-inch`,processor:`M4`,year:`2024`,additional:`Four ports`},{key:`Mac16,2`,name:`iMac`,size:`24-inch`,processor:`M4`,year:`2024`,additional:`Two ports`},{key:`Mac15,5`,name:`iMac`,size:`24-inch`,processor:`M3`,year:`2023`,additional:`Four ports`},{key:`Mac15,4`,name:`iMac`,size:`24-inch`,processor:`M3`,year:`2023`,additional:`Two ports`},{key:`iMac21,1`,name:`iMac`,size:`24-inch`,processor:`M1`,year:`2021`,additional:``},{key:`iMac21,2`,name:`iMac`,size:`24-inch`,processor:`M1`,year:`2021`,additional:``},{key:`iMac20,1`,name:`iMac`,size:`27-inch`,processor:``,year:`2020`,additional:`Retina 5K`},{key:`iMac20,2`,name:`iMac`,size:`27-inch`,processor:``,year:`2020`,additional:`Retina 5K`},{key:`iMac19,1`,name:`iMac`,size:`27-inch`,processor:``,year:`2019`,additional:`Retina 5K`},{key:`iMac19,2`,name:`iMac`,size:`21.5-inch`,processor:``,year:`2019`,additional:`Retina 4K`},{key:`iMacPro1,1`,name:`iMac Pro`,size:``,processor:``,year:`2017`,additional:``},{key:`iMac18,3`,name:`iMac`,size:`27-inch`,processor:``,year:`2017`,additional:`Retina 5K`},{key:`iMac18,2`,name:`iMac`,size:`21.5-inch`,processor:``,year:`2017`,additional:`Retina 4K`},{key:`iMac18,1`,name:`iMac`,size:`21.5-inch`,processor:``,year:`2017`,additional:``},{key:`iMac17,1`,name:`iMac`,size:`27-inch`,processor:``,year:`Late 2015`,additional:`Retina 5K`},{key:`iMac16,2`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Late 2015`,additional:`Retina 4K`},{key:`iMac16,1`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Late 2015`,additional:``},{key:`iMac15,1`,name:`iMac`,size:`27-inch`,processor:``,year:`Late 2014`,additional:`Retina 5K`},{key:`iMac14,4`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Mid 2014`,additional:``},{key:`iMac14,2`,name:`iMac`,size:`27-inch`,processor:``,year:`Late 2013`,additional:``},{key:`iMac14,1`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Late 2013`,additional:``},{key:`iMac13,2`,name:`iMac`,size:`27-inch`,processor:``,year:`Late 2012`,additional:``},{key:`iMac13,1`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Late 2012`,additional:``},{key:`iMac12,2`,name:`iMac`,size:`27-inch`,processor:``,year:`Mid 2011`,additional:``},{key:`iMac12,1`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Mid 2011`,additional:``},{key:`iMac11,3`,name:`iMac`,size:`27-inch`,processor:``,year:`Mid 2010`,additional:``},{key:`iMac11,2`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Mid 2010`,additional:``},{key:`iMac10,1`,name:`iMac`,size:`21.5-inch`,processor:``,year:`Late 2009`,additional:``},{key:`iMac9,1`,name:`iMac`,size:`20-inch`,processor:``,year:`Early 2009`,additional:``},{key:`Mac14,8`,name:`Mac Pro`,size:``,processor:``,year:`2023`,additional:``},{key:`Mac14,8`,name:`Mac Pro`,size:``,processor:``,year:`2023`,additional:`Rack`},{key:`MacPro7,1`,name:`Mac Pro`,size:``,processor:``,year:`2019`,additional:``},{key:`MacPro7,1`,name:`Mac Pro`,size:``,processor:``,year:`2019`,additional:`Rack`},{key:`MacPro6,1`,name:`Mac Pro`,size:``,processor:``,year:`Late 2013`,additional:``},{key:`MacPro5,1`,name:`Mac Pro`,size:``,processor:``,year:`Mid 2012`,additional:``},{key:`MacPro5,1`,name:`Mac Pro Server`,size:``,processor:``,year:`Mid 2012`,additional:`Server`},{key:`MacPro5,1`,name:`Mac Pro`,size:``,processor:``,year:`Mid 2010`,additional:``},{key:`MacPro5,1`,name:`Mac Pro Server`,size:``,processor:``,year:`Mid 2010`,additional:`Server`},{key:`MacPro4,1`,name:`Mac Pro`,size:``,processor:``,year:`Early 2009`,additional:``}].filter(t=>t.key===e);if(t.length===0)return{key:e,model:`Apple`,version:`Unknown`};let n=[];return t[0].size&&n.push(t[0].size),t[0].processor&&n.push(t[0].processor),t[0].year&&n.push(t[0].year),t[0].additional&&n.push(t[0].additional),{key:e,model:t[0].name,version:t[0].name+` (`+n.join(`, `)+`)`}}function tt(e,t=5e3){let n=e.startsWith(`https:`)||e.indexOf(`:443/`)>0||e.indexOf(`:8443/`)>0?s(`https`):s(`http`),r=Date.now();return new Promise(i=>{let a=n.get(e,t=>{t.on(`data`,()=>{}),t.on(`end`,()=>{i({url:e,statusCode:t.statusCode,message:t.statusMessage,time:Date.now()-r})})}).on(`error`,t=>{i({url:e,statusCode:404,message:t.message,time:Date.now()-r})}).setTimeout(t,()=>{a.destroy(),i({url:e,statusCode:408,message:`Request Timeout`,time:Date.now()-r})})})}function nt(e){return e.replace(/To Be Filled By O.E.M./g,``)}function rt(e,t){return e.split(`
86
86
  `).filter(e=>e.includes(t)).join(`
87
- `)}function it(){}function at(e){return e===`__proto__`||e===`constructor`||e===`prototype`}e.toInt=ee,e.splitByNumber=te,e.execOptsWin=A,e.execOptsLinux=j,e.getCodepage=De,e.execWin=je,e.isFunction=le,e.unique=ue,e.sortByKey=de,e.cores=fe,e.getValue=pe,e.decodeEscapeSequence=me,e.parseDateTime=_e,e.parseHead=ve,e.findObjectByKey=ye,e.darwinXcodeExists=Me,e.getVboxmanage=xe,e.powerShell=Te,e.powerShellStart=Ce,e.powerShellRelease=we,e.execSafe=Ee,e.nanoSeconds=Ne,e.countUniqueLines=Pe,e.countLines=Fe,e.noop=it,e.isRaspberry=ke,e.isRaspbian=Ae,e.sanitizeShellString=Ie,e.sanitizeContainerID=Le,e.sanitizeImageID=ze,e.isPrototypePolluted=Be,e.sanitizeString=Ve,e.sanitizeDriveLetter=Re,e.decodePiCpuinfo=We,e.getRpiGpu=Ge,e.promiseAll=Ke,e.promisify=qe,e.promisifySave=Je,e.smartMonToolsInstalled=Oe,e.linuxVersion=Ye,e.plistParser=Xe,e.plistReader=Qe,e.stringObj=M,e.stringReplace=N,e.stringToLower=ne,e.stringToString=re,e.stringSubstr=ie,e.stringSubstring=ae,e.stringTrim=oe,e.stringStartWith=se,e.mathMin=ce,e.WINDIR=y,e.getFilesInPath=Ue,e.semverCompare=$e,e.getAppleModel=et,e.checkWebsite=tt,e.cleanString=nt,e.grep=rt,e.getPowershell=be})),Pb=r((e=>{var t=s(`os`),n=s(`child_process`).exec,r=s(`child_process`).execSync,i=s(`child_process`).execFileSync,a=s(`fs`).readFileSync,o=s(`fs`),c=Nb(),l=process.platform,u=l===`linux`||l===`android`,d=l===`darwin`,f=l===`win32`,p=l===`freebsd`,m=l===`openbsd`,h=l===`netbsd`,g=l===`sunos`,_=Object.create(null),v=``,y={},b=[],x=[],S={},C;function w(){let e=``,n=``;try{let i=t.networkInterfaces(),a=9999;for(let t in i)({}).hasOwnProperty.call(i,t)&&i[t].forEach(r=>{r&&r.internal===!1&&(n||=t,r.scopeid&&r.scopeid<a&&(e=t,a=r.scopeid))});if(e=e||n||``,f){let n=``;if(r(`netstat -r`,c.execOptsWin).toString().split(t.EOL).forEach(e=>{if(e=e.replace(/\s+/g,` `).trim(),e.indexOf(`0.0.0.0 0.0.0.0`)>-1&&!/[a-zA-Z]/.test(e)){let t=e.split(` `);t.length>=5&&(n=t[t.length-2])}}),n)for(let t in i)({}).hasOwnProperty.call(i,t)&&i[t].forEach(r=>{r&&r.address&&r.address===n&&(e=t)})}if(u){let t=r(`ip route 2> /dev/null | grep default`,c.execOptsLinux).toString().split(`
87
+ `)}function it(){}function at(e){return e===`__proto__`||e===`constructor`||e===`prototype`}e.toInt=ee,e.splitByNumber=te,e.execOptsWin=A,e.execOptsLinux=j,e.getCodepage=De,e.execWin=je,e.isFunction=le,e.unique=ue,e.sortByKey=de,e.cores=fe,e.getValue=pe,e.decodeEscapeSequence=me,e.parseDateTime=_e,e.parseHead=ve,e.findObjectByKey=ye,e.darwinXcodeExists=Me,e.getVboxmanage=xe,e.powerShell=Te,e.powerShellStart=Ce,e.powerShellRelease=we,e.execSafe=Ee,e.nanoSeconds=Ne,e.countUniqueLines=Pe,e.countLines=Fe,e.noop=it,e.isRaspberry=ke,e.isRaspbian=Ae,e.sanitizeShellString=Ie,e.sanitizeContainerID=Le,e.sanitizeImageID=ze,e.isPrototypePolluted=Be,e.sanitizeString=Ve,e.sanitizeDriveLetter=Re,e.decodePiCpuinfo=We,e.getRpiGpu=Ge,e.promiseAll=Ke,e.promisify=qe,e.promisifySave=Je,e.smartMonToolsInstalled=Oe,e.linuxVersion=Ye,e.plistParser=Xe,e.plistReader=Qe,e.stringObj=M,e.stringReplace=N,e.stringToLower=ne,e.stringToString=re,e.stringSubstr=ie,e.stringSubstring=ae,e.stringTrim=oe,e.stringStartWith=se,e.mathMin=ce,e.WINDIR=y,e.getFilesInPath=Ue,e.semverCompare=$e,e.getAppleModel=et,e.checkWebsite=tt,e.cleanString=nt,e.grep=rt,e.getPowershell=be})),Lb=r((e=>{var t=s(`os`),n=s(`child_process`).exec,r=s(`child_process`).execSync,i=s(`child_process`).execFileSync,a=s(`fs`).readFileSync,o=s(`fs`),c=Ib(),l=process.platform,u=l===`linux`||l===`android`,d=l===`darwin`,f=l===`win32`,p=l===`freebsd`,m=l===`openbsd`,h=l===`netbsd`,g=l===`sunos`,_=Object.create(null),v=``,y={},b=[],x=[],S={},C;function w(){let e=``,n=``;try{let i=t.networkInterfaces(),a=9999;for(let t in i)({}).hasOwnProperty.call(i,t)&&i[t].forEach(r=>{r&&r.internal===!1&&(n||=t,r.scopeid&&r.scopeid<a&&(e=t,a=r.scopeid))});if(e=e||n||``,f){let n=``;if(r(`netstat -r`,c.execOptsWin).toString().split(t.EOL).forEach(e=>{if(e=e.replace(/\s+/g,` `).trim(),e.indexOf(`0.0.0.0 0.0.0.0`)>-1&&!/[a-zA-Z]/.test(e)){let t=e.split(` `);t.length>=5&&(n=t[t.length-2])}}),n)for(let t in i)({}).hasOwnProperty.call(i,t)&&i[t].forEach(r=>{r&&r.address&&r.address===n&&(e=t)})}if(u){let t=r(`ip route 2> /dev/null | grep default`,c.execOptsLinux).toString().split(`
88
88
  `)[0].split(/\s+/);t[0]===`none`&&t[5]?e=t[5]:t[4]&&(e=t[4]),e.indexOf(`:`)>-1&&(e=e.split(`:`)[1].trim())}if(d||p||m||h||g){let t=``;u&&(t=`ip route 2> /dev/null | grep default | awk '{print $5}'`),d&&(t=`route -n get default 2>/dev/null | grep interface: | awk '{print $2}'`),(p||m||h||g)&&(t=`route get 0.0.0.0 | grep interface:`),e=r(t).toString().split(`
89
89
  `)[0],e.indexOf(`:`)>-1&&(e=e.split(`:`)[1].trim())}}catch{c.noop()}return e&&(v=e),v}e.getDefaultNetworkInterface=w;function T(){let e=``,t=``,n={};if(u||p||m||h){if(C===void 0)try{let e=r(`which ip`,c.execOptsLinux).toString().split(`
90
90
  `);C=e.length&&e[0].indexOf(`:`)===-1&&e[0].indexOf(`/`)===0?e[0]:``}catch{C=``}try{let i=r(`export LC_ALL=C; `+(C?C+` link show up`:`/sbin/ifconfig`)+`; unset LC_ALL`,c.execOptsLinux).toString().split(`
@@ -141,7 +141,7 @@ Profile on interface`)}catch(e){return e.status===1&&e.stdout.includes(`AutoConf
141
141
  `),a=(t&&t[0]?t[0]:``).split(` via `);a&&a[1]&&(a=a[1].split(` `),i=a[0]),e&&e(i),r(i)}})}catch{e&&e(i),r(i)}if(d){let t=`route -n get default`;try{n(t,{maxBuffer:104857600},(a,o)=>{if(!a){let e=o.toString().split(`
142
142
  `).map(e=>e.trim());i=c.getValue(e,`gateway`)}i?(e&&e(i),r(i)):(t=`netstat -rn | awk '/default/ {print $2}'`,n(t,{maxBuffer:104857600},(t,n)=>{i=n.toString().split(`
143
143
  `).map(e=>e.trim()).find(e=>/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(e)),e&&e(i),r(i)}))})}catch{e&&e(i),r(i)}}if(f)try{n(`netstat -r`,c.execOptsWin,(n,a)=>{a.toString().split(t.EOL).forEach(e=>{if(e=e.replace(/\s+/g,` `).trim(),e.indexOf(`0.0.0.0 0.0.0.0`)>-1&&!/[a-zA-Z]/.test(e)){let t=e.split(` `);t.length>=5&&t[t.length-3].indexOf(`.`)>-1&&(i=t[t.length-3])}}),i?(e&&e(i),r(i)):c.powerShell(`Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0' }`).then(t=>{let n=t.toString().split(`\r
144
- `);n.length>1&&!i&&(i=c.getValue(n,`NextHop`),e&&e(i),r(i))})})}catch{e&&e(i),r(i)}})})}e.networkGatewayDefault=ye})),Fb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getNetworkData=void 0;var t=Pb();function n(){return new Promise(e=>{(0,t.networkStats)().then(e).catch(()=>{e([])})})}e.getNetworkData=n})),Ib=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=void 0;var t=Ab(),n=jb(),r=Mb(),i=Fb();e.HostMetrics=class extends t.BaseMetrics{_batchUpdateCpuUsages(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._cpuTime,i.user,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.system,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.idle,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.interrupt,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.nice,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.userP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.systemP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.idleP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.interruptP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.niceP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber})}}_batchUpdateProcessCpuUsages(e,t){e.observe(this._processCpuTime,t.user,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuTime,t.system,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM}),e.observe(this._processCpuUtilization,t.userP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuUtilization,t.systemP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM})}_batchUpdateMemUsages(e,t){e.observe(this._memoryUsage,t.used,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUsage,t.free,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE}),e.observe(this._memoryUtilization,t.usedP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUtilization,t.freeP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE})}_batchUpdateProcessMemUsage(e,t){e.observe(this._processMemoryUsage,t)}_batchUpdateNetworkData(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._networkDropped,i.rx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkDropped,i.tx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkErrors,i.rx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkErrors,i.tx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkIo,i.rx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkIo,i.tx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT})}}_createMetrics(){let e=[],t=!this._metricGroups||this._metricGroups.includes(`system.cpu`),a=!this._metricGroups||this._metricGroups.includes(`system.memory`),o=!this._metricGroups||this._metricGroups.includes(`system.network`),s=!this._metricGroups||this._metricGroups.includes(`process.cpu`),c=!this._metricGroups||this._metricGroups.includes(`process.memory`);t&&(this._cpuTime=this._meter.createObservableCounter(n.METRIC_SYSTEM_CPU_TIME,{description:`Cpu time in seconds`,unit:`s`}),e.push(this._cpuTime),this._cpuUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_CPU_UTILIZATION,{description:`Cpu usage time 0-1`}),e.push(this._cpuUtilization)),a&&(this._memoryUsage=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_USAGE,{description:`Memory usage in bytes`}),e.push(this._memoryUsage),this._memoryUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_UTILIZATION,{description:`Memory usage 0-1`}),e.push(this._memoryUtilization)),o&&(this._networkDropped=this._meter.createObservableCounter(`system.network.dropped`,{description:`Network dropped packets`}),e.push(this._networkDropped),this._networkErrors=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_ERRORS,{description:`Network errors counter`}),e.push(this._networkErrors),this._networkIo=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_IO,{description:`Network transmit and received bytes`}),e.push(this._networkIo)),s&&(this._processCpuTime=this._meter.createObservableCounter(n.METRIC_PROCESS_CPU_TIME,{description:`Process Cpu time in seconds`,unit:`s`}),e.push(this._processCpuTime),this._processCpuUtilization=this._meter.createObservableGauge(n.METRIC_PROCESS_CPU_UTILIZATION,{description:`Process Cpu usage time 0-1`}),e.push(this._processCpuUtilization)),c&&(this._processMemoryUsage=this._meter.createObservableGauge(n.METRIC_PROCESS_MEMORY_USAGE,{description:`Process Memory usage in bytes`}),e.push(this._processMemoryUsage)),this._meter.addBatchObservableCallback(async e=>{if(t){let t=(0,r.getCpuUsageData)();this._batchUpdateCpuUsages(e,t)}if(a){let t=(0,r.getMemoryData)();this._batchUpdateMemUsages(e,t)}if(s){let t=(0,r.getProcessCpuUsageData)();this._batchUpdateProcessCpuUsages(e,t)}if(c){let t=(0,r.getProcessMemoryData)();this._batchUpdateProcessMemUsage(e,t)}if(o){let t=await(0,i.getNetworkData)();this._batchUpdateNetworkData(e,t)}},e)}start(){this._createMetrics()}_cpuTime;_cpuUtilization;_memoryUsage;_memoryUtilization;_processCpuTime;_processCpuUtilization;_processMemoryUsage;_networkDropped;_networkErrors;_networkIo}})),Lb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=e.BaseMetrics=void 0;var t=Ab();Object.defineProperty(e,"BaseMetrics",{enumerable:!0,get:function(){return t.BaseMetrics}});var n=Ib();Object.defineProperty(e,"HostMetrics",{enumerable:!0,get:function(){return n.HostMetrics}})})),Rb=_b(),zb=Lb(),Bb=`bearer `,Vb=4096;function Hb(e){if(e===void 0||e.length>Vb||e.slice(0,7).toLowerCase()!==Bb)return;let t=e.slice(7).trim();return t.length>0?t:void 0}u(),C(),oc();var Ub=`aventure-mcp-server`,Wb=`http_server_requests_seconds`,Gb=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],Kb,qb,Jb,Yb,Xb;function Zb(e,t){if(qb!==void 0)return;let n=e?new Rb.PrometheusExporter({preventServerStart:!0}):void 0,r=new rc({resource:yt({...Rr(),"service.version":process.env.GIT_SHA??process.env.SENTRY_RELEASE??Hr().version}),readers:[...n===void 0?[]:[n],...t===void 0?[]:[new Eo({exporter:new Ob({url:t}),exportIntervalMillis:1e4,exportTimeoutMillis:5e3})]]});a.setGlobalMeterProvider(r),qb=r,Kb=n;let i=new zb.HostMetrics({meterProvider:r,name:Ub});i.start(),Xb=i}function Qb(){return Jb===void 0&&(Jb=qb?.getMeter(Ub)),Jb}function $b(e,t,n,r,{rpcMethod:i,toolName:a}){let o=Qb();o!==void 0&&(Yb===void 0&&(Yb=o.createHistogram(Wb,{description:`HTTP server request latency in seconds, partitioned by method/route/status/rpc_method/tool.`,unit:`s`,advice:{explicitBucketBoundaries:Gb}})),Yb.record(r/1e3,{method:e.toUpperCase(),route:t,status:String(n),rpc_method:i,tool:a}))}function ex(e,t){let n=Hr().registry===``&&!!t,r=process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?.trim()||void 0;if(!n&&r===void 0)return;Zb(n,r);let i=Kb;if(!n||t===void 0||i===void 0)return;let a=Ni(`sha256`).update(t).digest();e.get(`/metrics`,(e,t,n)=>{if(!nx(e.headers.authorization,a)){t.status(401).type(`text/plain`).send(`Unauthorized`);return}n()},(e,t)=>{i.getMetricsRequestHandler(e,t)})}async function tx(){let e=qb;Xb!==void 0&&(Xb=void 0),qb=void 0,Kb=void 0,Jb=void 0,Yb=void 0,e!==void 0&&await e.shutdown()}function nx(e,t){let n=Hb(e);if(n===void 0)return!1;let r=Ni(`sha256`).update(n).digest();return r.length===t.length&&Fi(r,t)}var rx=`#/components/schemas/`,ix=/"#\/components\/schemas\/([^"]+)"/g,ax=-32011,ox=-32012,sx=-32013,cx=-32015,lx=On(wn);function ux(e){let t=lx.components.schemas[e];if(t===void 0)throw Error(`OpenAPI has no component ${e}`);return t}function dx(e){let t=A(e?.content?.[`application/json`]?.schema);return t===void 0?void 0:ux(t)}function fx(e){let t=Object.keys(e).length===1?A(e):void 0,n=t===void 0?e:ux(t),r={},i=e=>{for(let[,t]of JSON.stringify(e).matchAll(ix))t===void 0||t in r||(r[t]=ux(t),i(r[t]))};i(n);let a=Object.keys(r).length===0?n:{...n,$defs:r},o=Re.safeParse(JSON.parse(JSON.stringify(a).replaceAll(`"${rx}`,`"#/$defs/`)));if(!o.success)throw Error(`Event schema is not JSON: ${o.error}`);return o.data}function px(e,t){let n=Object.entries(lx.paths).find(([,n])=>dx(n[e]?.requestBody)?.properties?.name?.$ref===t);if(n===void 0)throw Error(`OpenAPI has no ${e} operation for ${t}`);return n[0]}var mx=new Map(Object.entries(lx.webhooks??{}).map(([e,t])=>{let n=dx(t.post.requestBody),r=n?.properties?.name?.$ref,i=n?.properties?.data;if(r===void 0||i===void 0)throw Error(`Webhook ${e} body must carry a name enum $ref and a data schema`);let a=px(`put`,r),o=dx(lx.paths[a]?.put?.requestBody)?.properties?.arguments;if(o===void 0)throw Error(`Subscribe body for ${e} must carry an arguments schema`);return[e,{descriptor:{name:e,description:t.post.description,delivery:[`webhook`],inputSchema:fx(o),payloadSchema:fx(i)},subscribePath:a,unsubscribePath:px(`delete`,r)}]})),hx=G({name:W()}).catchall(Re),gx=F(W(),Re);function _x(e){let t=mx.get(e);if(t===void 0)throw new Z(ax,`Unknown event ${e}`);return t}async function vx(e,t,n){let{_meta:r,...i}=n,a=await sr({method:e,path:t,body:i,auth:`auto`});if(a.ok){let e=gx.safeParse(a.data!==null&&typeof a.data==`object`&&`response`in a.data?a.data.response??{}:{});if(e.success)return e.data;throw new Z(X.InternalError,`${t} answered a non-object body`)}let o=yx(a.problem?.code);throw o===void 0?a.problem?.code===`news_subscription_limit`?new Z(sx,a.summary,{limit:`subscriptions`}):new Z(bx(a.httpStatus),a.summary,a.problem):new Z(cx,`CallbackEndpointError`,{reason:o})}function yx(e){switch(e){case`callback_connection_refused`:return`connection_refused`;case`callback_timeout`:return`timeout`;case`callback_tls_error`:return`tls_error`;case`callback_http_4xx`:return`http_4xx`;case`callback_http_5xx`:return`http_5xx`;case`callback_challenge_failed`:return`challenge_failed`;default:return}}function bx(e){switch(e){case 400:case 422:return X.InvalidParams;case 401:case 403:return ox;case 404:return ax;default:return X.InternalError}}function xx(e){if(mx.size===0)return;let t=[...mx.values()].map(e=>e.descriptor);e.server.setRequestHandler(`events/list`,{params:G({})},()=>({events:t})),e.server.setRequestHandler(`events/subscribe`,{params:hx},e=>vx(`PUT`,_x(e.name).subscribePath,e)),e.server.setRequestHandler(`events/unsubscribe`,{params:hx},e=>vx(`DELETE`,_x(e.name).unsubscribePath,e))}async function Sx(e){try{return await sr(e)}catch(t){return Or({component:`aventure-mcp-server`,event:`tool_request_failed`,fields:{requestId:Vn(),method:e.method},error:t}),v($t(t))}}function Cx(e,t){return t?e:e.map(wx)}function wx(e){let t=e.parameter.flatMap(Ex),n=Tx(e.requestBody);return Ox(t,e.parameter)&&n===e.requestBody?e:{...e,parameter:t,...n===void 0?{}:{requestBody:n}}}function Tx(e){if(e===void 0)return;let t=e.map(e=>{let t=e.parameter.flatMap(Ex);return Ox(t,e.parameter)?e:{...e,parameter:t}});return t.every((t,n)=>t===e[n])?e:t}function Ex(e){if(!Dx(e))return[];let t=e.itemProperty?.filter(Dx);return Ox(t,e.itemProperty)?[e]:[{...e,...t===void 0||t.length===0?{}:{itemProperty:t}}]}var Dx=e=>e.visibility!==`private`;function Ox(e,t){return e===t?!0:e?.length!==t?.length||e===void 0||t===void 0?!1:e.every((e,n)=>e===t[n])}new RegExp(Yr.join(`|`),`i`);function kx(e){let t=Ax(Hn(e)),n=wi(t.data,t.summary)??JSON.stringify(t);return{isError:!t.ok,structuredContent:t,content:[{type:`text`,text:n}]}}function Ax(e){let{omitted:t,ids:n,counts:r,references:i,warnings:a,...o}=e;return{...o,...t.length>0?{omitted:t}:{},...n.length>0?{ids:n}:{},...Object.keys(r).length>0?{counts:r}:{},...i.length>0?{references:i}:{},...a.length>0?{warnings:a}:{}}}var jx=`aventure_status`,Mx=`aventure_help`,Nx=`aventure_read`,Px=`aventure_lookup`,Fx=`aventure_search`,Ix=`aventure_write`,Lx=`aventure_delete`,Rx=[jx,Mx,Nx,Px,Fx,Ix,Lx],zx=I([W(),U(),H()]),Bx=F(W(),I([W(),U()])).optional(),Vx=F(W(),I([zx,B(zx)])).optional(),Hx=F(W(),W()).optional(),Ux=V([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Wx=I([zx,vi(),B(li()),F(W(),li())]).optional().describe(`JSON request body. For multipart/form-data operations, pass an object keyed by form part name; binary part values are http(s) URLs.`),Gx=G({operationId:W().optional().describe(`Exact OpenAPI operationId, as listed by aventure_help. Takes precedence over method and path.`),method:Ux.optional().describe(`HTTP method when resolving by method+path.`),path:W().optional().describe(`OpenAPI route template or concrete API path.`),pathParams:Bx.describe(`Values for route template parameters.`),query:Vx.describe(`Query parameters.`),headers:Hx.describe(`Headers declared by the selected OpenAPI operation.`),contentType:W().optional().describe(`Declared request media type; omit for the first supported descriptor.`),responseFormat:V([`auto`,`json`,`text`]).optional().describe(`Response format for endpoints that offer both JSON and text/plain.`)}),Kx=G({q:W().optional().describe(`Plain-English task text, ranked against operationId, path, CLI command, summary, description, and query-parameter enum values. This tool reads no argument named query. Omitting q returns the catalog head unranked.`),root:W().optional().describe(`Filter by resource or first CLI segment.`),method:Ux.optional().describe(`Filter by HTTP method.`),scope:V([`read`,`write`]).optional().describe(`Filter by required MCP auth scope.`),limit:gi().min(1).max(100).default(20).describe(`Maximum rows to return.`),resolve:H().default(!1).describe(`Resolve q to one operation with the server resolver (requires sign-in): operation advice with an mcpCall skeleton, a clarification between candidate operations, or an abstention. scope narrows it; root, method, and limit do not apply.`)}),qx=Gx.extend({body:Wx});async function Jx(e,t,n){let r=bi.find(e=>e.intent===`status`&&e.resource===`status`);if(r===void 0)return v(`No system status operation exists in the generated catalog.`);let i;try{i=j().host}catch(e){return v(e.message)}let a=await Sx({method:r.method,path:r.path,auth:r.projection.auth,requesterScope:e,signal:n});return{...a,data:{transportScope:e,permissionGrant:t?.permissionGrant,host:i,status:a.data}}}var Yx=(e,t)=>Cx(bi,t?.operationAccess===`ADMIN`||t===void 0&&e===`write`).filter(n=>(t===void 0?e===`write`||n.projection.scope===`read`&&(n.projection.auth===`read`||n.projection.auth===`none`):t.operationAccess!==`READ`||n.projection.scope===`read`||n.projection.visibility!==`private`)&&(t===void 0||t.operation.some(e=>e.operationId===n.operationId&&e.method===n.method&&e.path===n.path)));async function Xx(e,t,n,r,i,a){let o=Ti(e,r)??Zt(e);if(!o.ok)return v(o.summary,o.warnings);if(o.data===null)return v(`OpenAPI operation resolution returned no data.`);let{method:s,operation:c,path:l,template:u}=o.data,d=c.operationId,f=r.find(e=>e.operationId===d&&e.method.toLowerCase()===s&&e.path===u);if(f===void 0)return v(`Operation `+d+` is not in the MCP catalog.`);if(!t.includes(f.intent))return v(`Operation `+d+` has intent=`+f.intent+`; call aventure_`+f.intent+` `+JSON.stringify({operationId:d,pathParams:e.pathParams,query:e.query,body:e.body})+`.`);let p=qe(f.requestBody??[],e.contentType);if(!p.ok||p.data===null)return v(p.summary,p.warnings);let m=p.data;return f.intent===`delete`&&m===void 0&&e.body!==void 0?v(d+` does not accept a request body.`):await Sx({method:f.method,path:l,searchParams:e.query,headers:e.headers,body:e.body,contentType:e.contentType,auth:f.projection.auth,requesterScope:n,responseFormat:e.responseFormat,clientInfo:i,signal:a})}function Zx(e,t,n){let r=Yx(t,n),i=()=>e.server.getClientVersion();e.registerTool(jx,{title:`aVenture status`,annotations:{readOnlyHint:!0},description:`Return API status, host, MCP auth scope, and your role and permission grant. Scope write means some write is callable, not every write; aventure_help with scope write lists the writes this grant allows.`,inputSchema:G({})},async(e,r)=>kx(await Jx(t,n,r?.mcpReq.signal))),e.registerTool(Mx,{title:`aVenture help`,annotations:{readOnlyHint:!0},description:`Lists the aVenture API operations this connection may call. Each row gives operationId, method, path, CLI command, intent (the aventure_<intent> tool that runs it), required scope, request body shape, and arguments. q ranks rows against a plain-English task without calling the API. resolve asks the server to resolve q to one operation and returns the aventure_<intent> call to run it.`,inputSchema:Kx},async(e,n)=>{if(e.resolve)return kx(await Ci(t===`read`?{...e,scope:`read`}:e,r,bi,(e,r)=>Sx({method:e.method,path:br(e.operationId,{}),body:r.body,auth:e.projection.auth,requesterScope:t,responseFormat:`json`,clientInfo:i(),signal:n?.mcpReq.signal})));let{summary:a,data:o,counts:s}=Si(e,r);return kx(Ln(a,o,{counts:s}))}),e.registerTool(Nx,{title:`aVenture read`,annotations:{readOnlyHint:!0},description:`Runs one catalog operation whose intent is read: fetch a record by id or slug, list the records attached to it, or list a collection. Put route values in pathParams and URL query values in query. Example for an aventure.vc profile URL, slug, website, or domain: {"operationId":"getEntityLookup","query":{"url":"https://aventure.vc/investors/firms/<slug>"}}. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`read`],t,r,i(),n?.mcpReq.signal))),e.registerTool(Px,{title:`aVenture lookup`,annotations:{readOnlyHint:!1},description:`Runs one catalog operation whose intent is lookup: identify a record from a name plus clues (such as lookupRecord), resolve a ticker or other identifier, or run a batch, preview, or duplicate check. Most lookups are POST operations that take a JSON body. An exact aventure.vc profile URL, slug, website, or domain is a read, not a lookup: call aventure_read with operationId getEntityLookup (or getPersonLookup) and query {url} or {slug}. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`lookup`],t,r,i(),n?.mcpReq.signal))),e.registerTool(Fx,{title:`aVenture search`,annotations:{readOnlyHint:!1,destructiveHint:!1},description:`Runs one catalog operation whose intent is search: search or filter companies, people, news, publications, content, links, or the web, or answer a question. It has no free-text argument of its own: pass search text and filters where the chosen operation declares them, in query or body. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`search`],t,r,i(),n?.mcpReq.signal))),r.some(e=>e.intent===`write`)&&e.registerTool(Ix,{title:`aVenture write`,annotations:{readOnlyHint:!1,destructiveHint:!0},description:`Runs one catalog operation whose intent is write, limited to the writes your grant allows: create or change records in the shared aVenture corpus where your grant permits curation, or submit an account or enrichment request such as a billing checkout, plan change, portal session, or entity or person enrichment; aventure_help with scope write lists your writes, and each takes effect immediately. Pass the body the operation declares. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`write`],t,r,i(),n?.mcpReq.signal))),r.some(e=>e.intent===`delete`)&&e.registerTool(Lx,{title:`aVenture delete`,annotations:{readOnlyHint:!1,destructiveHint:!0},description:`Runs one catalog operation whose intent is delete: remove one record, or one link between records, from the shared aVenture corpus. A body sent to an operation that declares none is refused. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`delete`],t,r,i(),n?.mcpReq.signal)))}var Qx=Hr().version,$x={tools:{},events:{}};function eS(e,t){let n=new hy({name:`aventure-mcp-server`,title:`aVenture MCP Server`,version:Qx},{capabilities:$x,instructions:wn.info.description});return Zx(n,e,t),xx(n),n}var tS=new Set([...Ht.options,...Nt.options].map(e=>e.shape.method.value)),nS=new Set(Rx);function rS(e){let t=typeof e==`object`&&e?Reflect.get(e,`method`):void 0,n=typeof e==`object`&&e?Reflect.get(e,`params`):void 0,r=typeof n==`object`&&n?Reflect.get(n,`name`):void 0;return{rpcMethod:typeof t==`string`&&tS.has(t)?t:`other`,toolName:typeof r==`string`&&nS.has(r)?r:`none`}}var iS=bi.map(({operationId:e,method:t,path:n,parameter:r})=>({operationId:e,method:t,path:n,authorizationPath:Xn(n,Object.fromEntries(r.filter(e=>e.in===`path`).map(e=>e.schemaEnum?.[0]===void 0?e.schemaFormat===`uuid`?[e.name,Pi()]:e.schemaType===`integer`||e.schemaType===`number`?[e.name,1]:[e.name,`authorization-probe`]:[e.name,e.schemaEnum[0]])),e)})),aS={ttlMs:6e4,maxEntries:128};function oS(e){if(!e.includes(`.`))return 1/0;try{let{exp:t}=Le(e);return t===void 0?1/0:t*1e3}catch(e){if(!(e instanceof He))throw e;return 1/0}}function sS(e=aS){let t=new Map,n=(n,r)=>{let i=`${Ni(`sha256`).update(n).digest(`hex`)} ${r?.href??``}`,a=t.get(i);if(t.delete(i),a!==void 0&&a.expiresAt>Date.now())return t.set(i,a),a.verification;let o=Er(n,r,iS),s={verification:o,expiresAt:1/0};t.set(i,s);for(let n of t.keys()){if(t.size<=e.maxEntries)break;t.delete(n)}let c=()=>{t.get(i)===s&&t.delete(i)};return o.then(t=>{t===null||t===`forbidden`?c():s.expiresAt=Math.min(Date.now()+e.ttlMs,oS(n))},c),o};return async(e,t)=>{let r=Hb(e.header(`authorization`));if(r===void 0)return{ok:!1,reason:`missing_credential`,hasAuthorization:!1};try{let e=await n(r,t);if(e===`forbidden`)return{ok:!1,reason:`forbidden`,hasAuthorization:!0};if(e!==null)return{ok:!0,scope:e.operationAccess===`READ`?`read`:`write`,userBearerToken:r,authorization:e}}catch(e){if(!(e instanceof He))throw e;Kn({component:`aventure-mcp-server`,event:`invalid_bearer_jwt`,fields:{requestId:Vn()},error:e})}return{ok:!1,reason:`credential_mismatch`,hasAuthorization:!0}}}function cS(e,t){let n=`an API key from https://aventure.vc/settings/api-keys as Authorization: Bearer <key>`,r=t?`Sign in with OAuth through the authorization server in this server's resource metadata; a client that cannot register itself needs the OAuth client ID at https://docs.aventure.vc/mcp. Or send ${n}.`:`Send ${n}. This server advertises no OAuth authorization server.`;return e===`forbidden`?`The supplied credential is valid, but its account may not use this MCP server.`:e===`missing_credential`?r:`The supplied credential was rejected or expired; reconnect this server in the MCP client to sign in again. ${r}`}var lS=1024,uS=lS*lS,dS=1,fS=2,pS=`b`,mS=`kb`,hS=`mb`,gS=/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/u;function _S(e){let t=yS(e.limit),n=vS(e.path);return(r,i,a)=>{if(t===void 0||r.method!==`POST`||vS(r.path)!==n){a();return}let o=bS(r.header(`content-length`));if(o===void 0||o<=t){a();return}i.setHeader(`Connection`,`close`),e.reject(i)}}function vS(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;return t===``?`/`:t}function yS(e){if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:void 0;let t=gS.exec(e.trim().toLowerCase());if(t===null)return;let n=Number(t[dS]);if(Number.isFinite(n))switch(t[fS]??pS){case hS:return Math.floor(n*uS);case mS:return Math.floor(n*lS);case pS:return Math.floor(n)}}function bS(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}var xS=400,SS=400,CS=413,wS=`10mb`,TS=`127.0.0.1`,ES=`0.0.0.0`;async function DS(e){let t=e.jsonBodyLimit??wS,n=sS(),r=e.host??TS,i=r!==ES,a=(t,n)=>{let r=`${t.protocol}://${t.host}`;return URL.canParse(e.path,r)&&new URL(e.path,r).href===n?.resourceUrl.href?n:void 0},o=(0,Vd.default)();o.disable(`x-powered-by`),o.set(`trust proxy`,1),o.use((e,t,n)=>{let r=Pi(),i=performance.now(),a={requestId:r,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},o=AS(e);o||ln({component:`aventure-mcp-server`,event:`http_request`,fields:a}),t.on(`finish`,()=>{let n=Math.round(performance.now()-i),r=e.route,s=typeof r==`object`&&r?Reflect.get(r,`path`):null,c=rS(e.body);$b(e.method,typeof s==`string`?s:`unmatched`,t.statusCode,n,c),(t.statusCode>=xS&&!o?Kn:ln)({component:`aventure-mcp-server`,event:`http_response`,fields:{...a,...c,status:t.statusCode,durationMs:n}})}),_(r,()=>n())}),o.use(i?(0,Bd.default)({origin:kS}):(0,Bd.default)()),o.use(_S({path:e.path,limit:t,reject:e=>jS(e,CS,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),o.use(Vd.json({limit:t})),o.get(`/health`,(...e)=>{let t=e[1],n=process.env.GIT_SHA?.trim();t.setHeader(`X-Aventure-Revision`,n&&/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):`unknown`),t.status(200).json({status:`UP`})}),o.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,Bd.default)(),async(t,n,r)=>{let i=await e.resolveOAuthDiscovery();if(i===void 0){jS(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=a(t,i);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),ex(o,e.metricsScrapeSecret),o.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),o.get(`/favicon.ico`,(...e)=>{e[1].status(204).end()});let s=gf({windowMs:6e4,limit:120});return o.post(e.path,s,async(t,r)=>{let o=Vn(),s=t.header(`origin`);if(i&&!OS(s)){Kn({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:o,method:t.method,path:t.path,origin:s}}),jS(r,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let c,l;try{let r=await e.resolveOAuthDiscovery();l=a(t,r),c=await n(t,r?.resourceUrl)}catch(e){wc(e,`authentication_unavailable`),Or({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:o,method:t.method,path:t.path},error:e});let n=e instanceof tr&&(e.problem.status===429||qt(e.problem.status))?e.problem:void 0;n===void 0?jS(r,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof n.retryAfterSeconds==`number`&&r.set(`Retry-After`,String(n.retryAfterSeconds)),MS(r,n));return}if(!c.ok){Kn({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:o,method:t.method,path:t.path,reason:c.reason,hasAuthorization:c.hasAuthorization}});let e=[l===void 0?void 0:`resource_metadata="${Hv(l.resourceUrl)}"`,l===void 0?void 0:`scope="${l.client.scope.join(` `)}"`,c.reason===`credential_mismatch`?`error="invalid_token"`:void 0,c.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,c.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);r.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`),c.reason===`forbidden`?jS(r,403,`Forbidden`,cS(c.reason,l!==void 0)):jS(r,401,`Unauthorized`,cS(c.reason,l!==void 0));return}let u=t.header(`accept`)??`*/*`;if(!u.includes(`*/*`)&&(!u.includes(`application/json`)||!u.includes(`text/event-stream`))){jS(r,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}ln({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:o,method:t.method,path:t.path,scope:c.scope}});let d=[],f=e=>{wc(e,`transport_error`),Or({component:`aventure-mcp-server`,event:`transport_error`,message:$t(e),fields:{requestId:o,method:t.method,path:t.path},error:e})},p=Uy(()=>eS(c.scope,c.authorization),{onerror:e=>d.push(e),maxSubscriptions:0}),m=async()=>{await lb(p,{onerror:f})(t,r,t.body);for(let e of d)qt(r.statusCode)?f(e):(r.statusCode<xS?ln:Kn)({component:`aventure-mcp-server`,event:`mcp_request_rejected`,message:$t(e),fields:{requestId:o,method:t.method,path:t.path,status:r.statusCode}})};c.userBearerToken===void 0?await m():await In(c.userBearerToken,m)}),o.all(e.path,(...e)=>{let t=e[1];jS(t,405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)}),o.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=NS(e);if(i===void 0){r(e);return}Kn({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:Vn(),method:t.method,path:t.path,status:i.status}}),jS(n,i.status,i.status===CS?`Payload Too Large`:`Bad Request`,i.status===CS?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,n)=>{let i;i=o.listen(e.port,r,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await tx()}})}),i.on(`error`,n)})}function OS(e){if(e===void 0)return!0;if(!URL.canParse(e))return!1;let{hostname:t}=new URL(e);return t===`localhost`?!0:t.startsWith(`[`)?t===`[::1]`:ji(t)&&t.startsWith(`127.`)}var kS=(e,t)=>t(null,OS(e)),AS=e=>e.method===`GET`&&/^\/robots\.txt\/?$/iu.test(e.path);function jS(e,t,n,r){MS(e,{type:`about:blank`,title:n,status:t,detail:r})}function MS(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function NS(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?CS:e.type===`entity.parse.failed`?SS:e.status===CS||e.status===SS?e.status:void 0;return t===void 0?void 0:{status:t,message:`message`in e&&typeof e.message==`string`?e.message:`JSON body rejected`}}var PS=65535,FS=55e3,IS=Hr(ki(import.meta.url)),{host:LS}=(await new cn().name(IS.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(IS.version).option(`--host <address>`,`Bind this address instead of 127.0.0.1; 0.0.0.0 exposes the server to the network.`).addHelpText(`after`,`
144
+ `);n.length>1&&!i&&(i=c.getValue(n,`NextHop`),e&&e(i),r(i))})})}catch{e&&e(i),r(i)}})})}e.networkGatewayDefault=ye})),Rb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getNetworkData=void 0;var t=Lb();function n(){return new Promise(e=>{(0,t.networkStats)().then(e).catch(()=>{e([])})})}e.getNetworkData=n})),zb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=void 0;var t=Nb(),n=Pb(),r=Fb(),i=Rb();e.HostMetrics=class extends t.BaseMetrics{_batchUpdateCpuUsages(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._cpuTime,i.user,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.system,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.idle,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.interrupt,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.nice,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.userP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.systemP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.idleP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.interruptP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.niceP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber})}}_batchUpdateProcessCpuUsages(e,t){e.observe(this._processCpuTime,t.user,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuTime,t.system,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM}),e.observe(this._processCpuUtilization,t.userP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuUtilization,t.systemP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM})}_batchUpdateMemUsages(e,t){e.observe(this._memoryUsage,t.used,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUsage,t.free,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE}),e.observe(this._memoryUtilization,t.usedP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUtilization,t.freeP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE})}_batchUpdateProcessMemUsage(e,t){e.observe(this._processMemoryUsage,t)}_batchUpdateNetworkData(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._networkDropped,i.rx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkDropped,i.tx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkErrors,i.rx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkErrors,i.tx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkIo,i.rx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkIo,i.tx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT})}}_createMetrics(){let e=[],t=!this._metricGroups||this._metricGroups.includes(`system.cpu`),a=!this._metricGroups||this._metricGroups.includes(`system.memory`),o=!this._metricGroups||this._metricGroups.includes(`system.network`),s=!this._metricGroups||this._metricGroups.includes(`process.cpu`),c=!this._metricGroups||this._metricGroups.includes(`process.memory`);t&&(this._cpuTime=this._meter.createObservableCounter(n.METRIC_SYSTEM_CPU_TIME,{description:`Cpu time in seconds`,unit:`s`}),e.push(this._cpuTime),this._cpuUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_CPU_UTILIZATION,{description:`Cpu usage time 0-1`}),e.push(this._cpuUtilization)),a&&(this._memoryUsage=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_USAGE,{description:`Memory usage in bytes`}),e.push(this._memoryUsage),this._memoryUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_UTILIZATION,{description:`Memory usage 0-1`}),e.push(this._memoryUtilization)),o&&(this._networkDropped=this._meter.createObservableCounter(`system.network.dropped`,{description:`Network dropped packets`}),e.push(this._networkDropped),this._networkErrors=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_ERRORS,{description:`Network errors counter`}),e.push(this._networkErrors),this._networkIo=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_IO,{description:`Network transmit and received bytes`}),e.push(this._networkIo)),s&&(this._processCpuTime=this._meter.createObservableCounter(n.METRIC_PROCESS_CPU_TIME,{description:`Process Cpu time in seconds`,unit:`s`}),e.push(this._processCpuTime),this._processCpuUtilization=this._meter.createObservableGauge(n.METRIC_PROCESS_CPU_UTILIZATION,{description:`Process Cpu usage time 0-1`}),e.push(this._processCpuUtilization)),c&&(this._processMemoryUsage=this._meter.createObservableGauge(n.METRIC_PROCESS_MEMORY_USAGE,{description:`Process Memory usage in bytes`}),e.push(this._processMemoryUsage)),this._meter.addBatchObservableCallback(async e=>{if(t){let t=(0,r.getCpuUsageData)();this._batchUpdateCpuUsages(e,t)}if(a){let t=(0,r.getMemoryData)();this._batchUpdateMemUsages(e,t)}if(s){let t=(0,r.getProcessCpuUsageData)();this._batchUpdateProcessCpuUsages(e,t)}if(c){let t=(0,r.getProcessMemoryData)();this._batchUpdateProcessMemUsage(e,t)}if(o){let t=await(0,i.getNetworkData)();this._batchUpdateNetworkData(e,t)}},e)}start(){this._createMetrics()}_cpuTime;_cpuUtilization;_memoryUsage;_memoryUtilization;_processCpuTime;_processCpuUtilization;_processMemoryUsage;_networkDropped;_networkErrors;_networkIo}})),Bb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=e.BaseMetrics=void 0;var t=Nb();Object.defineProperty(e,"BaseMetrics",{enumerable:!0,get:function(){return t.BaseMetrics}});var n=zb();Object.defineProperty(e,"HostMetrics",{enumerable:!0,get:function(){return n.HostMetrics}})}));u();var Vb=bb(),Hb=Bb();C(),oc();var Ub=`aventure-mcp-server`,Wb=`http_server_requests_seconds`,Gb=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],Kb,qb,Jb,Yb,Xb;function Zb(e,t){if(qb!==void 0)return;let n=e?new Vb.PrometheusExporter({preventServerStart:!0}):void 0,r=new rc({resource:yt({...Rr(),"service.version":process.env.GIT_SHA??process.env.SENTRY_RELEASE??Hr().version}),readers:[...n===void 0?[]:[n],...t===void 0?[]:[new Eo({exporter:new jb({url:t}),exportIntervalMillis:1e4,exportTimeoutMillis:5e3})]]});a.setGlobalMeterProvider(r),qb=r,Kb=n;let i=new Hb.HostMetrics({meterProvider:r,name:Ub});i.start(),Xb=i}function Qb(){return Jb===void 0&&(Jb=qb?.getMeter(Ub)),Jb}function $b(e,t,n,r,{rpcMethod:i,toolName:a}){let o=Qb();o!==void 0&&(Yb===void 0&&(Yb=o.createHistogram(Wb,{description:`HTTP server request latency in seconds, partitioned by method/route/status/rpc_method/tool.`,unit:`s`,advice:{explicitBucketBoundaries:Gb}})),Yb.record(r/1e3,{method:e.toUpperCase(),route:t,status:String(n),rpc_method:i,tool:a}))}function ex(e,t){let n=Hr().registry===``&&!!t,r=process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?.trim()||void 0;if(!n&&r===void 0)return;Zb(n,r);let i=Kb;if(!n||t===void 0||i===void 0)return;let a=Ni(`sha256`).update(t).digest();e.get(`/metrics`,(e,t,n)=>{if(!nx(e.headers.authorization,a)){t.status(401).type(`text/plain`).send(`Unauthorized`);return}n()},(e,t)=>{i.getMetricsRequestHandler(e,t)})}async function tx(){let e=qb;Xb!==void 0&&(Xb=void 0),qb=void 0,Kb=void 0,Jb=void 0,Yb=void 0,e!==void 0&&await e.shutdown()}function nx(e,t){let n=gb(e);if(n===void 0)return!1;let r=Ni(`sha256`).update(n).digest();return r.length===t.length&&Fi(r,t)}var rx=`#/components/schemas/`,ix=/"#\/components\/schemas\/([^"]+)"/g,ax=-32011,ox=-32012,sx=-32013,cx=-32015,lx=On(wn);function ux(e){let t=lx.components.schemas[e];if(t===void 0)throw Error(`OpenAPI has no component ${e}`);return t}function dx(e){let t=A(e?.content?.[`application/json`]?.schema);return t===void 0?void 0:ux(t)}function fx(e){let t=Object.keys(e).length===1?A(e):void 0,n=t===void 0?e:ux(t),r={},i=e=>{for(let[,t]of JSON.stringify(e).matchAll(ix))t===void 0||t in r||(r[t]=ux(t),i(r[t]))};i(n);let a=Object.keys(r).length===0?n:{...n,$defs:r},o=Re.safeParse(JSON.parse(JSON.stringify(a).replaceAll(`"${rx}`,`"#/$defs/`)));if(!o.success)throw Error(`Event schema is not JSON: ${o.error}`);return o.data}function px(e,t){let n=Object.entries(lx.paths).find(([,n])=>dx(n[e]?.requestBody)?.properties?.name?.$ref===t);if(n===void 0)throw Error(`OpenAPI has no ${e} operation for ${t}`);return n[0]}var mx=new Map(Object.entries(lx.webhooks??{}).map(([e,t])=>{let n=dx(t.post.requestBody),r=n?.properties?.name?.$ref,i=n?.properties?.data;if(r===void 0||i===void 0)throw Error(`Webhook ${e} body must carry a name enum $ref and a data schema`);let a=px(`put`,r),o=dx(lx.paths[a]?.put?.requestBody)?.properties?.arguments;if(o===void 0)throw Error(`Subscribe body for ${e} must carry an arguments schema`);return[e,{descriptor:{name:e,description:t.post.description,delivery:[`webhook`],inputSchema:fx(o),payloadSchema:fx(i)},subscribePath:a,unsubscribePath:px(`delete`,r)}]})),hx=G({name:W()}).catchall(Re),gx=F(W(),Re);function _x(e){let t=mx.get(e);if(t===void 0)throw new Z(ax,`Unknown event ${e}`);return t}async function vx(e,t,n){let{_meta:r,...i}=n,a=await sr({method:e,path:t,body:i,auth:`auto`});if(a.ok){let e=gx.safeParse(a.data!==null&&typeof a.data==`object`&&`response`in a.data?a.data.response??{}:{});if(e.success)return e.data;throw new Z(X.InternalError,`${t} answered a non-object body`)}let o=yx(a.problem?.code);throw o===void 0?a.problem?.code===`news_subscription_limit`?new Z(sx,a.summary,{limit:`subscriptions`}):new Z(bx(a.httpStatus),a.summary,a.problem):new Z(cx,`CallbackEndpointError`,{reason:o})}function yx(e){switch(e){case`callback_connection_refused`:return`connection_refused`;case`callback_timeout`:return`timeout`;case`callback_tls_error`:return`tls_error`;case`callback_http_4xx`:return`http_4xx`;case`callback_http_5xx`:return`http_5xx`;case`callback_challenge_failed`:return`challenge_failed`;default:return}}function bx(e){switch(e){case 400:case 422:return X.InvalidParams;case 401:case 403:return ox;case 404:return ax;default:return X.InternalError}}function xx(e){if(mx.size===0)return;let t=[...mx.values()].map(e=>e.descriptor);e.server.setRequestHandler(`events/list`,{params:G({})},()=>({events:t})),e.server.setRequestHandler(`events/subscribe`,{params:hx},e=>vx(`PUT`,_x(e.name).subscribePath,e)),e.server.setRequestHandler(`events/unsubscribe`,{params:hx},e=>vx(`DELETE`,_x(e.name).unsubscribePath,e))}async function Sx(e){try{return await sr(e)}catch(t){return Or({component:`aventure-mcp-server`,event:`tool_request_failed`,fields:{requestId:Vn(),method:e.method},error:t}),v($t(t))}}function Cx(e,t){return t?e:e.map(wx)}function wx(e){let t=e.parameter.flatMap(Ex),n=Tx(e.requestBody);return Ox(t,e.parameter)&&n===e.requestBody?e:{...e,parameter:t,...n===void 0?{}:{requestBody:n}}}function Tx(e){if(e===void 0)return;let t=e.map(e=>{let t=e.parameter.flatMap(Ex);return Ox(t,e.parameter)?e:{...e,parameter:t}});return t.every((t,n)=>t===e[n])?e:t}function Ex(e){if(!Dx(e))return[];let t=e.itemProperty?.filter(Dx);return Ox(t,e.itemProperty)?[e]:[{...e,...t===void 0||t.length===0?{}:{itemProperty:t}}]}var Dx=e=>e.visibility!==`private`;function Ox(e,t){return e===t?!0:e?.length!==t?.length||e===void 0||t===void 0?!1:e.every((e,n)=>e===t[n])}new RegExp(Yr.join(`|`),`i`);function kx(e){let t=Ax(Hn(e)),n=wi(t.data,t.summary)??JSON.stringify(t);return{isError:!t.ok,structuredContent:t,content:[{type:`text`,text:n}]}}function Ax(e){let{omitted:t,ids:n,counts:r,references:i,warnings:a,...o}=e;return{...o,...t.length>0?{omitted:t}:{},...n.length>0?{ids:n}:{},...Object.keys(r).length>0?{counts:r}:{},...i.length>0?{references:i}:{},...a.length>0?{warnings:a}:{}}}var jx=`aventure_status`,Mx=`aventure_help`,Nx=`aventure_read`,Px=`aventure_lookup`,Fx=`aventure_search`,Ix=`aventure_write`,Lx=`aventure_delete`,Rx=[jx,Mx,Nx,Px,Fx,Ix,Lx],zx=I([W(),U(),H()]),Bx=F(W(),I([W(),U()])).optional(),Vx=F(W(),I([zx,B(zx)])).optional(),Hx=F(W(),W()).optional(),Ux=V([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Wx=I([zx,vi(),B(li()),F(W(),li())]).optional().describe(`JSON request body. For multipart/form-data operations, pass an object keyed by form part name; binary part values are http(s) URLs.`),Gx=G({operationId:W().optional().describe(`Exact OpenAPI operationId, as listed by aventure_help. Takes precedence over method and path.`),method:Ux.optional().describe(`HTTP method when resolving by method+path.`),path:W().optional().describe(`OpenAPI route template or concrete API path.`),pathParams:Bx.describe(`Values for route template parameters.`),query:Vx.describe(`Query parameters.`),headers:Hx.describe(`Headers declared by the selected OpenAPI operation.`),contentType:W().optional().describe(`Declared request media type; omit for the first supported descriptor.`),responseFormat:V([`auto`,`json`,`text`]).optional().describe(`Response format for endpoints that offer both JSON and text/plain.`)}),Kx=G({q:W().optional().describe(`Plain-English task text, ranked against operationId, path, CLI command, summary, description, and query-parameter enum values. This tool reads no argument named query. Omitting q returns the catalog head unranked.`),root:W().optional().describe(`Filter by resource or first CLI segment.`),method:Ux.optional().describe(`Filter by HTTP method.`),scope:V([`read`,`write`]).optional().describe(`Filter by required MCP auth scope.`),limit:gi().min(1).max(100).default(20).describe(`Maximum rows to return.`),resolve:H().default(!1).describe(`Resolve q to one operation with the server resolver (requires sign-in): operation advice with an mcpCall skeleton, a clarification between candidate operations, or an abstention. scope narrows it; root, method, and limit do not apply.`)}),qx=Gx.extend({body:Wx});async function Jx(e,t,n){let r=bi.find(e=>e.intent===`status`&&e.resource===`status`);if(r===void 0)return v(`No system status operation exists in the generated catalog.`);let i;try{i=j().host}catch(e){return v(e.message)}let a=await Sx({method:r.method,path:r.path,auth:r.projection.auth,requesterScope:e,signal:n});return{...a,data:{transportScope:e,permissionGrant:t?.permissionGrant,host:i,status:a.data}}}var Yx=(e,t)=>Cx(bi,t?.operationAccess===`ADMIN`||t===void 0&&e===`write`).filter(n=>(t===void 0?e===`write`||n.projection.scope===`read`&&(n.projection.auth===`read`||n.projection.auth===`none`):t.operationAccess!==`READ`||n.projection.scope===`read`||n.projection.visibility!==`private`)&&(t===void 0||t.operation.some(e=>e.operationId===n.operationId&&e.method===n.method&&e.path===n.path)));async function Xx(e,t,n,r,i,a){let o=Ti(e,r)??Zt(e);if(!o.ok)return v(o.summary,o.warnings);if(o.data===null)return v(`OpenAPI operation resolution returned no data.`);let{method:s,operation:c,path:l,template:u}=o.data,d=c.operationId,f=r.find(e=>e.operationId===d&&e.method.toLowerCase()===s&&e.path===u);if(f===void 0)return v(`Operation `+d+` is not in the MCP catalog.`);if(!t.includes(f.intent))return v(`Operation `+d+` has intent=`+f.intent+`; call aventure_`+f.intent+` `+JSON.stringify({operationId:d,pathParams:e.pathParams,query:e.query,body:e.body})+`.`);let p=qe(f.requestBody??[],e.contentType);if(!p.ok||p.data===null)return v(p.summary,p.warnings);let m=p.data;return f.intent===`delete`&&m===void 0&&e.body!==void 0?v(d+` does not accept a request body.`):await Sx({method:f.method,path:l,searchParams:e.query,headers:e.headers,body:e.body,contentType:e.contentType,auth:f.projection.auth,requesterScope:n,responseFormat:e.responseFormat,clientInfo:i,signal:a})}function Zx(e,t,n){let r=Yx(t,n),i=()=>e.server.getClientVersion();e.registerTool(jx,{title:`aVenture status`,annotations:{readOnlyHint:!0},description:`Return API status, host, MCP auth scope, and your role and permission grant. Scope write means some write is callable, not every write; aventure_help with scope write lists the writes this grant allows.`,inputSchema:G({})},async(e,r)=>kx(await Jx(t,n,r?.mcpReq.signal))),e.registerTool(Mx,{title:`aVenture help`,annotations:{readOnlyHint:!0},description:`Lists the aVenture API operations this connection may call. Each row gives operationId, method, path, CLI command, intent (the aventure_<intent> tool that runs it), required scope, request body shape, and arguments. q ranks rows against a plain-English task without calling the API. resolve asks the server to resolve q to one operation and returns the aventure_<intent> call to run it.`,inputSchema:Kx},async(e,n)=>{if(e.resolve)return kx(await Ci(t===`read`?{...e,scope:`read`}:e,r,bi,(e,r)=>Sx({method:e.method,path:br(e.operationId,{}),body:r.body,auth:e.projection.auth,requesterScope:t,responseFormat:`json`,clientInfo:i(),signal:n?.mcpReq.signal})));let{summary:a,data:o,counts:s}=Si(e,r);return kx(Ln(a,o,{counts:s}))}),e.registerTool(Nx,{title:`aVenture read`,annotations:{readOnlyHint:!0},description:`Runs one catalog operation whose intent is read: fetch a record by id or slug, list the records attached to it, or list a collection. Put route values in pathParams and URL query values in query. Example for an aventure.vc profile URL, slug, website, or domain: {"operationId":"getEntityLookup","query":{"url":"https://aventure.vc/investors/firms/<slug>"}}. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`read`],t,r,i(),n?.mcpReq.signal))),e.registerTool(Px,{title:`aVenture lookup`,annotations:{readOnlyHint:!1},description:`Runs one catalog operation whose intent is lookup: identify a record from a name plus clues (such as lookupRecord), resolve a ticker or other identifier, or run a batch, preview, or duplicate check. Most lookups are POST operations that take a JSON body. An exact aventure.vc profile URL, slug, website, or domain is a read, not a lookup: call aventure_read with operationId getEntityLookup (or getPersonLookup) and query {url} or {slug}. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`lookup`],t,r,i(),n?.mcpReq.signal))),e.registerTool(Fx,{title:`aVenture search`,annotations:{readOnlyHint:!1,destructiveHint:!1},description:`Runs one catalog operation whose intent is search: search or filter companies, people, news, publications, content, links, or the web, or answer a question. It has no free-text argument of its own: pass search text and filters where the chosen operation declares them, in query or body. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`search`],t,r,i(),n?.mcpReq.signal))),r.some(e=>e.intent===`write`)&&e.registerTool(Ix,{title:`aVenture write`,annotations:{readOnlyHint:!1,destructiveHint:!0},description:`Runs one catalog operation whose intent is write, limited to the writes your grant allows: create or change records in the shared aVenture corpus where your grant permits curation, or submit an account or enrichment request such as a billing checkout, plan change, portal session, or entity or person enrichment; aventure_help with scope write lists your writes, and each takes effect immediately. Pass the body the operation declares. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`write`],t,r,i(),n?.mcpReq.signal))),r.some(e=>e.intent===`delete`)&&e.registerTool(Lx,{title:`aVenture delete`,annotations:{readOnlyHint:!1,destructiveHint:!0},description:`Runs one catalog operation whose intent is delete: remove one record, or one link between records, from the shared aVenture corpus. A body sent to an operation that declares none is refused. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:qx},async(e,n)=>kx(await Xx(e,[`delete`],t,r,i(),n?.mcpReq.signal)))}var Qx=Hr().version,$x={tools:{},events:{}};function eS(e,t){let n=new hy({name:`aventure-mcp-server`,title:`aVenture MCP Server`,version:Qx},{capabilities:$x,instructions:wn.info.description});return Zx(n,e,t),xx(n),n}var tS=new Set([...Ht.options,...Nt.options].map(e=>e.shape.method.value)),nS=new Set(Rx);function rS(e){let t=typeof e==`object`&&e?Reflect.get(e,`method`):void 0,n=typeof e==`object`&&e?Reflect.get(e,`params`):void 0,r=typeof n==`object`&&n?Reflect.get(n,`name`):void 0;return{rpcMethod:typeof t==`string`&&tS.has(t)?t:`other`,toolName:typeof r==`string`&&nS.has(r)?r:`none`}}var iS=bi.map(({operationId:e,method:t,path:n,parameter:r})=>({operationId:e,method:t,path:n,authorizationPath:Xn(n,Object.fromEntries(r.filter(e=>e.in===`path`).map(e=>e.schemaEnum?.[0]===void 0?e.schemaFormat===`uuid`?[e.name,Pi()]:e.schemaType===`integer`||e.schemaType===`number`?[e.name,1]:[e.name,`authorization-probe`]:[e.name,e.schemaEnum[0]])),e)})),aS={ttlMs:6e4,maxEntries:128};function oS(e){if(!e.includes(`.`))return 1/0;try{let{exp:t}=Le(e);return t===void 0?1/0:t*1e3}catch(e){if(!(e instanceof He))throw e;return 1/0}}var sS=(e,t)=>`${Ni(`sha256`).update(e).digest(`hex`)} ${t?.href??``}`;function cS(e=aS){let t=new Map,n=(n,r)=>{let i=sS(n,r),a=t.get(i);if(t.delete(i),a!==void 0&&a.expiresAt>Date.now())return t.set(i,a),a.verification;let o=Er(n,r,iS),s={verification:o,expiresAt:1/0};t.set(i,s);for(let n of t.keys()){if(t.size<=e.maxEntries)break;t.delete(n)}let c=()=>{t.get(i)===s&&t.delete(i)};return o.then(t=>{t===null||t===`forbidden`?c():s.expiresAt=Math.min(Date.now()+e.ttlMs,oS(n))},c),o};return Object.assign(async(e,t)=>{let r=gb(e.header(`authorization`));if(r===void 0)return{ok:!1,reason:`missing_credential`,hasAuthorization:!1};try{let e=await n(r,t);if(e===`forbidden`)return{ok:!1,reason:`forbidden`,hasAuthorization:!0};if(e!==null)return{ok:!0,scope:e.operationAccess===`READ`?`read`:`write`,userBearerToken:r,authorization:e}}catch(e){if(!(e instanceof He))throw e;Kn({component:`aventure-mcp-server`,event:`invalid_bearer_jwt`,fields:{requestId:Vn()},error:e})}return{ok:!1,reason:`credential_mismatch`,hasAuthorization:!0}},{holdsGrant:(e,n)=>{let r=gb(e.header(`authorization`));if(r===void 0)return!1;let i=t.get(sS(r,n))?.expiresAt;return i!==void 0&&Number.isFinite(i)&&i>Date.now()}})}function lS(e,t){let n=`an API key from https://aventure.vc/settings/api-keys as Authorization: Bearer <key>`,r=t?`Sign in with OAuth through the authorization server in this server's resource metadata; a client that cannot register itself needs the OAuth client ID at https://docs.aventure.vc/mcp. Or send ${n}.`:`Send ${n}. This server advertises no OAuth authorization server.`;return e===`forbidden`?`The supplied credential is valid, but its account may not use this MCP server.`:e===`missing_credential`?r:`The supplied credential was rejected or expired; reconnect this server in the MCP client to sign in again. ${r}`}var uS=1024,dS=uS*uS,fS=1,pS=2,mS=`b`,hS=`kb`,gS=`mb`,_S=/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/u;function vS(e){let t=bS(e.limit),n=yS(e.path);return(r,i,a)=>{if(t===void 0||r.method!==`POST`||yS(r.path)!==n){a();return}let o=xS(r.header(`content-length`));if(o===void 0||o<=t){a();return}i.setHeader(`Connection`,`close`),e.reject(i)}}function yS(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;return t===``?`/`:t}function bS(e){if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:void 0;let t=_S.exec(e.trim().toLowerCase());if(t===null)return;let n=Number(t[fS]);if(Number.isFinite(n))switch(t[pS]??mS){case gS:return Math.floor(n*dS);case hS:return Math.floor(n*uS);case mS:return Math.floor(n)}}function xS(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}var SS=400,CS=400,wS=413,TS=`10mb`,ES=`127.0.0.1`,DS=`0.0.0.0`;async function OS(e){let t=e.jsonBodyLimit??TS,n=cS(),r=e.host??ES,i=r!==DS,a=(t,n)=>{let r=`${t.protocol}://${t.host}`;return URL.canParse(e.path,r)&&new URL(e.path,r).href===n?.resourceUrl.href?n:void 0},o=(0,Vd.default)();o.disable(`x-powered-by`),o.set(`trust proxy`,1),o.use((e,t,n)=>{let r=Pi(),i=performance.now(),a={requestId:r,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},o=jS(e);o||ln({component:`aventure-mcp-server`,event:`http_request`,fields:a}),t.on(`finish`,()=>{let n=Math.round(performance.now()-i),r=e.route,s=typeof r==`object`&&r?Reflect.get(r,`path`):null,c=rS(e.body);$b(e.method,typeof s==`string`?s:`unmatched`,t.statusCode,n,c),(t.statusCode>=SS&&!o?Kn:ln)({component:`aventure-mcp-server`,event:`http_response`,fields:{...a,...c,status:t.statusCode,durationMs:n}})}),_(r,()=>n())}),o.use(i?(0,Bd.default)({origin:AS}):(0,Bd.default)()),o.use(vS({path:e.path,limit:t,reject:e=>MS(e,wS,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),o.use(Vd.json({limit:t})),o.get(`/health`,(...e)=>{let t=e[1],n=process.env.GIT_SHA?.trim();t.setHeader(`X-Aventure-Revision`,n&&/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):`unknown`),t.status(200).json({status:`UP`})}),o.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,Bd.default)(),async(t,n,r)=>{let i=await e.resolveOAuthDiscovery();if(i===void 0){MS(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=a(t,i);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),ex(o,e.metricsScrapeSecret),o.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),o.get(`/favicon.ico`,(...e)=>e[1].status(204).end());let s=[gf({windowMs:6e4,limit:120,skipSuccessfulRequests:!0,skip:async t=>n.holdsGrant(t,(await e.resolveOAuthDiscovery())?.resourceUrl)}),gf({windowMs:6e4,limit:120,keyGenerator:FS})];return o.post(e.path,s,async(t,r)=>{let o=Vn(),s=t.header(`origin`);if(i&&!kS(s)){Kn({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:o,method:t.method,path:t.path,origin:s}}),MS(r,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let c,l;try{let r=await e.resolveOAuthDiscovery();l=a(t,r),c=await n(t,r?.resourceUrl)}catch(e){wc(e,`authentication_unavailable`),Or({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:o,method:t.method,path:t.path},error:e});let n=e instanceof tr&&(e.problem.status===429||qt(e.problem.status))?e.problem:void 0;n===void 0?MS(r,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof n.retryAfterSeconds==`number`&&r.set(`Retry-After`,String(n.retryAfterSeconds)),NS(r,n));return}if(!c.ok){Kn({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:o,method:t.method,path:t.path,reason:c.reason,hasAuthorization:c.hasAuthorization}});let e=[l===void 0?void 0:`resource_metadata="${Hv(l.resourceUrl)}"`,l===void 0?void 0:`scope="${l.client.scope.join(` `)}"`,c.reason===`credential_mismatch`?`error="invalid_token"`:void 0,c.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,c.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);r.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`);let n=c.reason===`forbidden`;MS(r,n?403:401,n?`Forbidden`:`Unauthorized`,lS(c.reason,l!==void 0));return}let u=t.header(`accept`)??`*/*`;if(!u.includes(`*/*`)&&(!u.includes(`application/json`)||!u.includes(`text/event-stream`))){MS(r,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}ln({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:o,method:t.method,path:t.path,scope:c.scope}});let d=[],f=e=>{wc(e,`transport_error`),Or({component:`aventure-mcp-server`,event:`transport_error`,message:$t(e),fields:{requestId:o,method:t.method,path:t.path},error:e})},p=Uy(()=>eS(c.scope,c.authorization),{onerror:e=>d.push(e),maxSubscriptions:0}),m=async()=>{await lb(p,{onerror:f})(t,r,t.body);for(let e of d)qt(r.statusCode)?f(e):(r.statusCode<SS?ln:Kn)({component:`aventure-mcp-server`,event:`mcp_request_rejected`,message:$t(e),fields:{requestId:o,method:t.method,path:t.path,status:r.statusCode}})};c.userBearerToken===void 0?await m():await In(c.userBearerToken,m)}),o.all(e.path,(...e)=>MS(e[1],405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)),o.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=PS(e);if(i===void 0){r(e);return}Kn({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:Vn(),method:t.method,path:t.path,status:i.status}}),MS(n,i.status,i.status===wS?`Payload Too Large`:`Bad Request`,i.status===wS?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,n)=>{let i;i=o.listen(e.port,r,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await tx()}})}),i.on(`error`,n)})}function kS(e){if(e===void 0)return!0;if(!URL.canParse(e))return!1;let{hostname:t}=new URL(e);return t===`localhost`?!0:t.startsWith(`[`)?t===`[::1]`:ji(t)&&t.startsWith(`127.`)}var AS=(e,t)=>t(null,kS(e)),jS=e=>e.method===`GET`&&/^\/robots\.txt\/?$/iu.test(e.path);function MS(e,t,n,r){NS(e,{type:`about:blank`,title:n,status:t,detail:r})}function NS(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function PS(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?wS:e.type===`entity.parse.failed`?CS:e.status===wS||e.status===CS?e.status:void 0;return t===void 0?void 0:{status:t,message:`message`in e&&typeof e.message==`string`?e.message:`JSON body rejected`}}function FS(e){let t=gb(e.header(`authorization`));return t===void 0?Gd(e.ip??``):Ni(`sha256`).update(t).digest(`base64url`)}var IS=65535,LS=55e3,RS=Hr(ki(import.meta.url)),{host:zS}=(await new cn().name(RS.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(RS.version).option(`--host <address>`,`Bind this address instead of 127.0.0.1; 0.0.0.0 exposes the server to the network.`).addHelpText(`after`,`
145
145
  Connect an MCP client to the server's /mcp URL and send
146
146
  Authorization: Bearer <credential> using an OAuth access token or API key from
147
147
  aventure.vc. The hosted
@@ -153,4 +153,4 @@ Environment:
153
153
  AVENTURE_MCP_PORT Select the HTTP listening port.
154
154
  AVENTURE_MCP_PATH Select the MCP route.
155
155
  AVENTURE_MCP_JSON_LIMIT Limit request body size.
156
- `).parseAsync()).opts();dr(),await Cc(),delete process.env[rn.authToken];var RS=WS(),zS=process.env.AVENTURE_MCP_PATH??`/mcp`,BS=process.env.AVENTURE_MCP_JSON_LIMIT??`10mb`,VS=Zn()||void 0,HS=!1;function US(e){Promise.allSettled([bn(),Tc()]).then(e=>{for(let t of e){if(t.status!==`rejected`)continue;let e=$t(t.reason);process.stderr.write(`${IS.bin[0]} telemetry shutdown failed: ${e}\n`)}}).catch(e=>{let t=$t(e);process.stderr.write(`${IS.bin[0]} telemetry shutdown failed: ${t}\n`)}).finally(()=>process.exit(e))}DS({port:RS,host:LS,path:zS,resolveOAuthDiscovery:vc(),jsonBodyLimit:BS,metricsScrapeSecret:VS}).then(e=>{ln({component:`aventure-mcp-server`,event:`server_listening`,fields:{port:RS,path:zS}}),process.stdout.write(`${IS.bin[0]} listening at http://localhost:${RS}${zS}\n`);let t=t=>{if(HS)return;HS=!0,ln({component:`aventure-mcp-server`,event:`server_shutdown_started`,fields:{signal:t}});let n=setTimeout(()=>{Or({component:`aventure-mcp-server`,event:`server_shutdown_timeout`,message:`MCP server did not drain before the platform forced-shutdown window`,fields:{signal:t,forceExitMs:FS}}),US(1)},FS);n.unref(),e.close().then(()=>{clearTimeout(n),ln({component:`aventure-mcp-server`,event:`server_shutdown_completed`,fields:{signal:t}}),US(0)}).catch(e=>{let r=$t(e);clearTimeout(n),Or({component:`aventure-mcp-server`,event:`server_shutdown_failed`,message:r,fields:{signal:t},error:e}),US(1)})};for(let e of[`SIGTERM`,`SIGINT`])process.on(e,t)},async e=>{let t=$t(e);wc(e,`server_start_failed`),Or({component:`aventure-mcp-server`,event:`server_start_failed`,message:t,error:e}),process.stderr.write(`${IS.bin[0]} failed to start: ${t}\n`),US(1)});function WS(){let e=process.env.AVENTURE_MCP_PORT??process.env.PORT??`3333`,t=Number(e);if(!Number.isInteger(t)||t<1||t>PS)throw Error(`Invalid MCP server port: ${e}`);return t}export{};
156
+ `).parseAsync()).opts();dr(),await Cc(),delete process.env[rn.authToken];var BS=KS(),VS=process.env.AVENTURE_MCP_PATH??`/mcp`,HS=process.env.AVENTURE_MCP_JSON_LIMIT??`10mb`,US=Zn()||void 0,WS=!1;function GS(e){Promise.allSettled([bn(),Tc()]).then(e=>{for(let t of e){if(t.status!==`rejected`)continue;let e=$t(t.reason);process.stderr.write(`${RS.bin[0]} telemetry shutdown failed: ${e}\n`)}}).catch(e=>{let t=$t(e);process.stderr.write(`${RS.bin[0]} telemetry shutdown failed: ${t}\n`)}).finally(()=>process.exit(e))}OS({port:BS,host:zS,path:VS,resolveOAuthDiscovery:vc(),jsonBodyLimit:HS,metricsScrapeSecret:US}).then(e=>{ln({component:`aventure-mcp-server`,event:`server_listening`,fields:{port:BS,path:VS}}),process.stdout.write(`${RS.bin[0]} listening at http://localhost:${BS}${VS}\n`);let t=t=>{if(WS)return;WS=!0,ln({component:`aventure-mcp-server`,event:`server_shutdown_started`,fields:{signal:t}});let n=setTimeout(()=>{Or({component:`aventure-mcp-server`,event:`server_shutdown_timeout`,message:`MCP server did not drain before the platform forced-shutdown window`,fields:{signal:t,forceExitMs:LS}}),GS(1)},LS);n.unref(),e.close().then(()=>{clearTimeout(n),ln({component:`aventure-mcp-server`,event:`server_shutdown_completed`,fields:{signal:t}}),GS(0)}).catch(e=>{let r=$t(e);clearTimeout(n),Or({component:`aventure-mcp-server`,event:`server_shutdown_failed`,message:r,fields:{signal:t},error:e}),GS(1)})};for(let e of[`SIGTERM`,`SIGINT`])process.on(e,t)},async e=>{let t=$t(e);wc(e,`server_start_failed`),Or({component:`aventure-mcp-server`,event:`server_start_failed`,message:t,error:e}),process.stderr.write(`${RS.bin[0]} failed to start: ${t}\n`),GS(1)});function KS(){let e=process.env.AVENTURE_MCP_PORT??process.env.PORT??`3333`,t=Number(e);if(!Number.isInteger(t)||t<1||t>IS)throw Error(`Invalid MCP server port: ${e}`);return t}export{};