@aventurevc/mcp-server 0.8.19 → 0.8.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -4
- package/dist/chunks/auth-BQhqInzT.js +114 -0
- package/dist/chunks/{index.node-C8cqiqhR.js → index.node-nawcv-ES.js} +1 -1
- package/dist/chunks/text-field-DflWl93l.js +1 -0
- package/dist/chunks/{text-response-NPhfN0Zd.js → text-response-DCOgL8vr.js} +1 -1
- package/dist/mcp-server/index.js +8 -8
- package/package.json +3 -3
- package/dist/chunks/auth-D_S3IqOC.js +0 -114
- package/dist/chunks/text-field-C6AhgJXF.js +0 -1
package/dist/mcp-server/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"../chunks/rolldown-runtime-tZXQYakl.js";import{A as o,B as s,Ct as c,D as l,Et as u,G as d,H as f,L as p,M as m,Nt as h,O as g,Ot as _,Pt as v,Tt as y,V as b,W as x,X as S,Y as C,Z as w,_ as T,at as E,bt as D,ct as O,d as k,dt as A,ft as j,gt as ee,ht as te,it as M,jt as N,k as ne,kt as re,l as ie,lt as ae,mt as oe,nt as se,o as ce,ot as le,p as ue,pt as de,s as fe,u as pe,ut as me,v as he,vt as ge,wt as _e,xt as ve,y as ye,yt as be,z as xe}from"../chunks/auth-D_S3IqOC.js";import{D as Se,G as Ce,T as P,U as we,_ as Te,n as Ee,o as De,s as Oe,t as ke,v as F,w as Ae}from"../chunks/ResourceImpl-Dm7ANMDE.js";import{a as je,f as Me,i as Ne,m as Pe,n as Fe,o as Ie,s as Le,t as Re,u as ze}from"../chunks/src-BqpNQELF.js";import{A as Be,B as Ve,C as I,F as He,H as Ue,I as We,L as Ge,M as Ke,N as qe,P as Je,V as Ye,_ as Xe,a as Ze,c as Qe,f as $e,h as et,i as tt,l as nt,o as rt,s as it,v as at,w as ot,x as st,z as ct}from"../chunks/person-owner-BqBLyw4S.js";import{a as lt}from"../chunks/text-field-C6AhgJXF.js";import{A as ut,B as dt,C as ft,D as pt,E as mt,F as ht,G as gt,H as _t,I as vt,K as yt,L as bt,M as xt,N as St,O as Ct,P as wt,R as Tt,S as Et,T as Dt,U as Ot,V as kt,W as At,_ as jt,a as Mt,b as Nt,c as Pt,f as Ft,g as It,h as Lt,i as Rt,j as L,k as zt,l as Bt,m as R,n as Vt,o as Ht,p as Ut,q as Wt,r as Gt,s as Kt,u as qt,v as Jt,w as Yt,x as Xt,y as Zt,z as Qt}from"../chunks/index.node-C8cqiqhR.js";import{i as $t,t as en}from"../chunks/text-response-NPhfN0Zd.js";import{Buffer as tn}from"node:buffer";import{fileURLToPath as nn}from"node:url";import{isIP as rn,isIPv4 as an,isIPv6 as on}from"node:net";import"node:http";import{Readable as sn}from"node:stream";import{createHash as cn,randomUUID as ln,timingSafeEqual as un}from"node:crypto";import{Http2ServerRequest as dn,constants as fn}from"node:http2";import{hostname as pn}from"node:os";var mn={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}},hn,gn=n((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(hn||={})})),z,_n,vn=n((()=>{(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(z||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(_n||={})}));function yn(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function bn(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function xn(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new Tn(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function Sn(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Cn(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 wn(e,t){return e.toLowerCase()===t.toLowerCase()}var Tn,En=n((()=>{Tn=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),Dn,On=n((()=>{(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(Dn||={})})),kn,An=n((()=>{On(),kn=class{kind=Dn.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function jn(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 Mn,Nn,Pn=n((()=>{On(),vn(),En(),Mn=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=jn(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=Cn(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Nn=class{kind=Dn.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new Mn(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 Mn(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 Mn(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:_n.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===z.GAUGE||e.type===z.UP_DOWN_COUNTER||e.type===z.OBSERVABLE_GAUGE||e.type===z.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}}})}}}})),Fn,In,Ln=n((()=>{Fn=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new In,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))}},In=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 Rn(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&Bn)>>20)-Hn}function zn(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),r=t.getUint32(4);return(n&Vn)*2**32+r}var Bn,Vn,Hn,Un,Wn,Gn,Kn=n((()=>{Bn=2146435072,Vn=1048575,Hn=1023,Un=-1022,Wn=Hn,Gn=2**-1022}));function qn(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function Jn(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var Yn=n((()=>{})),Xn,Zn=n((()=>{Xn=class extends Error{}})),Qn,$n=n((()=>{Kn(),Yn(),Zn(),Qn=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<Gn?this._minNormalLowerBoundaryIndex():Rn(e)+this._rightShift(zn(e)-1,52)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Xn(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Xn(`overflow: ${e} is > maximum lower boundary: ${n}`);return qn(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=Un>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return Wn>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),er,tr=n((()=>{Kn(),Yn(),Zn(),er=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=qn(Math.LOG2E,e),this._inverseFactor=qn(Math.LN2,-e)}mapToIndex(e){if(e<=Gn)return this._minNormalLowerBoundaryIndex()-1;if(zn(e)===0)return(Rn(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 Xn(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Gn;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Xn(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Un<<this._scale}_maxNormalLowerBoundaryIndex(){return(Wn+1<<this._scale)-1}}}));function nr(e){if(e>ir||e<rr)throw new Xn(`expected scale >= ${rr} && <= ${ir}, got: ${e}`);return ar[e+10]}var rr,ir,ar,or=n((()=>{$n(),tr(),Zn(),rr=-10,ir=20,ar=Array.from({length:31},(e,t)=>t>10?new er(t-10):new Qn(t-10))})),sr,cr,lr,ur,dr,fr,pr=n((()=>{On(),vn(),F(),Ln(),or(),Yn(),sr=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}},cr=20,lr=160,ur=2,dr=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=lr,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new Fn,l=new Fn,u=nr(cr)){this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=r,this._count=i,this._zeroCount=a,this._min=o,this._max=s,this._positive=c,this._negative=l,this._mapping=u,this._maxSize<ur&&(P.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
|
|
3
|
-
changing to the minimum size of: ${ur}`),this._maxSize=ur)}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.isNaN(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=Jn(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=nr(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=sr.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=sr.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 sr(0,-1);let r=t-n;return new sr(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()}},fr=class{kind=Dn.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new dr(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:_n.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===z.GAUGE||e.type===z.UP_DOWN_COUNTER||e.type===z.OBSERVABLE_GAUGE||e.type===z.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}}})}}}})),mr,hr,gr=n((()=>{On(),be(),vn(),mr=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=_(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},hr=class{kind=Dn.LAST_VALUE;createAccumulation(e){return new mr(e)}merge(e,t){let n=y(t.sampleTime)>=y(e.sampleTime)?t:e;return new mr(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,t){let n=y(t.sampleTime)>=y(e.sampleTime)?t:e;return new mr(t.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_n.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()}))}}}})),_r,vr,yr=n((()=>{On(),vn(),_r=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}},vr=class{kind=Dn.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new _r(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue();return t.reset?new _r(t.startTime,this.monotonic,r,t.reset):new _r(e.startTime,this.monotonic,n+r)}diff(e,t){let n=e.toPointValue(),r=t.toPointValue();return this.monotonic&&n>r?new _r(t.startTime,this.monotonic,r,!0):new _r(t.startTime,this.monotonic,r-n)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_n.SUM,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),br=n((()=>{An(),Pn(),pr(),gr(),yr()})),xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr=n((()=>{F(),br(),vn(),xr=class e{static DEFAULT_INSTANCE=new kn;createAggregator(t){return e.DEFAULT_INSTANCE}},Sr=class e{static MONOTONIC_INSTANCE=new vr(!0);static NON_MONOTONIC_INSTANCE=new vr(!1);createAggregator(t){switch(t.type){case z.COUNTER:case z.OBSERVABLE_COUNTER:case z.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}},Cr=class e{static DEFAULT_INSTANCE=new hr;createAggregator(t){return e.DEFAULT_INSTANCE}},wr=class e{static DEFAULT_INSTANCE=new Nn([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(t){return e.DEFAULT_INSTANCE}},Tr=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 Nn(this._boundaries,this._recordMinMax)}},Er=class{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new fr(this._maxSize,this._recordMinMax)}},Dr=class{_resolve(e){switch(e.type){case z.COUNTER:case z.UP_DOWN_COUNTER:case z.OBSERVABLE_COUNTER:case z.OBSERVABLE_UP_DOWN_COUNTER:return kr;case z.GAUGE:case z.OBSERVABLE_GAUGE:return Ar;case z.HISTOGRAM:return e.advice.explicitBucketBoundaries?new Tr(e.advice.explicitBucketBoundaries):jr}return P.warn(`Unable to recognize instrument type: ${e.type}`),Or}createAggregator(e){return this._resolve(e).createAggregator(e)}},Or=new xr,kr=new Sr,Ar=new Cr,jr=new wr,new Er,Mr=new Dr}));function Pr(e){switch(e.type){case Fr.DEFAULT:return Mr;case Fr.DROP:return Or;case Fr.SUM:return kr;case Fr.LAST_VALUE:return Ar;case Fr.EXPONENTIAL_HISTOGRAM:{let t=e;return new Er(t.options?.maxSize,t.options?.recordMinMax)}case Fr.EXPLICIT_BUCKET_HISTOGRAM:{let t=e;return t.options==null?jr:new Tr(t.options?.boundaries,t.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}var Fr,Ir=n((()=>{Nr(),(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`})(Fr||={})})),Lr,Rr,zr=n((()=>{gn(),Ir(),Lr=e=>({type:Fr.DEFAULT}),Rr=e=>hn.CUMULATIVE})),Br,Vr,Hr,Ur,Wr,Gr=n((()=>{Br=`otel.component.name`,Vr=`otel.component.type`,Hr=`periodic_metric_reader`,Ur=`otel.sdk.metric_reader.collection.duration`,Wr=`error.type`})),Kr,qr,Jr=n((()=>{Gr(),Kr=new Map,qr=class{collectionDuration;standardAttrs;constructor(e,t){let n=Kr.get(e)??0;Kr.set(e,n+1),this.standardAttrs={[Vr]:e,[Br]:`${e}/${n}`},this.collectionDuration=t.createHistogram(Ur,{unit:`s`,description:`The duration of the collect operation of the metric reader.`,advice:{explicitBucketBoundaries:[]}})}recordCollection(e,t){let n=t?{...this.standardAttrs,[Wr]:t}:this.standardAttrs;this.collectionDuration.record(e,n)}}})),Yr,Xr=n((()=>{Yr=`2.10.0`})),Zr,Qr=n((()=>{F(),En(),zr(),Jr(),Xr(),be(),Zr=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_selfObsMetrics;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;_otelComponentType;constructor(e){this._aggregationSelector=e?.aggregationSelector??Lr,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??Rr,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector,this._otelComponentType=e?.otelComponentType??this.constructor.name,this._selfObsMetrics=new qr(this._otelComponentType,Ce())}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`,Yr);this._selfObsMetrics=new qr(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=c(),[n,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),i=c(),a=n.errors.concat(r.flatMap(e=>e.errors)),o=u(_e(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){P.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await xn(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){P.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await xn(this.onForceFlush(),e.timeoutMillis)}}}));function $r(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 ei=n((()=>{})),ti,ni=n((()=>{F(),be(),Qr(),En(),vn(),ei(),Gr(),ti=class extends Zr{_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:Hr,metricProducers:r,cardinalitySelector:e=>{let t={default:2e3,...i};switch(e){case z.COUNTER:return t.counter??t.default;case z.GAUGE:return t.gauge??t.default;case z.HISTOGRAM:return t.histogram??t.default;case z.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case z.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case z.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case z.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`);P.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){N(e)}}async _doRun(){if(this._ongoingExportPromise){P.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&&P.error(`PeriodicExportingMetricReader: metrics collection errors`,...t),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){P.debug(`Error while resolving async portion of resource: `,e),N(e)}if(e.scopeMetrics.length===0)return;let n=this._maxExportBatchSize?$r(e,this._maxExportBatchSize):[e],r=null;for(let e of n)try{let t=await xn(D._export(this._exporter,e),this._exportTimeout);t.code!==ve.SUCCESS&&(r=Error(`PeriodicExportingMetricReader: metrics export failed (error ${t.error})`))}catch(e){if(e instanceof Tn){P.error(`PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`);break}P.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){P.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()}}})),ri,ii=n((()=>{be(),ri=class{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){if(this._shutdown){setTimeout(()=>t({code:ve.FAILED}),0);return}this._metrics.push(e),setTimeout(()=>t({code:ve.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()}}})),ai,oi=n((()=>{be(),zr(),ai=class e{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??Rr}export(t,n){if(this._shutdown){n({code:ve.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:ve.SUCCESS})}}})),si,ci=n((()=>{si=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 li(e,t,n){return fi(e)||P.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??we.DOUBLE,advice:n?.advice??{}}}function ui(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 di(e,t){return wn(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}function fi(e){return pi.test(e)}var pi,mi=n((()=>{F(),En(),pi=/^[a-z][a-z0-9_.\-/]{0,254}$/i}));function hi(e){return e instanceof xi}var gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti=n((()=>{F(),gi=class{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},n){if(typeof e!=`number`){P.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===we.INT&&!Number.isInteger(e)&&(P.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())}},_i=class extends gi{add(e,t,n){this._record(e,t,n)}},vi=class extends gi{add(e,t,n){if(e<0){P.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},yi=class extends gi{record(e,t,n){this._record(e,t,n)}},bi=class extends gi{record(e,t,n){if(e<0){P.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},xi=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)}},Si=class extends xi{},Ci=class extends xi{},wi=class extends xi{}})),Ei,Di=n((()=>{mi(),Ti(),vn(),Ei=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){let n=li(e,z.GAUGE,t),r=this._meterSharedState.registerMetricStorage(n);return new yi(r,n)}createHistogram(e,t){let n=li(e,z.HISTOGRAM,t),r=this._meterSharedState.registerMetricStorage(n);return new bi(r,n)}createCounter(e,t){let n=li(e,z.COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new vi(r,n)}createUpDownCounter(e,t){let n=li(e,z.UP_DOWN_COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new _i(r,n)}createObservableGauge(e,t){let n=li(e,z.OBSERVABLE_GAUGE,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Ci(n,r,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){let n=li(e,z.OBSERVABLE_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Si(n,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){let n=li(e,z.OBSERVABLE_UP_DOWN_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new wi(n,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),Oi,ki=n((()=>{mi(),Oi=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=li(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),Ai,ji,Mi=n((()=>{En(),Ai=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}},ji=class extends Ai{constructor(){super(yn)}}})),Ni,Pi=n((()=>{be(),En(),Mi(),Ni=class{_activeCollectionStorage=new ji;_cumulativeMemoStorage=new ji;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=yn(this._overflowAttributes)}record(e,t,n){let r=this._activeCollectionStorage.get(t);if(!r){let i=_(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 ji,e}}}));function Fi(e){return Array.from(e.entries())}var Ii,Li=n((()=>{gn(),Mi(),Ii=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===hn.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=Fi(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 ji,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}}})),Ri,zi=n((()=>{ki(),Pi(),Li(),Mi(),Ri=class extends Oi{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new Ni(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ii(t,r),this._attributesProcessor=n}record(e,t){if(this._attributesProcessor===void 0){this._deltaMetricStorage.batchCumulate(e,t);return}let n=new ji;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 Bi(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 Vi(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function Hi(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function Ui(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 Wi(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}'
|
|
2
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"../chunks/rolldown-runtime-tZXQYakl.js";import{A as o,At as s,B as c,D as l,Dt as u,Et as d,Ft as f,G as p,H as m,L as h,M as g,Mt as _,O as v,Pt as y,Q as b,St as x,Tt as S,V as C,W as w,Y as T,Z as E,_ as D,_t as O,at as k,bt as A,d as j,dt as ee,ft as te,gt as M,ht as N,k as ne,kt as re,l as ie,lt as ae,mt as oe,o as se,ot as ce,p as le,pt as ue,rt as de,s as fe,st as pe,u as me,ut as he,v as ge,wt as _e,xt as ve,y as ye,yt as be,z as xe}from"../chunks/auth-BQhqInzT.js";import{D as Se,G as Ce,T as P,U as we,_ as Te,n as Ee,o as De,s as Oe,t as ke,v as F,w as Ae}from"../chunks/ResourceImpl-Dm7ANMDE.js";import{a as je,f as Me,i as Ne,m as Pe,n as Fe,o as Ie,s as Le,t as Re,u as ze}from"../chunks/src-BqpNQELF.js";import{A as Be,B as Ve,C as I,F as He,H as Ue,I as We,L as Ge,M as Ke,N as qe,P as Je,V as Ye,_ as Xe,a as Ze,c as Qe,f as $e,h as et,i as tt,l as nt,o as rt,s as it,v as at,w as ot,x as st,z as ct}from"../chunks/person-owner-BqBLyw4S.js";import{a as lt}from"../chunks/text-field-DflWl93l.js";import{A as ut,B as dt,C as ft,D as pt,E as mt,F as ht,G as gt,H as _t,I as vt,K as yt,L as bt,M as xt,N as St,O as Ct,P as wt,R as Tt,S as Et,T as Dt,U as Ot,V as kt,W as At,_ as jt,a as Mt,b as Nt,c as Pt,f as Ft,g as It,h as Lt,i as Rt,j as L,k as zt,l as Bt,m as R,n as Vt,o as Ht,p as Ut,q as Wt,r as Gt,s as Kt,u as qt,v as Jt,w as Yt,x as Xt,y as Zt,z as Qt}from"../chunks/index.node-nawcv-ES.js";import{i as $t,t as en}from"../chunks/text-response-DCOgL8vr.js";import{Buffer as tn}from"node:buffer";import{fileURLToPath as nn}from"node:url";import{isIP as rn,isIPv4 as an,isIPv6 as on}from"node:net";import"node:http";import{Readable as sn}from"node:stream";import{createHash as cn,randomUUID as ln,timingSafeEqual as un}from"node:crypto";import{Http2ServerRequest as dn,constants as fn}from"node:http2";import{hostname as pn}from"node:os";var mn={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}},hn,gn=n((()=>{(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(hn||={})})),z,_n,vn=n((()=>{(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(z||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(_n||={})}));function yn(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function bn(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}function xn(e,t){let n,r=new Promise(function(e,r){n=setTimeout(function(){r(new Tn(`Operation timed out.`))},t)});return Promise.race([e,r]).then(e=>(clearTimeout(n),e),e=>{throw clearTimeout(n),e})}function Sn(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Cn(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 wn(e,t){return e.toLowerCase()===t.toLowerCase()}var Tn,En=n((()=>{Tn=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}}})),Dn,On=n((()=>{(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(Dn||={})})),kn,An=n((()=>{On(),kn=class{kind=Dn.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,n,r){}}}));function jn(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 Mn,Nn,Pn=n((()=>{On(),vn(),En(),Mn=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,n=!0,r=jn(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=Cn(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},Nn=class{kind=Dn.HISTOGRAM;_boundaries;_recordMinMax;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new Mn(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 Mn(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 Mn(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:_n.HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===z.GAUGE||e.type===z.UP_DOWN_COUNTER||e.type===z.OBSERVABLE_GAUGE||e.type===z.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}}})}}}})),Fn,In,Ln=n((()=>{Fn=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new In,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))}},In=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 Rn(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&Bn)>>20)-Hn}function zn(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),r=t.getUint32(4);return(n&Vn)*2**32+r}var Bn,Vn,Hn,Un,Wn,Gn,Kn=n((()=>{Bn=2146435072,Vn=1048575,Hn=1023,Un=-1022,Wn=Hn,Gn=2**-1022}));function qn(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}function Jn(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}var Yn=n((()=>{})),Xn,Zn=n((()=>{Xn=class extends Error{}})),Qn,$n=n((()=>{Kn(),Yn(),Zn(),Qn=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<Gn?this._minNormalLowerBoundaryIndex():Rn(e)+this._rightShift(zn(e)-1,52)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new Xn(`underflow: ${e} is < minimum lower boundary: ${t}`);let n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new Xn(`overflow: ${e} is > maximum lower boundary: ${n}`);return qn(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=Un>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return Wn>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),er,tr=n((()=>{Kn(),Yn(),Zn(),er=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=qn(Math.LOG2E,e),this._inverseFactor=qn(Math.LN2,-e)}mapToIndex(e){if(e<=Gn)return this._minNormalLowerBoundaryIndex()-1;if(zn(e)===0)return(Rn(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 Xn(`overflow: ${e} is > maximum lower boundary: ${t}`)}let n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Gn;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new Xn(`overflow: ${e} is < minimum lower boundary: ${n}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return Un<<this._scale}_maxNormalLowerBoundaryIndex(){return(Wn+1<<this._scale)-1}}}));function nr(e){if(e>ir||e<rr)throw new Xn(`expected scale >= ${rr} && <= ${ir}, got: ${e}`);return ar[e+10]}var rr,ir,ar,or=n((()=>{$n(),tr(),Zn(),rr=-10,ir=20,ar=Array.from({length:31},(e,t)=>t>10?new er(t-10):new Qn(t-10))})),sr,cr,lr,ur,dr,fr,pr=n((()=>{On(),vn(),F(),Ln(),or(),Yn(),sr=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}},cr=20,lr=160,ur=2,dr=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=lr,n=!0,r=0,i=0,a=0,o=1/0,s=-1/0,c=new Fn,l=new Fn,u=nr(cr)){this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=r,this._count=i,this._zeroCount=a,this._min=o,this._max=s,this._positive=c,this._negative=l,this._mapping=u,this._maxSize<ur&&(P.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
|
|
3
|
+
changing to the minimum size of: ${ur}`),this._maxSize=ur)}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.isNaN(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=Jn(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=nr(t)}_minScale(e){let t=Math.min(this.scale,e.scale),n=sr.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),r=sr.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 sr(0,-1);let r=t-n;return new sr(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()}},fr=class{kind=Dn.EXPONENTIAL_HISTOGRAM;_maxSize;_recordMinMax;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new dr(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:_n.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(([t,n])=>{let i=n.toPointValue(),a=e.type===z.GAUGE||e.type===z.UP_DOWN_COUNTER||e.type===z.OBSERVABLE_GAUGE||e.type===z.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}}})}}}})),mr,hr,gr=n((()=>{On(),A(),vn(),mr=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=re(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}},hr=class{kind=Dn.LAST_VALUE;createAccumulation(e){return new mr(e)}merge(e,t){let n=d(t.sampleTime)>=d(e.sampleTime)?t:e;return new mr(e.startTime,n.toPointValue(),n.sampleTime)}diff(e,t){let n=d(t.sampleTime)>=d(e.sampleTime)?t:e;return new mr(t.startTime,n.toPointValue(),n.sampleTime)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_n.GAUGE,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()}))}}}})),_r,vr,yr=n((()=>{On(),vn(),_r=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}},vr=class{kind=Dn.SUM;monotonic;constructor(e){this.monotonic=e}createAccumulation(e){return new _r(e,this.monotonic)}merge(e,t){let n=e.toPointValue(),r=t.toPointValue();return t.reset?new _r(t.startTime,this.monotonic,r,t.reset):new _r(e.startTime,this.monotonic,n+r)}diff(e,t){let n=e.toPointValue(),r=t.toPointValue();return this.monotonic&&n>r?new _r(t.startTime,this.monotonic,r,!0):new _r(t.startTime,this.monotonic,r-n)}toMetricData(e,t,n,r){return{descriptor:e,aggregationTemporality:t,dataPointType:_n.SUM,dataPoints:n.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:r,value:t.toPointValue()})),isMonotonic:this.monotonic}}}})),br=n((()=>{An(),Pn(),pr(),gr(),yr()})),xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr=n((()=>{F(),br(),vn(),xr=class e{static DEFAULT_INSTANCE=new kn;createAggregator(t){return e.DEFAULT_INSTANCE}},Sr=class e{static MONOTONIC_INSTANCE=new vr(!0);static NON_MONOTONIC_INSTANCE=new vr(!1);createAggregator(t){switch(t.type){case z.COUNTER:case z.OBSERVABLE_COUNTER:case z.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}}},Cr=class e{static DEFAULT_INSTANCE=new hr;createAggregator(t){return e.DEFAULT_INSTANCE}},wr=class e{static DEFAULT_INSTANCE=new Nn([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(t){return e.DEFAULT_INSTANCE}},Tr=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 Nn(this._boundaries,this._recordMinMax)}},Er=class{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new fr(this._maxSize,this._recordMinMax)}},Dr=class{_resolve(e){switch(e.type){case z.COUNTER:case z.UP_DOWN_COUNTER:case z.OBSERVABLE_COUNTER:case z.OBSERVABLE_UP_DOWN_COUNTER:return kr;case z.GAUGE:case z.OBSERVABLE_GAUGE:return Ar;case z.HISTOGRAM:return e.advice.explicitBucketBoundaries?new Tr(e.advice.explicitBucketBoundaries):jr}return P.warn(`Unable to recognize instrument type: ${e.type}`),Or}createAggregator(e){return this._resolve(e).createAggregator(e)}},Or=new xr,kr=new Sr,Ar=new Cr,jr=new wr,new Er,Mr=new Dr}));function Pr(e){switch(e.type){case Fr.DEFAULT:return Mr;case Fr.DROP:return Or;case Fr.SUM:return kr;case Fr.LAST_VALUE:return Ar;case Fr.EXPONENTIAL_HISTOGRAM:{let t=e;return new Er(t.options?.maxSize,t.options?.recordMinMax)}case Fr.EXPLICIT_BUCKET_HISTOGRAM:{let t=e;return t.options==null?jr:new Tr(t.options?.boundaries,t.options?.recordMinMax)}default:throw Error(`Unsupported Aggregation`)}}var Fr,Ir=n((()=>{Nr(),(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`})(Fr||={})})),Lr,Rr,zr=n((()=>{gn(),Ir(),Lr=e=>({type:Fr.DEFAULT}),Rr=e=>hn.CUMULATIVE})),Br,Vr,Hr,Ur,Wr,Gr=n((()=>{Br=`otel.component.name`,Vr=`otel.component.type`,Hr=`periodic_metric_reader`,Ur=`otel.sdk.metric_reader.collection.duration`,Wr=`error.type`})),Kr,qr,Jr=n((()=>{Gr(),Kr=new Map,qr=class{collectionDuration;standardAttrs;constructor(e,t){let n=Kr.get(e)??0;Kr.set(e,n+1),this.standardAttrs={[Vr]:e,[Br]:`${e}/${n}`},this.collectionDuration=t.createHistogram(Ur,{unit:`s`,description:`The duration of the collect operation of the metric reader.`,advice:{explicitBucketBoundaries:[]}})}recordCollection(e,t){let n=t?{...this.standardAttrs,[Wr]:t}:this.standardAttrs;this.collectionDuration.record(e,n)}}})),Yr,Xr=n((()=>{Yr=`2.10.0`})),Zr,Qr=n((()=>{F(),En(),zr(),Jr(),Xr(),A(),Zr=class{_shutdown=!1;_metricProducers;_sdkMetricProducer;_selfObsMetrics;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;_otelComponentType;constructor(e){this._aggregationSelector=e?.aggregationSelector??Lr,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??Rr,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector,this._otelComponentType=e?.otelComponentType??this.constructor.name,this._selfObsMetrics=new qr(this._otelComponentType,Ce())}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`,Yr);this._selfObsMetrics=new qr(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=_e(),[n,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),i=_e(),a=n.errors.concat(r.flatMap(e=>e.errors)),o=u(S(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){P.error(`Cannot call shutdown twice.`);return}e?.timeoutMillis==null?await this.onShutdown():await xn(this.onShutdown(),e.timeoutMillis),this._shutdown=!0}async forceFlush(e){if(this._shutdown){P.warn(`Cannot forceFlush on already shutdown MetricReader.`);return}if(e?.timeoutMillis==null){await this.onForceFlush();return}await xn(this.onForceFlush(),e.timeoutMillis)}}}));function $r(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 ei=n((()=>{})),ti,ni=n((()=>{F(),A(),Qr(),En(),vn(),ei(),Gr(),ti=class extends Zr{_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:Hr,metricProducers:r,cardinalitySelector:e=>{let t={default:2e3,...i};switch(e){case z.COUNTER:return t.counter??t.default;case z.GAUGE:return t.gauge??t.default;case z.HISTOGRAM:return t.histogram??t.default;case z.OBSERVABLE_COUNTER:return t.observableCounter??t.default;case z.OBSERVABLE_UP_DOWN_COUNTER:return t.observableUpDownCounter??t.default;case z.OBSERVABLE_GAUGE:return t.observableGauge??t.default;case z.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`);P.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){_(e)}}async _doRun(){if(this._ongoingExportPromise){P.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&&P.error(`PeriodicExportingMetricReader: metrics collection errors`,...t),e.resource.asyncAttributesPending)try{await e.resource.waitForAsyncAttributes?.()}catch(e){P.debug(`Error while resolving async portion of resource: `,e),_(e)}if(e.scopeMetrics.length===0)return;let n=this._maxExportBatchSize?$r(e,this._maxExportBatchSize):[e],r=null;for(let e of n)try{let t=await xn(ve._export(this._exporter,e),this._exportTimeout);t.code!==x.SUCCESS&&(r=Error(`PeriodicExportingMetricReader: metrics export failed (error ${t.error})`))}catch(e){if(e instanceof Tn){P.error(`PeriodicExportingMetricReader: metrics export timed out after ${this._exportTimeout}ms`);break}P.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){P.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()}}})),ri,ii=n((()=>{A(),ri=class{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){if(this._shutdown){setTimeout(()=>t({code:x.FAILED}),0);return}this._metrics.push(e),setTimeout(()=>t({code:x.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()}}})),ai,oi=n((()=>{A(),zr(),ai=class e{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??Rr}export(t,n){if(this._shutdown){n({code:x.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:x.SUCCESS})}}})),si,ci=n((()=>{si=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 li(e,t,n){return fi(e)||P.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??we.DOUBLE,advice:n?.advice??{}}}function ui(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 di(e,t){return wn(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}function fi(e){return pi.test(e)}var pi,mi=n((()=>{F(),En(),pi=/^[a-z][a-z0-9_.\-/]{0,254}$/i}));function hi(e){return e instanceof xi}var gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti=n((()=>{F(),gi=class{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},n){if(typeof e!=`number`){P.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`);return}this._descriptor.valueType===we.INT&&!Number.isInteger(e)&&(P.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())}},_i=class extends gi{add(e,t,n){this._record(e,t,n)}},vi=class extends gi{add(e,t,n){if(e<0){P.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},yi=class extends gi{record(e,t,n){this._record(e,t,n)}},bi=class extends gi{record(e,t,n){if(e<0){P.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`);return}this._record(e,t,n)}},xi=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)}},Si=class extends xi{},Ci=class extends xi{},wi=class extends xi{}})),Ei,Di=n((()=>{mi(),Ti(),vn(),Ei=class{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){let n=li(e,z.GAUGE,t),r=this._meterSharedState.registerMetricStorage(n);return new yi(r,n)}createHistogram(e,t){let n=li(e,z.HISTOGRAM,t),r=this._meterSharedState.registerMetricStorage(n);return new bi(r,n)}createCounter(e,t){let n=li(e,z.COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new vi(r,n)}createUpDownCounter(e,t){let n=li(e,z.UP_DOWN_COUNTER,t),r=this._meterSharedState.registerMetricStorage(n);return new _i(r,n)}createObservableGauge(e,t){let n=li(e,z.OBSERVABLE_GAUGE,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Ci(n,r,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){let n=li(e,z.OBSERVABLE_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new Si(n,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){let n=li(e,z.OBSERVABLE_UP_DOWN_COUNTER,t),r=this._meterSharedState.registerAsyncMetricStorage(n);return new wi(n,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}})),Oi,ki=n((()=>{mi(),Oi=class{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=li(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}})),Ai,ji,Mi=n((()=>{En(),Ai=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}},ji=class extends Ai{constructor(){super(yn)}}})),Ni,Pi=n((()=>{A(),En(),Mi(),Ni=class{_activeCollectionStorage=new ji;_cumulativeMemoStorage=new ji;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;_aggregator;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=yn(this._overflowAttributes)}record(e,t,n){let r=this._activeCollectionStorage.get(t);if(!r){let i=re(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 ji,e}}}));function Fi(e){return Array.from(e.entries())}var Ii,Li=n((()=>{gn(),Mi(),Ii=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===hn.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=Fi(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 ji,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}}})),Ri,zi=n((()=>{ki(),Pi(),Li(),Mi(),Ri=class extends Oi{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new Ni(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ii(t,r),this._attributesProcessor=n}record(e,t){if(this._attributesProcessor===void 0){this._deltaMetricStorage.batchCumulate(e,t);return}let n=new ji;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 Bi(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 Vi(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function Hi(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function Ui(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 Wi(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 Gi(e,t){return e.valueType===t.valueType?e.unit===t.unit?e.type===t.type?e.description===t.description?``:Wi(e,t):Ui(e,t):Hi(e,t):Vi(e,t)}var Ki=n((()=>{})),qi,Ji=n((()=>{mi(),F(),Ki(),qi=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();di(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&r.updateDescription(e.description),P.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.
|
|
6
6
|
`,`Details:
|
|
@@ -8,7 +8,7 @@ import{a as e,i as t,n,o as r,r as i,t as a}from"../chunks/rolldown-runtime-tZXQ
|
|
|
8
8
|
To resolve the conflict:`,Gi(t,e))),n=r):P.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
|
|
9
9
|
`,`Details:
|
|
10
10
|
`,Bi(t,e),`To resolve the conflict:
|
|
11
|
-
`,Gi(t,e))}return n}}})),Yi,Xi=n((()=>{F(),Yi=class{_backingStorages;hasAttributeProcessor;constructor(e){this._backingStorages=e,this.hasAttributeProcessor=e.some(e=>e.hasAttributeProcessor)}record(e,t,n,r){this.hasAttributeProcessor&&n===void 0&&(n=Se.active());let i=this._backingStorages;for(let a=0;a<i.length;a++)i[a].record(e,t,n,r)}}})),Zi,Qi,$i=n((()=>{F(),Mi(),Ti(),Zi=class{_buffer=new ji;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){if(typeof e!=`number`){P.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===we.INT&&!Number.isInteger(e)&&(P.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)}},Qi=class{_buffer=new Map;observe(e,t,n={}){if(!hi(e))return;let r=this._buffer.get(e);if(r??(r=new ji,this._buffer.set(e,r)),typeof t!=`number`){P.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`);return}e._descriptor.valueType===we.INT&&!Number.isInteger(t)&&(P.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),!Number.isInteger(t))||r.set(n,t)}}})),ea,ta=n((()=>{F(),Ti(),$i(),En(),ea=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,t){let n=new Set(t.filter(hi));if(n.size===0){P.error(`BatchObservableCallback is not associated with valid instruments`,t);return}this._findBatchCallback(e,n)>=0||this._batchCallbacks.push({callback:e,instruments:n})}removeBatchCallback(e,t){let n=new Set(t.filter(hi)),r=this._findBatchCallback(e,n);r<0||this._batchCallbacks.splice(r,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:r})=>{let i=new Zi(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=xn(a,t)),await a,r._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:r})=>{let i=new Qi,a=Promise.resolve(n(i));t!=null&&(a=xn(a,t)),await a,r.forEach(t=>{let n=i._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&Sn(n.instruments,t))}}})),na,ra=n((()=>{F(),ki(),Pi(),Li(),na=class extends Oi{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new Ni(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ii(t,r),this._attributesProcessor=n,this.hasAttributeProcessor=n!==void 0}hasAttributeProcessor;record(e,t,n,r){this._attributesProcessor!==void 0&&(t=this._attributesProcessor.process(t,n??Se.active())),this._deltaMetricStorage.record(e,t,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),ia,aa=n((()=>{mi(),Di(),zi(),Ji(),Xi(),ta(),ra(),ia=class{metricStorageRegistry=new qi;observableRegistry=new ea;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Ei(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,na);return t.length===1?t[0]:new Yi(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,Ri)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,t){let n=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(n=>{let r=ui(n,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(i!=null)return i;let a=new t(r,n.aggregation.createAggregator(r),n.attributesProcessor,this._meterProviderSharedState.metricCollectors,n.aggregationCardinalityLimit);return this.metricStorageRegistry.register(a),a});if(n.length===0){let r=this._meterProviderSharedState.selectAggregations(e.type).map(([n,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(n,e);if(i!=null)return i;let a=r.createAggregator(e),o=n.selectCardinalityLimit(e.type),s=new t(e,a,void 0,[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}}})),oa,sa=n((()=>{En(),ci(),aa(),Ir(),oa=class{viewRegistry=new si;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let t=bn(e),n=this.meterSharedStates.get(t);return n??(n=new ia(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,Pr(n.selectAggregation(e))]);return t}}})),ca,la=n((()=>{be(),ca=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let t=_(Date.now()),n=[],r=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,t,e);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&r.push(...a.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:r}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),ua,da,fa,pa=n((()=>{ua=/[\^$\\.+?()[\]{}|]/g,da=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(ua,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},fa=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}}));function ma(){return Sa}function ha(e){return new ya(e)}function ga(e){return new ba(e)}function _a(e){return new xa(e)}var va,ya,ba,xa,Sa,Ca=n((()=>{va=class{process(e,t){return e}},ya=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},ba=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._allowedAttributeNames.has(t)&&(n[t]=e[t]);return n}},xa=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&!this._deniedAttributeNames.has(t)&&(n[t]=e[t]);return n}},Sa=new va})),wa,Ta=n((()=>{pa(),wa=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new da(e?.name??`*`),this._type=e?.type,this._unitFilter=new fa(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),Ea,Da=n((()=>{pa(),Ea=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new fa(e?.name),this._versionFilter=new fa(e?.version),this._schemaUrlFilter=new fa(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}}));function Oa(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function ka(e){if(Oa(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||da.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}var Aa,ja=n((()=>{pa(),Ca(),Ta(),Da(),Ir(),Aa=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){ka(e),this.attributesProcessor=e.attributesProcessors==null?ma():ha(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=Pr(e.aggregation??{type:Fr.DEFAULT}),this.instrumentSelector=new wa({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Ea({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),Ma,Na=n((()=>{F(),te(),Qr(),sa(),la(),ja(),Ma=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new oa(e?.resource??ee()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new Aa(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let n=new ca(this._sharedState,t);t.setMetricProducer(n),this._sharedState.metricCollectors.push(n),e.sdkMetricsEnabled&&t instanceof Zr&&t._setSelfObsMeterProvider(this)}}getMeter(e,t=``,n={}){return this._shutdown?(P.warn(`A shutdown MeterProvider cannot provide a Meter`),Ce()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){P.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){P.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),Pa=i({AggregationTemporality:()=>hn,AggregationType:()=>Fr,ConsoleMetricExporter:()=>ai,DataPointType:()=>_n,InMemoryMetricExporter:()=>ri,InstrumentType:()=>z,MeterProvider:()=>Ma,MetricReader:()=>Zr,PeriodicExportingMetricReader:()=>ti,TimeoutError:()=>Tn,createAllowListAttributesProcessor:()=>ga,createDenyListAttributesProcessor:()=>_a}),Fa=n((()=>{gn(),vn(),Qr(),ni(),ii(),oi(),Na(),Ir(),Ca(),En()})),Ia;(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(Ia||={}),F(),Fa();function La(e,t){let n=de(e.resource,t);return{resource:n,schemaUrl:n.schemaUrl,scopeMetrics:Ra(e.scopeMetrics,t)}}function Ra(e,t){return Array.from(e.map(e=>({scope:j(e.scope,t),metrics:e.metrics.map(e=>za(e,t)),schemaUrl:e.scope.schemaUrl})))}function za(e,t){let n={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},r=Wa(e.aggregationTemporality);switch(e.dataPointType){case _n.SUM:n.sum={aggregationTemporality:r,isMonotonic:e.isMonotonic,dataPoints:Va(e,t)};break;case _n.GAUGE:n.gauge={dataPoints:Va(e,t)};break;case _n.HISTOGRAM:n.histogram={aggregationTemporality:r,dataPoints:Ha(e,t)};break;case _n.EXPONENTIAL_HISTOGRAM:n.exponentialHistogram={aggregationTemporality:r,dataPoints:Ua(e,t)}}return n}function Ba(e,t,n){let r={attributes:oe(e.attributes,n),startTimeUnixNano:n.encodeHrTime(e.startTime),timeUnixNano:n.encodeHrTime(e.endTime)};switch(t){case we.INT:r.asInt=e.value;break;case we.DOUBLE:r.asDouble=e.value}return r}function Va(e,t){return e.dataPoints.map(n=>Ba(n,e.descriptor.valueType,t))}function Ha(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:oe(e.attributes,t),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Ua(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:oe(e.attributes,t),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Wa(e){switch(e){case hn.DELTA:return Ia.AGGREGATION_TEMPORALITY_DELTA;case hn.CUMULATIVE:return Ia.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Ga(e,t){return{resourceMetrics:e.map(e=>La(e,t))}}F();var Ka={serializeRequest:e=>{let t=Ga([e],A);return new TextEncoder().encode(JSON.stringify(t))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;try{return JSON.parse(t.decode(e))}catch(e){return P.warn(`Failed to parse metrics export response: ${e.message}. Returning empty response`),{}}}},qa;(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(qa||={}),F();function Ja(e,t){return new Promise(n=>{Se.with(Pe(Se.active()),()=>{e.export(t,n)})})}var Ya={_export:Ja};function Xa(){let e,t;return async()=>(e===void 0&&(e=await(t??=Za().finally(()=>{t=void 0}))),e)}async function Za(){let e=`getAuthProviderCatalog`,t=await ue(se(),{method:`GET`,path:fe(e,{}),headers:{},operationId:e},Wt).catch(e=>{b({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:p(e),fields:{requestId:g()},error:e})});if(t===void 0)return;if(!t.ok){b({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:`the API did not return an OAuth provider catalog`,fields:{requestId:g()}});return}let n=t.data.oauthClient;if(n==null){b({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published no OAuth client; retrying on the next request that needs one`,fields:{requestId:g()}});return}let r=n.mcpResource;if(r==null){b({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an OAuth client without an MCP resource indicator, so this server has no resource to advertise or audience to verify; retrying on the next request that needs one`,fields:{requestId:g()}});return}if(!URL.canParse(r)){b({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an unusable MCP resource indicator: ${r}`,fields:{requestId:g()}});return}let i=new URL(r);return s({component:`aventure-mcp-server`,event:`oauth_discovery_ready`,fields:{requestId:g(),resource:i.href,authorizationServer:n.authorizationServer}}),{client:n,resourceUrl:i}}var Qa=2e3,$a={userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,graphQL:{document:!1,variables:!1},genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,stackFrameVariables:!1,frameContextLines:0},eo;async function to(){if(C().registry!==``)return;let e=io(process.env.SENTRY_DSN);if(e===void 0)return;let t=io(process.env.SENTRY_RELEASE);if(t===void 0)throw Error(`SENTRY_RELEASE is required when SENTRY_DSN is configured`);let n=await import(`../chunks/esm-DJxYRwLA.js`);n.init({dsn:e,environment:f()[`deployment.environment.name`],release:t,enableLogs:!1,dataCollection:$a,beforeBreadcrumb:()=>null,beforeSend:e=>{let t=e.tags?.failure;return delete e.request,delete e.user,delete e.breadcrumbs,delete e.contexts,delete e.extra,delete e.transaction,delete e.tags,(t===`server_start_failed`||t===`transport_error`)&&(e.tags={failure:t}),e}}),eo=n}function no(e,t){eo?.captureException(e,{tags:{failure:t}})}async function ro(){let e=eo;eo=void 0,e!==void 0&&await e.close(Qa)}function io(e){return e?.trim()||void 0}var ao=a(((e,t)=>{var n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(e==null)throw TypeError(`Object.assign cannot be called with null or undefined`);return Object(e)}function o(){try{if(!Object.assign)return!1;var e=new String(`abc`);if(e[5]=`de`,Object.getOwnPropertyNames(e)[0]===`5`)return!1;for(var t={},n=0;n<10;n++)t[`_`+String.fromCharCode(n)]=n;if(Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(``)!==`0123456789`)return!1;var r={};return`abcdefghijklmnopqrst`.split(``).forEach(function(e){r[e]=e}),Object.keys(Object.assign({},r)).join(``)===`abcdefghijklmnopqrst`}catch{return!1}}t.exports=o()?Object.assign:function(e,t){for(var o,s=a(e),c,l=1;l<arguments.length;l++){for(var u in o=Object(arguments[l]),o)r.call(o,u)&&(s[u]=o[u]);if(n){c=n(o);for(var d=0;d<c.length;d++)i.call(o,c[d])&&(s[c[d]]=o[c[d]])}}return s}})),oo=a(((e,t)=>{t.exports=a,t.exports.append=r;var n=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function r(e,t){if(typeof e!=`string`)throw TypeError(`header argument is required`);if(!t)throw TypeError(`field argument is required`);for(var r=Array.isArray(t)?t:i(String(t)),a=0;a<r.length;a++)if(!n.test(r[a]))throw TypeError(`field argument contains an invalid header name`);if(e===`*`)return e;var o=e,s=i(e.toLowerCase());if(r.indexOf(`*`)!==-1||s.indexOf(`*`)!==-1)return`*`;for(var c=0;c<r.length;c++){var l=r[c].toLowerCase();s.indexOf(l)===-1&&(s.push(l),o=o?o+`, `+r[c]:r[c])}return o}function i(e){for(var t=0,n=[],r=0,i=0,a=e.length;i<a;i++)switch(e.charCodeAt(i)){case 32:r===t&&(r=t=i+1);break;case 44:n.push(e.substring(r,t)),r=t=i+1;break;default:t=i+1}return n.push(e.substring(r,t)),n}function a(e,t){if(!e||!e.getHeader||!e.setHeader)throw TypeError(`res argument is required`);var n=e.getHeader(`Vary`)||``;(n=r(Array.isArray(n)?n.join(`, `):String(n),t))&&e.setHeader(`Vary`,n)}})),so=a(((e,t)=>{(function(){var e=ao(),n=oo(),r={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,preflightContinue:!1,optionsSuccessStatus:204};function i(e){return typeof e==`string`||e instanceof String}function a(e,t){if(Array.isArray(t)){for(var n=0;n<t.length;++n)if(a(e,t[n]))return!0;return!1}return i(t)?e===t:t instanceof RegExp?t.test(e):!!t}function o(e,t){var n=t.headers.origin,r=[],o;return!e.origin||e.origin===`*`?r.push([{key:`Access-Control-Allow-Origin`,value:`*`}]):i(e.origin)?(r.push([{key:`Access-Control-Allow-Origin`,value:e.origin}]),r.push([{key:`Vary`,value:`Origin`}])):(o=a(n,e.origin),r.push([{key:`Access-Control-Allow-Origin`,value:o?n:!1}]),r.push([{key:`Vary`,value:`Origin`}])),r}function s(e){var t=e.methods;return t.join&&(t=e.methods.join(`,`)),{key:`Access-Control-Allow-Methods`,value:t}}function c(e){return e.credentials===!0?{key:`Access-Control-Allow-Credentials`,value:`true`}:null}function l(e,t){var n=e.allowedHeaders||e.headers,r=[];return n?n.join&&(n=n.join(`,`)):(n=t.headers[`access-control-request-headers`],r.push([{key:`Vary`,value:`Access-Control-Request-Headers`}])),n&&n.length&&r.push([{key:`Access-Control-Allow-Headers`,value:n}]),r}function u(e){var t=e.exposedHeaders;if(t)t.join&&(t=t.join(`,`));else return null;return t&&t.length?{key:`Access-Control-Expose-Headers`,value:t}:null}function d(e){var t=(typeof e.maxAge==`number`||e.maxAge)&&e.maxAge.toString();return t&&t.length?{key:`Access-Control-Max-Age`,value:t}:null}function f(e,t){for(var r=0,i=e.length;r<i;r++){var a=e[r];a&&(Array.isArray(a)?f(a,t):a.key===`Vary`&&a.value?n(t,a.value):a.value&&t.setHeader(a.key,a.value))}}function p(e,t,n,r){var i=[];(t.method&&t.method.toUpperCase&&t.method.toUpperCase())===`OPTIONS`?(i.push(o(e,t)),i.push(c(e)),i.push(s(e)),i.push(l(e,t)),i.push(d(e)),i.push(u(e)),f(i,n),e.preflightContinue?r():(n.statusCode=e.optionsSuccessStatus,n.setHeader(`Content-Length`,`0`),n.end())):(i.push(o(e,t)),i.push(c(e)),i.push(u(e)),f(i,n),r())}function m(t){var n=null;return n=typeof t==`function`?t:function(e,n){n(null,t)},function(t,i,a){n(t,function(n,o){if(n)a(n);else{var s=e({},r,o),c=null;s.origin&&typeof s.origin==`function`?c=s.origin:s.origin&&(c=function(e,t){t(null,s.origin)}),c?c(t.headers.origin,function(e,n){e||!n?a(e):(s.origin=n,p(s,t,i,a))}):a()}})}}t.exports=m})()})),co=a(((e,n)=>{var r=t(`path`).relative;n.exports=l;var i=process.cwd();function a(e,t){for(var n=e.split(/[ ,]+/),r=String(t).toLowerCase(),i=0;i<n.length;i++){var a=n[i];if(a&&(a===`*`||a.toLowerCase()===r))return!0}return!1}function o(e,t,n){var r=Object.getOwnPropertyDescriptor(e,t),i=r.value;return r.get=function(){return i},r.writable&&(r.set=function(e){return i=e}),delete r.value,delete r.writable,Object.defineProperty(e,t,r),r}function s(e){for(var t=``,n=0;n<e;n++)t+=`, arg`+n;return t.substr(2)}function c(e){var t=this.name+`: `+this.namespace;this.message&&(t+=` deprecated `+this.message);for(var n=0;n<e.length;n++)t+=`
|
|
11
|
+
`,Gi(t,e))}return n}}})),Yi,Xi=n((()=>{F(),Yi=class{_backingStorages;hasAttributeProcessor;constructor(e){this._backingStorages=e,this.hasAttributeProcessor=e.some(e=>e.hasAttributeProcessor)}record(e,t,n,r){this.hasAttributeProcessor&&n===void 0&&(n=Se.active());let i=this._backingStorages;for(let a=0;a<i.length;a++)i[a].record(e,t,n,r)}}})),Zi,Qi,$i=n((()=>{F(),Mi(),Ti(),Zi=class{_buffer=new ji;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){if(typeof e!=`number`){P.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===we.INT&&!Number.isInteger(e)&&(P.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)}},Qi=class{_buffer=new Map;observe(e,t,n={}){if(!hi(e))return;let r=this._buffer.get(e);if(r??(r=new ji,this._buffer.set(e,r)),typeof t!=`number`){P.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`);return}e._descriptor.valueType===we.INT&&!Number.isInteger(t)&&(P.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),!Number.isInteger(t))||r.set(n,t)}}})),ea,ta=n((()=>{F(),Ti(),$i(),En(),ea=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,t){let n=new Set(t.filter(hi));if(n.size===0){P.error(`BatchObservableCallback is not associated with valid instruments`,t);return}this._findBatchCallback(e,n)>=0||this._batchCallbacks.push({callback:e,instruments:n})}removeBatchCallback(e,t){let n=new Set(t.filter(hi)),r=this._findBatchCallback(e,n);r<0||this._batchCallbacks.splice(r,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:r})=>{let i=new Zi(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=xn(a,t)),await a,r._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:r})=>{let i=new Qi,a=Promise.resolve(n(i));t!=null&&(a=xn(a,t)),await a,r.forEach(t=>{let n=i._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&Sn(n.instruments,t))}}})),na,ra=n((()=>{F(),ki(),Pi(),Li(),na=class extends Oi{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new Ni(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ii(t,r),this._attributesProcessor=n,this.hasAttributeProcessor=n!==void 0}hasAttributeProcessor;record(e,t,n,r){this._attributesProcessor!==void 0&&(t=this._attributesProcessor.process(t,n??Se.active())),this._deltaMetricStorage.record(e,t,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),ia,aa=n((()=>{mi(),Di(),zi(),Ji(),Xi(),ta(),ra(),ia=class{metricStorageRegistry=new qi;observableRegistry=new ea;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Ei(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,na);return t.length===1?t[0]:new Yi(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,Ri)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,t){let n=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(n=>{let r=ui(n,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(i!=null)return i;let a=new t(r,n.aggregation.createAggregator(r),n.attributesProcessor,this._meterProviderSharedState.metricCollectors,n.aggregationCardinalityLimit);return this.metricStorageRegistry.register(a),a});if(n.length===0){let r=this._meterProviderSharedState.selectAggregations(e.type).map(([n,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(n,e);if(i!=null)return i;let a=r.createAggregator(e),o=n.selectCardinalityLimit(e.type),s=new t(e,a,void 0,[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}}})),oa,sa=n((()=>{En(),ci(),aa(),Ir(),oa=class{viewRegistry=new si;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let t=bn(e),n=this.meterSharedStates.get(t);return n??(n=new ia(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,Pr(n.selectAggregation(e))]);return t}}})),ca,la=n((()=>{A(),ca=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let t=re(Date.now()),n=[],r=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,t,e);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&r.push(...a.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:r}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),ua,da,fa,pa=n((()=>{ua=/[\^$\\.+?()[\]{}|]/g,da=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(ua,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},fa=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}}));function ma(){return Sa}function ha(e){return new ya(e)}function ga(e){return new ba(e)}function _a(e){return new xa(e)}var va,ya,ba,xa,Sa,Ca=n((()=>{va=class{process(e,t){return e}},ya=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},ba=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._allowedAttributeNames.has(t)&&(n[t]=e[t]);return n}},xa=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=new Set(e)}process(e,t){let n={};for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&!this._deniedAttributeNames.has(t)&&(n[t]=e[t]);return n}},Sa=new va})),wa,Ta=n((()=>{pa(),wa=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new da(e?.name??`*`),this._type=e?.type,this._unitFilter=new fa(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),Ea,Da=n((()=>{pa(),Ea=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new fa(e?.name),this._versionFilter=new fa(e?.version),this._schemaUrlFilter=new fa(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}}));function Oa(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function ka(e){if(Oa(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||da.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}var Aa,ja=n((()=>{pa(),Ca(),Ta(),Da(),Ir(),Aa=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){ka(e),this.attributesProcessor=e.attributesProcessors==null?ma():ha(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=Pr(e.aggregation??{type:Fr.DEFAULT}),this.instrumentSelector=new wa({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Ea({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),Ma,Na=n((()=>{F(),M(),Qr(),sa(),la(),ja(),Ma=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new oa(e?.resource??O()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new Aa(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let n=new ca(this._sharedState,t);t.setMetricProducer(n),this._sharedState.metricCollectors.push(n),e.sdkMetricsEnabled&&t instanceof Zr&&t._setSelfObsMeterProvider(this)}}getMeter(e,t=``,n={}){return this._shutdown?(P.warn(`A shutdown MeterProvider cannot provide a Meter`),Ce()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){P.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){P.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),Pa=i({AggregationTemporality:()=>hn,AggregationType:()=>Fr,ConsoleMetricExporter:()=>ai,DataPointType:()=>_n,InMemoryMetricExporter:()=>ri,InstrumentType:()=>z,MeterProvider:()=>Ma,MetricReader:()=>Zr,PeriodicExportingMetricReader:()=>ti,TimeoutError:()=>Tn,createAllowListAttributesProcessor:()=>ga,createDenyListAttributesProcessor:()=>_a}),Fa=n((()=>{gn(),vn(),Qr(),ni(),ii(),oi(),Na(),Ir(),Ca(),En()})),Ia;(function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`,e[e.AGGREGATION_TEMPORALITY_DELTA=1]=`AGGREGATION_TEMPORALITY_DELTA`,e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`})(Ia||={}),F(),Fa();function La(e,t){let n=oe(e.resource,t);return{resource:n,schemaUrl:n.schemaUrl,scopeMetrics:Ra(e.scopeMetrics,t)}}function Ra(e,t){return Array.from(e.map(e=>({scope:ue(e.scope,t),metrics:e.metrics.map(e=>za(e,t)),schemaUrl:e.scope.schemaUrl})))}function za(e,t){let n={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},r=Wa(e.aggregationTemporality);switch(e.dataPointType){case _n.SUM:n.sum={aggregationTemporality:r,isMonotonic:e.isMonotonic,dataPoints:Va(e,t)};break;case _n.GAUGE:n.gauge={dataPoints:Va(e,t)};break;case _n.HISTOGRAM:n.histogram={aggregationTemporality:r,dataPoints:Ha(e,t)};break;case _n.EXPONENTIAL_HISTOGRAM:n.exponentialHistogram={aggregationTemporality:r,dataPoints:Ua(e,t)}}return n}function Ba(e,t,n){let r={attributes:N(e.attributes,n),startTimeUnixNano:n.encodeHrTime(e.startTime),timeUnixNano:n.encodeHrTime(e.endTime)};switch(t){case we.INT:r.asInt=e.value;break;case we.DOUBLE:r.asDouble=e.value}return r}function Va(e,t){return e.dataPoints.map(n=>Ba(n,e.descriptor.valueType,t))}function Ha(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:N(e.attributes,t),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Ua(e,t){return e.dataPoints.map(e=>{let n=e.value;return{attributes:N(e.attributes,t),count:n.count,min:n.min,max:n.max,sum:n.sum,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},scale:n.scale,zeroCount:n.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Wa(e){switch(e){case hn.DELTA:return Ia.AGGREGATION_TEMPORALITY_DELTA;case hn.CUMULATIVE:return Ia.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Ga(e,t){return{resourceMetrics:e.map(e=>La(e,t))}}F();var Ka={serializeRequest:e=>{let t=Ga([e],te);return new TextEncoder().encode(JSON.stringify(t))},deserializeResponse:e=>{if(e.length===0)return{};let t=new TextDecoder;try{return JSON.parse(t.decode(e))}catch(e){return P.warn(`Failed to parse metrics export response: ${e.message}. Returning empty response`),{}}}},qa;(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(qa||={}),F();function Ja(e,t){return new Promise(n=>{Se.with(Pe(Se.active()),()=>{e.export(t,n)})})}var Ya={_export:Ja};function Xa(){let e,t;return async()=>(e===void 0&&(e=await(t??=Za().finally(()=>{t=void 0}))),e)}async function Za(){let e=`getAuthProviderCatalog`,t=await le(de(),{method:`GET`,path:fe(e,{}),headers:{},operationId:e},Wt).catch(e=>{C({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:h(e),fields:{requestId:v()},error:e})});if(t===void 0)return;if(!t.ok){C({component:`aventure-mcp-server`,event:`oauth_catalog_unavailable`,message:`the API did not return an OAuth provider catalog`,fields:{requestId:v()}});return}let n=t.data.oauthClient;if(n==null){C({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published no OAuth client; retrying on the next request that needs one`,fields:{requestId:v()}});return}let r=n.mcpResource;if(r==null){C({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an OAuth client without an MCP resource indicator, so this server has no resource to advertise or audience to verify; retrying on the next request that needs one`,fields:{requestId:v()}});return}if(!URL.canParse(r)){C({component:`aventure-mcp-server`,event:`oauth_discovery_disabled`,message:`the API published an unusable MCP resource indicator: ${r}`,fields:{requestId:v()}});return}let i=new URL(r);return c({component:`aventure-mcp-server`,event:`oauth_discovery_ready`,fields:{requestId:v(),resource:i.href,authorizationServer:n.authorizationServer}}),{client:n,resourceUrl:i}}var Qa=2e3,$a={userInfo:!1,cookies:!1,httpHeaders:{request:!1,response:!1},httpBodies:[],urlQueryParams:!1,graphQL:{document:!1,variables:!1},genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,stackFrameVariables:!1,frameContextLines:0},eo;async function to(){if(T().registry!==``)return;let e=io(process.env.SENTRY_DSN);if(e===void 0)return;let t=io(process.env.SENTRY_RELEASE);if(t===void 0)throw Error(`SENTRY_RELEASE is required when SENTRY_DSN is configured`);let n=await import(`../chunks/esm-DJxYRwLA.js`);n.init({dsn:e,environment:m()[`deployment.environment.name`],release:t,enableLogs:!1,dataCollection:$a,beforeBreadcrumb:()=>null,beforeSend:e=>{let t=e.tags?.failure;return delete e.request,delete e.user,delete e.breadcrumbs,delete e.contexts,delete e.extra,delete e.transaction,delete e.tags,(t===`server_start_failed`||t===`transport_error`)&&(e.tags={failure:t}),e}}),eo=n}function no(e,t){eo?.captureException(e,{tags:{failure:t}})}async function ro(){let e=eo;eo=void 0,e!==void 0&&await e.close(Qa)}function io(e){return e?.trim()||void 0}var ao=a(((e,t)=>{var n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(e==null)throw TypeError(`Object.assign cannot be called with null or undefined`);return Object(e)}function o(){try{if(!Object.assign)return!1;var e=new String(`abc`);if(e[5]=`de`,Object.getOwnPropertyNames(e)[0]===`5`)return!1;for(var t={},n=0;n<10;n++)t[`_`+String.fromCharCode(n)]=n;if(Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(``)!==`0123456789`)return!1;var r={};return`abcdefghijklmnopqrst`.split(``).forEach(function(e){r[e]=e}),Object.keys(Object.assign({},r)).join(``)===`abcdefghijklmnopqrst`}catch{return!1}}t.exports=o()?Object.assign:function(e,t){for(var o,s=a(e),c,l=1;l<arguments.length;l++){for(var u in o=Object(arguments[l]),o)r.call(o,u)&&(s[u]=o[u]);if(n){c=n(o);for(var d=0;d<c.length;d++)i.call(o,c[d])&&(s[c[d]]=o[c[d]])}}return s}})),oo=a(((e,t)=>{t.exports=a,t.exports.append=r;var n=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function r(e,t){if(typeof e!=`string`)throw TypeError(`header argument is required`);if(!t)throw TypeError(`field argument is required`);for(var r=Array.isArray(t)?t:i(String(t)),a=0;a<r.length;a++)if(!n.test(r[a]))throw TypeError(`field argument contains an invalid header name`);if(e===`*`)return e;var o=e,s=i(e.toLowerCase());if(r.indexOf(`*`)!==-1||s.indexOf(`*`)!==-1)return`*`;for(var c=0;c<r.length;c++){var l=r[c].toLowerCase();s.indexOf(l)===-1&&(s.push(l),o=o?o+`, `+r[c]:r[c])}return o}function i(e){for(var t=0,n=[],r=0,i=0,a=e.length;i<a;i++)switch(e.charCodeAt(i)){case 32:r===t&&(r=t=i+1);break;case 44:n.push(e.substring(r,t)),r=t=i+1;break;default:t=i+1}return n.push(e.substring(r,t)),n}function a(e,t){if(!e||!e.getHeader||!e.setHeader)throw TypeError(`res argument is required`);var n=e.getHeader(`Vary`)||``;(n=r(Array.isArray(n)?n.join(`, `):String(n),t))&&e.setHeader(`Vary`,n)}})),so=a(((e,t)=>{(function(){var e=ao(),n=oo(),r={origin:`*`,methods:`GET,HEAD,PUT,PATCH,POST,DELETE`,preflightContinue:!1,optionsSuccessStatus:204};function i(e){return typeof e==`string`||e instanceof String}function a(e,t){if(Array.isArray(t)){for(var n=0;n<t.length;++n)if(a(e,t[n]))return!0;return!1}return i(t)?e===t:t instanceof RegExp?t.test(e):!!t}function o(e,t){var n=t.headers.origin,r=[],o;return!e.origin||e.origin===`*`?r.push([{key:`Access-Control-Allow-Origin`,value:`*`}]):i(e.origin)?(r.push([{key:`Access-Control-Allow-Origin`,value:e.origin}]),r.push([{key:`Vary`,value:`Origin`}])):(o=a(n,e.origin),r.push([{key:`Access-Control-Allow-Origin`,value:o?n:!1}]),r.push([{key:`Vary`,value:`Origin`}])),r}function s(e){var t=e.methods;return t.join&&(t=e.methods.join(`,`)),{key:`Access-Control-Allow-Methods`,value:t}}function c(e){return e.credentials===!0?{key:`Access-Control-Allow-Credentials`,value:`true`}:null}function l(e,t){var n=e.allowedHeaders||e.headers,r=[];return n?n.join&&(n=n.join(`,`)):(n=t.headers[`access-control-request-headers`],r.push([{key:`Vary`,value:`Access-Control-Request-Headers`}])),n&&n.length&&r.push([{key:`Access-Control-Allow-Headers`,value:n}]),r}function u(e){var t=e.exposedHeaders;if(t)t.join&&(t=t.join(`,`));else return null;return t&&t.length?{key:`Access-Control-Expose-Headers`,value:t}:null}function d(e){var t=(typeof e.maxAge==`number`||e.maxAge)&&e.maxAge.toString();return t&&t.length?{key:`Access-Control-Max-Age`,value:t}:null}function f(e,t){for(var r=0,i=e.length;r<i;r++){var a=e[r];a&&(Array.isArray(a)?f(a,t):a.key===`Vary`&&a.value?n(t,a.value):a.value&&t.setHeader(a.key,a.value))}}function p(e,t,n,r){var i=[];(t.method&&t.method.toUpperCase&&t.method.toUpperCase())===`OPTIONS`?(i.push(o(e,t)),i.push(c(e)),i.push(s(e)),i.push(l(e,t)),i.push(d(e)),i.push(u(e)),f(i,n),e.preflightContinue?r():(n.statusCode=e.optionsSuccessStatus,n.setHeader(`Content-Length`,`0`),n.end())):(i.push(o(e,t)),i.push(c(e)),i.push(u(e)),f(i,n),r())}function m(t){var n=null;return n=typeof t==`function`?t:function(e,n){n(null,t)},function(t,i,a){n(t,function(n,o){if(n)a(n);else{var s=e({},r,o),c=null;s.origin&&typeof s.origin==`function`?c=s.origin:s.origin&&(c=function(e,t){t(null,s.origin)}),c?c(t.headers.origin,function(e,n){e||!n?a(e):(s.origin=n,p(s,t,i,a))}):a()}})}}t.exports=m})()})),co=a(((e,n)=>{var r=t(`path`).relative;n.exports=l;var i=process.cwd();function a(e,t){for(var n=e.split(/[ ,]+/),r=String(t).toLowerCase(),i=0;i<n.length;i++){var a=n[i];if(a&&(a===`*`||a.toLowerCase()===r))return!0}return!1}function o(e,t,n){var r=Object.getOwnPropertyDescriptor(e,t),i=r.value;return r.get=function(){return i},r.writable&&(r.set=function(e){return i=e}),delete r.value,delete r.writable,Object.defineProperty(e,t,r),r}function s(e){for(var t=``,n=0;n<e;n++)t+=`, arg`+n;return t.substr(2)}function c(e){var t=this.name+`: `+this.namespace;this.message&&(t+=` deprecated `+this.message);for(var n=0;n<e.length;n++)t+=`
|
|
12
12
|
at `+e[n].toString();return t}function l(e){if(!e)throw TypeError(`argument namespace is required`);var t=m(y()[1])[0];function n(e){p.call(n,e)}return n._file=t,n._ignored=d(e),n._namespace=e,n._traced=f(e),n._warned=Object.create(null),n.function=x,n.property=S,n}function u(e,t){return(typeof e.listenerCount==`function`?e.listenerCount(t):e.listeners(t).length)>0}function d(e){return process.noDeprecation?!0:a(process.env.NO_DEPRECATION||``,e)}function f(e){return process.traceDeprecation?!0:a(process.env.TRACE_DEPRECATION||``,e)}function p(e,t){var n=u(process,`deprecation`);if(n||!this._ignored){var r,i,a,o,s=0,c=!1,l=y(),d=this._file;for(t?(o=t,a=m(l[1]),a.name=o.name,d=a[0]):(s=2,o=m(l[s]),a=o);s<l.length;s++)if(r=m(l[s]),i=r[0],i===d)c=!0;else if(i===this._file)d=this._file;else if(c)break;var f=r?o.join(`:`)+`__`+r.join(`:`):void 0;if(!(f!==void 0&&f in this._warned)){this._warned[f]=!0;var p=e;if(p||=a===o||!a.name?h(o):h(a),n){var v=C(this._namespace,p,l.slice(s));process.emit(`deprecation`,v);return}var b=(process.stderr.isTTY?_:g).call(this,p,r,l.slice(s));process.stderr.write(b+`
|
|
13
13
|
`,`utf8`)}}}function m(e){var t=e.getFileName()||`<anonymous>`,n=e.getLineNumber(),r=e.getColumnNumber();e.isEval()&&(t=e.getEvalOrigin()+`, `+t);var i=[t,n,r];return i.callSite=e,i.name=e.getFunctionName(),i}function h(e){var t=e.callSite,n=e.name;n||=`<anonymous@`+v(e)+`>`;var r=t.getThis(),i=r&&t.getTypeName();return i===`Object`&&(i=void 0),i===`Function`&&(i=r.name||i),i&&t.getMethodName()?i+`.`+n:n}function g(e,t,n){var r=new Date().toUTCString()+` `+this._namespace+` deprecated `+e;if(this._traced){for(var i=0;i<n.length;i++)r+=`
|
|
14
14
|
at `+n[i].toString();return r}return t&&(r+=` at `+v(t)),r}function _(e,t,n){var r=`\x1B[36;1m`+this._namespace+`\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m`+e+`\x1B[39m`;if(this._traced){for(var i=0;i<n.length;i++)r+=`
|
|
@@ -57,8 +57,8 @@ return fn.apply(this, arguments)
|
|
|
57
57
|
`}function f(){return function(){this.error(404)}}function p(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var t=a.original(this.req);t.path=null,t.pathname=u(t.pathname+`/`);var n=r(c.format(t)),o=d(`Redirecting`,`Redirecting to `+i(n));e.statusCode=301,e.setHeader(`Content-Type`,`text/html; charset=UTF-8`),e.setHeader(`Content-Length`,Buffer.byteLength(o)),e.setHeader(`Content-Security-Policy`,`default-src 'none'`),e.setHeader(`X-Content-Type-Options`,`nosniff`),e.setHeader(`Location`,n),e.end(o)}}})),tl=a(((e,n)=>{var r=vc(),i=t(`node:events`).EventEmitter,a=yc(),o=Rc(),s=Lc(),c=Jc(),l=$c();e=n.exports=u;function u(){var e=function(t,n,r){e.handle(t,n,r)};return a(e,i.prototype,!1),a(e,o,!1),e.request=Object.create(c,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.response=Object.create(l,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.init(),e}e.application=o,e.request=c,e.response=l,e.Route=s.Route,e.Router=s,e.json=r.json,e.raw=r.raw,e.static=el(),e.text=r.text,e.urlencoded=r.urlencoded})),nl=a(((e,t)=>{t.exports=tl()})),rl=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AddressError=void 0,e.AddressError=class extends Error{constructor(e,t){super(e),this.name=`AddressError`,this.parseMessage=t}}})),il=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isInSubnet=n,e.isHostInSubnet=r,e.isGloballyReachable=i,e.offsetBigInt=a,e.isCorrect=o,e.prefixLengthFromMask=s,e.assertByteArray=c,e.numberToPaddedHex=l,e.stringToPaddedHex=u,e.testBit=d;var t=rl();function n(e){return this.subnetMask<e.subnetMask?!1:r.call(this,e)}function r(e){return this.mask(e.subnetMask)===e.mask()}function i(e){let t=null;for(let n=0;n<e.length;n++){let i=e[n];i.reachable!==null&&r.call(this,i.subnet)&&(t===null||i.subnet.subnetMask>t.subnet.subnetMask)&&(t=i)}return t===null||t.reachable}function a(e,n,r,i){if(typeof n==`number`&&!Number.isSafeInteger(n)||typeof n!=`number`&&typeof n!=`bigint`)throw new t.AddressError(`${i} offset must be an integer`);let a=e+BigInt(n);if(a<BigInt(0)||a>(BigInt(1)<<BigInt(r))-BigInt(1))throw new t.AddressError(`${i} offset leaves the address space`);return a}function o(e){return function(){return this.addressMinusSuffix===this.correctForm()?this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask):!1}}function s(e,n){let r=e.toString(2).padStart(n,`0`);if(r.length>n)throw new t.AddressError(`Invalid subnet mask.`);let i=r.indexOf(`0`);if(i===-1)return n;if(r.slice(i).includes(`1`))throw new t.AddressError(`Invalid subnet mask.`);return i}function c(e,n,r,i){if(e.length!==n)throw new t.AddressError(`${r} addresses require exactly ${n} bytes`);for(let n=0;n<e.length;n++)if(!Number.isInteger(e[n])||e[n]<i||e[n]>255)throw new t.AddressError(`All bytes must be integers between ${i} and 255`)}function l(e){return e.toString(16).padStart(2,`0`)}function u(e){return l(parseInt(e,10))}function d(e,t){let{length:n}=e;if(t>n)return!1;let r=n-t;return e.substring(r,r+1)===`1`}})),al=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_SUBNET_STRING=e.RE_ADDRESS=e.GROUPS=e.BITS=void 0,e.BITS=32,e.GROUPS=4,e.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g,e.RE_SUBNET_STRING=/\/\d{1,2}$/,e.SPECIAL_PURPOSE=[[`0.0.0.0/8`,`This network`,!1],[`0.0.0.0/32`,`This host on this network`,!1],[`10.0.0.0/8`,`Private-Use`,!1],[`100.64.0.0/10`,`Shared Address Space`,!1],[`127.0.0.0/8`,`Loopback`,!1],[`169.254.0.0/16`,`Link Local`,!1],[`172.16.0.0/12`,`Private-Use`,!1],[`192.0.0.0/24`,`IETF Protocol Assignments`,!1],[`192.0.0.0/29`,`IPv4 Service Continuity Prefix`,!1],[`192.0.0.8/32`,`IPv4 dummy address`,!1],[`192.0.0.9/32`,`Port Control Protocol Anycast`,!0],[`192.0.0.10/32`,`Traversal Using Relays around NAT Anycast`,!0],[`192.0.0.170/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.0.171/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.2.0/24`,`Documentation (TEST-NET-1)`,!1],[`192.31.196.0/24`,`AS112-v4`,!0],[`192.52.193.0/24`,`AMT`,!0],[`192.88.99.0/24`,`Deprecated (6to4 Relay Anycast)`,null],[`192.88.99.2/32`,`6a44-relay anycast address`,!1],[`192.168.0.0/16`,`Private-Use`,!1],[`192.175.48.0/24`,`Direct Delegation AS112 Service`,!0],[`198.18.0.0/15`,`Benchmarking`,!1],[`198.51.100.0/24`,`Documentation (TEST-NET-2)`,!1],[`203.0.113.0/24`,`Documentation (TEST-NET-3)`,!1],[`240.0.0.0/4`,`Reserved`,!1],[`255.255.255.255/32`,`Limited Broadcast`,!1]]})),ol=a((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address4=void 0;var i=r(il()),a=r(al()),o=rl(),s=i.isCorrect(a.BITS),c=class e{constructor(e){this.addressMinusSuffix=``,this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet=``,this.subnet=`/32`,this.subnetMask=32,this.v4=!0,this.isCorrect=s,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.address=e;let t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new o.AddressError(`Invalid subnet mask.`);e=e.replace(a.RE_SUBNET_STRING,``)}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(t){try{return new e(t),!0}catch{return!1}}parse(e){let t=e.split(`.`);if(t.some(e=>/^0\d/.test(e)))throw new o.AddressError(`IPv4 addresses can't have leading zeroes.`);if(!e.match(a.RE_ADDRESS))throw new o.AddressError(`Invalid IPv4 address.`);return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(`.`)}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),a.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(a.BITS))-BigInt(1),o=i.prefixLengthFromMask(r,a.BITS);return new e(`${t}/${o}`)}static fromWildcard(t){let n=t.split(`.`);if(n.length!==a.GROUPS)throw new o.AddressError(`Wildcard pattern must have 4 octets`);let r=-1;for(let e=0;e<n.length;e++)if(n[e]===`*`)r===-1&&(r=e);else if(r!==-1)throw new o.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let i=r===-1?0:n.length-r,s=n.map(e=>e===`*`?`0`:e),c=a.BITS-i*8;return new e(`${s.join(`.`)}/${c}`)}static fromHex(t){let n=t.replace(/:/g,``);if(!/^[0-9a-fA-F]{8}$/.test(n))throw new o.AddressError(`IPv4 hex must be exactly 8 hex digits`);let r=[];for(let e=0;e<8;e+=2)r.push(parseInt(n.slice(e,e+2),16));return new e(r.join(`.`))}static fromInteger(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new o.AddressError(`IPv4 integer must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromArpa(t){let n=t.replace(/(\.in-addr\.arpa)?\.$/,``).split(`.`).reverse().join(`.`);return new e(n)}toHex(){return this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(`:`)}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],t=0;for(;t<a.GROUPS;t+=2)e.push(`${i.stringToPaddedHex(this.parsedAddress[t])}${i.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(``)}`)}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(a.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(a.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(a.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(a.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(t){if(t<BigInt(0)||t>BigInt(4294967295))throw new o.AddressError(`IPv4 BigInt must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromByteArray(e){return i.assertByteArray(e,4,`IPv4`,0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(t){if(t.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);let n=t.join(`.`);return new e(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||={};let t=this.correctForm().split(`.`).reverse().join(`.`);return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(l)}isPrivate(){return u.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(d)}isLinkLocal(){return this.isHostInSubnet(f)}isUnspecified(){return this.isHostInSubnet(p)}isBroadcast(){return this.isHostInSubnet(m)}isCGNAT(){return this.isHostInSubnet(h)}isDocumentation(){return g.some(e=>this.isHostInSubnet(e))}isBenchmarking(){return this.isHostInSubnet(_)}isReserved(){return this.isHostInSubnet(v)}isGlobal(){return!this.isMulticast()&&i.isGloballyReachable.call(this,y)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(a.BITS,`0`)),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(`.`)}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(`.`)}</span>`)}};e.Address4=c;var l=new c(`224.0.0.0/4`),u=[new c(`10.0.0.0/8`),new c(`172.16.0.0/12`),new c(`192.168.0.0/16`)],d=new c(`127.0.0.0/8`),f=new c(`169.254.0.0/16`),p=new c(`0.0.0.0/32`),m=new c(`255.255.255.255/32`),h=new c(`100.64.0.0/10`),g=[new c(`192.0.2.0/24`),new c(`198.51.100.0/24`),new c(`203.0.113.0/24`)],_=new c(`198.18.0.0/15`),v=new c(`240.0.0.0/4`),y=a.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new c(e),reachable:t}))})),sl=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_URL_WITH_PORT=e.RE_URL=e.RE_ZONE_STRING=e.RE_SUBNET_STRING=e.RE_BAD_ADDRESS=e.RE_BAD_CHARACTERS=e.TYPES=e.SCOPES=e.GROUPS=e.BITS=void 0,e.BITS=128,e.GROUPS=8,e.SCOPES={0:`Reserved`,1:`Interface local`,2:`Link local`,4:`Admin local`,5:`Site local`,8:`Organization local`,14:`Global`,15:`Reserved`},e.TYPES={"ff01::1/128":`Multicast (All nodes on this interface)`,"ff01::2/128":`Multicast (All routers on this interface)`,"ff02::1/128":`Multicast (All nodes on this link)`,"ff02::2/128":`Multicast (All routers on this link)`,"ff05::2/128":`Multicast (All routers in this site)`,"ff02::5/128":`Multicast (OSPFv3 AllSPF routers)`,"ff02::6/128":`Multicast (OSPFv3 AllDR routers)`,"ff02::9/128":`Multicast (RIP routers)`,"ff02::a/128":`Multicast (EIGRP routers)`,"ff02::d/128":`Multicast (PIM routers)`,"ff02::16/128":`Multicast (MLDv2 reports)`,"ff01::fb/128":`Multicast (mDNSv6)`,"ff02::fb/128":`Multicast (mDNSv6)`,"ff05::fb/128":`Multicast (mDNSv6)`,"ff02::1:2/128":`Multicast (All DHCP servers and relay agents on this link)`,"ff05::1:2/128":`Multicast (All DHCP servers and relay agents in this site)`,"ff02::1:3/128":`Multicast (All DHCP servers on this link)`,"ff05::1:3/128":`Multicast (All DHCP servers in this site)`,"::/128":`Unspecified`,"::1/128":`Loopback`,"::ffff:0:0/96":`IPv4-mapped`,"ff00::/8":`Multicast`,"fe80::/10":`Link-local unicast`,"fc00::/7":`Unique local`,"2001::/32":`Teredo`,"2001:2::/48":`Benchmarking`,"2002::/16":`6to4`,"2001:db8::/32":`Documentation`,"3fff::/20":`Documentation`,"100::/64":`Discard-only`,"fec0::/10":`Site-local unicast (deprecated)`,"::/96":`IPv4-compatible (deprecated)`,"64:ff9b::/96":`NAT64 (well-known)`,"64:ff9b:1::/48":`NAT64 (local-use)`},e.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,e.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,e.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,e.RE_ZONE_STRING=/%.*$/,e.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i,e.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i,e.SPECIAL_PURPOSE=[[`::1/128`,`Loopback Address`,!1],[`::/128`,`Unspecified Address`,!1],[`::ffff:0:0/96`,`IPv4-mapped Address`,!1],[`64:ff9b::/96`,`IPv4-IPv6 Translat.`,!0],[`64:ff9b:1::/48`,`IPv4-IPv6 Translat.`,!1],[`100::/64`,`Discard-Only Address Block`,!1],[`100:0:0:1::/64`,`Dummy IPv6 Prefix`,!1],[`2001::/23`,`IETF Protocol Assignments`,!1],[`2001::/32`,`TEREDO`,!1],[`2001:1::1/128`,`Port Control Protocol Anycast`,!0],[`2001:1::2/128`,`Traversal Using Relays around NAT Anycast`,!0],[`2001:1::3/128`,`DNS-SD Service Registration Protocol Anycast`,!0],[`2001:2::/48`,`Benchmarking`,!1],[`2001:3::/32`,`AMT`,!0],[`2001:4:112::/48`,`AS112-v6`,!0],[`2001:10::/28`,`Deprecated (previously ORCHID)`,null],[`2001:20::/28`,`ORCHIDv2`,!0],[`2001:30::/28`,`Drone Remote ID Protocol Entity Tags (DETs) Prefix`,!0],[`2001:db8::/32`,`Documentation`,!1],[`2002::/16`,`6to4`,!1],[`2620:4f:8000::/48`,`Direct Delegation AS112 Service`,!0],[`3fff::/20`,`Documentation`,!1],[`5f00::/16`,`Segment Routing (SRv6) SIDs`,!1],[`fc00::/7`,`Unique-Local`,!1],[`fe80::/10`,`Link-Local Unicast`,!1]]})),cl=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.escapeHtml=t,e.spanAllZeroes=n,e.spanAll=r,e.spanLeadingZeroes=a,e.simpleGroup=o;function t(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function n(e){return t(e).replace(/(0+)/g,`<span class="zero">$1</span>`)}function r(e,r=0){return e.split(``).map((e,i)=>`<span class="digit value-${t(e)} position-${i+r}">${n(e)}</span>`).join(``)}function i(e){return t(e).replace(/^(0+)/,`<span class="zero">$1</span>`)}function a(e){return e.split(`:`).map(e=>i(e)).join(`:`)}function o(e,t=0){return e.split(`:`).map((e,n)=>/group-v4/.test(e)?e:`<span class="hover-group group-${n+t}">${i(e)}</span>`)}})),ll=a((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.ADDRESS_BOUNDARY=void 0,e.groupPossibilities=a,e.padGroup=o,e.simpleRegularExpression=s,e.possibleElisions=c;var i=r(sl());function a(e){return`(${e.join(`|`)})`}function o(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}e.ADDRESS_BOUNDARY=`[^A-Fa-f0-9:]`;function s(e){let t=[];e.forEach((e,n)=>{parseInt(e,16)===0&&t.push(n)});let n=t.map(t=>e.map((e,n)=>{if(n===t){let t=n===0||n===i.GROUPS-1?`:`:``;return a([o(e),t])}return o(e)}).join(`:`));return n.push(e.map(o).join(`:`)),a(n)}function c(e,t,n){let r=t?``:`:`,i=n?``:`:`,o=[];!t&&!n&&o.push(`::`),t&&n&&o.push(``),(n&&!t||!n&&t)&&o.push(`:`),o.push(`${r}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let n=1;n<e-t;n++)o.push(`(0{1,4}:){${n}}:(0{1,4}:){${e-n-t-1}}0{1,4}`);return a(o)}})),ul=a((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address6=void 0;var i=r(il()),a=r(al()),o=r(sl()),s=r(cl()),c=ol(),l=ll(),u=rl(),d=il(),f=i.isCorrect(o.BITS);function p(e){if(!e)throw Error(`Assertion failed.`)}function m(e){let t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,`$1,$2`);return e}function h(e){return e=e.replace(/^(0{1,})([1-9]+)$/,`<span class="parse-error">$1</span>$2`),e=e.replace(/^(0{1,})(0)$/,`<span class="parse-error">$1</span>$2`),e}function g(e,t){let n=[],r=[],i=0;for(;i<e.length;i++)i<t[0]?n.push(e[i]):i>t[1]&&r.push(e[i]);return n.concat([`compact`]).concat(r)}function _(e){return parseInt(e,16).toString(16).padStart(4,`0`)}function v(e){return e&255}var y=class e{constructor(e,t){this.addressMinusSuffix=``,this.parsedSubnet=``,this.subnet=`/128`,this.subnetMask=128,this.v4=!1,this.zone=``,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.isCorrect=f,this.groups=t===void 0?o.GROUPS:t,this.address=e;let n=o.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>o.BITS)throw new u.AddressError(`Invalid subnet mask.`);e=e.replace(o.RE_SUBNET_STRING,``)}if(/\//.test(e))throw new u.AddressError(`Invalid subnet mask.`);let r=o.RE_ZONE_STRING.exec(e);r&&(this.zone=r[0],e=e.replace(o.RE_ZONE_STRING,``)),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(t){try{return new e(t),!0}catch{return!1}}static fromBigInt(t){if(t<BigInt(0)||t>(BigInt(1)<<BigInt(o.BITS))-BigInt(1))throw new u.AddressError(`IPv6 BigInt must be in the range 0 to 2**128 - 1`);let n=t.toString(16).padStart(32,`0`),r=[];for(let e=0;e<o.GROUPS;e++)r.push(n.slice(e*4,(e+1)*4));return new e(r.join(`:`))}static fromURL(t){let n,r=null,i,a,s=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,``);if(s.indexOf(`[`)!==-1&&s.indexOf(`]:`)!==-1){if(a=`failed to parse address with port`,i=o.RE_URL_WITH_PORT.exec(s),i===null)return{error:a,address:null,port:null};n=i[1],r=i[2]}else{if(a=`failed to parse address from URL`,i=o.RE_URL.exec(s),i===null)return{error:a,address:null,port:null};n=i[1]??i[2]}r?(r=parseInt(r,10),(r<0||r>65535)&&(r=null)):r=null;let c;try{c=new e(n)}catch{return{error:a,address:null,port:null}}return{address:c,port:r}}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),o.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(o.BITS))-BigInt(1),a=i.prefixLengthFromMask(r,o.BITS);return new e(`${t}/${a}`)}static fromWildcard(t){if(t.includes(`%`)||t.includes(`/`))throw new u.AddressError(`Wildcard pattern must not include a zone or CIDR suffix`);let n=t.split(`::`);if(n.length>2)throw new u.AddressError(`Wildcard pattern cannot contain more than one '::'`);let r;if(n.length===2){let e=n[0]===``?[]:n[0].split(`:`),t=n[1]===``?[]:n[1].split(`:`),i=o.GROUPS-e.length-t.length;if(i<1)throw new u.AddressError(`Wildcard pattern with '::' has too many groups`);r=[...e,...Array(i).fill(`0`),...t]}else r=t.split(`:`);if(r.length!==o.GROUPS)throw new u.AddressError(`Wildcard pattern must have 8 groups`);let i=-1;for(let e=0;e<r.length;e++)if(r[e]===`*`)i===-1&&(i=e);else if(i!==-1)throw new u.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let a=i===-1?0:r.length-i,s=r.map(e=>e===`*`?`0`:e),c=o.BITS-a*16;return new e(`${s.join(`:`)}/${c}`)}static fromAddress4(t){let n=new c.Address4(t),r=o.BITS-(a.BITS-n.subnetMask);return new e(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(t){let n=t.replace(/(\.ip6\.arpa)?\.?$/,``);if(!/^[0-9a-f](\.[0-9a-f]){0,31}$/i.test(n))throw new u.AddressError(`Invalid 'ip6.arpa' form.`);let r=n.split(`.`).reverse(),i=r.length*4,a=r.join(``).padEnd(32,`0`),s=[];for(let e=0;e<o.GROUPS;e++)s.push(a.slice(e*4,(e+1)*4));return new e(`${s.join(`:`)}/${i}`)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,`-`)}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let t=o.BITS-this.subnetMask-Math.abs(e-o.BITS);return t<0?`0`:m((BigInt(`2`)**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(o.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(o.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(o.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(o.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)?o.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||`Unknown`:e===`Link-local unicast`||e===`Loopback`?`Link local`:e===`Unspecified`?`Unknown`:`Global`}getType(){for(let e=0;e<b.length;e++){let t=b[e];if(this.isHostInSubnet(t[0]))return t[1]}return`Global unicast`}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){let n=t-e;if(n%4!=0)throw Error(`Length of bits to retrieve must be divisible by four`);return this.getBits(e,t).toString(16).padStart(n/4,`0`)}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,o.BITS)}reverseForm(e){e||={};let t=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,``).split(``).slice(0,t).reverse().join(`.`);return t>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?``:`ip6.arpa.`}correctForm(){let e,t=[],n=0,r=[];for(e=0;e<this.parsedAddress.length;e++){let t=parseInt(this.parsedAddress[e],16);t===0&&n++,t!==0&&n>0&&(n>1&&r.push([e-n,e-1]),n=0)}n>1&&r.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let i=r.map(e=>e[1]-e[0]+1);if(r.length>0){let e=i.indexOf(Math.max(...i));t=g(this.parsedAddress,r[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)t[e]!==`compact`&&(t[e]=parseInt(t[e],16).toString(16));let a=t.join(`:`);return a=a.replace(/^compact$/,`::`),a=a.replace(/(^compact)|(compact$)/,`:`),a=a.replace(/compact/,``),a}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(o.BITS,`0`)),this._binaryZeroPad}parse4in6(e){if(e.indexOf(`.`)===-1)return e;let t=e.split(`:`),n=t.slice(-1)[0],r=n.split(`.`);if(r.length===a.GROUPS&&r.every(e=>/^\d{1,3}$/.test(e))&&r.some(e=>/^0\d/.test(e))){let e=r.map(h).join(`.`),n=t.slice(0,-1).map(s.escapeHtml).join(`:`),i=t.length>1?`:`:``;throw new u.AddressError(`IPv4 addresses can't have leading zeroes.`,`${n}${i}${e}`)}let i=n.match(a.RE_ADDRESS);if(i){this.parsedAddress4=i[0];let n=this.subnetMask>=96?`/${this.subnetMask-96}`:``;this.address4=new c.Address4(`${this.parsedAddress4}${n}`),this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(`:`)}return e}parse(e){e=this.parse4in6(e);let t=e.match(o.RE_BAD_CHARACTERS);if(t)throw new u.AddressError(`Bad character${t.length>1?`s`:``} detected in address: ${t.join(``)}`,e.replace(o.RE_BAD_CHARACTERS,`<span class="parse-error">$1</span>`));let n=e.match(o.RE_BAD_ADDRESS);if(n)throw new u.AddressError(`Address failed regex: ${n.join(``)}`,e.replace(o.RE_BAD_ADDRESS,`<span class="parse-error">$1</span>`));let r=[],i=e.split(`::`);if(i.length===2){let e=i[0].split(`:`),t=i[1].split(`:`);e.length===1&&e[0]===``&&(e=[]),t.length===1&&t[0]===``&&(t=[]);let n=this.groups-(e.length+t.length);if(!n)throw new u.AddressError(`Error parsing groups`);this.elidedGroups=n,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,r=r.concat(e);for(let e=0;e<n;e++)r.push(`0`);r=r.concat(t)}else if(i.length===1)r=e.split(`:`),this.elidedGroups=0;else throw new u.AddressError(`Too many :: groups found`);if(r=r.map(e=>parseInt(e,16).toString(16)),r.length!==this.groups)throw new u.AddressError(`Incorrect number of groups found`);return r}canonicalForm(){return this.parsedAddress.map(_).join(`:`)}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,`0`)).join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(_).join(``)}`)}to4(){let e=this.binaryZeroPad().split(``),t=BigInt(`0b${e.slice(96,128).join(``)}`).toString(16).padStart(8,`0`);if(this.subnetMask>=96){let e=this.subnetMask-96,n=[];for(let e=0;e<8;e+=2)n.push(parseInt(t.slice(e,e+2),16));return new c.Address4(`${n.join(`.`)}/${e}`)}return c.Address4.fromHex(t)}to4in6(){let t=this.to4(),n=new e(this.parsedAddress.slice(0,6).join(`:`),6).correctForm(),r=``;return/:$/.test(n)||(r=`:`),n+r+t.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt(`0xffff`)).toString(),n=c.Address4.fromHex(this.getBitsBase16(32,64)),r=this.getBits(96,128),i=c.Address4.fromHex((r^BigInt(`0xffffffff`)).toString(16).padStart(8,`0`)),a=this.getBitsBase2(64,80),o=(0,d.testBit)(a,15),s=(0,d.testBit)(a,14),l=(0,d.testBit)(a,8),u=(0,d.testBit)(a,9),f=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:n.address,client4:i.address,flags:a,coneNat:o,microsoft:{reserved:s,universalLocal:u,groupIndividual:l,nonce:f},udpPort:t}}inspect6to4(){let e=this.getBitsBase16(0,16),t=c.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;let t=[`2002`,this.getBitsBase16(96,112),this.getBitsBase16(112,128),``,`/16`].join(`:`);return new e(t)}static fromAddress4Nat64(t,n=`64:ff9b::/96`){let r=new c.Address4(t),i=new e(n),a=i.subnetMask;if(a!==32&&a!==40&&a!==48&&a!==56&&a!==64&&a!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);let o=i.binaryZeroPad(),s=r.binaryZeroPad(),l;if(a===96)l=o.slice(0,96)+s;else{let e=64-a;l=[o.slice(0,a),s.slice(0,e),`00000000`,s.slice(e),`0`.repeat(56-(32-e))].join(``)}let d=BigInt(`0b${l}`).toString(16).padStart(32,`0`),f=[];for(let e=0;e<8;e++)f.push(d.slice(e*4,(e+1)*4));return new e(f.join(`:`))}toAddress4Nat64(t=`64:ff9b::/96`){let n=new e(t),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);if(!this.isHostInSubnet(n))return null;let i=this.binaryZeroPad(),a;if(r===96)a=i.slice(96,128);else{let e=64-r;a=i.slice(r,r+e)+i.slice(72,72+(32-e))}let o=[];for(let e=0;e<4;e++)o.push(parseInt(a.slice(e*8,(e+1)*8),2).toString());return new c.Address4(o.join(`.`))}toByteArray(){let e=this.bigInt().toString(16).padStart(o.BITS/4,`0`),t=[];for(let n=0,r=e.length;n<r;n+=2)t.push(parseInt(e.substring(n,n+2),16));return t}toUnsignedByteArray(){return this.toByteArray().map(v)}static fromByteArray(e){return i.assertByteArray(e,16,`IPv6`,-128),this.fromUnsignedByteArray(e.map(v))}static fromUnsignedByteArray(t){i.assertByteArray(t,16,`IPv6`,0);let n=BigInt(`256`),r=BigInt(`0`),a=BigInt(`1`);for(let e=t.length-1;e>=0;e--)r+=a*BigInt(t[e].toString(10)),a*=n;return e.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let e=this.embeddedIPv4();return e?e.isLinkLocal():this.isHostInSubnet(w)}isMulticast(){let e=this.embeddedIPv4();if(e)return e.isMulticast();let t=this.getType();return t===`Multicast`||t.startsWith(`Multicast `)}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(k)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(A)?this.to4():null}isTeredo(){return this.isHostInSubnet(x)}is6to4(){return this.isHostInSubnet(S)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()===`Loopback`}isULA(){return this.isHostInSubnet(C)}isPrivate(){let e=this.embeddedIPv4();return e?e.isPrivate():this.isULA()||this.isHostInSubnet(j)}isCGNAT(){let e=this.embeddedIPv4();return e?e.isCGNAT():!1}isBroadcast(){let e=this.embeddedIPv4();return e?e.isBroadcast():!1}isUnspecified(){let e=this.embeddedIPv4();return e?e.isUnspecified():this.getType()===`Unspecified`}isDocumentation(){return T.some(e=>this.isHostInSubnet(e))}isBenchmarking(){let e=this.embeddedIPv4();return e?e.isBenchmarking():this.isHostInSubnet(E)}isGlobal(){let e=this.embeddedIPv4();return e?e.isGlobal():this.isHostInSubnet(D)&&i.isGloballyReachable.call(this,O)}href(e){return e=e===void 0?``:`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||={},e.className===void 0&&(e.className=``),e.prefix===void 0&&(e.prefix=`/#address=`),e.v4===void 0&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);let n=t.call(this),r=s.escapeHtml(`${e.prefix}${n}`),i=s.escapeHtml(n);return e.className?`<a href="${r}" class="${s.escapeHtml(e.className)}">${i}</a>`:`<a href="${r}">${i}</a>`}group(){if(this.elidedGroups===0)return s.simpleGroup(this.addressMinusSuffix).join(`:`);p(typeof this.elidedGroups==`number`),p(typeof this.elisionBegin==`number`);let e=[],[t,n]=this.addressMinusSuffix.split(`::`);t.length?e.push(...s.simpleGroup(t)):e.push(``);let r=[`hover-group`];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)r.push(`group-${e}`);return e.push(`<span class="${r.join(` `)}"></span>`),n.length?e.push(...s.simpleGroup(n,this.elisionEnd)):e.push(``),this.is4()&&(p(this.address4 instanceof c.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(`:`)}regularExpressionString(t=!1){let n=[],r=new e(this.correctForm());if(r.elidedGroups===0)n.push((0,l.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===o.GROUPS)n.push((0,l.possibleElisions)(o.GROUPS));else{let e=r.address.split(`::`);e[0].length&&n.push((0,l.simpleRegularExpression)(e[0].split(`:`))),p(typeof r.elidedGroups==`number`),n.push((0,l.possibleElisions)(r.elidedGroups,e[0].length!==0,e[1].length!==0)),e[1].length&&n.push((0,l.simpleRegularExpression)(e[1].split(`:`))),n=[n.join(`:`)]}return t||(n=[`(?=^|`,l.ADDRESS_BOUNDARY,`|[^\\w\\:])(`,...n,`)(?=[^\\w\\:]|`,l.ADDRESS_BOUNDARY,`|$)`]),n.join(``)}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),`i`)}};e.Address6=y;var b=Object.keys(o.TYPES).map(e=>[new y(e),o.TYPES[e]]),x=new y(`2001::/32`),S=new y(`2002::/16`),C=new y(`fc00::/7`),w=new y(`fe80::/10`),T=[new y(`2001:db8::/32`),new y(`3fff::/20`)],E=new y(`2001:2::/48`),D=new y(`2000::/3`),O=o.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new y(e),reachable:t})),k=new y(`::ffff:0:0/96`),A=new y(`64:ff9b::/96`),j=new y(`64:ff9b:1::/48`)})),dl=a((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;var i=ol();Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});var a=ul();Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return a.Address6}});var o=rl();Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}}),e.v6={helpers:r(cl())}})),fl=r(so(),1),pl=r(nl(),1),ml=dl(),hl=r(Re(),1),gl=new ml.Address6(`::/96`);function _l(e,t=56){if(on(e)){let n=new ml.Address6(e);if(n.isMapped4()||n.is4()&&n.isInSubnet(gl))return n.to4().correctForm();if(t)return new ml.Address6(`${e}/${t}`).networkForm()}return e}var vl=class{constructor(e){this.validations=e,this.previous=new Map,this.current=new Map,this.localKeys=!0}init(e){this.windowMs=e.windowMs,this.validations?.windowMs(this.windowMs),this.interval&&clearInterval(this.interval),this.interval=setInterval(()=>{this.clearExpired()},this.windowMs),this.interval.unref?.()}async get(e){return this.current.get(e)??this.previous.get(e)}async increment(e){let t=this.getClient(e),n=Date.now();return t.resetTime.getTime()<=n&&this.resetClient(t,n),t.totalHits++,t}async decrement(e){let t=this.getClient(e);t.totalHits>0&&t.totalHits--}async resetKey(e){this.current.delete(e),this.previous.delete(e)}async resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.windowMs),e}getClient(e){if(this.current.has(e))return this.current.get(e);let t;return this.previous.has(e)?(t=this.previous.get(e),this.previous.delete(e)):(t={totalHits:0,resetTime:new Date},this.resetClient(t)),this.current.set(e,t),t}clearExpired(){this.previous=this.current,this.current=new Map}},yl={warn(...e){console.warn(...e.reverse())},error(...e){console.error(...e.reverse())}},bl=[`draft-6`,`draft-7`,`draft-8`],xl=(e,t)=>{let n;if(t){let e=Math.ceil((t.getTime()-Date.now())/1e3);n=Math.max(0,e)}else n=Math.ceil(e/1e3);return n},Sl=e=>{let t=cn(`sha256`);t.update(e);let n=t.digest(`hex`).slice(0,12);return tn.from(n).toString(`base64`)},Cl=(e,t)=>{e.headersSent||(e.setHeader(`X-RateLimit-Limit`,t.limit.toString()),e.setHeader(`X-RateLimit-Remaining`,t.remaining.toString()),t.resetTime instanceof Date&&(e.setHeader(`Date`,new Date().toUTCString()),e.setHeader(`X-RateLimit-Reset`,Math.ceil(t.resetTime.getTime()/1e3).toString())))},wl=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=xl(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit-Limit`,t.limit.toString()),e.setHeader(`RateLimit-Remaining`,t.remaining.toString()),typeof i==`number`&&e.setHeader(`RateLimit-Reset`,i.toString())},Tl=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=xl(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit`,`limit=${t.limit}, remaining=${t.remaining}, reset=${i}`)},El=(e,t,n,r,i)=>{if(e.headersSent)return;let a=Math.ceil(n/1e3),o=xl(n,t.resetTime),s=Sl(i),c=`r=${t.remaining}; t=${o}`,l=`q=${t.limit}; w=${a}; pk=:${s}:`;e.append(`RateLimit`,`"${r}"; ${c}`),e.append(`RateLimit-Policy`,`"${r}"; ${l}`)},Dl=(e,t,n,r)=>{if(e.headersSent)return;let i=r??xl(n,t.resetTime);e.setHeader(`Retry-After`,i.toString())},Ol=e=>{let t={};for(let n of Object.keys(e)){let r=n;e[r]!==void 0&&(t[r]=e[r])}return t},kl=class extends Error{constructor(e,t){let n=`https://express-rate-limit.github.io/${e}/`;super(`${t} See ${n} for more information.`),this.name=this.constructor.name,this.code=e,this.help=n}},Al=class extends kl{},jl=new Set,Ml=new WeakMap,Nl={enabled:{default:!0},disable(){for(let e of Object.keys(this.enabled))this.enabled[e]=!1},ip(e){if(e===void 0)throw new kl(`ERR_ERL_UNDEFINED_IP_ADDRESS`,`An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`);if(!rn(e))throw new kl(`ERR_ERL_INVALID_IP_ADDRESS`,`An invalid 'request.ip' (${e}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`)},trustProxy(e){if(e.app.get(`trust proxy`)===!0)throw new kl(`ERR_ERL_PERMISSIVE_TRUST_PROXY`,`The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`)},xForwardedForHeader(e){if(e.headers[`x-forwarded-for`]&&e.app.get(`trust proxy`)===!1)throw new kl(`ERR_ERL_UNEXPECTED_X_FORWARDED_FOR`,`The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`)},forwardedHeader(e){if(e.headers.forwarded&&e.ip===e.socket?.remoteAddress)throw new kl(`ERR_ERL_FORWARDED_HEADER`,`The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.`)},positiveHits(e){if(typeof e!=`number`||e<1||e!==Math.round(e))throw new kl(`ERR_ERL_INVALID_HITS`,`The totalHits value returned from the store must be a positive integer, got ${e}`)},unsharedStore(e){if(jl.has(e)){let t=e?.localKeys?``:` (with a unique prefix)`;throw new kl(`ERR_ERL_STORE_REUSE`,`A Store instance must not be shared across multiple rate limiters. Create a new instance of ${e.constructor.name}${t} for each limiter instead.`)}jl.add(e)},singleCount(e,t,n){let r=Ml.get(e);r||(r=new Map,Ml.set(e,r));let i=t.localKeys?t:t.constructor.name,a=r.get(i);a||(a=[],r.set(i,a));let o=`${t.prefix??``}${n}`;if(a.includes(o))throw new kl(`ERR_ERL_DOUBLE_COUNT`,`The hit count for ${n} was incremented more than once for a single request.`);a.push(o)},limit(e){if(e===0)throw new Al(`WRN_ERL_MAX_ZERO`,`Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7`)},draftPolliHeaders(e){if(e)throw new Al(`WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS`,`The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`)},onLimitReached(e){if(e)throw new Al(`WRN_ERL_DEPRECATED_ON_LIMIT_REACHED`,`The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.`)},headersDraftVersion(e){if(typeof e!=`string`||!bl.includes(e))throw new kl(`ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION`,`standardHeaders: only the following versions of the IETF draft specification are supported: ${bl.join(`, `)}.`)},headersResetTime(e){if(!e)throw new kl(`ERR_ERL_HEADERS_NO_RESET`,`standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`)},knownOptions(e){if(!e)return;let t=Object.keys({windowMs:!0,limit:!0,message:!0,statusCode:!0,legacyHeaders:!0,standardHeaders:!0,identifier:!0,retryAfter:!0,requestPropertyName:!0,skipFailedRequests:!0,skipSuccessfulRequests:!0,keyGenerator:!0,ipv6Subnet:!0,handler:!0,skip:!0,requestWasSuccessful:!0,store:!0,validate:!0,headers:!0,max:!0,passOnStoreError:!0,logger:!0}).concat(`draft_polli_ratelimit_headers`,`delayAfter`,`delayMs`,`maxDelayMs`);for(let n of Object.keys(e))if(!t.includes(n))throw new kl(`ERR_ERL_UNKNOWN_OPTION`,`Unexpected configuration option: ${n}`)},validationsConfig(){let e=Object.keys(this).filter(e=>![`enabled`,`disable`].includes(e));e.push(`default`);for(let t of Object.keys(this.enabled))if(!e.includes(t))throw new kl(`ERR_ERL_UNKNOWN_VALIDATION`,`options.validate.${t} is not recognized. Supported validate options are: ${e.join(`, `)}.`)},creationStack(e){let{stack:t}=Error(`express-rate-limit validation check (set options.validate.creationStack=false to disable)`);if(t?.includes(`Layer.handle [as handle_request]`)||t?.includes(`Layer.handleRequest`))throw e.localKeys?new kl(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should be created at app initialization, not when responding to a request.`):new kl(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should *usually* be created at app initialization, not when responding to a request.`)},ipv6Subnet(e){if(e!==!1&&(!Number.isInteger(e)||e<32||e>64))throw new kl(`ERR_ERL_IPV6_SUBNET`,`Unexpected ipv6Subnet value: ${e}. Expected an integer between 32 and 64 (usually 48-64).`)},ipv6SubnetOrKeyGenerator(e){if(e.ipv6Subnet!==void 0&&e.keyGenerator)throw new kl(`ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR`,`Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.`)},keyGeneratorIpFallback(e){if(!e)return;let t=e.toString();if((t.includes(`req.ip`)||t.includes(`request.ip`))&&!t.includes(`ipKeyGenerator`))throw new kl(`ERR_ERL_KEY_GEN_IPV6`,`Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits.`)},windowMs(e){let t=2**31-1;if(typeof e!=`number`||Number.isNaN(e)||e<1||e>t)throw new kl(`ERR_ERL_WINDOW_MS`,`Invalid windowMs value: ${e}${typeof e==`number`?``:` (${typeof e})`}, must be a number between 1 and ${t} when using the default MemoryStore`)}};function Pl(e){if(typeof e!=`object`||typeof e.error!=`function`||typeof e.warn!=`function`)throw TypeError(`Provided logger does not implement the Logger interface`)}var Fl=(e,t)=>{Pl(t);let n;n=typeof e==`boolean`?{default:e}:{default:!0,...e};let r={enabled:n};for(let[e,i]of Object.entries(Nl))typeof i==`function`&&(r[e]=(...a)=>{if(n[e]??n.default){n[e]=!1;try{i.apply(r,a)}catch(e){e instanceof Al?t.warn(e):t.error(e)}}});let i=Symbol.for(`nodejs.util.inspect.custom`);return i&&(r[i]=()=>r.enabled),r},Il=e=>typeof e.incr==`function`&&typeof e.increment!=`function`,Ll=e=>{if(!Il(e))return e;let t=e;class n{async increment(e){return new Promise((n,r)=>{t.incr(e,(e,t,i)=>{e&&r(e),n({totalHits:t,resetTime:i})})})}async decrement(e){return t.decrement(e)}async resetKey(e){return t.resetKey(e)}async resetAll(){if(typeof t.resetAll==`function`)return t.resetAll()}}return new n},Rl=e=>{let{validations:t,...n}=e;return{...n,validate:t.enabled}},zl=e=>{let t=Ol(e),n=e.logger??yl,r=Fl(t?.validate??!0,n);r.validationsConfig(),r.knownOptions(e),r.draftPolliHeaders(t.draft_polli_ratelimit_headers),r.onLimitReached(t.onLimitReached),t.ipv6Subnet!==void 0&&typeof t.ipv6Subnet!=`function`&&r.ipv6Subnet(t.ipv6Subnet),r.keyGeneratorIpFallback(t.keyGenerator),r.ipv6SubnetOrKeyGenerator(t);let i=t.standardHeaders??!1;i===!0&&(i=`draft-6`);let a={windowMs:6e4,limit:e.max??5,message:`Too many requests, please try again later.`,statusCode:429,legacyHeaders:e.headers??!0,identifier(e,t){let n=``,{limit:r}=e[a.requestPropertyName],i=a.windowMs/1e3,o=a.windowMs/6e4,s=a.windowMs/36e5,c=a.windowMs/864e5;return n=i<60?`${i}sec`:o<60?`${o}min`:s<24?`${s}hr${s>1?`s`:``}`:`${c}day${c>1?`s`:``}`,`${r}-in-${n}`},requestPropertyName:`rateLimit`,skipFailedRequests:!1,skipSuccessfulRequests:!1,requestWasSuccessful:(e,t)=>t.statusCode<400,skip:(e,t)=>!1,async keyGenerator(e,t){r.ip(e.ip),r.trustProxy(e),r.xForwardedForHeader(e),r.forwardedHeader(e);let n=e.ip,i=56;return on(n)&&(i=typeof a.ipv6Subnet==`function`?await a.ipv6Subnet(e,t):a.ipv6Subnet,typeof a.ipv6Subnet==`function`&&r.ipv6Subnet(i)),_l(n,i)},ipv6Subnet:56,async handler(e,t,n,r){t.status(a.statusCode);let i=typeof a.message==`function`?await a.message(e,t):a.message;t.writableEnded||t.send(i)},passOnStoreError:!1,...t,standardHeaders:i,store:Ll(t.store??new vl(r)),validations:r,logger:n};if(typeof a.store.increment!=`function`||typeof a.store.decrement!=`function`||typeof a.store.resetKey!=`function`||a.store.resetAll!==void 0&&typeof a.store.resetAll!=`function`||a.store.init!==void 0&&typeof a.store.init!=`function`)throw TypeError("An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface.");return a},Bl=e=>async(t,n,r)=>{try{await Promise.resolve(e(t,n,r)).catch(r)}catch(e){r(e)}},Vl=e=>{let t=zl(e??{}),n=Rl(t),r=(0,hl.default)(`express-rate-limit`);r(`creating new rate limiter with %o`,t.store.constructor.name);for(let[e,n]of Object.entries(t))r(`set %s to %o`,e,n);if(t.validations.creationStack(t.store),t.validations.unsharedStore(t.store),typeof t.store.init==`function`){r(`executing init for store`);try{let e=t.store.init(n);e instanceof Promise&&e.catch(e=>t.logger.error(e,`express-rate-limit: async error during store initialization.`))}catch(e){t.logger.error(e,`express-rate-limit: error during store initialization.`)}}let i=Bl(async(e,i,a)=>{let o=t.skipFailedRequests&&new Promise(e=>i.once(`close`,e)),s=(t.skipFailedRequests||t.skipSuccessfulRequests)&&new Promise(e=>i.once(`finish`,e)),c=t.skipFailedRequests&&new Promise(e=>i.once(`error`,e));if(r(`requested %o`,e.originalUrl),r(`request from ip %o`,e.ip),await t.skip(e,i)){r(`skipping request`),a();return}let l=e,u=await t.keyGenerator(e,i);r(`computed key %o`,u),r(`incrementing count`);let d=0,f;try{let e=await t.store.increment(u);d=e.totalHits,f=e.resetTime}catch(e){if(t.passOnStoreError){t.logger.error(e,`express-rate-limit: error from store, allowing request without rate-limiting.`),a();return}throw e}t.validations.positiveHits(d),t.validations.singleCount(e,t.store,u);let p=await(typeof t.limit==`function`?t.limit(e,i):t.limit);t.validations.limit(p);let m={limit:p,used:d,remaining:Math.max(p-d,0),resetTime:f,key:u};for(let[e,n]of Object.entries(m))r(`set request.%s.%s to be %o`,t.requestPropertyName,e,n);if(Object.defineProperty(m,"current",{configurable:!1,enumerable:!1,value:d}),l[t.requestPropertyName]=m,t.legacyHeaders&&!i.headersSent&&(r(`set legacy headers`),Cl(i,m)),t.standardHeaders&&!i.headersSent)switch(t.standardHeaders){case`draft-6`:r(`set ietf draft 6 headers`),wl(i,m,t.windowMs);break;case`draft-7`:r(`set ietf draft 7 headers`),t.validations.headersResetTime(m.resetTime),Tl(i,m,t.windowMs);break;case`draft-8`:{let n=await(typeof t.identifier==`function`?t.identifier(e,i):t.identifier);r(`set ietf draft 8 headers`),r(`set name to %o`,n),t.validations.headersResetTime(m.resetTime),El(i,m,t.windowMs,n,u);break}default:t.validations.headersDraftVersion(t.standardHeaders)}if(t.skipFailedRequests||t.skipSuccessfulRequests){let n=!1,a=async()=>{if(!n){if(f&&Date.now()>=f.getTime())return;r(`decrementing count`),await t.store.decrement(u),n=!0}};t.skipFailedRequests&&(s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n||await a()}),o&&o.then(async()=>{i.writableEnded||await a()}),c&&c.then(async()=>{await a()})),t.skipSuccessfulRequests&&s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n&&await a()})}if(d>p){if(r(`limit exceeded`),t.legacyHeaders||t.standardHeaders){r(`set retry-after header`);let n=await(typeof t.retryAfter==`function`?t.retryAfter(e,i):t.retryAfter);Dl(i,m,t.windowMs,n)}t.handler(e,i,a,n);return}a()});return i.resetKey=t.store.resetKey.bind(t.store),i.getKey=typeof t.store.get==`function`?t.store.get.bind(t.store):()=>{throw Error(`The current store does not support the get/getKey method`)},i},Hl=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Ul=new Set([`age`,`authorization`,`content-length`,`content-type`,`etag`,`expires`,`from`,`host`,`if-modified-since`,`if-unmodified-since`,`last-modified`,`location`,`max-forwards`,`proxy-authorization`,`referer`,`retry-after`,`server`,`user-agent`]),Wl=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,Gl=e=>e===9||e===10||e===13||e===32,Kl=e=>{if(!Gl(e.charCodeAt(0))&&!Gl(e.charCodeAt(e.length-1)))return e;let t=0,n=e.length;for(;t<n&&Gl(e.charCodeAt(t));)t++;for(;n>t&&Gl(e.charCodeAt(n-1));)n--;return e.slice(t,n)},ql=/[\0\r\n]/,Jl=globalThis.Headers,Yl=(e,t=Jl)=>{let n=new t;for(let t=0;t<e.length;t+=2){let r=e[t];r.startsWith(`:`)||n.append(r,e[t+1])}return n},Xl=class{#e;#t;#n;#r;constructor(e){this.#e=e,e instanceof dn&&(this.#t=e.rawHeaders.slice())}get#i(){return this.#t??=this.#e.rawHeaders.slice()}get#a(){return this.#n||(this.#n=Yl(this.#i),this.#t=void 0),this.#n}#o(e){if(typeof e==`string`){if(!Wl.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof dn?void 0:this.#e.headers;if(!t||Ul.has(e)||e===`set-cookie`||e===`__proto__`)return;if(!Object.hasOwn(t,e))return null;let n=t[e];if(typeof n==`string`){let e=Kl(n);return ql.test(e)?void 0:e}}#c(e,t){let n=t===`cookie`?`; `:`, `,r=null;for(let i=0;i<e.length;i+=2){let a=e[i];if(a.length===t.length&&a.toLowerCase()===t){let t=Kl(e[i+1]);if(ql.test(t)){this.#r=!0;return}r=r===null?t:r+n+t}}return r}append(e,t){this.#a.append(e,t)}delete(e){this.#a.delete(e)}get(e){let t=this.#o(e);if(t&&!this.#n&&!this.#r){let e=this.#s(t);if(e!==void 0)return e;let n=this.#c(this.#i,t);if(n!==void 0)return n}return this.#a.get(e)}has(e){let t=this.#o(e);if(t&&!this.#n&&!this.#r){let e=this.#s(t);if(e!==void 0)return e!==null;let n=this.#c(this.#i,t);if(n!==void 0)return n!==null}return this.#a.has(e)}set(e,t){this.#a.set(e,t)}getSetCookie(){return this.#a.getSetCookie()}keys(){return this.#a.keys()}values(){return this.#a.values()}entries(){return this.#a.entries()}forEach(e,t){this.#a.forEach((n,r)=>{e.call(t,n,r,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Xl.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Headers (lightweight) ${n(Object.fromEntries(this),{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Xl.prototype,Jl.prototype);var Zl=e=>globalThis.Headers===Jl?new Xl(e):Yl(e.rawHeaders,globalThis.Headers),Ql=/^\/[!#$&-;=?-\[\]_a-z~]*$/,$l=/\/\.\.?(?:[/?#]|$)/,eu=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,tu=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!eu.test(t)){let e=new URL(r);if(e.hostname.length!==t.length&&e.hostname!==(t.includes(`:`)?t.replace(/:\d+$/,``):t).toLowerCase())throw new Hl(`Invalid host header`);return e.href}if(n.length===0)return r+`/`;if(n.charCodeAt(0)!==47)throw new Hl(`Invalid URL`);return!Ql.test(n)||$l.test(n)?new URL(r).href:r},nu=e=>e instanceof Hl?e:new Hl(e.message,{cause:e}),ru=global.Request,iu=class extends ru{constructor(e,t){if(typeof e==`object`&&gu in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[Du]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[gu]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},au=Symbol(`wrapBodyStream`),ou=new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),su=e=>e===null||ou.has(e),cu=Symbol(`bodyBufferedBeforeDisconnect`),lu=Symbol(`bodyBufferedLengthBeforeDisconnect`),uu=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),du=e=>!(e instanceof dn)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&su(e.readableEncoding),fu=e=>{if(e.readableDidRead||!du(e))return;let t=e;t[lu]??=e.readableLength},pu=(e,t)=>{if(e.readableDidRead&&!t||!du(e))return;let n=e;if(n[cu]!==void 0)return n[cu];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[lu]!==void 0&&e.readableLength!==n[lu])r=Au();else{let n=t??[],i=e.read();i!==null&&n.push(uu(i,e.readableEncoding));let a=n.length===1?n[0]:Buffer.concat(n);r=a;let o=e.headers[`content-length`];if(typeof o==`string`&&/^\d+$/.test(o)){let e=Number(o);Number.isSafeInteger(e)&&a.length!==e&&(r=Au())}}return n[cu]=r,r},mu=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},hu=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new iu(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[au]){let e;a.body=new ReadableStream({async pull(t){try{if(!e){let e=pu(r);if(e!==void 0){mu(t,e);return}}e||=sn.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=pu(r);a.body=e===void 0?sn.toWeb(r):new ReadableStream({start(t){mu(t,e)}})}}return new iu(t,a)},gu=Symbol(`getRequestCache`),_u=Symbol(`requestCache`),vu=Symbol(`incomingKey`),yu=Symbol(`urlKey`),bu=Symbol(`methodKey`),xu=Symbol(`headersKey`),Su=Symbol(`abortControllerKey`),Cu=Symbol(`getAbortController`),wu=Symbol(`abortRequest`),Tu=Symbol(`bodyBuffer`),Eu=Symbol(`bodyReadPromise`),Du=Symbol(`bodyConsumedDirectly`),Ou=Symbol(`bodyLockReader`),ku=Symbol(`abortReason`),Au=()=>TypeError(`Body is unusable`),ju=()=>Promise.reject(Au()),Mu=new TextDecoder,Nu=e=>{if(e[Du])return ju();e[Du]=!0},Pu=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),Fu=e=>(e[xu]||=Zl(e[vu])).get(`content-type`)||``,Iu=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Lu=e=>{if(typeof e!=`string`||e.length===0)return`GET`;switch(e){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`PATCH`:case`POST`:case`PUT`:case`QUERY`:return e}let t=e.toUpperCase();switch(t){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`POST`:case`PUT`:return t;default:return e}},Ru=e=>{if(!Iu.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return TypeError(`'${e}' HTTP method is unsupported.`)},zu=(e,t,n)=>{if(e[Du])return ju();let r=e.method;if(r===`GET`||r===`HEAD`)return e[gu]()[t]();let i=Ru(r);if(i)return Promise.reject(i);if(e[_u]&&r!==`TRACE`)return e[_u][t]();let a=Nu(e);if(a)return a;let o=Bu(e);if(o){let t=Promise.resolve(n(o,e));return e[Tu]=void 0,t}return Hu(e).then(t=>{let r=n(t,e);return e[Tu]=void 0,r})},Bu=e=>{let t=e[vu];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},Vu=(e,t)=>{if(t.errored)return t.errored;let n=e[ku];return n===void 0?Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},Hu=e=>{if(e[Tu])return Promise.resolve(e[Tu]);if(e[Eu])return e[Eu];let t=e[vu];if(t.readableDidRead)return ju();let n=pu(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[Tu]=n,Promise.resolve(n));let r=new Promise((n,r)=>{let i=[],a=!1,o=e=>{a||(a=!0,f(),e())},s=a=>{let s=t.errored??a;return!du(t)||s&&s.code!==`ECONNRESET`?!1:(o(()=>{let o=pu(t,i);o instanceof Error?r(o):o===void 0?r(a??Vu(e,t)):(e[Tu]=o,n(o))}),!0)},c=e=>{i.push(uu(e,t.readableEncoding))},l=()=>{o(()=>{let t=i.length===1?i[0]:Buffer.concat(i);e[Tu]=t,n(t)})},u=e=>{s(e)||o(()=>{r(e)})},d=()=>{if(t.readableEnded){l();return}s()||o(()=>{r(Vu(e,t))})},f=()=>{t.off(`data`,c),t.off(`end`,l),t.off(`error`,u),t.off(`close`,d),e[Eu]=void 0};t.on(`data`,c),t.on(`end`,l),t.on(`error`,u),t.on(`close`,d),queueMicrotask(()=>{a||(t.readableEnded?l():t.errored?u(t.errored):t.destroyed&&d())})});return e[Eu]=r,r},Uu={get method(){return this[bu]},get url(){return this[yu]},get headers(){return this[xu]||=Zl(this[vu])},[wu](e){this[ku]===void 0&&(this[ku]=e);let t=this[Su];t&&!t.signal.aborted&&t.abort(e)},[Cu](){return this[Su]||=new AbortController,this[ku]!==void 0&&!this[Su].signal.aborted&&this[Su].abort(this[ku]),this[Su]},[gu](){let e=this[Cu]();if(this[_u])return this[_u];let t=this.method;if(this[Du]&&t!==`GET`&&t!==`HEAD`){this[Tu]=void 0;let n={method:t===`TRACE`?`GET`:t,headers:this.headers,signal:e.signal};t!==`TRACE`&&(n.body=new ReadableStream({start(e){e.close()}}),n.duplex=`half`);let r=new iu(this[yu],n);return t===`TRACE`&&Object.defineProperty(r,"method",{get(){return`TRACE`}}),this[_u]=r}return this[_u]=hu(this.method,this[yu],this.headers,this[vu],e)},get body(){if(!this[Du])return this[gu]().body;let e=this[gu]();return!this[Ou]&&e.body&&(this[Ou]=e.body.getReader()),e.body},get bodyUsed(){return this[Du]?!0:this[_u]?this[_u].bodyUsed:!1}};Object.defineProperty(Uu,"signal",{get(){return this[Cu]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(Uu,e,{get(){return this[gu]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(Uu,e,{value:function(){if(this[Du]){if(e===`clone`)throw Au();return ju()}return this[gu]()[e]()}})}),Object.defineProperty(Uu,"text",{value:function(){return zu(this,`text`,e=>Mu.decode(e))}}),Object.defineProperty(Uu,"arrayBuffer",{value:function(){return zu(this,`arrayBuffer`,e=>Pu(e))}}),Object.defineProperty(Uu,"blob",{value:function(){return zu(this,`blob`,(e,t)=>{let n=Fu(t);return new Response(e,n?{headers:{"content-type":n}}:void 0).blob()})}}),Object.defineProperty(Uu,"json",{value:function(){return this[Du]?ju():this.text().then(JSON.parse)}}),Object.defineProperty(Uu,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[_u]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Uu,iu.prototype);var Wu=(e,t)=>{let n=Object.create(Uu);n[vu]=e,n[bu]=Lu(e.method);let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof dn)throw new Hl(`Absolute URL for :path is not allowed in HTTP/2`);try{n[yu]=new URL(r).href}catch(e){throw new Hl(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof dn?e.authority:e.headers.host)||t;if(!i)throw new Hl(`Missing host header`);let a;if(e instanceof dn){if(a=e.scheme,a!==`http`&&a!==`https`)throw new Hl(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;try{n[yu]=tu(a,i,r)}catch(e){throw e instanceof Hl?e:new Hl(`Invalid URL`,{cause:e})}return n},Gu=`text/plain; charset=UTF-8`,Ku=Symbol(`responseCache`),qu=Symbol(`getResponseCache`),Ju=Symbol(`cache`),Yu=global.Response,Xu=class e{#e;#t;[qu](){let e=this[Ju],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[Ju],this[Ku]||=new Yu(this.#e,t?{status:this.#t?.status,statusText:this.#t?.statusText,headers:t}:this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof Yu){let t=n[Ku];if(t){this.#t=t,this[qu]();return}this.#t=n instanceof e?n.#t:n,r=new Headers(n.headers)}else this.#t=n;(t==null||typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[Ju]=[n?.status||200,t??null,r||n?.headers])}get headers(){let e=this[Ju];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":Gu}))),e[2]):this[qu]().headers}get status(){return this[Ju]?.[0]??this[qu]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Xu.prototype,e,{get(){return this[qu]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Xu.prototype,e,{value:function(){return this[qu]()[e]()}})}),Object.defineProperty(Xu.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[Ku]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Xu,Yu),Object.setPrototypeOf(Xu.prototype,Yu.prototype);var Zu=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,Qu=e=>e instanceof URL?e.href:Zu.test(e)?e:new URL(e).href,$u=new Set([301,302,303,307,308]);Object.defineProperty(Xu,"redirect",{value:function(e,t=302){if(!$u.has(t))throw RangeError(`Invalid status code`);return new Xu(null,{status:t,headers:{location:Qu(e)}})},writable:!0,configurable:!0}),Object.defineProperty(Xu,"json",{value:function(e,t){let n=JSON.stringify(e);if(n===void 0)throw TypeError(`The data is not JSON serializable`);let r=t?.headers,i;return r?(i=new Headers(r),i.has(`content-type`)||i.set(`content-type`,`application/json`)):i={"content-type":`application/json`},new Xu(n,{status:t?.status??200,statusText:t?.statusText,headers:i})},writable:!0,configurable:!0});async function ed(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function td(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function nd(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return td(e.getReader(),t)}var rd=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has(`set-cookie`)){let t=[];for(let[r,i]of e)r===`set-cookie`?t.push(i):n[r]=i;t.length>0&&(n[`set-cookie`]=t)}else for(let[t,r]of e)n[t]=r;return t&&(n[`content-type`]??=t),n},id=Symbol(`outgoingEnded`),ad=Symbol(`incomingDraining`),od=500,sd=67108864,cd=e=>{let t=e;if(e.destroyed||t[ad])return;if(t[ad]=!0,e instanceof dn){try{e.stream?.close?.(fn.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(a),e.off(`data`,o),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&(typeof t.destroySoon==`function`?t.destroySoon():typeof t.destroy==`function`&&t.destroy())},a=setTimeout(i,od);a.unref?.();let o=e=>{n+=e.length,n>sd&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},ld=(e,t,n,r)=>()=>{t.errored?(fu(t),e[wu](t.errored.toString())):n.writableFinished||(fu(t),e[wu](`Client connection prematurely closed.`)),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{cd(t)})})},ud=e=>{if(!(Ju in e))return!1;let t=e[Ju][1];return t===null||typeof t==`string`||t instanceof Uint8Array},dd=()=>new Response(null,{status:400}),fd=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),pd=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},md=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},hd=async(e,t)=>{let[n,r,i]=e[Ju];if(!i){r===null?(t.writeHead(n),t.end()):typeof r==`string`?(t.writeHead(n,{"Content-Type":Gu,"Content-Length":Buffer.byteLength(r)}),t.end(r)):r instanceof Uint8Array?(t.writeHead(n,{"Content-Type":Gu,"Content-Length":r.byteLength}),t.end(r)):r instanceof Blob?(t.writeHead(n,{"Content-Type":Gu,"Content-Length":r.size}),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":Gu}),md(t),await nd(r,t)?.catch(e=>pd(e,t))),t[id]?.();return}let a=!1;if(i instanceof Headers)a=i.has(`content-length`),i=rd(i,r===null?void 0:Gu);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=rd(e,r===null?void 0:Gu)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),r==null?t.end():typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(md(t),await nd(r,t)?.catch(e=>pd(e,t))),t[id]?.()},gd=e=>typeof e.then==`function`,_d=async(e,t,n={})=>{if(gd(e)){if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(fd)}if(Ju in e)return hd(e,t);let r=rd(e.headers,e.body===null?void 0:Gu);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await ed(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&md(t),await td(n,t,o))}else r[`x-hono-already-sent`]||(t.writeHead(e.status,r),t.end());t[id]?.()},vd=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==iu&&(Object.defineProperty(global,"Request",{value:iu}),Object.defineProperty(global,"Response",{value:Xu})),async(r,i)=>{let a,o,s=!1,c=!1,l=()=>{o&&!c&&(c=!0,i.on(`close`,ld(o,r,i,s)))};try{if(o=Wu(r,t.hostname),s=n&&r.method!==`GET`&&r.method!==`HEAD`,s&&(r[au]=!0,r instanceof dn&&(i[id]=()=>{r.readableEnded||setTimeout(()=>{r.readableEnded||setTimeout(()=>{r.destroy(),i.destroy()})})})),a=e(o,{incoming:r,outgoing:i}),!gd(a)&&ud(a))return s&&!r.readableEnded&&i.once(`finish`,()=>{r.readableEnded||cd(r)}),hd(a,i);l()}catch(e){if(a)return pd(e,i);if(t.errorHandler){if(l(),a=await t.errorHandler(o?e:nu(e)),!a)return}else a=o?fd(e):dd()}try{return await _d(a,i,t)}catch(e){return pd(e,i)}}};globalThis.CloseEvent,globalThis.ErrorEvent;var yd=r(Tc(),1);function bd(e){if(e)try{return yd.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function xd(e){return e===`application/json`||bd(e)===`application/json`}var Sd=2**31-1;function Cd(e,t){if(!Number.isFinite(e)||e<1)return;let n=setInterval(t,Math.min(e,Sd));return n.unref?.(),n}var wd=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._resumableStreams=new Set,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this._closed=!1,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._keepAliveMs=e.keepAliveMs??15e3}startKeepAlive(e,t){if(this._closed)return;let n=Cd(this._keepAliveMs,()=>{try{e.enqueue(t.encode(`: keepalive
|
|
58
58
|
|
|
59
59
|
`))}catch{n!==void 0&&clearInterval(n)}});return n}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:i,id:null}),{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}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()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)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)),this._resumableStreams.add(n)}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,s=!1,c=new ReadableStream({start:e=>{i=e},cancel:()=>{s=!0,a!==void 0&&clearInterval(a),o!==void 0&&this._streamMapping.get(o)?.controller===i&&this._streamMapping.delete(o)}}),l=new Set;if(o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(this.writeSSEEvent(i,r,t,e))l.add(e);else{this.onerror?.(Error(`Failed replay events`));try{i.close()}catch{}}}}),this._closed||s){try{i.close()}catch{}return this.createJsonErrorResponse(404,-32001,`Session not found`)}return this._streamMapping.get(o)?.cleanup(),this._streamMapping.set(o,{controller:i,encoder:r,replayedEventIds:l,cleanup:()=>{a!==void 0&&clearInterval(a),this._streamMapping.delete(o);try{i.close()}catch{}}}),this._resumableStreams.add(o),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
|
|
60
|
-
`;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.`)),new Response(JSON.stringify({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(!xd(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={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(t?.parsedBody!==void 0)i=t.parsedBody;else try{i=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let a;try{a=Array.isArray(i)?i.map(e=>Xt.parse(e)):[Xt.parse(i)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),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(kt);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`);if(!a.some(At)){for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:r});return new Response(null,{status:202})}let s=crypto.randomUUID(),c=a.find(e=>kt(e)),l=c?c.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(s,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(s)}});for(let e of a)At(e)&&this._requestToStreamMapping.set(e.id,s);for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:r})});let u=new TextEncoder,d,f,p=new ReadableStream({start:e=>{d=e},cancel:()=>{f!==void 0&&clearInterval(f),this._streamMapping.get(s)?.controller===d&&this._streamMapping.delete(s)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of a)At(e)&&(this._streamMapping.set(s,{controller:d,encoder:u,cleanup:()=>{f!==void 0&&clearInterval(f),this._streamMapping.delete(s);try{d.close()}catch{}}}),this._requestToStreamMapping.set(e.id,s));try{await this.writePrimingEvent(d,u,s,l);for(let e of a){let n,i;At(e)&&this._eventStore&&l>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:r,closeSSEStream:n,closeStandaloneSSEStream:i})}}catch(e){this._streamMapping.get(s)?.cleanup(),this._resumableStreams.delete(s);for(let e of a)At(e)&&this._requestToStreamMapping.delete(e.id);throw e}return this._streamMapping.get(s)?.controller===d&&(f=this.startKeepAlive(d,u)),new Response(p,{status:200,headers:m})}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&&!vt.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${vt.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${vt.join(`, `)})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.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((gt(e)||_t(e))&&(n=e.id),n===void 0){if(gt(e)||_t(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)&&t!==void 0&&this._resumableStreams.add(r)}if(gt(e)||_t(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._closed){for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(r)){for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);this._resumableStreams.delete(r);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);throw Error(`No connection established for request ID: ${String(n)}`)}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(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);this._resumableStreams.delete(r)}}}},Td=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new wd(e),this._requestListener=vd(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,n){let r=e.auth;await vd(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};at({client_id:I(),client_secret:I().optional()}),at({grant_type:I()}),at({code:I(),code_verifier:I(),redirect_uri:I().optional(),resource:I().url().optional()}),at({refresh_token:I(),scope:I().optional(),resource:I().url().optional()}),at({client_id:I(),redirect_uri:I().optional().refine(e=>e===void 0||URL.canParse(e),{message:`redirect_uri must be a valid URL`})}),at({response_type:et(`code`),code_challenge:I(),code_challenge_method:et(`S256`),scope:I().optional(),state:I().optional(),resource:I().url().optional()}),(process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL===`true`||process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL===`1`)&&console.warn(`MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL is enabled - HTTP issuer URLs are allowed. Do not use in production.`);function Ed(e){let t=new URL(e.href),n=t.pathname&&t.pathname!==`/`?t.pathname:``;return new URL(`/.well-known/oauth-protected-resource${n}`,t).href}var Dd=a((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrometheusSerializer=void 0;var n=(F(),e(Te)),r=(Fa(),e(Pa)),i=(be(),e(ge)),a=(Oe(),e(De)),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,u=/_{2,}/g;function d(e){return e.replace(l,`_`).replace(u,`_`)}function f(e,t){return!e.endsWith(`_total`)&&t.dataPointType===r.DataPointType.SUM&&t.isMonotonic&&(e+=`_total`),e}function p(e){return e===1/0?`+Inf`:e===-1/0?`-Inf`:`${e}`}function m(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 h(e,t,n,r,i){let a=!1,o=``;for(let[e,n]of Object.entries(t)){let t=d(e);a=!0,o+=`${o.length>0?`,`:``}${t}="${c(n)}"`}if(i)for(let[e,t]of Object.entries(i)){let n=d(e);a=!0,o+=`${o.length>0?`,`:``}${n}="${c(t)}"`}return a&&(e+=`{${o}}`),`${e} ${p(n)}${r===void 0?``:` `+String(r)}\n`}var g=`# no registered metrics`;t.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+=g),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+`
|
|
61
|
-
`)}return t}_serializeMetricData(e,t){let i=d(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=f(i,e);let l=`# HELP ${i} ${s(e.descriptor.description||`description missing`)}`,u=e.descriptor.unit?`\n# UNIT ${i} ${s(e.descriptor.unit)}`:``,p=`# TYPE ${i} ${m(e)}`,h;if(this._withoutScopeInfo)h=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),h=Object.assign(e,this._additionalAttributes)}let g=``;switch(c){case r.DataPointType.SUM:case r.DataPointType.GAUGE:g=e.dataPoints.map(t=>this._serializeSingularDataPoint(i,e,t,h)).join(``);break;case r.DataPointType.HISTOGRAM:g=e.dataPoints.map(t=>this._serializeHistogramDataPoint(i,e,t,h)).join(``);break;default:n.diag.error(`Unrecognizable DataPointType: ${c} for metric "${i}"`)}return`${l}${u}\n${p}\n${g}`.trim()}_serializeSingularDataPoint(e,t,n,r){let a=``,{value:o,attributes:s}=n,c=(0,i.hrTimeToMilliseconds)(n.endTime);return a+=h(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+=h(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+=h(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${h(t,e.attributes,1).trim()}\n`}}})),Od=a((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`})),kd=a((n=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PrometheusExporter=void 0;var r=(F(),e(Te)),i=(be(),e(ge)),a=(Fa(),e(Pa)),o=t(`http`),s=Dd(),c=Od(),l=t(`url`);n.PrometheusExporter=class e extends a.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={},n=()=>{}){super({aggregationSelector:e=>({type:a.AggregationType.DEFAULT}),aggregationTemporalitySelector:e=>a.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 i=t.withResourceConstantLabels||e.DEFAULT_OPTIONS.withResourceConstantLabels,l=t.withoutScopeInfo||e.DEFAULT_OPTIONS.withoutScopeInfo,u=t.withoutTargetInfo||e.DEFAULT_OPTIONS.withoutTargetInfo;this._server=(0,o.createServer)(this._requestHandler).unref(),this._serializer=new s.PrometheusSerializer(this._prefix,this._appendTimestamp,i,u,l),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(t.endpoint||e.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,`/$1`),t.preventServerStart===!0?n&&queueMicrotask(n):this.startServer().then(n,e=>{r.diag.error(e),n(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,i.globalErrorHandler)(t):r.diag.debug(`Prometheus exporter was stopped`),e()})}):(r.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},()=>{r.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:n,errors:i}=t;i.length&&r.diag.error(`PrometheusExporter: metrics collection errors`,...i),e.end(this._serializer.serialize(n))},t=>{e.end(`# failed to export metrics: ${t}`)})};_notFound=e=>{e.statusCode=404,e.end()}}})),Ad=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=e.PrometheusExporter=void 0;var t=kd();Object.defineProperty(e,"PrometheusExporter",{enumerable:!0,get:function(){return t.PrometheusExporter}});var n=Dd();Object.defineProperty(e,"PrometheusSerializer",{enumerable:!0,get:function(){return n.PrometheusSerializer}})})),jd;(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`,e[e.LOWMEMORY=2]=`LOWMEMORY`})(jd||={}),be(),Fa(),F();var Md=()=>hn.CUMULATIVE,Nd=e=>{switch(e){case z.COUNTER:case z.OBSERVABLE_COUNTER:case z.GAUGE:case z.HISTOGRAM:case z.OBSERVABLE_GAUGE:return hn.DELTA;case z.UP_DOWN_COUNTER:case z.OBSERVABLE_UP_DOWN_COUNTER:return hn.CUMULATIVE}},Pd=e=>{switch(e){case z.COUNTER:case z.HISTOGRAM:return hn.DELTA;case z.GAUGE:case z.UP_DOWN_COUNTER:case z.OBSERVABLE_UP_DOWN_COUNTER:case z.OBSERVABLE_COUNTER:case z.OBSERVABLE_GAUGE:return hn.CUMULATIVE}};function Fd(){let e=(re(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`)??`cumulative`).toLowerCase();return e===`cumulative`?Md:e===`delta`?Nd:e===`lowmemory`?Pd:(P.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),Md)}function Id(e){return e==null?Fd():e===jd.DELTA?Nd:e===jd.LOWMEMORY?Pd:Md}var Ld=Object.freeze({type:Fr.DEFAULT});function Rd(e){return e?.aggregationPreference??(()=>Ld)}var zd=class extends h{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=Rd(t),this._aggregationTemporalitySelector=Id(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}},Bd=`otlp_http_metric_exporter`,Vd=class extends zd{_url;constructor(e){super(ae(O(e??{},`METRICS`,`v1/metrics`,{"Content-Type":`application/json`}),Ka,Bd,mn,e?.selfObsMeterProvider),e),this._url=e?.url}setSelfObsMeterProvider(e){this.setMetrics(me(Bd,mn,this._url,e))}},Hd=a((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`})),Ud=a((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BaseMetrics=void 0;var n=(F(),e(Te)),r=Hd(),i=r.PACKAGE_NAME;t.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}}})),Wd=a((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`})),Gd=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getProcessMemoryData=e.getMemoryData=e.getProcessCpuUsageData=e.getCpuUsageData=void 0;var n=t(`os`),r=1/1e3,i=1/1e6,a={time:Date.now(),cpus:(0,n.cpus)()};function o(){let e=Date.now(),t=e-a.time,i={time:e,cpus:(0,n.cpus)()},o=i.cpus.map((e,n)=>{let i=a.cpus[n].times,o=e.times,s=o.idle*r,c=o.user*r,l=o.sys*r,u=o.irq*r,d=o.nice*r,f=(o.idle-i.idle)/t,p=(o.user-i.user)/t,m=(o.sys-i.sys)/t,h=(o.irq-i.irq)/t,g=(o.nice-i.nice)/t;return{cpuNumber:String(n),idle:s,user:c,system:l,interrupt:u,nice:d,userP:p,systemP:m,idleP:f,interruptP:h,niceP:g}});return a=i,o}e.getCpuUsageData=o;var s={time:Date.now(),usage:process.cpuUsage()};function c(){let e=Date.now(),t=process.cpuUsage(),n=s.usage,r=(e-s.time)*1e3*a.cpus.length,o=t.user*i,c=t.system*i,l=(t.user-n.user)/r,u=(t.system-n.system)/r;return s={time:e,usage:t},{user:o,system:c,userP:l,systemP:u}}e.getProcessCpuUsageData=c;function l(){let e=(0,n.totalmem)(),t=(0,n.freemem)(),r=e-t,i=t/e;return{used:r,free:t,usedP:r/e,freeP:i}}e.getMemoryData=l;function u(){return process.memoryUsage.rss?process.memoryUsage.rss():process.memoryUsage().rss}e.getProcessMemoryData=u})),Kd=a((e=>{var n=t(`os`),r=t(`fs`),i=t(`path`),a=t(`child_process`).spawn,o=t(`child_process`).exec,s=t(`child_process`).execSync;t(`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=n.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`;r.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=a(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 P(){try{b&&(b.stdin.write(`exit`+n.EOL),b.stdin.end())}catch{b&&b.kill()}C=!1,b=null}function we(e){if(C){let t=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function i(e){r(e)}S.push({id:t,cmd:e,callback:i,start:new Date});try{b&&b.pid&&b.stdin.write(T+`echo `+E+t+`--##ID##--; `+n.EOL+e+n.EOL+`echo --###ENDCMD###--`+n.EOL)}catch{r(``)}})})}{let t=``;return new Promise(r=>{process.nextTick(()=>{try{let i=n.release().split(`.`).map(Number),o=i[0]<10?[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,`-`]:[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,T+e],s=a(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(t)}),s&&s.pid){if(s.stdout.on(`data`,e=>{t+=e.toString(`utf8`)}),s.stderr.on(`data`,()=>{s.kill(),r(t)}),s.on(`close`,()=>{s.kill(),r(t)}),s.on(`error`,()=>{s.kill(),r(t)}),i[0]<10)try{s.stdin.write(T+e+n.EOL),s.stdin.write(`exit`+n.EOL),s.stdin.end()}catch{s.kill(),r(t)}}else r(t)}catch{r(t)}})})}}function Te(e,t,n){let r=``;return n||={},new Promise(i=>{process.nextTick(()=>{try{let o=a(e,t,n);o&&!o.pid&&o.on(`error`,()=>{i(r)}),o&&o.pid?(o.stdout.on(`data`,e=>{r+=e.toString()}),o.on(`close`,()=>{o.kill(),i(r)}),o.on(`error`,()=>{o.kill(),i(r)})):i(r)}catch{i(r)}})})}function Ee(){if(d){if(!g)try{let e=s(`chcp`,A).toString().split(`\r
|
|
60
|
+
`;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.`)),new Response(JSON.stringify({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(!xd(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={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(t?.parsedBody!==void 0)i=t.parsedBody;else try{i=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let a;try{a=Array.isArray(i)?i.map(e=>Xt.parse(e)):[Xt.parse(i)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),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(kt);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`);if(!a.some(At)){for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:r});return new Response(null,{status:202})}let s=crypto.randomUUID(),c=a.find(e=>kt(e)),l=c?c.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(s,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(s)}});for(let e of a)At(e)&&this._requestToStreamMapping.set(e.id,s);for(let e of a)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:r})});let u=new TextEncoder,d,f,p=new ReadableStream({start:e=>{d=e},cancel:()=>{f!==void 0&&clearInterval(f),this._streamMapping.get(s)?.controller===d&&this._streamMapping.delete(s)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of a)At(e)&&(this._streamMapping.set(s,{controller:d,encoder:u,cleanup:()=>{f!==void 0&&clearInterval(f),this._streamMapping.delete(s);try{d.close()}catch{}}}),this._requestToStreamMapping.set(e.id,s));try{await this.writePrimingEvent(d,u,s,l);for(let e of a){let n,i;At(e)&&this._eventStore&&l>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:r,closeSSEStream:n,closeStandaloneSSEStream:i})}}catch(e){this._streamMapping.get(s)?.cleanup(),this._resumableStreams.delete(s);for(let e of a)At(e)&&this._requestToStreamMapping.delete(e.id);throw e}return this._streamMapping.get(s)?.controller===d&&(f=this.startKeepAlive(d,u)),new Response(p,{status:200,headers:m})}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&&!vt.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${vt.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${vt.join(`, `)})`)}async close(){this._closed||(this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.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((gt(e)||_t(e))&&(n=e.id),n===void 0){if(gt(e)||_t(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)&&t!==void 0&&this._resumableStreams.add(r)}if(gt(e)||_t(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._closed){for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(r)){for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);this._resumableStreams.delete(r);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);throw Error(`No connection established for request ID: ${String(n)}`)}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(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);this._resumableStreams.delete(r)}}}},Td=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new wd(e),this._requestListener=vd(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,n){let r=e.auth;await vd(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};at({client_id:I(),client_secret:I().optional()}),at({grant_type:I()}),at({code:I(),code_verifier:I(),redirect_uri:I().optional(),resource:I().url().optional()}),at({refresh_token:I(),scope:I().optional(),resource:I().url().optional()}),at({client_id:I(),redirect_uri:I().optional().refine(e=>e===void 0||URL.canParse(e),{message:`redirect_uri must be a valid URL`})}),at({response_type:et(`code`),code_challenge:I(),code_challenge_method:et(`S256`),scope:I().optional(),state:I().optional(),resource:I().url().optional()}),(process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL===`true`||process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL===`1`)&&console.warn(`MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL is enabled - HTTP issuer URLs are allowed. Do not use in production.`);function Ed(e){let t=new URL(e.href),n=t.pathname&&t.pathname!==`/`?t.pathname:``;return new URL(`/.well-known/oauth-protected-resource${n}`,t).href}var Dd=a((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrometheusSerializer=void 0;var n=(F(),e(Te)),r=(Fa(),e(Pa)),i=(A(),e(be)),a=(Oe(),e(De)),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,u=/_{2,}/g;function d(e){return e.replace(l,`_`).replace(u,`_`)}function f(e,t){return!e.endsWith(`_total`)&&t.dataPointType===r.DataPointType.SUM&&t.isMonotonic&&(e+=`_total`),e}function p(e){return e===1/0?`+Inf`:e===-1/0?`-Inf`:`${e}`}function m(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 h(e,t,n,r,i){let a=!1,o=``;for(let[e,n]of Object.entries(t)){let t=d(e);a=!0,o+=`${o.length>0?`,`:``}${t}="${c(n)}"`}if(i)for(let[e,t]of Object.entries(i)){let n=d(e);a=!0,o+=`${o.length>0?`,`:``}${n}="${c(t)}"`}return a&&(e+=`{${o}}`),`${e} ${p(n)}${r===void 0?``:` `+String(r)}\n`}var g=`# no registered metrics`;t.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+=g),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+`
|
|
61
|
+
`)}return t}_serializeMetricData(e,t){let i=d(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=f(i,e);let l=`# HELP ${i} ${s(e.descriptor.description||`description missing`)}`,u=e.descriptor.unit?`\n# UNIT ${i} ${s(e.descriptor.unit)}`:``,p=`# TYPE ${i} ${m(e)}`,h;if(this._withoutScopeInfo)h=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),h=Object.assign(e,this._additionalAttributes)}let g=``;switch(c){case r.DataPointType.SUM:case r.DataPointType.GAUGE:g=e.dataPoints.map(t=>this._serializeSingularDataPoint(i,e,t,h)).join(``);break;case r.DataPointType.HISTOGRAM:g=e.dataPoints.map(t=>this._serializeHistogramDataPoint(i,e,t,h)).join(``);break;default:n.diag.error(`Unrecognizable DataPointType: ${c} for metric "${i}"`)}return`${l}${u}\n${p}\n${g}`.trim()}_serializeSingularDataPoint(e,t,n,r){let a=``,{value:o,attributes:s}=n,c=(0,i.hrTimeToMilliseconds)(n.endTime);return a+=h(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+=h(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+=h(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${h(t,e.attributes,1).trim()}\n`}}})),Od=a((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`})),kd=a((n=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PrometheusExporter=void 0;var r=(F(),e(Te)),i=(A(),e(be)),a=(Fa(),e(Pa)),o=t(`http`),s=Dd(),c=Od(),l=t(`url`);n.PrometheusExporter=class e extends a.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={},n=()=>{}){super({aggregationSelector:e=>({type:a.AggregationType.DEFAULT}),aggregationTemporalitySelector:e=>a.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 i=t.withResourceConstantLabels||e.DEFAULT_OPTIONS.withResourceConstantLabels,l=t.withoutScopeInfo||e.DEFAULT_OPTIONS.withoutScopeInfo,u=t.withoutTargetInfo||e.DEFAULT_OPTIONS.withoutTargetInfo;this._server=(0,o.createServer)(this._requestHandler).unref(),this._serializer=new s.PrometheusSerializer(this._prefix,this._appendTimestamp,i,u,l),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(t.endpoint||e.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,`/$1`),t.preventServerStart===!0?n&&queueMicrotask(n):this.startServer().then(n,e=>{r.diag.error(e),n(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,i.globalErrorHandler)(t):r.diag.debug(`Prometheus exporter was stopped`),e()})}):(r.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},()=>{r.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:n,errors:i}=t;i.length&&r.diag.error(`PrometheusExporter: metrics collection errors`,...i),e.end(this._serializer.serialize(n))},t=>{e.end(`# failed to export metrics: ${t}`)})};_notFound=e=>{e.statusCode=404,e.end()}}})),Ad=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrometheusSerializer=e.PrometheusExporter=void 0;var t=kd();Object.defineProperty(e,"PrometheusExporter",{enumerable:!0,get:function(){return t.PrometheusExporter}});var n=Dd();Object.defineProperty(e,"PrometheusSerializer",{enumerable:!0,get:function(){return n.PrometheusSerializer}})})),jd;(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`,e[e.LOWMEMORY=2]=`LOWMEMORY`})(jd||={}),A(),Fa(),F();var Md=()=>hn.CUMULATIVE,Nd=e=>{switch(e){case z.COUNTER:case z.OBSERVABLE_COUNTER:case z.GAUGE:case z.HISTOGRAM:case z.OBSERVABLE_GAUGE:return hn.DELTA;case z.UP_DOWN_COUNTER:case z.OBSERVABLE_UP_DOWN_COUNTER:return hn.CUMULATIVE}},Pd=e=>{switch(e){case z.COUNTER:case z.HISTOGRAM:return hn.DELTA;case z.GAUGE:case z.UP_DOWN_COUNTER:case z.OBSERVABLE_UP_DOWN_COUNTER:case z.OBSERVABLE_COUNTER:case z.OBSERVABLE_GAUGE:return hn.CUMULATIVE}};function Fd(){let e=(s(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`)??`cumulative`).toLowerCase();return e===`cumulative`?Md:e===`delta`?Nd:e===`lowmemory`?Pd:(P.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),Md)}function Id(e){return e==null?Fd():e===jd.DELTA?Nd:e===jd.LOWMEMORY?Pd:Md}var Ld=Object.freeze({type:Fr.DEFAULT});function Rd(e){return e?.aggregationPreference??(()=>Ld)}var zd=class extends y{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=Rd(t),this._aggregationTemporalitySelector=Id(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}},Bd=`otlp_http_metric_exporter`,Vd=class extends zd{_url;constructor(e){super(he(ae(e??{},`METRICS`,`v1/metrics`,{"Content-Type":`application/json`}),Ka,Bd,mn,e?.selfObsMeterProvider),e),this._url=e?.url}setSelfObsMeterProvider(e){this.setMetrics(ee(Bd,mn,this._url,e))}},Hd=a((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`})),Ud=a((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BaseMetrics=void 0;var n=(F(),e(Te)),r=Hd(),i=r.PACKAGE_NAME;t.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}}})),Wd=a((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`})),Gd=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getProcessMemoryData=e.getMemoryData=e.getProcessCpuUsageData=e.getCpuUsageData=void 0;var n=t(`os`),r=1/1e3,i=1/1e6,a={time:Date.now(),cpus:(0,n.cpus)()};function o(){let e=Date.now(),t=e-a.time,i={time:e,cpus:(0,n.cpus)()},o=i.cpus.map((e,n)=>{let i=a.cpus[n].times,o=e.times,s=o.idle*r,c=o.user*r,l=o.sys*r,u=o.irq*r,d=o.nice*r,f=(o.idle-i.idle)/t,p=(o.user-i.user)/t,m=(o.sys-i.sys)/t,h=(o.irq-i.irq)/t,g=(o.nice-i.nice)/t;return{cpuNumber:String(n),idle:s,user:c,system:l,interrupt:u,nice:d,userP:p,systemP:m,idleP:f,interruptP:h,niceP:g}});return a=i,o}e.getCpuUsageData=o;var s={time:Date.now(),usage:process.cpuUsage()};function c(){let e=Date.now(),t=process.cpuUsage(),n=s.usage,r=(e-s.time)*1e3*a.cpus.length,o=t.user*i,c=t.system*i,l=(t.user-n.user)/r,u=(t.system-n.system)/r;return s={time:e,usage:t},{user:o,system:c,userP:l,systemP:u}}e.getProcessCpuUsageData=c;function l(){let e=(0,n.totalmem)(),t=(0,n.freemem)(),r=e-t,i=t/e;return{used:r,free:t,usedP:r/e,freeP:i}}e.getMemoryData=l;function u(){return process.memoryUsage.rss?process.memoryUsage.rss():process.memoryUsage().rss}e.getProcessMemoryData=u})),Kd=a((e=>{var n=t(`os`),r=t(`fs`),i=t(`path`),a=t(`child_process`).spawn,o=t(`child_process`).exec,s=t(`child_process`).execSync;t(`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=n.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`;r.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=a(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 P(){try{b&&(b.stdin.write(`exit`+n.EOL),b.stdin.end())}catch{b&&b.kill()}C=!1,b=null}function we(e){if(C){let t=Math.random().toString(36).substring(2,12);return new Promise(r=>{process.nextTick(()=>{function i(e){r(e)}S.push({id:t,cmd:e,callback:i,start:new Date});try{b&&b.pid&&b.stdin.write(T+`echo `+E+t+`--##ID##--; `+n.EOL+e+n.EOL+`echo --###ENDCMD###--`+n.EOL)}catch{r(``)}})})}{let t=``;return new Promise(r=>{process.nextTick(()=>{try{let i=n.release().split(`.`).map(Number),o=i[0]<10?[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-NoExit`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,`-`]:[`-NoProfile`,`-NoLogo`,`-InputFormat`,`Text`,`-ExecutionPolicy`,`Unrestricted`,`-Command`,T+e],s=a(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(t)}),s&&s.pid){if(s.stdout.on(`data`,e=>{t+=e.toString(`utf8`)}),s.stderr.on(`data`,()=>{s.kill(),r(t)}),s.on(`close`,()=>{s.kill(),r(t)}),s.on(`error`,()=>{s.kill(),r(t)}),i[0]<10)try{s.stdin.write(T+e+n.EOL),s.stdin.write(`exit`+n.EOL),s.stdin.end()}catch{s.kill(),r(t)}}else r(t)}catch{r(t)}})})}}function Te(e,t,n){let r=``;return n||={},new Promise(i=>{process.nextTick(()=>{try{let o=a(e,t,n);o&&!o.pid&&o.on(`error`,()=>{i(r)}),o&&o.pid?(o.stdout.on(`data`,e=>{r+=e.toString()}),o.on(`close`,()=>{o.kill(),i(r)}),o.on(`error`,()=>{o.kill(),i(r)})):i(r)}catch{i(r)}})})}function Ee(){if(d){if(!g)try{let e=s(`chcp`,A).toString().split(`\r
|
|
62
62
|
`)[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=s(`echo $LANG`,j).toString().split(`\r
|
|
63
63
|
`)[0].split(`.`);g=e.length>1?e[1].trim():``,g||=`UTF-8`}catch{g=`UTF-8`}return g}}function De(){if(_!==null)return _;if(_=!1,d)try{let e=s(`WHERE smartctl 2>nul`,A).toString().split(`\r
|
|
64
64
|
`);_=e&&e.length?e[0].indexOf(`:\\`)>=0:!1}catch{_=!1}if(l||u||f||p||m)try{_=s(`which smartctl 2>/dev/null`,j).toString().split(`\r
|
|
@@ -135,7 +135,7 @@ Profile on interface`)}catch(e){return e.status===1&&e.stdout.includes(`AutoConf
|
|
|
135
135
|
To resolve the conflict:`,Gp(t,e))),n=r):P.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
|
|
136
136
|
`,`Details:
|
|
137
137
|
`,Bp(t,e),`To resolve the conflict:
|
|
138
|
-
`,Gp(t,e))}return n}};F();var qp=class{_backingStorages;hasAttributeProcessor;constructor(e){this._backingStorages=e,this.hasAttributeProcessor=e.some(e=>e.hasAttributeProcessor)}record(e,t,n,r){this.hasAttributeProcessor&&n===void 0&&(n=Se.active());let i=this._backingStorages;for(let a=0;a<i.length;a++)i[a].record(e,t,n,r)}};F();var Jp=class{_buffer=new Fp;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){if(typeof e!=`number`){P.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===we.INT&&!Number.isInteger(e)&&(P.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)}},Yp=class{_buffer=new Map;observe(e,t,n={}){if(!jp(e))return;let r=this._buffer.get(e);if(r??(r=new Fp,this._buffer.set(e,r)),typeof t!=`number`){P.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`);return}e._descriptor.valueType===we.INT&&!Number.isInteger(t)&&(P.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),!Number.isInteger(t))||r.set(n,t)}};F();var Xp=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,t){let n=new Set(t.filter(jp));if(n.size===0){P.error(`BatchObservableCallback is not associated with valid instruments`,t);return}this._findBatchCallback(e,n)>=0||this._batchCallbacks.push({callback:e,instruments:n})}removeBatchCallback(e,t){let n=new Set(t.filter(jp)),r=this._findBatchCallback(e,n);r<0||this._batchCallbacks.splice(r,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:r})=>{let i=new Jp(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=nf(a,t)),await a,r._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:r})=>{let i=new Yp,a=Promise.resolve(n(i));t!=null&&(a=nf(a,t)),await a,r.forEach(t=>{let n=i._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&rf(n.instruments,t))}};F();var Zp=class extends Np{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new Ip(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Lp(t,r),this._attributesProcessor=n,this.hasAttributeProcessor=n!==void 0}hasAttributeProcessor;record(e,t,n,r){this._attributesProcessor!==void 0&&(t=this._attributesProcessor.process(t,n??Se.active())),this._deltaMetricStorage.record(e,t,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}},Qp=class{metricStorageRegistry=new Kp;observableRegistry=new Xp;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Mp(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,Zp);return t.length===1?t[0]:new qp(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,zp)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,t){let n=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(n=>{let r=vp(n,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(i!=null)return i;let a=new t(r,n.aggregation.createAggregator(r),n.attributesProcessor,this._meterProviderSharedState.metricCollectors,n.aggregationCardinalityLimit);return this.metricStorageRegistry.register(a),a});if(n.length===0){let r=this._meterProviderSharedState.selectAggregations(e.type).map(([n,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(n,e);if(i!=null)return i;let a=r.createAggregator(e),o=n.selectCardinalityLimit(e.type),s=new t(e,a,void 0,[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}},$p=class{viewRegistry=new gp;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let t=ef(e),n=this.meterSharedStates.get(t);return n??(n=new Qp(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,np(n.selectAggregation(e))]);return t}},em=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let t=ze(Date.now()),n=[],r=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,t,e);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&r.push(...a.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:r}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}},tm=/[\^$\\.+?()[\]{}|]/g,nm=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(tm,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},rm=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}},im=class{process(e,t){return e}},am=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}};function om(){return cm}function sm(e){return new am(e)}var cm=new im,lm=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new nm(e?.name??`*`),this._type=e?.type,this._unitFilter=new rm(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}},um=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new rm(e?.name),this._versionFilter=new rm(e?.version),this._schemaUrlFilter=new rm(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}};function dm(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function fm(e){if(dm(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||nm.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}var pm=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){fm(e),this.attributesProcessor=e.attributesProcessors==null?om():sm(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=np(e.aggregation??{type:tp.DEFAULT}),this.instrumentSelector=new lm({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new um({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}};F();var mm=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new $p(e?.resource??ke()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new pm(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let n=new em(this._sharedState,t);t.setMetricProducer(n),this._sharedState.metricCollectors.push(n),e.sdkMetricsEnabled&&t instanceof pp&&t._setSelfObsMeterProvider(this)}}getMeter(e,t=``,n={}){return this._shutdown?(P.warn(`A shutdown MeterProvider cannot provide a Meter`),Ce()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){P.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){P.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}},hm=Ad(),gm=Xd(),_m=`bearer `,vm=4096;function ym(e){if(e===void 0||e.length>vm||e.slice(0,7).toLowerCase()!==_m)return;let t=e.slice(7).trim();return t.length>0?t:void 0}F();var bm=`aventure-mcp-server`,xm=`http_server_requests_seconds`,Sm=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],Cm,wm,Tm,Em,Dm;function Om(e,t){if(wm!==void 0)return;let n=e?new hm.PrometheusExporter({preventServerStart:!0}):void 0,r=new mm({resource:Ee({...f(),"service.instance.id":pn(),"service.version":process.env.GIT_SHA??process.env.SENTRY_RELEASE??C().version}),readers:[...n===void 0?[]:[n],...t===void 0?[]:[new hp({exporter:new Vd({url:t}),exportIntervalMillis:1e4,exportTimeoutMillis:5e3})]]});Ae.setGlobalMeterProvider(r),wm=r,Cm=n;let i=new gm.HostMetrics({meterProvider:r,name:bm});i.start(),Dm=i}function km(){return Tm===void 0&&(Tm=wm?.getMeter(bm)),Tm}function Am(e,t,n,r){let i=km();i!==void 0&&(Em===void 0&&(Em=i.createHistogram(xm,{description:`HTTP server request latency in seconds, partitioned by method/route/status.`,unit:`s`,advice:{explicitBucketBoundaries:Sm}})),Em.record(r/1e3,{method:e.toUpperCase(),route:t,status:String(n)}))}function jm(e,t){let n=C().registry===``&&!!t,r=process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?.trim()||void 0;if(!n&&r===void 0)return;Om(n,r);let i=Cm;if(!n||t===void 0||i===void 0)return;let a=cn(`sha256`).update(t).digest();e.get(`/metrics`,(e,t,n)=>{if(!Nm(e.headers.authorization,a)){t.status(401).type(`text/plain`).send(`Unauthorized`);return}n()},(e,t)=>{i.getMetricsRequestHandler(e,t)})}async function Mm(){let e=wm;Dm!==void 0&&(Dm=void 0),wm=void 0,Cm=void 0,Tm=void 0,Em=void 0,e!==void 0&&await e.shutdown()}function Nm(e,t){let n=ym(e);if(n===void 0)return!1;let r=cn(`sha256`).update(n).digest();return r.length===t.length&&un(r,t)}var V;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(V||={});var Pm;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Pm||={});var H=V.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Fm=e=>{switch(typeof e){case`undefined`:return H.undefined;case`string`:return H.string;case`number`:return Number.isNaN(e)?H.nan:H.number;case`boolean`:return H.boolean;case`function`:return H.function;case`bigint`:return H.bigint;case`symbol`:return H.symbol;case`object`:return Array.isArray(e)?H.array:e===null?H.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?H.promise:typeof Map<`u`&&e instanceof Map?H.map:typeof Set<`u`&&e instanceof Set?H.set:typeof Date<`u`&&e instanceof Date?H.date:H.object;default:return H.unknown}},U=V.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),Im=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,V.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Im.create=e=>new Im(e);var Lm=(e,t)=>{let n;switch(e.code){case U.invalid_type:n=e.received===H.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case U.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,V.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(e.keys,`, `)}`;break;case U.invalid_union:n=`Invalid input`;break;case U.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(e.options)}`;break;case U.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(e.options)}, received '${e.received}'`;break;case U.invalid_arguments:n=`Invalid function arguments`;break;case U.invalid_return_type:n=`Invalid function return type`;break;case U.invalid_date:n=`Invalid date`;break;case U.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:V.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case U.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case U.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case U.custom:n=`Invalid input`;break;case U.invalid_intersection_types:n=`Intersection results could not be merged`;break;case U.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case U.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,V.assertNever(e)}return{message:n}},Rm=Lm;function zm(){return Rm}var Bm=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function W(e,t){let n=zm(),r=Bm({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Lm?void 0:Lm].filter(e=>!!e)});e.common.issues.push(r)}var Vm=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return G;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return G;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},G=Object.freeze({status:`aborted`}),Hm=e=>({status:`dirty`,value:e}),Um=e=>({status:`valid`,value:e}),Wm=e=>e.status===`aborted`,Gm=e=>e.status===`dirty`,Km=e=>e.status===`valid`,qm=e=>typeof Promise<`u`&&e instanceof Promise,K;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(K||={});var Jm=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ym=(e,t)=>{if(Km(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new Im(e.common.issues);return this._error=t,this._error}}};function q(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var J=class{get description(){return this._def.description}_getType(e){return Fm(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Fm(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Vm,ctx:{common:e.parent.common,data:e.data,parsedType:Fm(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qm(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fm(e)};return Ym(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fm(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Km(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Km(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fm(e)},r=this._parse({data:e,path:n.path,parent:n});return Ym(n,await(qm(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:U.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new Qh({schema:this,typeName:Y.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return $h.create(this,this._def)}nullable(){return eg.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nh.create(this)}promise(){return Zh.create(this,this._def)}or(e){return Ih.create([this,e],this._def)}and(e){return Bh.create(this,e,this._def)}transform(e){return new Qh({...q(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new tg({...q(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new ig({typeName:Y.ZodBranded,type:this,...q(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ng({...q(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ag.create(this,e)}readonly(){return og.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Xm=/^c[^\s-]{8,}$/i,Zm=/^[0-9a-z]+$/,Qm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$m=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,eh=/^[a-z0-9_-]{21}$/i,th=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nh=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ih=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,ah,oh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ch=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,lh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fh=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,ph=RegExp(`^${fh}$`);function mh(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function hh(e){return RegExp(`^${mh(e)}$`)}function gh(e){let t=`${fh}T${mh(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function _h(e,t){return!((t!==`v4`&&t||!oh.test(e))&&(t!==`v6`&&t||!ch.test(e)))}function vh(e,t){if(!th.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function yh(e,t){return!((t!==`v4`&&t||!sh.test(e))&&(t!==`v6`&&t||!lh.test(e)))}var bh=class e extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.string){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.string,received:t.parsedType}),G}let t=new Vm,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?W(n,{code:U.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&W(n,{code:U.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)rh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`email`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)ah||=new RegExp(ih,`u`),ah.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`emoji`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)$m.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`uuid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)eh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`nanoid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Xm.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`cuid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Zm.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`cuid2`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Qm.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`ulid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),W(n,{validation:`url`,code:U.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`regex`,code:U.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?gh(r).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ph.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?hh(r).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?nh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`duration`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?_h(e.data,r.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`ip`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?vh(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`jwt`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?yh(e.data,r.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`cidr`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?uh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`base64`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?dh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`base64url`,code:U.invalid_string,message:r.message}),t.dirty()):V.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:U.invalid_string,...K.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...K.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...K.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...K.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...K.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...K.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...K.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...K.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...K.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...K.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...K.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...K.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...K.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...K.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...K.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...K.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...K.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...K.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...K.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...K.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...K.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...K.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...K.errToObj(t)})}nonempty(e){return this.min(1,K.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};bh.create=e=>new bh({checks:[],typeName:Y.ZodString,coerce:e?.coerce??!1,...q(e)});function xh(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Sh=class e extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==H.number){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.number,received:t.parsedType}),G}let t,n=new Vm;for(let r of this._def.checks)r.kind===`int`?V.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),W(t,{code:U.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?xh(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),W(t,{code:U.not_finite,message:r.message}),n.dirty()):V.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,K.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,K.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,K.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,K.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:K.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:K.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:K.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:K.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:K.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&V.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Sh.create=e=>new Sh({checks:[],typeName:Y.ZodNumber,coerce:e?.coerce||!1,...q(e)});var Ch=class e extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==H.bigint)return this._getInvalidInput(e);let t,n=new Vm;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):V.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.bigint,received:t.parsedType}),G}gte(e,t){return this.setLimit(`min`,e,!0,K.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,K.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,K.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,K.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:K.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ch.create=e=>new Ch({checks:[],typeName:Y.ZodBigInt,coerce:e?.coerce??!1,...q(e)});var wh=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.boolean){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.boolean,received:t.parsedType}),G}return Um(e.data)}};wh.create=e=>new wh({typeName:Y.ZodBoolean,coerce:e?.coerce||!1,...q(e)});var Th=class e extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.date){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.date,received:t.parsedType}),G}if(Number.isNaN(e.data.getTime()))return W(this._getOrReturnCtx(e),{code:U.invalid_date}),G;let t=new Vm,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):V.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:K.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:K.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Th.create=e=>new Th({checks:[],coerce:e?.coerce||!1,typeName:Y.ZodDate,...q(e)});var Eh=class extends J{_parse(e){if(this._getType(e)!==H.symbol){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.symbol,received:t.parsedType}),G}return Um(e.data)}};Eh.create=e=>new Eh({typeName:Y.ZodSymbol,...q(e)});var Dh=class extends J{_parse(e){if(this._getType(e)!==H.undefined){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.undefined,received:t.parsedType}),G}return Um(e.data)}};Dh.create=e=>new Dh({typeName:Y.ZodUndefined,...q(e)});var Oh=class extends J{_parse(e){if(this._getType(e)!==H.null){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.null,received:t.parsedType}),G}return Um(e.data)}};Oh.create=e=>new Oh({typeName:Y.ZodNull,...q(e)});var kh=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return Um(e.data)}};kh.create=e=>new kh({typeName:Y.ZodAny,...q(e)});var Ah=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Um(e.data)}};Ah.create=e=>new Ah({typeName:Y.ZodUnknown,...q(e)});var jh=class extends J{_parse(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.never,received:t.parsedType}),G}};jh.create=e=>new jh({typeName:Y.ZodNever,...q(e)});var Mh=class extends J{_parse(e){if(this._getType(e)!==H.undefined){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.void,received:t.parsedType}),G}return Um(e.data)}};Mh.create=e=>new Mh({typeName:Y.ZodVoid,...q(e)});var Nh=class e extends J{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==H.array)return W(t,{code:U.invalid_type,expected:H.array,received:t.parsedType}),G;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(W(t,{code:e?U.too_big:U.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(W(t,{code:U.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(W(t,{code:U.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Jm(t,e,t.path,n)))).then(e=>Vm.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Jm(t,e,t.path,n)));return Vm.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(e){return this.min(1,e)}};Nh.create=(e,t)=>new Nh({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...q(t)});function Ph(e){if(e instanceof Fh){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=$h.create(Ph(r))}return new Fh({...e._def,shape:()=>t})}return e instanceof Nh?new Nh({...e._def,type:Ph(e.element)}):e instanceof $h?$h.create(Ph(e.unwrap())):e instanceof eg?eg.create(Ph(e.unwrap())):e instanceof Vh?Vh.create(e.items.map(e=>Ph(e))):e}var Fh=class e extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=V.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==H.object){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.object,received:t.parsedType}),G}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof jh&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Jm(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof jh){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(W(n,{code:U.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Jm(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Vm.mergeObjectSync(t,e)):Vm.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:K.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of V.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of V.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ph(this)}partial(t){let n={};for(let e of V.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of V.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof $h;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Jh(V.objectKeys(this.shape))}};Fh.create=(e,t)=>new Fh({shape:()=>e,unknownKeys:`strip`,catchall:jh.create(),typeName:Y.ZodObject,...q(t)}),Fh.strictCreate=(e,t)=>new Fh({shape:()=>e,unknownKeys:`strict`,catchall:jh.create(),typeName:Y.ZodObject,...q(t)}),Fh.lazycreate=(e,t)=>new Fh({shape:e,unknownKeys:`strip`,catchall:jh.create(),typeName:Y.ZodObject,...q(t)});var Ih=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Im(e.ctx.common.issues));return W(t,{code:U.invalid_union,unionErrors:n}),G}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Im(e));return W(t,{code:U.invalid_union,unionErrors:i}),G}}get options(){return this._def.options}};Ih.create=(e,t)=>new Ih({options:e,typeName:Y.ZodUnion,...q(t)});var Lh=e=>e instanceof Kh?Lh(e.schema):e instanceof Qh?Lh(e.innerType()):e instanceof qh?[e.value]:e instanceof Yh?e.options:e instanceof Xh?V.objectValues(e.enum):e instanceof tg?Lh(e._def.innerType):e instanceof Dh?[void 0]:e instanceof Oh?[null]:e instanceof $h?[void 0,...Lh(e.unwrap())]:e instanceof eg?[null,...Lh(e.unwrap())]:e instanceof ig||e instanceof og?Lh(e.unwrap()):e instanceof ng?Lh(e._def.innerType):[],Rh=class e extends J{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==H.object)return W(t,{code:U.invalid_type,expected:H.object,received:t.parsedType}),G;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(W(t,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Lh(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Y.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...q(r)})}};function zh(e,t){let n=Fm(e),r=Fm(t);if(e===t)return{valid:!0,data:e};if(n===H.object&&r===H.object){let n=V.objectKeys(t),r=V.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=zh(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===H.array&&r===H.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=zh(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===H.date&&r===H.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Bh=class extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Wm(e)||Wm(r))return G;let i=zh(e.value,r.value);return i.valid?((Gm(e)||Gm(r))&&t.dirty(),{status:t.value,value:i.data}):(W(n,{code:U.invalid_intersection_types}),G)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Bh.create=(e,t,n)=>new Bh({left:e,right:t,typeName:Y.ZodIntersection,...q(n)});var Vh=class e extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.array)return W(n,{code:U.invalid_type,expected:H.array,received:n.parsedType}),G;if(n.data.length<this._def.items.length)return W(n,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),G;!this._def.rest&&n.data.length>this._def.items.length&&(W(n,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Jm(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Vm.mergeArray(t,e)):Vm.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Vh.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Vh({items:e,typeName:Y.ZodTuple,rest:null,...q(t)})};var Hh=class e extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.object)return W(n,{code:U.invalid_type,expected:H.object,received:n.parsedType}),G;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Jm(n,e,n.path,e)),value:a._parse(new Jm(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Vm.mergeObjectAsync(t,r):Vm.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof J?new e({keyType:t,valueType:n,typeName:Y.ZodRecord,...q(r)}):new e({keyType:bh.create(),valueType:t,typeName:Y.ZodRecord,...q(n)})}},Uh=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.map)return W(n,{code:U.invalid_type,expected:H.map,received:n.parsedType}),G;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Jm(n,e,n.path,[a,`key`])),value:i._parse(new Jm(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return G;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return G;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Uh.create=(e,t,n)=>new Uh({valueType:t,keyType:e,typeName:Y.ZodMap,...q(n)});var Wh=class e extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.set)return W(n,{code:U.invalid_type,expected:H.set,received:n.parsedType}),G;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(W(n,{code:U.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(W(n,{code:U.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return G;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Jm(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:K.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Wh.create=(e,t)=>new Wh({valueType:e,minSize:null,maxSize:null,typeName:Y.ZodSet,...q(t)});var Gh=class e extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==H.function)return W(t,{code:U.invalid_type,expected:H.function,received:t.parsedType}),G;function n(e,n){return Bm({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zm(),Lm].filter(e=>!!e),issueData:{code:U.invalid_arguments,argumentsError:n}})}function r(e,n){return Bm({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zm(),Lm].filter(e=>!!e),issueData:{code:U.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Zh){let e=this;return Um(async function(...t){let o=new Im([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return Um(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Im([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Im([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Vh.create(t).rest(Ah.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Vh.create([]).rest(Ah.create()),returns:n||Ah.create(),typeName:Y.ZodFunction,...q(r)})}},Kh=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Kh.create=(e,t)=>new Kh({getter:e,typeName:Y.ZodLazy,...q(t)});var qh=class extends J{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return W(t,{received:t.data,code:U.invalid_literal,expected:this._def.value}),G}return{status:`valid`,value:e.data}}get value(){return this._def.value}};qh.create=(e,t)=>new qh({value:e,typeName:Y.ZodLiteral,...q(t)});function Jh(e,t){return new Yh({values:e,typeName:Y.ZodEnum,...q(t)})}var Yh=class e extends J{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return W(t,{expected:V.joinValues(n),received:t.parsedType,code:U.invalid_type}),G}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return W(t,{received:t.data,code:U.invalid_enum_value,options:n}),G}return Um(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Yh.create=Jh;var Xh=class extends J{_parse(e){let t=V.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==H.string&&n.parsedType!==H.number){let e=V.objectValues(t);return W(n,{expected:V.joinValues(e),received:n.parsedType,code:U.invalid_type}),G}if(this._cache||=new Set(V.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=V.objectValues(t);return W(n,{received:n.data,code:U.invalid_enum_value,options:e}),G}return Um(e.data)}get enum(){return this._def.values}};Xh.create=(e,t)=>new Xh({values:e,typeName:Y.ZodNativeEnum,...q(t)});var Zh=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==H.promise&&t.common.async===!1?(W(t,{code:U.invalid_type,expected:H.promise,received:t.parsedType}),G):Um((t.parsedType===H.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Zh.create=(e,t)=>new Zh({type:e,typeName:Y.ZodPromise,...q(t)});var Qh=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{W(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return G;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?G:r.status===`dirty`||t.value===`dirty`?Hm(r.value):r});{if(t.value===`aborted`)return G;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?G:r.status===`dirty`||t.value===`dirty`?Hm(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?G:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?G:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Km(e))return G;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Km(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):G)}V.assertNever(r)}};Qh.create=(e,t,n)=>new Qh({schema:e,typeName:Y.ZodEffects,effect:t,...q(n)}),Qh.createWithPreprocess=(e,t,n)=>new Qh({schema:t,effect:{type:`preprocess`,transform:e},typeName:Y.ZodEffects,...q(n)});var $h=class extends J{_parse(e){return this._getType(e)===H.undefined?Um(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$h.create=(e,t)=>new $h({innerType:e,typeName:Y.ZodOptional,...q(t)});var eg=class extends J{_parse(e){return this._getType(e)===H.null?Um(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};eg.create=(e,t)=>new eg({innerType:e,typeName:Y.ZodNullable,...q(t)});var tg=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===H.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};tg.create=(e,t)=>new tg({innerType:e,typeName:Y.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...q(t)});var ng=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qm(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Im(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Im(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ng.create=(e,t)=>new ng({innerType:e,typeName:Y.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...q(t)});var rg=class extends J{_parse(e){if(this._getType(e)!==H.nan){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.nan,received:t.parsedType}),G}return{status:`valid`,value:e.data}}};rg.create=e=>new rg({typeName:Y.ZodNaN,...q(e)});var ig=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ag=class e extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?G:e.status===`dirty`?(t.dirty(),Hm(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?G:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Y.ZodPipeline})}},og=class extends J{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Km(e)&&(e.value=Object.freeze(e.value)),e);return qm(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};og.create=(e,t)=>new og({innerType:e,typeName:Y.ZodReadonly,...q(t)}),Fh.lazycreate;var Y;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Y||={}),bh.create,Sh.create,rg.create,Ch.create,wh.create,Th.create,Eh.create,Dh.create,Oh.create,kh.create,Ah.create,jh.create,Mh.create,Nh.create;var sg=Fh.create;Fh.strictCreate,Ih.create,Rh.create,Bh.create,Vh.create,Hh.create,Uh.create,Wh.create,Gh.create,Kh.create,qh.create,Yh.create,Xh.create,Zh.create,Qh.create,$h.create,eg.create,Qh.createWithPreprocess,ag.create;var cg=Ue(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);qe.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Je(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>We(e,t,n),e.parseAsync=async(t,n)=>He(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ge(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>ct(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),lg=Ue(`ZodMiniObject`,(e,t)=>{Ke.init(e,t),cg.init(e,t),Ve(e,`shape`,()=>t.shape)});function ug(e,t){return new lg({type:`object`,shape:e??{},...Ye(t)})}function dg(e){return!!e._zod}function fg(e){let t=Object.values(e);if(t.length===0)return ug({});let n=t.every(dg),r=t.every(e=>!dg(e));if(n)return ug(e);if(r)return sg(e);throw Error(`Mixed Zod versions detected in object shape.`)}function pg(e,t){return dg(e)?We(e,t):e.safeParse(t)}async function mg(e,t){return dg(e)?await Ge(e,t):await e.safeParseAsync(t)}function hg(e){if(!e)return;let t;if(t=dg(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function gg(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return fg(e)}}if(dg(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function _g(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function vg(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${_g(e.path)}`:e.message).join(`
|
|
138
|
+
`,Gp(t,e))}return n}};F();var qp=class{_backingStorages;hasAttributeProcessor;constructor(e){this._backingStorages=e,this.hasAttributeProcessor=e.some(e=>e.hasAttributeProcessor)}record(e,t,n,r){this.hasAttributeProcessor&&n===void 0&&(n=Se.active());let i=this._backingStorages;for(let a=0;a<i.length;a++)i[a].record(e,t,n,r)}};F();var Jp=class{_buffer=new Fp;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){if(typeof e!=`number`){P.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===we.INT&&!Number.isInteger(e)&&(P.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(t,e)}},Yp=class{_buffer=new Map;observe(e,t,n={}){if(!jp(e))return;let r=this._buffer.get(e);if(r??(r=new Fp,this._buffer.set(e,r)),typeof t!=`number`){P.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`);return}e._descriptor.valueType===we.INT&&!Number.isInteger(t)&&(P.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),!Number.isInteger(t))||r.set(n,t)}};F();var Xp=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,t){let n=new Set(t.filter(jp));if(n.size===0){P.error(`BatchObservableCallback is not associated with valid instruments`,t);return}this._findBatchCallback(e,n)>=0||this._batchCallbacks.push({callback:e,instruments:n})}removeBatchCallback(e,t){let n=new Set(t.filter(jp)),r=this._findBatchCallback(e,n);r<0||this._batchCallbacks.splice(r,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...n,...r])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:r})=>{let i=new Jp(r._descriptor.name,r._descriptor.valueType),a=Promise.resolve(n(i));t!=null&&(a=nf(a,t)),await a,r._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:r})=>{let i=new Yp,a=Promise.resolve(n(i));t!=null&&(a=nf(a,t)),await a,r.forEach(t=>{let n=i._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&rf(n.instruments,t))}};F();var Zp=class extends Np{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,n,r,i){super(e),this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new Ip(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Lp(t,r),this._attributesProcessor=n,this.hasAttributeProcessor=n!==void 0}hasAttributeProcessor;record(e,t,n,r){this._attributesProcessor!==void 0&&(t=this._attributesProcessor.process(t,n??Se.active())),this._deltaMetricStorage.record(e,t,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}},Qp=class{metricStorageRegistry=new Kp;observableRegistry=new Xp;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new Mp(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,Zp);return t.length===1?t[0]:new qp(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,zp)}async collect(e,t,n){let r=await this.observableRegistry.observe(t,n?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(i.length===0)return null;let a=[];return i.forEach(n=>{let r=n.collect(e,t);r!=null&&a.push(r)}),a.length===0?{errors:r}:{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:r}}_registerMetricStorage(e,t){let n=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(n=>{let r=vp(n,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(i!=null)return i;let a=new t(r,n.aggregation.createAggregator(r),n.attributesProcessor,this._meterProviderSharedState.metricCollectors,n.aggregationCardinalityLimit);return this.metricStorageRegistry.register(a),a});if(n.length===0){let r=this._meterProviderSharedState.selectAggregations(e.type).map(([n,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(n,e);if(i!=null)return i;let a=r.createAggregator(e),o=n.selectCardinalityLimit(e.type),s=new t(e,a,void 0,[n],o);return this.metricStorageRegistry.registerForCollector(n,s),s});n=n.concat(r)}return n}},$p=class{viewRegistry=new gp;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let t=ef(e),n=this.meterSharedStates.get(t);return n??(n=new Qp(this,e),this.meterSharedStates.set(t,n)),n}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,np(n.selectAggregation(e))]);return t}},em=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let t=ze(Date.now()),n=[],r=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,t,e);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&r.push(...a.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:r}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}},tm=/[\^$\\.+?()[\]{}|]/g,nm=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(tm,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},rm=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}},im=class{process(e,t){return e}},am=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}};function om(){return cm}function sm(e){return new am(e)}var cm=new im,lm=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new nm(e?.name??`*`),this._type=e?.type,this._unitFilter=new rm(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}},um=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new rm(e?.name),this._versionFilter=new rm(e?.version),this._schemaUrlFilter=new rm(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}};function dm(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function fm(e){if(dm(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||nm.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}var pm=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){fm(e),this.attributesProcessor=e.attributesProcessors==null?om():sm(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=np(e.aggregation??{type:tp.DEFAULT}),this.instrumentSelector=new lm({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new um({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}};F();var mm=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new $p(e?.resource??ke()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new pm(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let n=new em(this._sharedState,t);t.setMetricProducer(n),this._sharedState.metricCollectors.push(n),e.sdkMetricsEnabled&&t instanceof pp&&t._setSelfObsMeterProvider(this)}}getMeter(e,t=``,n={}){return this._shutdown?(P.warn(`A shutdown MeterProvider cannot provide a Meter`),Ce()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter}async shutdown(e){if(this._shutdown){P.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){P.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}},hm=Ad(),gm=Xd(),_m=`bearer `,vm=4096;function ym(e){if(e===void 0||e.length>vm||e.slice(0,7).toLowerCase()!==_m)return;let t=e.slice(7).trim();return t.length>0?t:void 0}F();var bm=`aventure-mcp-server`,xm=`http_server_requests_seconds`,Sm=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],Cm,wm,Tm,Em,Dm;function Om(e,t){if(wm!==void 0)return;let n=e?new hm.PrometheusExporter({preventServerStart:!0}):void 0,r=new mm({resource:Ee({...m(),"service.instance.id":pn(),"service.version":process.env.GIT_SHA??process.env.SENTRY_RELEASE??T().version}),readers:[...n===void 0?[]:[n],...t===void 0?[]:[new hp({exporter:new Vd({url:t}),exportIntervalMillis:1e4,exportTimeoutMillis:5e3})]]});Ae.setGlobalMeterProvider(r),wm=r,Cm=n;let i=new gm.HostMetrics({meterProvider:r,name:bm});i.start(),Dm=i}function km(){return Tm===void 0&&(Tm=wm?.getMeter(bm)),Tm}function Am(e,t,n,r){let i=km();i!==void 0&&(Em===void 0&&(Em=i.createHistogram(xm,{description:`HTTP server request latency in seconds, partitioned by method/route/status.`,unit:`s`,advice:{explicitBucketBoundaries:Sm}})),Em.record(r/1e3,{method:e.toUpperCase(),route:t,status:String(n)}))}function jm(e,t){let n=T().registry===``&&!!t,r=process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?.trim()||void 0;if(!n&&r===void 0)return;Om(n,r);let i=Cm;if(!n||t===void 0||i===void 0)return;let a=cn(`sha256`).update(t).digest();e.get(`/metrics`,(e,t,n)=>{if(!Nm(e.headers.authorization,a)){t.status(401).type(`text/plain`).send(`Unauthorized`);return}n()},(e,t)=>{i.getMetricsRequestHandler(e,t)})}async function Mm(){let e=wm;Dm!==void 0&&(Dm=void 0),wm=void 0,Cm=void 0,Tm=void 0,Em=void 0,e!==void 0&&await e.shutdown()}function Nm(e,t){let n=ym(e);if(n===void 0)return!1;let r=cn(`sha256`).update(n).digest();return r.length===t.length&&un(r,t)}var V;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(V||={});var Pm;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Pm||={});var H=V.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Fm=e=>{switch(typeof e){case`undefined`:return H.undefined;case`string`:return H.string;case`number`:return Number.isNaN(e)?H.nan:H.number;case`boolean`:return H.boolean;case`function`:return H.function;case`bigint`:return H.bigint;case`symbol`:return H.symbol;case`object`:return Array.isArray(e)?H.array:e===null?H.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?H.promise:typeof Map<`u`&&e instanceof Map?H.map:typeof Set<`u`&&e instanceof Set?H.set:typeof Date<`u`&&e instanceof Date?H.date:H.object;default:return H.unknown}},U=V.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]),Im=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,V.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Im.create=e=>new Im(e);var Lm=(e,t)=>{let n;switch(e.code){case U.invalid_type:n=e.received===H.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case U.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,V.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(e.keys,`, `)}`;break;case U.invalid_union:n=`Invalid input`;break;case U.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(e.options)}`;break;case U.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(e.options)}, received '${e.received}'`;break;case U.invalid_arguments:n=`Invalid function arguments`;break;case U.invalid_return_type:n=`Invalid function return type`;break;case U.invalid_date:n=`Invalid date`;break;case U.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:V.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case U.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case U.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case U.custom:n=`Invalid input`;break;case U.invalid_intersection_types:n=`Intersection results could not be merged`;break;case U.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case U.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,V.assertNever(e)}return{message:n}},Rm=Lm;function zm(){return Rm}var Bm=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function W(e,t){let n=zm(),r=Bm({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Lm?void 0:Lm].filter(e=>!!e)});e.common.issues.push(r)}var Vm=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return G;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return G;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},G=Object.freeze({status:`aborted`}),Hm=e=>({status:`dirty`,value:e}),Um=e=>({status:`valid`,value:e}),Wm=e=>e.status===`aborted`,Gm=e=>e.status===`dirty`,Km=e=>e.status===`valid`,qm=e=>typeof Promise<`u`&&e instanceof Promise,K;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(K||={});var Jm=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ym=(e,t)=>{if(Km(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new Im(e.common.issues);return this._error=t,this._error}}};function q(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var J=class{get description(){return this._def.description}_getType(e){return Fm(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Fm(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Vm,ctx:{common:e.parent.common,data:e.data,parsedType:Fm(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qm(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fm(e)};return Ym(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fm(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Km(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Km(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fm(e)},r=this._parse({data:e,path:n.path,parent:n});return Ym(n,await(qm(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:U.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new Qh({schema:this,typeName:Y.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return $h.create(this,this._def)}nullable(){return eg.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nh.create(this)}promise(){return Zh.create(this,this._def)}or(e){return Ih.create([this,e],this._def)}and(e){return Bh.create(this,e,this._def)}transform(e){return new Qh({...q(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new tg({...q(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new ig({typeName:Y.ZodBranded,type:this,...q(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ng({...q(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ag.create(this,e)}readonly(){return og.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Xm=/^c[^\s-]{8,}$/i,Zm=/^[0-9a-z]+$/,Qm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$m=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,eh=/^[a-z0-9_-]{21}$/i,th=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nh=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ih=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,ah,oh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ch=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,lh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,uh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fh=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,ph=RegExp(`^${fh}$`);function mh(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function hh(e){return RegExp(`^${mh(e)}$`)}function gh(e){let t=`${fh}T${mh(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function _h(e,t){return!((t!==`v4`&&t||!oh.test(e))&&(t!==`v6`&&t||!ch.test(e)))}function vh(e,t){if(!th.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function yh(e,t){return!((t!==`v4`&&t||!sh.test(e))&&(t!==`v6`&&t||!lh.test(e)))}var bh=class e extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.string){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.string,received:t.parsedType}),G}let t=new Vm,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?W(n,{code:U.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&W(n,{code:U.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)rh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`email`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)ah||=new RegExp(ih,`u`),ah.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`emoji`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)$m.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`uuid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)eh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`nanoid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Xm.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`cuid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Zm.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`cuid2`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Qm.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`ulid`,code:U.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),W(n,{validation:`url`,code:U.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`regex`,code:U.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?gh(r).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ph.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?hh(r).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:U.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?nh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`duration`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?_h(e.data,r.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`ip`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?vh(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`jwt`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?yh(e.data,r.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`cidr`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?uh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`base64`,code:U.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?dh.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:`base64url`,code:U.invalid_string,message:r.message}),t.dirty()):V.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:U.invalid_string,...K.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...K.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...K.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...K.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...K.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...K.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...K.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...K.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...K.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...K.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...K.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...K.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...K.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...K.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...K.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...K.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...K.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...K.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...K.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...K.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...K.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...K.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...K.errToObj(t)})}nonempty(e){return this.min(1,K.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};bh.create=e=>new bh({checks:[],typeName:Y.ZodString,coerce:e?.coerce??!1,...q(e)});function xh(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Sh=class e extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==H.number){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.number,received:t.parsedType}),G}let t,n=new Vm;for(let r of this._def.checks)r.kind===`int`?V.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),W(t,{code:U.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?xh(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),W(t,{code:U.not_finite,message:r.message}),n.dirty()):V.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,K.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,K.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,K.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,K.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:K.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:K.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:K.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:K.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:K.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&V.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Sh.create=e=>new Sh({checks:[],typeName:Y.ZodNumber,coerce:e?.coerce||!1,...q(e)});var Ch=class e extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==H.bigint)return this._getInvalidInput(e);let t,n=new Vm;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),W(t,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):V.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.bigint,received:t.parsedType}),G}gte(e,t){return this.setLimit(`min`,e,!0,K.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,K.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,K.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,K.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:K.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:K.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ch.create=e=>new Ch({checks:[],typeName:Y.ZodBigInt,coerce:e?.coerce??!1,...q(e)});var wh=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.boolean){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.boolean,received:t.parsedType}),G}return Um(e.data)}};wh.create=e=>new wh({typeName:Y.ZodBoolean,coerce:e?.coerce||!1,...q(e)});var Th=class e extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.date){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.date,received:t.parsedType}),G}if(Number.isNaN(e.data.getTime()))return W(this._getOrReturnCtx(e),{code:U.invalid_date}),G;let t=new Vm,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:U.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):V.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:K.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:K.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Th.create=e=>new Th({checks:[],coerce:e?.coerce||!1,typeName:Y.ZodDate,...q(e)});var Eh=class extends J{_parse(e){if(this._getType(e)!==H.symbol){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.symbol,received:t.parsedType}),G}return Um(e.data)}};Eh.create=e=>new Eh({typeName:Y.ZodSymbol,...q(e)});var Dh=class extends J{_parse(e){if(this._getType(e)!==H.undefined){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.undefined,received:t.parsedType}),G}return Um(e.data)}};Dh.create=e=>new Dh({typeName:Y.ZodUndefined,...q(e)});var Oh=class extends J{_parse(e){if(this._getType(e)!==H.null){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.null,received:t.parsedType}),G}return Um(e.data)}};Oh.create=e=>new Oh({typeName:Y.ZodNull,...q(e)});var kh=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return Um(e.data)}};kh.create=e=>new kh({typeName:Y.ZodAny,...q(e)});var Ah=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Um(e.data)}};Ah.create=e=>new Ah({typeName:Y.ZodUnknown,...q(e)});var jh=class extends J{_parse(e){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.never,received:t.parsedType}),G}};jh.create=e=>new jh({typeName:Y.ZodNever,...q(e)});var Mh=class extends J{_parse(e){if(this._getType(e)!==H.undefined){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.void,received:t.parsedType}),G}return Um(e.data)}};Mh.create=e=>new Mh({typeName:Y.ZodVoid,...q(e)});var Nh=class e extends J{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==H.array)return W(t,{code:U.invalid_type,expected:H.array,received:t.parsedType}),G;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(W(t,{code:e?U.too_big:U.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(W(t,{code:U.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(W(t,{code:U.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Jm(t,e,t.path,n)))).then(e=>Vm.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Jm(t,e,t.path,n)));return Vm.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:K.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:K.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:K.toString(n)}})}nonempty(e){return this.min(1,e)}};Nh.create=(e,t)=>new Nh({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...q(t)});function Ph(e){if(e instanceof Fh){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=$h.create(Ph(r))}return new Fh({...e._def,shape:()=>t})}return e instanceof Nh?new Nh({...e._def,type:Ph(e.element)}):e instanceof $h?$h.create(Ph(e.unwrap())):e instanceof eg?eg.create(Ph(e.unwrap())):e instanceof Vh?Vh.create(e.items.map(e=>Ph(e))):e}var Fh=class e extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=V.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==H.object){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.object,received:t.parsedType}),G}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof jh&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Jm(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof jh){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(W(n,{code:U.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Jm(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Vm.mergeObjectSync(t,e)):Vm.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return K.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:K.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of V.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of V.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ph(this)}partial(t){let n={};for(let e of V.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of V.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof $h;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Jh(V.objectKeys(this.shape))}};Fh.create=(e,t)=>new Fh({shape:()=>e,unknownKeys:`strip`,catchall:jh.create(),typeName:Y.ZodObject,...q(t)}),Fh.strictCreate=(e,t)=>new Fh({shape:()=>e,unknownKeys:`strict`,catchall:jh.create(),typeName:Y.ZodObject,...q(t)}),Fh.lazycreate=(e,t)=>new Fh({shape:e,unknownKeys:`strip`,catchall:jh.create(),typeName:Y.ZodObject,...q(t)});var Ih=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new Im(e.ctx.common.issues));return W(t,{code:U.invalid_union,unionErrors:n}),G}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new Im(e));return W(t,{code:U.invalid_union,unionErrors:i}),G}}get options(){return this._def.options}};Ih.create=(e,t)=>new Ih({options:e,typeName:Y.ZodUnion,...q(t)});var Lh=e=>e instanceof Kh?Lh(e.schema):e instanceof Qh?Lh(e.innerType()):e instanceof qh?[e.value]:e instanceof Yh?e.options:e instanceof Xh?V.objectValues(e.enum):e instanceof tg?Lh(e._def.innerType):e instanceof Dh?[void 0]:e instanceof Oh?[null]:e instanceof $h?[void 0,...Lh(e.unwrap())]:e instanceof eg?[null,...Lh(e.unwrap())]:e instanceof ig||e instanceof og?Lh(e.unwrap()):e instanceof ng?Lh(e._def.innerType):[],Rh=class e extends J{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==H.object)return W(t,{code:U.invalid_type,expected:H.object,received:t.parsedType}),G;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(W(t,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Lh(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Y.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...q(r)})}};function zh(e,t){let n=Fm(e),r=Fm(t);if(e===t)return{valid:!0,data:e};if(n===H.object&&r===H.object){let n=V.objectKeys(t),r=V.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=zh(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===H.array&&r===H.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=zh(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===H.date&&r===H.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Bh=class extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Wm(e)||Wm(r))return G;let i=zh(e.value,r.value);return i.valid?((Gm(e)||Gm(r))&&t.dirty(),{status:t.value,value:i.data}):(W(n,{code:U.invalid_intersection_types}),G)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Bh.create=(e,t,n)=>new Bh({left:e,right:t,typeName:Y.ZodIntersection,...q(n)});var Vh=class e extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.array)return W(n,{code:U.invalid_type,expected:H.array,received:n.parsedType}),G;if(n.data.length<this._def.items.length)return W(n,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),G;!this._def.rest&&n.data.length>this._def.items.length&&(W(n,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Jm(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Vm.mergeArray(t,e)):Vm.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Vh.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Vh({items:e,typeName:Y.ZodTuple,rest:null,...q(t)})};var Hh=class e extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.object)return W(n,{code:U.invalid_type,expected:H.object,received:n.parsedType}),G;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Jm(n,e,n.path,e)),value:a._parse(new Jm(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Vm.mergeObjectAsync(t,r):Vm.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof J?new e({keyType:t,valueType:n,typeName:Y.ZodRecord,...q(r)}):new e({keyType:bh.create(),valueType:t,typeName:Y.ZodRecord,...q(n)})}},Uh=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.map)return W(n,{code:U.invalid_type,expected:H.map,received:n.parsedType}),G;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Jm(n,e,n.path,[a,`key`])),value:i._parse(new Jm(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return G;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return G;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Uh.create=(e,t,n)=>new Uh({valueType:t,keyType:e,typeName:Y.ZodMap,...q(n)});var Wh=class e extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.set)return W(n,{code:U.invalid_type,expected:H.set,received:n.parsedType}),G;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(W(n,{code:U.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(W(n,{code:U.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return G;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Jm(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:K.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:K.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Wh.create=(e,t)=>new Wh({valueType:e,minSize:null,maxSize:null,typeName:Y.ZodSet,...q(t)});var Gh=class e extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==H.function)return W(t,{code:U.invalid_type,expected:H.function,received:t.parsedType}),G;function n(e,n){return Bm({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zm(),Lm].filter(e=>!!e),issueData:{code:U.invalid_arguments,argumentsError:n}})}function r(e,n){return Bm({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zm(),Lm].filter(e=>!!e),issueData:{code:U.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Zh){let e=this;return Um(async function(...t){let o=new Im([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return Um(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Im([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Im([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Vh.create(t).rest(Ah.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Vh.create([]).rest(Ah.create()),returns:n||Ah.create(),typeName:Y.ZodFunction,...q(r)})}},Kh=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Kh.create=(e,t)=>new Kh({getter:e,typeName:Y.ZodLazy,...q(t)});var qh=class extends J{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return W(t,{received:t.data,code:U.invalid_literal,expected:this._def.value}),G}return{status:`valid`,value:e.data}}get value(){return this._def.value}};qh.create=(e,t)=>new qh({value:e,typeName:Y.ZodLiteral,...q(t)});function Jh(e,t){return new Yh({values:e,typeName:Y.ZodEnum,...q(t)})}var Yh=class e extends J{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return W(t,{expected:V.joinValues(n),received:t.parsedType,code:U.invalid_type}),G}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return W(t,{received:t.data,code:U.invalid_enum_value,options:n}),G}return Um(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Yh.create=Jh;var Xh=class extends J{_parse(e){let t=V.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==H.string&&n.parsedType!==H.number){let e=V.objectValues(t);return W(n,{expected:V.joinValues(e),received:n.parsedType,code:U.invalid_type}),G}if(this._cache||=new Set(V.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=V.objectValues(t);return W(n,{received:n.data,code:U.invalid_enum_value,options:e}),G}return Um(e.data)}get enum(){return this._def.values}};Xh.create=(e,t)=>new Xh({values:e,typeName:Y.ZodNativeEnum,...q(t)});var Zh=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==H.promise&&t.common.async===!1?(W(t,{code:U.invalid_type,expected:H.promise,received:t.parsedType}),G):Um((t.parsedType===H.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Zh.create=(e,t)=>new Zh({type:e,typeName:Y.ZodPromise,...q(t)});var Qh=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{W(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return G;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?G:r.status===`dirty`||t.value===`dirty`?Hm(r.value):r});{if(t.value===`aborted`)return G;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?G:r.status===`dirty`||t.value===`dirty`?Hm(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?G:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?G:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Km(e))return G;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Km(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):G)}V.assertNever(r)}};Qh.create=(e,t,n)=>new Qh({schema:e,typeName:Y.ZodEffects,effect:t,...q(n)}),Qh.createWithPreprocess=(e,t,n)=>new Qh({schema:t,effect:{type:`preprocess`,transform:e},typeName:Y.ZodEffects,...q(n)});var $h=class extends J{_parse(e){return this._getType(e)===H.undefined?Um(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$h.create=(e,t)=>new $h({innerType:e,typeName:Y.ZodOptional,...q(t)});var eg=class extends J{_parse(e){return this._getType(e)===H.null?Um(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};eg.create=(e,t)=>new eg({innerType:e,typeName:Y.ZodNullable,...q(t)});var tg=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===H.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};tg.create=(e,t)=>new tg({innerType:e,typeName:Y.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...q(t)});var ng=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qm(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Im(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Im(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ng.create=(e,t)=>new ng({innerType:e,typeName:Y.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...q(t)});var rg=class extends J{_parse(e){if(this._getType(e)!==H.nan){let t=this._getOrReturnCtx(e);return W(t,{code:U.invalid_type,expected:H.nan,received:t.parsedType}),G}return{status:`valid`,value:e.data}}};rg.create=e=>new rg({typeName:Y.ZodNaN,...q(e)});var ig=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ag=class e extends J{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?G:e.status===`dirty`?(t.dirty(),Hm(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?G:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Y.ZodPipeline})}},og=class extends J{_parse(e){let t=this._def.innerType._parse(e),n=e=>(Km(e)&&(e.value=Object.freeze(e.value)),e);return qm(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};og.create=(e,t)=>new og({innerType:e,typeName:Y.ZodReadonly,...q(t)}),Fh.lazycreate;var Y;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Y||={}),bh.create,Sh.create,rg.create,Ch.create,wh.create,Th.create,Eh.create,Dh.create,Oh.create,kh.create,Ah.create,jh.create,Mh.create,Nh.create;var sg=Fh.create;Fh.strictCreate,Ih.create,Rh.create,Bh.create,Vh.create,Hh.create,Uh.create,Wh.create,Gh.create,Kh.create,qh.create,Yh.create,Xh.create,Zh.create,Qh.create,$h.create,eg.create,Qh.createWithPreprocess,ag.create;var cg=Ue(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);qe.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Je(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>We(e,t,n),e.parseAsync=async(t,n)=>He(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ge(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>ct(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),lg=Ue(`ZodMiniObject`,(e,t)=>{Ke.init(e,t),cg.init(e,t),Ve(e,`shape`,()=>t.shape)});function ug(e,t){return new lg({type:`object`,shape:e??{},...Ye(t)})}function dg(e){return!!e._zod}function fg(e){let t=Object.values(e);if(t.length===0)return ug({});let n=t.every(dg),r=t.every(e=>!dg(e));if(n)return ug(e);if(r)return sg(e);throw Error(`Mixed Zod versions detected in object shape.`)}function pg(e,t){return dg(e)?We(e,t):e.safeParse(t)}async function mg(e,t){return dg(e)?await Ge(e,t):await e.safeParseAsync(t)}function hg(e){if(!e)return;let t;if(t=dg(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function gg(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return fg(e)}}if(dg(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function _g(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function vg(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${_g(e.path)}`:e.message).join(`
|
|
139
139
|
`);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function yg(e){return e.description}function bg(e){if(dg(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function xg(e){if(dg(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}function Sg(e){return e===`completed`||e===`failed`||e===`cancelled`}var Cg=Symbol(`Let zodToJsonSchema decide on which parser to use`),wg={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Tg=e=>typeof e==`string`?{...wg,name:e}:{...wg,...e},Eg=e=>{let t=Tg(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function Dg(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function X(e,t,n,r,i){e[t]=n,Dg(e,t,r,i)}var Og=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function kg(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Og(t,e.currentPath):t.join(`/`)}}function Ag(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Y.ZodAny&&(n.items=Z(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&X(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&X(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(X(n,`minItems`,e.exactLength.value,e.exactLength.message,t),X(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function jg(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?X(n,`minimum`,r.value,r.message,t):X(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),X(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?X(n,`maximum`,r.value,r.message,t):X(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),X(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:X(n,`multipleOf`,r.value,r.message,t)}return n}function Mg(){return{type:`boolean`}}function Ng(e,t){return Z(e.type._def,t)}var Pg=(e,t)=>Z(e.innerType._def,t);function Fg(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Fg(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Ig(e,t)}}var Ig=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:X(n,`minimum`,r.value,r.message,t);break;case`max`:X(n,`maximum`,r.value,r.message,t)}return n};function Lg(e,t){return{...Z(e.innerType._def,t),default:e.defaultValue()}}function Rg(e,t){return t.effectStrategy===`input`?Z(e.schema._def,t):kg(t)}function zg(e){return{type:`string`,enum:Array.from(e.values)}}var Bg=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Vg(e,t){let n=[Z(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Z(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Bg(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Hg(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var Ug=void 0,Wg={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ug===void 0&&(Ug=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Ug),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Gg(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:X(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:X(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Yg(n,`email`,r.message,t);break;case`format:idn-email`:Yg(n,`idn-email`,r.message,t);break;case`pattern:zod`:Xg(n,Wg.email,r.message,t)}break;case`url`:Yg(n,`uri`,r.message,t);break;case`uuid`:Yg(n,`uuid`,r.message,t);break;case`regex`:Xg(n,r.regex,r.message,t);break;case`cuid`:Xg(n,Wg.cuid,r.message,t);break;case`cuid2`:Xg(n,Wg.cuid2,r.message,t);break;case`startsWith`:Xg(n,RegExp(`^${Kg(r.value,t)}`),r.message,t);break;case`endsWith`:Xg(n,RegExp(`${Kg(r.value,t)}$`),r.message,t);break;case`datetime`:Yg(n,`date-time`,r.message,t);break;case`date`:Yg(n,`date`,r.message,t);break;case`time`:Yg(n,`time`,r.message,t);break;case`duration`:Yg(n,`duration`,r.message,t);break;case`length`:X(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),X(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Xg(n,RegExp(Kg(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Yg(n,`ipv4`,r.message,t),r.version!==`v4`&&Yg(n,`ipv6`,r.message,t);break;case`base64url`:Xg(n,Wg.base64url,r.message,t);break;case`jwt`:Xg(n,Wg.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Xg(n,Wg.ipv4Cidr,r.message,t),r.version!==`v4`&&Xg(n,Wg.ipv6Cidr,r.message,t);break;case`emoji`:Xg(n,Wg.emoji(),r.message,t);break;case`ulid`:Xg(n,Wg.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Yg(n,`binary`,r.message,t);break;case`contentEncoding:base64`:X(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Xg(n,Wg.base64,r.message,t)}break;case`nanoid`:Xg(n,Wg.nanoid,r.message,t)}return n}function Kg(e,t){return t.patternStrategy===`escape`?Jg(e):e}var qg=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Jg(e){let t=``;for(let n=0;n<e.length;n++)qg.has(e[n])||(t+=`\\`),t+=e[n];return t}function Yg(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):X(e,`format`,t,n,r)}function Xg(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Zg(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):X(e,`pattern`,Zg(t,r),n,r)}function Zg(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
140
140
|
]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
|
|
141
141
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Qg(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===Y.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??kg(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Y.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Gg(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===Y.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Y.ZodBranded&&e.keyType._def.type._def.typeName===Y.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Ng(e.keyType._def,t);return{...n,propertyNames:i}}return n}function $g(e,t){return t.mapStrategy===`record`?Qg(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Z(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||kg(t),Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||kg(t)],minItems:2,maxItems:2}}}function e_(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function t_(e){return e.target===`openAi`?void 0:{not:kg({...e,currentPath:[...e.currentPath,`not`]})}}function n_(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var r_={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function i_(e,t){if(t.target===`openApi3`)return a_(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in r_&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=r_[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return a_(e,t)}var a_=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function o_(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:r_[e.innerType._def.typeName],nullable:!0}:{type:[r_[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function s_(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,Dg(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?X(n,`minimum`,r.value,r.message,t):X(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),X(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?X(n,`maximum`,r.value,r.message,t):X(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),X(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:X(n,`multipleOf`,r.value,r.message,t)}return n}function c_(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=u_(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Z(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=l_(e,t);return o!==void 0&&(r.additionalProperties=o),r}function l_(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Z(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function u_(e){try{return e.isOptional()}catch{return!0}}var d_=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Z(e.innerType._def,t);let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:kg(t)},n]}:kg(t)},f_=(e,t)=>{if(t.pipeStrategy===`input`)return Z(e.in._def,t);if(t.pipeStrategy===`output`)return Z(e.out._def,t);let n=Z(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Z(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function p_(e,t){return Z(e.type._def,t)}function m_(e,t){let n={type:`array`,uniqueItems:!0,items:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&X(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&X(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function h_(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Z(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Z(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function g_(e){return{not:kg(e)}}function __(e){return kg(e)}var v_=(e,t)=>Z(e.innerType._def,t),y_=(e,t,n)=>{switch(t){case Y.ZodString:return Gg(e,n);case Y.ZodNumber:return s_(e,n);case Y.ZodObject:return c_(e,n);case Y.ZodBigInt:return jg(e,n);case Y.ZodBoolean:return Mg();case Y.ZodDate:return Fg(e,n);case Y.ZodUndefined:return g_(n);case Y.ZodNull:return n_(n);case Y.ZodArray:return Ag(e,n);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return i_(e,n);case Y.ZodIntersection:return Vg(e,n);case Y.ZodTuple:return h_(e,n);case Y.ZodRecord:return Qg(e,n);case Y.ZodLiteral:return Hg(e,n);case Y.ZodEnum:return zg(e);case Y.ZodNativeEnum:return e_(e);case Y.ZodNullable:return o_(e,n);case Y.ZodOptional:return d_(e,n);case Y.ZodMap:return $g(e,n);case Y.ZodSet:return m_(e,n);case Y.ZodLazy:return()=>e.getter()._def;case Y.ZodPromise:return p_(e,n);case Y.ZodNaN:case Y.ZodNever:return t_(n);case Y.ZodEffects:return Rg(e,n);case Y.ZodAny:return kg(n);case Y.ZodUnknown:return __(n);case Y.ZodDefault:return Lg(e,n);case Y.ZodBranded:return Ng(e,n);case Y.ZodReadonly:return v_(e,n);case Y.ZodCatch:return Pg(e,n);case Y.ZodPipeline:return f_(e,n);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(e=>void 0)(t)}};function Z(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Cg)return i}if(r&&!n){let e=b_(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=y_(e,e.typeName,t),o=typeof a==`function`?Z(a(),t):a;if(o&&x_(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var b_=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Og(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),kg(t)):t.$refStrategy===`seen`?kg(t):void 0}},x_=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),S_=(e,t)=>{let n=Eg(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Z(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??kg(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Z(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??kg(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function C_(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function w_(e,t){return dg(e)?Be(e,{target:C_(t?.target),io:t?.pipeStrategy??`input`}):S_(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function T_(e){let t=hg(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=xg(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function E_(e,t){let n=pg(e,t);if(!n.success)throw n.error;return n.data}var D_=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ht,e=>{this._oncancel(e)}),this.setNotificationHandler(St,e=>{this._onprogress(e)}),this.setRequestHandler(xt,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(jt,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new L(R.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(It,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new L(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new L(R.InvalidParams,`Task not found: ${r}`);if(!Sg(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Sg(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[wt]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(pt,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new L(R.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Rt,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new L(R.InvalidParams,`Task not found: ${e.params.taskId}`);if(Sg(n.status))throw new L(R.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new L(R.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof L?e:new L(R.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),L.fromError(R.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),gt(e)||_t(e)?this._onresponse(e):At(e)?this._onrequest(e,t):Ot(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=L.fromError(R.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[wt]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:R.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=yt(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new L(R.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:R.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),gt(e)?n(e):n(new L(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(gt(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),gt(e)?r(e):r(L.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof L?e:new L(R.InternalError,String(e))}}return}let i;try{let r=await this.request(e,qt,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new L(R.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Sg(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new L(R.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new L(R.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof L?e:new L(R.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[wt]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof L?e:new L(R.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=pg(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(L.fromError(R.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Jt,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Ct,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Mt,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[wt]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[wt]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[wt]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=T_(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=E_(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=T_(e);this._notificationHandlers.set(n,n=>{let r=E_(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&At(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new L(R.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new L(R.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new L(R.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new L(R.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Tt.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Sg(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new L(R.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Sg(a.status))throw new L(R.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Tt.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Sg(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function O_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function k_(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=O_(a)&&O_(i)?{...a,...i}:i}return n}var A_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),j_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=A_(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Q=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;var t=A_(),n=j_(),r=A_();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=j_();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=k(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=k(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=k(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(A(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>D(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(j(t),n instanceof e?[n]:n.nodes);if(t!==!1&&this.nodes.length)return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=k(this.condition,e,t),this}get names(){let e=super.names;return O(e,this.condition),this.else&&D(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=k(this.iteration,e,t),this}get names(){return D(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return O(O(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=k(this.iterable,e,t),this}get names(){return D(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&D(e,this.catch.names),this.finally&&D(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
@@ -145,7 +145,7 @@ To resolve the conflict:`,Gp(t,e))),n=r):P.warn(`A view or instrument with the n
|
|
|
145
145
|
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;var g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),R_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=Q(),n=$();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),z_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=Q(),n=$(),r=M_(),i=$();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;var h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),B_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=Q(),n=M_(),r=z_(),i=N_();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),V_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=Q(),n=$();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),H_=a(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),U_=a(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),W_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=$(),n=H_(),r=U_(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;var o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;var d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),G_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=P_(),n=L_(),r=I_(),i=L_(),a=R_(),o=B_(),s=V_(),c=Q(),l=M_(),u=W_(),d=$(),f=N_();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&A(e),D(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),j(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&A(e),O(e),k(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),E(e)}function T(e,t){if(e.opts.jtd)return te(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);te(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function D(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function O(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function k(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function A({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function j(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ee(e),t.return((0,c._)`${l.default.errors} === 0`))}function ee({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function te(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ue(e,`$ref`,h.all.$ref.definition));return}p.jtd||N(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),M(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):M(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function M(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ue(e,n.keyword,n.definition,t.type)})}function N(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(ne(e,t),e.opts.allowUnionTypes||re(e,t),ie(e,e.dataTypes))}function ne(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{oe(e.dataTypes,t)||ce(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),se(e,t)}}function re(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ce(e,`use allowUnionTypes to allow union type keyword`)}function ie(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>ae(t,e))&&ce(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ae(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function oe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function se(e,t){let n=[];for(let r of e.dataTypes)oe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ce(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var le=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,pe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=le;function ue(e,t,n,r){let i=new le(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}var de=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!de.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=fe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=pe})),K_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),q_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=W_();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),J_=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=Q(),n=K_(),r=M_(),i=W_(),a=$(),o=G_(),s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;var h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Y_=i({$id:()=>X_,additionalProperties:()=>!1,default:()=>tv,description:()=>Z_,properties:()=>ev,required:()=>$_,type:()=>Q_}),X_,Z_,Q_,$_,ev,tv,nv=n((()=>{X_=`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,Z_=`Meta-schema for $data reference (JSON AnySchema extension proposal)`,Q_=`object`,$_=[`$data`],ev={$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},tv={$id:X_,description:Z_,type:Q_,required:$_,properties:ev,additionalProperties:!1}})),rv=a(((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}var p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function S(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}var C={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},w=/[@/?#:]/g,T=/[@/?#]/g;function E(e,t){let n=t?T:w;return n.lastIndex=0,e.replace(n,e=>C[e])}function D(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function O(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=M(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function k(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function A(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function j(e){return A(e,l)}function ee(e){return A(e,c)}function te(e){return A(e,c)}function M(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function N(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=M(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function ne(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function re(e){let t=[];if(e.userinfo!==void 0&&(t.push(j(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=D(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:E(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:re,reescapeHostDelimiters:E,normalizePercentEncoding:D,normalizePathEncoding:O,serializePathEncoding:k,normalizeQueryFragmentEncoding:N,encodeUserinfo:j,encodeQuery:ee,encodeFragment:te,escapePreservingEscapes:ne,removeDotSegments:S,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),iv=a(((e,t)=>{var{isUUID:n}=rv(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}var h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),av=a(((e,t)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=rv(),{SCHEMES:m,getSchemeHandler:h}=iv(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=M(e,t):typeof e==`object`&&(e=te(C(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=ee(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=ee(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),S=y.host,w=S!==void 0&&S!==``&&(f(S)||n(S).isIPV6);j(y,r||{},b,w);let T=S&&S.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(S);if(y.error&&!T)throw Error(y.error);return i.skipEscape=!0,C(y,i)}function x(e,t,n,i){let a={};return i||(e=te(C(e,n),n),t=te(C(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function S(e,t,n){let r=ne(e,n),i=ne(t,n);return r!==void 0&&i!==void 0&&r===i}function C(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(n.path=o.skipEscape?a(n.path):s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}var w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,T=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,E=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function D(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function O(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function k(e){return e[0]===`[`&&e[e.length-1]===`]`}function A(e){let t=e[4];return O(e[3])||t!==void 0&&!k(t)&&O(t)||O(e[6])||O(e[7])||O(e[8])}function j(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!k(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function ee(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(T);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let S=e.match(E);if(S!==null){let e=S[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let C=e.match(w);if(C){if(i.scheme=C[1],i.userinfo=C[3],i.host=C[4],i.port=parseInt(C[5],10),i.path=C[6]||``,i.query=C[7],i.fragment=C[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=A(C),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=C[5]);let t=D(i,C);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host){if(f(i.host)===!1){let e=k(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);v||(p=j(i,r,x,b)),(!x||x&&!x.skipNormalize)&&(e.indexOf(`%`)!==-1&&i.host!==void 0&&!v&&(i.host=d(b?i.host:a(i.host,!0),b)),i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function te(e,t){return ee(e,t).parsed}function M(e,t){return N(e,t).normalized}function N(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=ee(e,t);return{normalized:r||i||a||o||s?e:C(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function ne(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:C(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=N(n,t);return i||a||o||s||c?void 0:r}var re={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:S,serialize:C,parse:te};t.exports=re,t.exports.default=re,t.exports.fastUri=re})),ov=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=av();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),sv=a((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var n=G_();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return n.KeywordCxt}});var r=Q();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});var i=K_(),a=q_(),o=F_(),s=J_(),c=Q(),l=W_(),u=L_(),d=$(),f=(nv(),e(Y_).default),p=ov(),m=(e,t)=>new RegExp(e,t);m.code=`new RegExp`;var h=[`removeAdditional`,`useDefaults`,`coerceTypes`],g=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),_={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},v={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},y=200;function b(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??m,a=e.uriResolver??p.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??y,loopEnum:e.loopEnum??y,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var x=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...b(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:g,es5:t,lines:n}),this.logger=k(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,o.getRules)(),S.call(this,_,e,`NOT SUPPORTED`),S.call(this,v,e,`DEPRECATED`,`warn`),this._metaOpts=D.call(this),e.formats&&T.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),w.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=f;n===`id`&&(r={...f},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await i.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function i(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof a.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await i.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,l.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=C.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new s.SchemaEnv({schema:{},schemaId:n});if(t=s.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=C.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,l.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(j.call(this,n,t),!t)return(0,d.eachItem)(n,e=>ee.call(this,e)),this;M.call(this,t);let r={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,d.eachItem)(n,r.type.length===0?e=>ee.call(this,e,r):e=>r.type.forEach(t=>ee.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=ne(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:o}=this.opts;if(typeof e==`object`)a=e[o];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let c=this._cache.get(e);if(c!==void 0)return c;n=(0,l.normalizeId)(a||n);let u=l.getSchemaRefs.call(this,e,n);return c=new s.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:n,localRefs:u}),this._cache.set(c.schema,c),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=c),r&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):s.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,e)}finally{this.opts=t}}};x.ValidationError=i.default,x.MissingRefError=a.default,t.default=x;function S(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function C(e){return e=(0,l.normalizeId)(e),this.schemas[e]||this.refs[e]}function w(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function T(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function D(){let e={...this.opts};for(let t of h)delete e[t];return e}var O={log(){},warn(){},error(){}};function k(e){if(e===!1)return O;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}var A=/^[a-z_$][a-z0-9_$:-]*$/i;function j(e,t){let{RULES:n}=this;if((0,d.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!A.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function ee(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?te.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function te(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function M(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=ne(t)),e.validateSchema=this.compile(t,!0))}var N={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function ne(e){return{anyOf:[e,N]}}})),cv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),lv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=q_(),n=z_(),r=Q(),i=M_(),a=J_(),o=$(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);return h instanceof a.SchemaEnv?_(h):v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),uv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=cv(),n=lv();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),dv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),fv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),pv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),mv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$(),r=pv();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),hv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=z_(),n=$(),r=Q();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),gv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),_v=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=z_(),n=Q(),r=$();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),vv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),yv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=H_();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),bv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=L_(),n=Q(),r=$(),i=yv();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),xv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$(),r=yv();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),Sv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$(),r=yv();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),Cv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=dv(),n=fv(),r=mv(),i=hv(),a=gv(),o=_v(),s=vv(),c=bv(),l=xv(),u=Sv();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),wv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=Q(),n=$(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),Tv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=Q(),n=$(),r=z_(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),Ev=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Tv();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Dv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$(),r=z_(),i=wv();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),Ov=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),kv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=Q(),n=$(),r=z_();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
|
|
146
146
|
missingProperty: ${i},
|
|
147
147
|
depsCount: ${n},
|
|
148
|
-
deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),Av=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),jv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=z_(),n=Q(),r=M_(),i=$();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Mv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=G_(),n=z_(),r=$(),i=jv();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Nv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=z_(),n=Q(),r=$(),i=$();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),Pv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),Fv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:z_().validateUnion,error:{message:`must match a schema in anyOf`}}})),Iv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),Lv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),Rv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),zv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Bv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wv(),n=Ev(),r=Tv(),i=Dv(),a=Ov(),o=kv(),s=Av(),c=jv(),l=Mv(),u=Nv(),d=Pv(),f=Fv(),p=Iv(),m=Lv(),h=Rv(),g=zv();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Vv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Hv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Vv().default]})),Uv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Wv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=uv(),n=Cv(),r=Bv(),i=Hv(),a=Uv();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Gv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Kv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=Gv(),r=J_(),i=q_(),a=$();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),qv=i({$id:()=>Yv,$schema:()=>Jv,default:()=>ey,definitions:()=>Zv,properties:()=>$v,title:()=>Xv,type:()=>Qv}),Jv,Yv,Xv,Zv,Qv,$v,ey,ty=n((()=>{Jv=`http://json-schema.org/draft-07/schema#`,Yv=`http://json-schema.org/draft-07/schema#`,Xv=`Core schema meta-schema`,Zv={schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},Qv=[`object`,`boolean`],$v={$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},ey={$schema:Jv,$id:Yv,title:Xv,definitions:Zv,type:Qv,properties:$v,default:!0}})),ny=a(((t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;var r=sv(),i=Wv(),a=Kv(),o=(ty(),e(qv).default),s=[`/properties`],c=`http://json-schema.org/draft-07/schema`,l=class extends r.default{_addVocabularies(){super._addVocabularies(),i.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(o,s):o;this.addMetaSchema(e,c,!1),this.refs[`http://json-schema.org/schema`]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}};t.Ajv=l,n.exports=t=l,n.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var u=G_();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var d=Q();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return d._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return d.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return d.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return d.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return d.CodeGen}});var f=K_();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=q_();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})),ry=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}var T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),iy=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=ny(),n=Q(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),ay=a(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=ry(),r=iy(),i=Q(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),oy=r(ny(),1),sy=r(ay(),1);function cy(){let e=new oy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sy.default)(e),e}var ly=class{constructor(e){this._ajv=e??cy()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},uy=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},Pt,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},Ft,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function dy(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function fy(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var py=class extends D_{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ut.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new ly,this.setRequestHandler(Zt,e=>this._oninitialize(e)),this.setNotificationHandler(Nt,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(bt,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=ut.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new uy(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=k_(this._capabilities,e)}setRequestHandler(e,t){let n=hg(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=xg(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=pg(Vt,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new L(R.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=pg(qt,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new L(R.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=pg(Gt,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new L(R.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){fy(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&dy(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:vt.includes(t)?t:Et,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},Ut)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},Bt,t):this.request({method:`sampling/createMessage`,params:e},Pt,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},Ft,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},Ft,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new L(R.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof L?e:new L(R.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},mt,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},my=Symbol.for(`mcp.completable`);function hy(e){return!!e&&typeof e==`object`&&my in e}function gy(e){return e[my]?.complete}var _y;(function(e){e.Completable=`McpCompletable`})(_y||={});var vy=/^[A-Za-z0-9._-]{1,128}$/;function yy(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!vy.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function by(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function xy(e){let t=yy(e);return by(e,t.warnings),t.isValid}var Sy=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Cy=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new py(e,t)}get experimental(){return this._experimental||={tasks:new Sy(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Ay(zt)),this.server.assertCanSetRequestHandler(Ay(Vt)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zt,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=gg(t.inputSchema);return e?w_(e,{strictUnions:!0,pipeStrategy:`input`}):wy})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=gg(t.outputSchema);e&&(n.outputSchema=w_(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Vt,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new L(R.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new L(R.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new L(R.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new L(R.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof L&&e.code===R.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await mg(gg(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=vg(`error`in r?r.error:`Unknown error`);throw new L(R.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new L(R.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await mg(gg(e.outputSchema),t.structuredContent);if(!r.success){let e=vg(`error`in r?r.error:`Unknown error`);throw new L(R.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new L(R.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Ay(Kt)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Kt,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Qt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return dt(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(R.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new L(R.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new L(R.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return My;let r=hg(n.argsSchema)?.[e.params.argument.name];if(!hy(r))return My;let i=gy(r);return i?jy(await i(e.params.argument.value,e.params.context)):My}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return My;throw new L(R.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?jy(await r(e.params.argument.value,e.params.context)):My}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Ay(Dt)),this.server.assertCanSetRequestHandler(Ay(Yt)),this.server.assertCanSetRequestHandler(Ay(ht)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Dt,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Yt,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ht,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new L(R.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new L(R.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Ay(ft)),this.server.assertCanSetRequestHandler(Ay(Lt)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ft,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?ky(t.argsSchema):void 0}))})),this.server.setRequestHandler(Lt,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new L(R.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new L(R.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await mg(gg(n.argsSchema),e.params.arguments);if(!r.success){let t=vg(`error`in r?r.error:`Unknown error`);throw new L(R.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:fg(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=fg(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>hy(e instanceof tt?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){xy(e);let l={title:t,description:n,inputSchema:Oy(r),outputSchema:Oy(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&xy(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=fg(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=fg(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(Dy(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Dy(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},wy={type:`object`,properties:{}};function Ty(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Ey(e){return`_def`in e||`_zod`in e||Ty(e)}function Dy(e){return typeof e!=`object`||!e||Ey(e)?!1:Object.keys(e).length===0||Object.values(e).some(Ty)}function Oy(e){if(e){if(Dy(e))return fg(e);if(!Ey(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function ky(e){let t=hg(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:yg(t),required:!bg(t)})):[]}function Ay(e){let t=hg(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=xg(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function jy(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var My={completion:{values:[],hasMore:!1}};function Ny(e,t){return t?e:e.map(Py)}function Py(e){let t=e.parameter.flatMap(Iy),n=Fy(e.requestBody);return Ry(t,e.parameter)&&n===e.requestBody?e:{...e,parameter:t,...n===void 0?{}:{requestBody:n}}}function Fy(e){if(e===void 0)return;let t=e.map(e=>{let t=e.parameter.flatMap(Iy);return Ry(t,e.parameter)?e:{...e,parameter:t}});return t.every((t,n)=>t===e[n])?e:t}function Iy(e){if(!Ly(e))return[];let t=e.itemProperty?.filter(Ly);return Ry(t,e.itemProperty)?[e]:[{...e,...t===void 0||t.length===0?{}:{itemProperty:t}}]}var Ly=e=>e.visibility!==`private`;function Ry(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(w.join(`|`),`i`);function zy(e){let t=M(e),n=en(t.data,t.summary)??JSON.stringify(t);return{isError:!t.ok,structuredContent:{...t},content:[{type:`text`,text:n}]}}var By=`aventure_status`,Vy=`aventure_help`,Hy=`aventure_read`,Uy=`aventure_lookup`,Wy=`aventure_search`,Gy=`aventure_write`,Ky=`aventure_delete`,qy=ot([I(),Xe(),nt()]),Jy=st(I(),ot([I(),Xe()])).optional(),Yy=st(I(),ot([qy,Qe(qy)])).optional(),Xy=st(I(),I()).optional(),Zy=Ze([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Qy=ot([qy,rt(),Qe(it()),st(I(),it())]).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.`),$y={operationId:I().optional().describe(`Exact OpenAPI operationId, as listed by aventure_help. Takes precedence over method and path.`),method:Zy.optional().describe(`HTTP method when resolving by method+path.`),path:I().optional().describe(`OpenAPI route template or concrete API path.`),pathParams:Jy.describe(`Values for route template parameters.`),query:Yy.describe(`Query parameters.`),headers:Xy.describe(`Headers declared by the selected OpenAPI operation.`),contentType:I().optional().describe(`Declared request media type; omit for the first supported descriptor.`),responseFormat:Ze([`auto`,`json`,`text`]).optional().describe(`Response format for endpoints that offer both JSON and text/plain.`)},eb={q:I().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:I().optional().describe(`Filter by resource or first CLI segment.`),method:Zy.optional().describe(`Filter by HTTP method.`),scope:Ze([`read`,`write`]).optional().describe(`Filter by required MCP auth scope.`),limit:$e().min(1).max(100).default(20).describe(`Maximum rows to return.`),resolve:nt().default(!1).describe(`Return one deterministic CLI recommendation for q.`)},tb={...$y,body:Qy};async function nb(e,t){let n=lt.find(e=>e.intent===`status`&&e.resource===`status`);if(n===void 0)return E(`No system status operation exists in the generated catalog.`);let r;try{r=se().host}catch(e){return E(e.message)}let i=await pe({method:n.method,path:n.path,auth:n.projection.auth,requesterScope:e});return{...i,data:{transportScope:e,permissionGrant:t?.permissionGrant,host:r,status:i.data}}}var rb=(e,t)=>Ny(lt,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`)&&(t===void 0||t.operation.some(e=>e.operationId===n.operationId&&e.method===n.method&&e.path===n.path)));async function ib(e,t,n,r,i){let a=ie(e);if(!a.ok)return E(a.summary,a.warnings);if(a.data===null)return E(`OpenAPI operation resolution returned no data.`);let{method:o,operation:s,path:c,template:u}=a.data,d=s.operationId,f=r.find(e=>e.operationId===d&&e.method.toLowerCase()===o&&e.path===u);if(f===void 0)return E(`Operation `+d+` is not in the MCP catalog.`);if(!t.includes(f.intent))return E(`Operation `+d+` has intent=`+f.intent+`; use aventure_`+f.intent+`.`);let p=l(f.requestBody??[],e.contentType);if(!p.ok||p.data===null)return E(p.summary,p.warnings);let m=p.data;return f.intent===`delete`&&m===void 0&&e.body!==void 0?E(d+` does not accept a request body.`):await pe({method:f.method,path:c,searchParams:e.query,headers:e.headers,body:e.body,contentType:e.contentType,auth:f.projection.auth,requesterScope:n,responseFormat:e.responseFormat,clientInfo:i})}function ab(e,t,n){let r=rb(t,n);e.registerTool(By,{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:{}},async()=>zy(await nb(t,n))),e.registerTool(Vy,{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; resolve returns one recommended operation for q. It describes operations only and calls no API.`,inputSchema:eb},async e=>{let{summary:t,data:n,counts:i}=$t(e,r);return zy(le(t,n,{counts:i}))});let i=()=>e.server.getClientVersion();e.registerTool(Hy,{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. 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:tb},async e=>zy(await ib(e,[`read`],t,r,i()))),e.registerTool(Uy,{title:`aVenture lookup`,annotations:{readOnlyHint:!1},description:`Runs one catalog operation whose intent is lookup: resolve a name, URL, domain, slug, ticker, or other identifier to the record that owns it, or run a batch, preview, or duplicate check. Most lookups are POST operations that take a JSON 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:tb},async e=>zy(await ib(e,[`lookup`],t,r,i()))),e.registerTool(Wy,{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:tb},async e=>zy(await ib(e,[`search`],t,r,i()))),r.some(e=>e.intent===`write`)&&e.registerTool(Gy,{title:`aVenture write`,annotations:{readOnlyHint:!1,destructiveHint:!0},description:`Runs one catalog operation whose intent is write: create or change records in the shared aVenture corpus, or start an account or enrichment action such as a billing checkout, plan change, or portal session, or an entity or person enrichment; the write 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:tb},async e=>zy(await ib(e,[`write`],t,r,i()))),r.some(e=>e.intent===`delete`)&&e.registerTool(Ky,{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:tb},async e=>zy(await ib(e,[`delete`],t,r,i())))}var ob=C().version;function sb(e,t){let n=new Cy({name:`aventure-mcp-server`,title:`aVenture MCP Server`,version:ob},{capabilities:{logging:{}},instructions:he.info.description});return ab(n,e,t),n}var cb=lt.map(({operationId:e,method:t,path:n,parameter:r})=>({operationId:e,method:t,path:n,authorizationPath:T(n,Object.fromEntries(r.filter(e=>e.in===`path`).map(e=>e.schemaEnum?.[0]===void 0?e.schemaFormat===`uuid`?[e.name,ln()]:e.schemaType===`integer`||e.schemaType===`number`?[e.name,1]:[e.name,`authorization-probe`]:[e.name,e.schemaEnum[0]])),e)}));async function lb(e,t){let n=ym(e.header(`authorization`));if(n===void 0)return{ok:!1,reason:`missing_credential`,hasAuthorization:!1};try{let e=await k(n,t,cb);if(e===`forbidden`)return{ok:!1,reason:`forbidden`,hasAuthorization:!0};if(e!==null)return{ok:!0,scope:e.operationAccess===`READ`?`read`:`write`,userBearerToken:n,authorization:e}}catch(e){if(!(e instanceof m))throw e;b({component:`aventure-mcp-server`,event:`invalid_bearer_jwt`,fields:{requestId:g()},error:e})}return{ok:!1,reason:`credential_mismatch`,hasAuthorization:!0}}function ub(e,t){let n=t?`Authenticate with OAuth using the authorization server in the resource metadata, or an API key from aventure.vc Settings -> API keys in Authorization: Bearer <key>.`:`Authenticate with an API key from aventure.vc Settings -> API keys in Authorization: Bearer <key>. 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`?n:`The supplied credential was rejected. ${n}`}var db=1024,fb=db*db,pb=1,mb=2,hb=`b`,gb=`kb`,_b=`mb`,vb=/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/u;function yb(e){let t=xb(e.limit),n=bb(e.path);return(r,i,a)=>{if(t===void 0||r.method!==`POST`||bb(r.path)!==n){a();return}let o=Sb(r.header(`content-length`));if(o===void 0||o<=t){a();return}i.setHeader(`Connection`,`close`),e.reject(i)}}function bb(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;return t===``?`/`:t}function xb(e){if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:void 0;let t=vb.exec(e.trim().toLowerCase());if(t===null)return;let n=Number(t[pb]);if(Number.isFinite(n))switch(t[mb]??hb){case _b:return Math.floor(n*fb);case gb:return Math.floor(n*db);case hb:return Math.floor(n)}}function Sb(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}var Cb=400,wb=400,Tb=413,Eb=`10mb`,Db=`127.0.0.1`,Ob=`0.0.0.0`;async function kb(e){let t=e.jsonBodyLimit??Eb,n=e.host??Db,r=n!==Ob,i=(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},a=(0,pl.default)();a.disable(`x-powered-by`),a.set(`trust proxy`,1),a.use((e,t,n)=>{let r=ln(),i=performance.now(),a={requestId:r,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},o=Mb(e);o||s({component:`aventure-mcp-server`,event:`http_request`,fields:a}),t.on(`finish`,()=>{let n=Math.round(performance.now()-i),r=e.route;Am(e.method,typeof r==`object`&&r&&`path`in r&&typeof r.path==`string`?r.path:`unmatched`,t.statusCode,n),(t.statusCode>=Cb&&!o?b:s)({component:`aventure-mcp-server`,event:`http_response`,fields:{...a,status:t.statusCode,durationMs:n}})}),ne(r,()=>n())}),a.use(r?(0,fl.default)({origin:jb}):(0,fl.default)()),a.use(yb({path:e.path,limit:t,reject:e=>Nb(e,Tb,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),a.use(pl.json({limit:t})),a.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`})}),a.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,fl.default)(),async(t,n,r)=>{let a=await e.resolveOAuthDiscovery();if(a===void 0){Nb(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=i(t,a);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),jm(a,e.metricsScrapeSecret),a.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),a.get(`/favicon.ico`,(...e)=>{e[1].status(204).end()});let c=Vl({windowMs:6e4,limit:120});return a.post(e.path,c,async(t,n)=>{let a=g(),c=t.header(`origin`);if(r&&!Ab(c)){b({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:a,method:t.method,path:t.path,origin:c}}),Nb(n,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let l,u;try{let n=await e.resolveOAuthDiscovery();u=i(t,n),l=await lb(t,n?.resourceUrl)}catch(e){xe({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:a,method:t.method,path:t.path},error:e});let r=e instanceof ce&&(e.problem.status===429||ye(e.problem.status))?e.problem:void 0;r===void 0?Nb(n,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof r.retryAfterSeconds==`number`&&n.set(`Retry-After`,String(r.retryAfterSeconds)),Pb(n,r));return}if(!l.ok){b({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:a,method:t.method,path:t.path,reason:l.reason,hasAuthorization:l.hasAuthorization}});let e=[u===void 0?void 0:`resource_metadata="${Ed(u.resourceUrl)}"`,u===void 0?void 0:`scope="${u.client.scope.join(` `)}"`,l.reason===`credential_mismatch`?`error="invalid_token"`:void 0,l.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,l.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);n.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`),l.reason===`forbidden`?Nb(n,403,`Forbidden`,ub(l.reason,u!==void 0)):Nb(n,401,`Unauthorized`,ub(l.reason,u!==void 0));return}let d=t.header(`accept`)??`*/*`;if(!d.includes(`*/*`)&&(!d.includes(`application/json`)||!d.includes(`text/event-stream`))){Nb(n,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}s({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:a,method:t.method,path:t.path,scope:l.scope}});let f=sb(l.scope,l.authorization),m=new Td({sessionIdGenerator:void 0});n.on(`close`,()=>{Ib(()=>m.close(),`transport_close_failed`,t,a),Ib(()=>f.close(),`mcp_close_failed`,t,a)});try{let e=async()=>{await f.connect(m),await m.handleRequest(t,n,t.body)};l.userBearerToken===void 0?await e():await o(l.userBearerToken,e)}catch(e){let r=p(e);no(e,`transport_error`),xe({component:`aventure-mcp-server`,event:`transport_error`,message:r,fields:{requestId:a,method:t.method,path:t.path},error:e}),n.headersSent||Nb(n,500,`MCP transport error`,r)}}),a.all(e.path,(...e)=>{let t=e[1];Nb(t,405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)}),a.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=Fb(e);if(i===void 0){r(e);return}b({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:g(),method:t.method,path:t.path,status:i.status}}),Nb(n,i.status,i.status===Tb?`Payload Too Large`:`Bad Request`,i.status===Tb?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,r)=>{let i;i=a.listen(e.port,n,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await Mm()}})}),i.on(`error`,r)})}function Ab(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]`:an(t)&&t.startsWith(`127.`)}var jb=(e,t)=>t(null,Ab(e)),Mb=e=>e.method===`GET`&&/^\/robots\.txt\/?$/iu.test(e.path);function Nb(e,t,n,r){Pb(e,{type:`about:blank`,title:n,status:t,detail:r})}function Pb(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function Fb(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?Tb:e.type===`entity.parse.failed`?wb:e.status===Tb||e.status===wb?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 Ib(e,t,n,r){e().catch(e=>{b({component:`aventure-mcp-server`,event:t,message:e.message,fields:{requestId:r,method:n.method,path:n.path},error:e})})}var Lb=65535,Rb=55e3,zb=C(nn(import.meta.url)),{host:Bb}=(await new v().name(zb.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(zb.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`,`
|
|
148
|
+
deps: ${r}}`};var i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),Av=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),jv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=z_(),n=Q(),r=M_(),i=$();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Mv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=G_(),n=z_(),r=$(),i=jv();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Nv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=z_(),n=Q(),r=$(),i=$();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),Pv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),Fv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:z_().validateUnion,error:{message:`must match a schema in anyOf`}}})),Iv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),Lv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),Rv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=$(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),zv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=$();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Bv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wv(),n=Ev(),r=Tv(),i=Dv(),a=Ov(),o=kv(),s=Av(),c=jv(),l=Mv(),u=Nv(),d=Pv(),f=Fv(),p=Iv(),m=Lv(),h=Rv(),g=zv();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Vv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Hv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Vv().default]})),Uv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Wv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=uv(),n=Cv(),r=Bv(),i=Hv(),a=Uv();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Gv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Kv=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Q(),n=Gv(),r=J_(),i=q_(),a=$();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),qv=i({$id:()=>Yv,$schema:()=>Jv,default:()=>ey,definitions:()=>Zv,properties:()=>$v,title:()=>Xv,type:()=>Qv}),Jv,Yv,Xv,Zv,Qv,$v,ey,ty=n((()=>{Jv=`http://json-schema.org/draft-07/schema#`,Yv=`http://json-schema.org/draft-07/schema#`,Xv=`Core schema meta-schema`,Zv={schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},Qv=[`object`,`boolean`],$v={$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},ey={$schema:Jv,$id:Yv,title:Xv,definitions:Zv,type:Qv,properties:$v,default:!0}})),ny=a(((t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;var r=sv(),i=Wv(),a=Kv(),o=(ty(),e(qv).default),s=[`/properties`],c=`http://json-schema.org/draft-07/schema`,l=class extends r.default{_addVocabularies(){super._addVocabularies(),i.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(o,s):o;this.addMetaSchema(e,c,!1),this.refs[`http://json-schema.org/schema`]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}};t.Ajv=l,n.exports=t=l,n.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var u=G_();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var d=Q();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return d._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return d.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return d.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return d.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return d.CodeGen}});var f=K_();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=q_();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})),ry=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}var d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}var b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}var T=/[^\\]\\Z/;function E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),iy=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=ny(),n=Q(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),ay=a(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=ry(),r=iy(),i=Q(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),oy=r(ny(),1),sy=r(ay(),1);function cy(){let e=new oy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sy.default)(e),e}var ly=class{constructor(e){this._ajv=e??cy()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},uy=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},Pt,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},Ft,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function dy(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function fy(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var py=class extends D_{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ut.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new ly,this.setRequestHandler(Zt,e=>this._oninitialize(e)),this.setNotificationHandler(Nt,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(bt,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=ut.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new uy(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=k_(this._capabilities,e)}setRequestHandler(e,t){let n=hg(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=xg(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=pg(Vt,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new L(R.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=pg(qt,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new L(R.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=pg(Gt,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new L(R.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){fy(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&dy(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:vt.includes(t)?t:Et,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},Ut)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},Bt,t):this.request({method:`sampling/createMessage`,params:e},Pt,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},Ft,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},Ft,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new L(R.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof L?e:new L(R.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},mt,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},my=Symbol.for(`mcp.completable`);function hy(e){return!!e&&typeof e==`object`&&my in e}function gy(e){return e[my]?.complete}var _y;(function(e){e.Completable=`McpCompletable`})(_y||={});var vy=/^[A-Za-z0-9._-]{1,128}$/;function yy(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!vy.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function by(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function xy(e){let t=yy(e);return by(e,t.warnings),t.isValid}var Sy=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Cy=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new py(e,t)}get experimental(){return this._experimental||={tasks:new Sy(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Ay(zt)),this.server.assertCanSetRequestHandler(Ay(Vt)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zt,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=gg(t.inputSchema);return e?w_(e,{strictUnions:!0,pipeStrategy:`input`}):wy})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=gg(t.outputSchema);e&&(n.outputSchema=w_(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Vt,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new L(R.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new L(R.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new L(R.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new L(R.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof L&&e.code===R.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await mg(gg(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=vg(`error`in r?r.error:`Unknown error`);throw new L(R.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new L(R.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await mg(gg(e.outputSchema),t.structuredContent);if(!r.success){let e=vg(`error`in r?r.error:`Unknown error`);throw new L(R.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new L(R.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Ay(Kt)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Kt,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Qt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return dt(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(R.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new L(R.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new L(R.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return My;let r=hg(n.argsSchema)?.[e.params.argument.name];if(!hy(r))return My;let i=gy(r);return i?jy(await i(e.params.argument.value,e.params.context)):My}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return My;throw new L(R.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?jy(await r(e.params.argument.value,e.params.context)):My}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Ay(Dt)),this.server.assertCanSetRequestHandler(Ay(Yt)),this.server.assertCanSetRequestHandler(Ay(ht)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Dt,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Yt,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ht,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new L(R.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new L(R.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Ay(ft)),this.server.assertCanSetRequestHandler(Ay(Lt)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ft,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?ky(t.argsSchema):void 0}))})),this.server.setRequestHandler(Lt,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new L(R.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new L(R.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await mg(gg(n.argsSchema),e.params.arguments);if(!r.success){let t=vg(`error`in r?r.error:`Unknown error`);throw new L(R.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:fg(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=fg(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>hy(e instanceof tt?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){xy(e);let l={title:t,description:n,inputSchema:Oy(r),outputSchema:Oy(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&xy(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=fg(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=fg(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(Dy(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Dy(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},wy={type:`object`,properties:{}};function Ty(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Ey(e){return`_def`in e||`_zod`in e||Ty(e)}function Dy(e){return typeof e!=`object`||!e||Ey(e)?!1:Object.keys(e).length===0||Object.values(e).some(Ty)}function Oy(e){if(e){if(Dy(e))return fg(e);if(!Ey(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function ky(e){let t=hg(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:yg(t),required:!bg(t)})):[]}function Ay(e){let t=hg(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=xg(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function jy(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var My={completion:{values:[],hasMore:!1}};function Ny(e,t){return t?e:e.map(Py)}function Py(e){let t=e.parameter.flatMap(Iy),n=Fy(e.requestBody);return Ry(t,e.parameter)&&n===e.requestBody?e:{...e,parameter:t,...n===void 0?{}:{requestBody:n}}}function Fy(e){if(e===void 0)return;let t=e.map(e=>{let t=e.parameter.flatMap(Iy);return Ry(t,e.parameter)?e:{...e,parameter:t}});return t.every((t,n)=>t===e[n])?e:t}function Iy(e){if(!Ly(e))return[];let t=e.itemProperty?.filter(Ly);return Ry(t,e.itemProperty)?[e]:[{...e,...t===void 0||t.length===0?{}:{itemProperty:t}}]}var Ly=e=>e.visibility!==`private`;function Ry(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(b.join(`|`),`i`);function zy(e){let t=k(e),n=en(t.data,t.summary)??JSON.stringify(t);return{isError:!t.ok,structuredContent:{...t},content:[{type:`text`,text:n}]}}var By=`aventure_status`,Vy=`aventure_help`,Hy=`aventure_read`,Uy=`aventure_lookup`,Wy=`aventure_search`,Gy=`aventure_write`,Ky=`aventure_delete`,qy=ot([I(),Xe(),nt()]),Jy=st(I(),ot([I(),Xe()])).optional(),Yy=st(I(),ot([qy,Qe(qy)])).optional(),Xy=st(I(),I()).optional(),Zy=Ze([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Qy=ot([qy,rt(),Qe(it()),st(I(),it())]).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.`),$y={operationId:I().optional().describe(`Exact OpenAPI operationId, as listed by aventure_help. Takes precedence over method and path.`),method:Zy.optional().describe(`HTTP method when resolving by method+path.`),path:I().optional().describe(`OpenAPI route template or concrete API path.`),pathParams:Jy.describe(`Values for route template parameters.`),query:Yy.describe(`Query parameters.`),headers:Xy.describe(`Headers declared by the selected OpenAPI operation.`),contentType:I().optional().describe(`Declared request media type; omit for the first supported descriptor.`),responseFormat:Ze([`auto`,`json`,`text`]).optional().describe(`Response format for endpoints that offer both JSON and text/plain.`)},eb={q:I().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:I().optional().describe(`Filter by resource or first CLI segment.`),method:Zy.optional().describe(`Filter by HTTP method.`),scope:Ze([`read`,`write`]).optional().describe(`Filter by required MCP auth scope.`),limit:$e().min(1).max(100).default(20).describe(`Maximum rows to return.`),resolve:nt().default(!1).describe(`Return one deterministic CLI recommendation for q.`)},tb={...$y,body:Qy};async function nb(e,t){let n=lt.find(e=>e.intent===`status`&&e.resource===`status`);if(n===void 0)return ce(`No system status operation exists in the generated catalog.`);let r;try{r=de().host}catch(e){return ce(e.message)}let i=await me({method:n.method,path:n.path,auth:n.projection.auth,requesterScope:e});return{...i,data:{transportScope:e,permissionGrant:t?.permissionGrant,host:r,status:i.data}}}var rb=(e,t)=>Ny(lt,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`)&&(t===void 0||t.operation.some(e=>e.operationId===n.operationId&&e.method===n.method&&e.path===n.path)));async function ib(e,t,n,r,i){let a=ie(e);if(!a.ok)return ce(a.summary,a.warnings);if(a.data===null)return ce(`OpenAPI operation resolution returned no data.`);let{method:o,operation:s,path:c,template:u}=a.data,d=s.operationId,f=r.find(e=>e.operationId===d&&e.method.toLowerCase()===o&&e.path===u);if(f===void 0)return ce(`Operation `+d+` is not in the MCP catalog.`);if(!t.includes(f.intent))return ce(`Operation `+d+` has intent=`+f.intent+`; use aventure_`+f.intent+`.`);let p=l(f.requestBody??[],e.contentType);if(!p.ok||p.data===null)return ce(p.summary,p.warnings);let m=p.data;return f.intent===`delete`&&m===void 0&&e.body!==void 0?ce(d+` does not accept a request body.`):await me({method:f.method,path:c,searchParams:e.query,headers:e.headers,body:e.body,contentType:e.contentType,auth:f.projection.auth,requesterScope:n,responseFormat:e.responseFormat,clientInfo:i})}function ab(e,t,n){let r=rb(t,n);e.registerTool(By,{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:{}},async()=>zy(await nb(t,n))),e.registerTool(Vy,{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; resolve returns one recommended operation for q. It describes operations only and calls no API.`,inputSchema:eb},async e=>{let{summary:t,data:n,counts:i}=$t(e,r);return zy(pe(t,n,{counts:i}))});let i=()=>e.server.getClientVersion();e.registerTool(Hy,{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. 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:tb},async e=>zy(await ib(e,[`read`],t,r,i()))),e.registerTool(Uy,{title:`aVenture lookup`,annotations:{readOnlyHint:!1},description:`Runs one catalog operation whose intent is lookup: resolve a name, URL, domain, slug, ticker, or other identifier to the record that owns it, or run a batch, preview, or duplicate check. Most lookups are POST operations that take a JSON 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:tb},async e=>zy(await ib(e,[`lookup`],t,r,i()))),e.registerTool(Wy,{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:tb},async e=>zy(await ib(e,[`search`],t,r,i()))),r.some(e=>e.intent===`write`)&&e.registerTool(Gy,{title:`aVenture write`,annotations:{readOnlyHint:!1,destructiveHint:!0},description:`Runs one catalog operation whose intent is write: create or change records in the shared aVenture corpus, or start an account or enrichment action such as a billing checkout, plan change, or portal session, or an entity or person enrichment; the write 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:tb},async e=>zy(await ib(e,[`write`],t,r,i()))),r.some(e=>e.intent===`delete`)&&e.registerTool(Ky,{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:tb},async e=>zy(await ib(e,[`delete`],t,r,i())))}var ob=T().version;function sb(e,t){let n=new Cy({name:`aventure-mcp-server`,title:`aVenture MCP Server`,version:ob},{capabilities:{logging:{}},instructions:ge.info.description});return ab(n,e,t),n}var cb=lt.map(({operationId:e,method:t,path:n,parameter:r})=>({operationId:e,method:t,path:n,authorizationPath:D(n,Object.fromEntries(r.filter(e=>e.in===`path`).map(e=>e.schemaEnum?.[0]===void 0?e.schemaFormat===`uuid`?[e.name,ln()]:e.schemaType===`integer`||e.schemaType===`number`?[e.name,1]:[e.name,`authorization-probe`]:[e.name,e.schemaEnum[0]])),e)}));async function lb(e,t){let n=ym(e.header(`authorization`));if(n===void 0)return{ok:!1,reason:`missing_credential`,hasAuthorization:!1};try{let e=await j(n,t,cb);if(e===`forbidden`)return{ok:!1,reason:`forbidden`,hasAuthorization:!0};if(e!==null)return{ok:!0,scope:e.operationAccess===`READ`?`read`:`write`,userBearerToken:n,authorization:e}}catch(e){if(!(e instanceof g))throw e;C({component:`aventure-mcp-server`,event:`invalid_bearer_jwt`,fields:{requestId:v()},error:e})}return{ok:!1,reason:`credential_mismatch`,hasAuthorization:!0}}function ub(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 db=1024,fb=db*db,pb=1,mb=2,hb=`b`,gb=`kb`,_b=`mb`,vb=/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/u;function yb(e){let t=xb(e.limit),n=bb(e.path);return(r,i,a)=>{if(t===void 0||r.method!==`POST`||bb(r.path)!==n){a();return}let o=Sb(r.header(`content-length`));if(o===void 0||o<=t){a();return}i.setHeader(`Connection`,`close`),e.reject(i)}}function bb(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;return t===``?`/`:t}function xb(e){if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:void 0;let t=vb.exec(e.trim().toLowerCase());if(t===null)return;let n=Number(t[pb]);if(Number.isFinite(n))switch(t[mb]??hb){case _b:return Math.floor(n*fb);case gb:return Math.floor(n*db);case hb:return Math.floor(n)}}function Sb(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}var Cb=400,wb=400,Tb=413,Eb=`10mb`,Db=`127.0.0.1`,Ob=`0.0.0.0`;async function kb(e){let t=e.jsonBodyLimit??Eb,n=e.host??Db,r=n!==Ob,i=(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},a=(0,pl.default)();a.disable(`x-powered-by`),a.set(`trust proxy`,1),a.use((e,t,n)=>{let r=ln(),i=performance.now(),a={requestId:r,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},o=Mb(e);o||c({component:`aventure-mcp-server`,event:`http_request`,fields:a}),t.on(`finish`,()=>{let n=Math.round(performance.now()-i),r=e.route;Am(e.method,typeof r==`object`&&r&&`path`in r&&typeof r.path==`string`?r.path:`unmatched`,t.statusCode,n),(t.statusCode>=Cb&&!o?C:c)({component:`aventure-mcp-server`,event:`http_response`,fields:{...a,status:t.statusCode,durationMs:n}})}),ne(r,()=>n())}),a.use(r?(0,fl.default)({origin:jb}):(0,fl.default)()),a.use(yb({path:e.path,limit:t,reject:e=>Nb(e,Tb,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),a.use(pl.json({limit:t})),a.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`})}),a.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,fl.default)(),async(t,n,r)=>{let a=await e.resolveOAuthDiscovery();if(a===void 0){Nb(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=i(t,a);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),jm(a,e.metricsScrapeSecret),a.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),a.get(`/favicon.ico`,(...e)=>{e[1].status(204).end()});let s=Vl({windowMs:6e4,limit:120});return a.post(e.path,s,async(t,n)=>{let a=v(),s=t.header(`origin`);if(r&&!Ab(s)){C({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:a,method:t.method,path:t.path,origin:s}}),Nb(n,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let l,u;try{let n=await e.resolveOAuthDiscovery();u=i(t,n),l=await lb(t,n?.resourceUrl)}catch(e){xe({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:a,method:t.method,path:t.path},error:e});let r=e instanceof se&&(e.problem.status===429||ye(e.problem.status))?e.problem:void 0;r===void 0?Nb(n,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof r.retryAfterSeconds==`number`&&n.set(`Retry-After`,String(r.retryAfterSeconds)),Pb(n,r));return}if(!l.ok){C({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:a,method:t.method,path:t.path,reason:l.reason,hasAuthorization:l.hasAuthorization}});let e=[u===void 0?void 0:`resource_metadata="${Ed(u.resourceUrl)}"`,u===void 0?void 0:`scope="${u.client.scope.join(` `)}"`,l.reason===`credential_mismatch`?`error="invalid_token"`:void 0,l.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,l.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);n.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`),l.reason===`forbidden`?Nb(n,403,`Forbidden`,ub(l.reason,u!==void 0)):Nb(n,401,`Unauthorized`,ub(l.reason,u!==void 0));return}let d=t.header(`accept`)??`*/*`;if(!d.includes(`*/*`)&&(!d.includes(`application/json`)||!d.includes(`text/event-stream`))){Nb(n,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}c({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:a,method:t.method,path:t.path,scope:l.scope}});let f=sb(l.scope,l.authorization),p=new Td({sessionIdGenerator:void 0});n.on(`close`,()=>{Ib(()=>p.close(),`transport_close_failed`,t,a),Ib(()=>f.close(),`mcp_close_failed`,t,a)});try{let e=async()=>{await f.connect(p),await p.handleRequest(t,n,t.body)};l.userBearerToken===void 0?await e():await o(l.userBearerToken,e)}catch(e){let r=h(e);no(e,`transport_error`),xe({component:`aventure-mcp-server`,event:`transport_error`,message:r,fields:{requestId:a,method:t.method,path:t.path},error:e}),n.headersSent||Nb(n,500,`MCP transport error`,r)}}),a.all(e.path,(...e)=>{let t=e[1];Nb(t,405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)}),a.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=Fb(e);if(i===void 0){r(e);return}C({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:v(),method:t.method,path:t.path,status:i.status}}),Nb(n,i.status,i.status===Tb?`Payload Too Large`:`Bad Request`,i.status===Tb?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,r)=>{let i;i=a.listen(e.port,n,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await Mm()}})}),i.on(`error`,r)})}function Ab(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]`:an(t)&&t.startsWith(`127.`)}var jb=(e,t)=>t(null,Ab(e)),Mb=e=>e.method===`GET`&&/^\/robots\.txt\/?$/iu.test(e.path);function Nb(e,t,n,r){Pb(e,{type:`about:blank`,title:n,status:t,detail:r})}function Pb(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function Fb(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?Tb:e.type===`entity.parse.failed`?wb:e.status===Tb||e.status===wb?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 Ib(e,t,n,r){e().catch(e=>{C({component:`aventure-mcp-server`,event:t,message:e.message,fields:{requestId:r,method:n.method,path:n.path},error:e})})}var Lb=65535,Rb=55e3,zb=T(nn(import.meta.url)),{host:Bb}=(await new f().name(zb.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(zb.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`,`
|
|
149
149
|
Connect an MCP client to the server's /mcp URL and send
|
|
150
150
|
Authorization: Bearer <api-key> using a key from aventure.vc. The hosted
|
|
151
151
|
mcp.aventure.vc also advertises an authorization server, so a client there can
|
|
@@ -156,4 +156,4 @@ Environment:
|
|
|
156
156
|
AVENTURE_MCP_PORT Select the HTTP listening port.
|
|
157
157
|
AVENTURE_MCP_PATH Select the MCP route.
|
|
158
158
|
AVENTURE_MCP_JSON_LIMIT Limit request body size.
|
|
159
|
-
`).parseAsync()).opts();await to(),delete process.env[
|
|
159
|
+
`).parseAsync()).opts();await to(),delete process.env[E.authToken];var Vb=qb(),Hb=process.env.AVENTURE_MCP_PATH??`/mcp`,Ub=process.env.AVENTURE_MCP_JSON_LIMIT??`10mb`,Wb=p()||void 0,Gb=!1;function Kb(e){Promise.allSettled([w(),ro()]).then(e=>{for(let t of e){if(t.status!==`rejected`)continue;let e=h(t.reason);process.stderr.write(`${zb.bin[0]} telemetry shutdown failed: ${e}\n`)}}).catch(e=>{let t=h(e);process.stderr.write(`${zb.bin[0]} telemetry shutdown failed: ${t}\n`)}).finally(()=>process.exit(e))}kb({port:Vb,host:Bb,path:Hb,resolveOAuthDiscovery:Xa(),jsonBodyLimit:Ub,metricsScrapeSecret:Wb}).then(e=>{c({component:`aventure-mcp-server`,event:`server_listening`,fields:{port:Vb,path:Hb}}),process.stdout.write(`${zb.bin[0]} listening at http://localhost:${Vb}${Hb}\n`);let t=t=>{if(Gb)return;Gb=!0,c({component:`aventure-mcp-server`,event:`server_shutdown_started`,fields:{signal:t}});let n=setTimeout(()=>{xe({component:`aventure-mcp-server`,event:`server_shutdown_timeout`,message:`MCP server did not drain before the platform forced-shutdown window`,fields:{signal:t,forceExitMs:Rb}}),Kb(1)},Rb);n.unref(),e.close().then(()=>{clearTimeout(n),c({component:`aventure-mcp-server`,event:`server_shutdown_completed`,fields:{signal:t}}),Kb(0)}).catch(e=>{let r=h(e);clearTimeout(n),xe({component:`aventure-mcp-server`,event:`server_shutdown_failed`,message:r,fields:{signal:t},error:e}),Kb(1)})};for(let e of[`SIGTERM`,`SIGINT`])process.on(e,t)},async e=>{let t=h(e);no(e,`server_start_failed`),xe({component:`aventure-mcp-server`,event:`server_start_failed`,message:t,error:e}),process.stderr.write(`${zb.bin[0]} failed to start: ${t}\n`),Kb(1)});function qb(){let e=process.env.AVENTURE_MCP_PORT??process.env.PORT??`3333`,t=Number(e);if(!Number.isInteger(t)||t<1||t>Lb)throw Error(`Invalid MCP server port: ${e}`);return t}export{};
|