@onyxsecurity/mcp-gateway 1.0.33 → 1.0.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/mcp-gateway.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{AccessControlBlockError as e,BUILD_TIME_CONFIG as t,Client as n,ConfigurationError as r,ProcessSpawnError as i,ProxyConnectionError as a,ReadBuffer as o,SSEClientTransport as s,Server as c,StdioServerTransport as l,StreamableHTTPClientTransport as u,TransportError as d,UnauthorizedError as f,__commonJSMin as p,__toESM as m,addBreadcrumbSafe as h,addGlobalTags as g,captureExceptionSafe as _,compressClientInfo as v,config as y,createParser as b,discoverAuthorizationServerMetadata as ee,discoverOAuthProtectedResourceMetadata as te,exchangeAuthorization as ne,getSessionData as re,initSentrySafe as x,initializeTrafficMirror as ie,logger as S,proxyServer as C,refreshAuthorization as ae,registerClient as oe,serializeMessage as se,startAuthorization as ce,startHTTPServer as le}from"../stdio-
|
|
2
|
+
import{AccessControlBlockError as e,BUILD_TIME_CONFIG as t,Client as n,ConfigurationError as r,ProcessSpawnError as i,ProxyConnectionError as a,ReadBuffer as o,SSEClientTransport as s,Server as c,StdioServerTransport as l,StreamableHTTPClientTransport as u,TransportError as d,UnauthorizedError as f,__commonJSMin as p,__toESM as m,addBreadcrumbSafe as h,addGlobalTags as g,captureExceptionSafe as _,compressClientInfo as v,config as y,createParser as b,discoverAuthorizationServerMetadata as ee,discoverOAuthProtectedResourceMetadata as te,exchangeAuthorization as ne,getSessionData as re,initSentrySafe as x,initializeTrafficMirror as ie,logger as S,proxyServer as C,refreshAuthorization as ae,registerClient as oe,serializeMessage as se,startAuthorization as ce,startHTTPServer as le}from"../stdio-Bk0V_i6g.js";import"../pkce-BlbkGwOt.js";import{createRequire as ue}from"node:module";import{readFileSync as de,readdirSync as fe}from"node:fs";import{join as pe}from"node:path";import{platform as me}from"node:os";import{createHash as w}from"node:crypto";import{basename as he,dirname as ge,extname as _e,join as ve,normalize as ye,relative as be,resolve as xe}from"path";import{format as Se,inspect as Ce}from"util";import{fileURLToPath as we}from"url";import{createServer as Te}from"node:http";import{setTimeout as Ee}from"node:timers";import De from"node:util";import{notStrictEqual as Oe,strictEqual as ke}from"assert";import{readFileSync as Ae,readdirSync as je,statSync as Me,writeFile as Ne}from"fs";import{execFile as Pe,spawn as Fe}from"node:child_process";import{URL as Ie}from"node:url";import{chmod as Le,mkdir as Re,readFile as ze,rm as Be,writeFile as Ve}from"node:fs/promises";import{PassThrough as He,Transform as Ue}from"node:stream";var We=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(qe(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(qe(this),t)}};function Ge(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Ke(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Ke).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Ke(e.cause)}`:e.message:`${e}`}function qe(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Je=e=>{throw TypeError(e)},Ye=(e,t,n)=>t.has(e)||Je(`Cannot `+n),T=(e,t,n)=>(Ye(e,t,`read from private field`),n?n.call(e):t.get(e)),E=(e,t,n)=>t.has(e)?Je(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),D=(e,t,n,r)=>(Ye(e,t,`write to private field`),t.set(e,n),n),Xe=(e,t,n)=>(Ye(e,t,`access private method`),n),O,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,st,ct,lt,ut,dt,ft,pt,mt,ht,gt,_t,vt,yt=class extends EventTarget{constructor(e,t){super(),E(this,lt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,E(this,O),E(this,Ze),E(this,Qe),E(this,$e),E(this,et),E(this,tt),E(this,nt),E(this,rt,null),E(this,it),E(this,at),E(this,ot,null),E(this,st,null),E(this,ct,null),E(this,dt,async e=>{var t;T(this,at).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Xe(this,lt,gt).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?D(this,Qe,new URL(e.url)):D(this,Qe,void 0),i!==200){Xe(this,lt,gt).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Xe(this,lt,gt).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(T(this,O)===this.CLOSED)return;D(this,O,this.OPEN);let o=new Event(`open`);if((t=T(this,ct))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Xe(this,lt,gt).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&T(this,at).feed(s.decode(t,{stream:!e})),e&&(l=!1,T(this,at).reset(),Xe(this,lt,_t).call(this))}while(l)}),E(this,ft,e=>{D(this,it,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&Xe(this,lt,_t).call(this,Ke(e))}),E(this,mt,e=>{typeof e.id==`string`&&D(this,rt,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:T(this,Qe)?T(this,Qe).origin:T(this,Ze).origin,lastEventId:e.id||``});T(this,st)&&(!e.event||e.event===`message`)&&T(this,st).call(this,t),this.dispatchEvent(t)}),E(this,ht,e=>{D(this,tt,e)}),E(this,vt,()=>{D(this,nt,void 0),T(this,O)===this.CONNECTING&&Xe(this,lt,ut).call(this)});try{if(e instanceof URL)D(this,Ze,e);else if(typeof e==`string`)D(this,Ze,new URL(e,bt()));else throw Error(`Invalid URL`)}catch{throw Ge(`An invalid or illegal string was specified`)}D(this,at,b({onEvent:T(this,mt),onRetry:T(this,ht)})),D(this,O,this.CONNECTING),D(this,tt,3e3),D(this,et,t?.fetch??globalThis.fetch),D(this,$e,t?.withCredentials??!1),Xe(this,lt,ut).call(this)}get readyState(){return T(this,O)}get url(){return T(this,Ze).href}get withCredentials(){return T(this,$e)}get onerror(){return T(this,ot)}set onerror(e){D(this,ot,e)}get onmessage(){return T(this,st)}set onmessage(e){D(this,st,e)}get onopen(){return T(this,ct)}set onopen(e){D(this,ct,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){T(this,nt)&&clearTimeout(T(this,nt)),T(this,O)!==this.CLOSED&&(T(this,it)&&T(this,it).abort(),D(this,O,this.CLOSED),D(this,it,void 0))}};O=new WeakMap,Ze=new WeakMap,Qe=new WeakMap,$e=new WeakMap,et=new WeakMap,tt=new WeakMap,nt=new WeakMap,rt=new WeakMap,it=new WeakMap,at=new WeakMap,ot=new WeakMap,st=new WeakMap,ct=new WeakMap,lt=new WeakSet,ut=function(){D(this,O,this.CONNECTING),D(this,it,new AbortController),T(this,et)(T(this,Ze),Xe(this,lt,pt).call(this)).then(T(this,dt)).catch(T(this,ft))},dt=new WeakMap,ft=new WeakMap,pt=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...T(this,rt)?{"Last-Event-ID":T(this,rt)}:void 0},cache:`no-store`,signal:T(this,it)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},mt=new WeakMap,ht=new WeakMap,gt=function(e,t){var n;T(this,O)!==this.CLOSED&&D(this,O,this.CLOSED);let r=new We(`error`,{code:t,message:e});(n=T(this,ot))==null||n.call(this,r),this.dispatchEvent(r)},_t=function(e,t){var n;if(T(this,O)===this.CLOSED)return;D(this,O,this.CONNECTING);let r=new We(`error`,{code:t,message:e});(n=T(this,ot))==null||n.call(this,r),this.dispatchEvent(r),D(this,nt,setTimeout(T(this,vt),T(this,tt)))},vt=new WeakMap,yt.CONNECTING=0,yt.OPEN=1,yt.CLOSED=2;function bt(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}const xt={right:Et,center:Dt};var St=class{constructor(e){this.width=e.width,this.wrap=e.wrap??!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0&&this.div(``),this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==`string`)return this.applyLayoutDSL(e[0]);let t=e.map(e=>typeof e==`string`?this.colFromString(e):e);return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==`string`&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
|
|
3
3
|
`).map(e=>e.split(` `)),n=0;return t.forEach(e=>{e.length>1&&k.stringWidth(e[0])>n&&(n=Math.min(Math.floor(this.width*.5),k.stringWidth(e[0])))}),t.forEach(e=>{this.div(...e.map((t,r)=>({text:t.trim(),padding:this.measurePadding(t),width:r===0&&e.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=k.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach(t=>{this.rowToString(t,e)}),e.filter(e=>!e.hidden).map(e=>e.text).join(`
|
|
4
4
|
`)}rowToString(e,t){return this.rasterize(e).forEach((n,r)=>{let i=``;n.forEach((n,a)=>{let{width:o}=e[a],s=this.negatePadding(e[a]),c=n;if(s>k.stringWidth(n)&&(c+=` `.repeat(s-k.stringWidth(n))),e[a].align&&e[a].align!==`left`&&this.wrap){let t=xt[e[a].align];c=t(c,s),k.stringWidth(c)<s&&(c+=` `.repeat((o||0)-k.stringWidth(c)-1))}let l=e[a].padding||[0,0,0,0];l[3]&&(i+=` `.repeat(l[3])),i+=Ct(e[a],c,`| `),i+=c,i+=Ct(e[a],c,` |`),l[1]&&(i+=` `.repeat(l[1])),r===0&&t.length>0&&(i=this.renderInline(i,t[t.length-1]))}),t.push({text:i.replace(/ +$/,``),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),r=n?n[0].length:0,i=t.text,a=k.stringWidth(i.trimRight());return t.span?this.wrap?r<a?e:(t.hidden=!0,i.trimRight()+` `.repeat(r-a)+e.trimLeft()):(t.hidden=!0,i+e):e}rasterize(e){let t=[],n=this.columnWidths(e),r;return e.forEach((e,i)=>{e.width=n[i],r=this.wrap?k.wrap(e.text,this.negatePadding(e),{hard:!0}).split(`
|
|
5
5
|
`):e.text.split(`
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Client as e,InMemoryEventStore as t,SSEClientTransport as n,Server as r,StdioServerTransport as i,StreamableHTTPClientTransport as a,config as o,proxyServer as s,startHTTPServer as c}from"./stdio-
|
|
1
|
+
import{Client as e,InMemoryEventStore as t,SSEClientTransport as n,Server as r,StdioServerTransport as i,StreamableHTTPClientTransport as a,config as o,proxyServer as s,startHTTPServer as c}from"./stdio-Bk0V_i6g.js";let l=function(e){return e.HTTPStream=`HTTPStream`,e.SSE=`SSE`,e}({});const u=async({initStdioServer:t,initStreamClient:c,serverType:u,transportOptions:d={},url:f})=>{let p;switch(u){case l.SSE:p=new n(new URL(f),d);break;default:p=new a(new URL(f),d)}let m=c?await c():new e({name:`mcp-gateway`,version:o.appVersion},{capabilities:{}});await m.connect(p);let h=m.getServerVersion(),g=m.getServerCapabilities(),_=t?await t():new r(h,{capabilities:g}),v=new i;return await _.connect(v),await s({authorizer:void 0,client:m,server:_,serverCapabilities:g}),_},d=(e,t)=>{let n=e.close.bind(e),r=e.onclose?.bind(e),i=e.onerror?.bind(e),a=e.onmessage?.bind(e),o=e.send.bind(e),s=e.start.bind(e);return e.close=async()=>(t({type:`close`}),n?.()),e.onclose=async()=>(t({type:`onclose`}),r?.()),e.onerror=async e=>(t({error:e,type:`onerror`}),i?.(e)),e.onmessage=async e=>(t({message:e,type:`onmessage`}),a?.(e)),e.send=async e=>(t({message:e,type:`send`}),o?.(e)),e.start=async()=>(t({type:`start`}),s?.()),e};export{t as InMemoryEventStore,l as ServerType,s as proxyServer,c as startHTTPServer,u as startStdioServer,d as tapTransport};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{randomUUID as t}from"crypto";import{existsSync as n,mkdirSync as r,readFileSync as i}from"node:fs";import{join as a}from"node:path";import o from"winston";import s from"winston-daily-rotate-file";import c from"env-var";import{homedir as l,hostname as u,userInfo as d}from"node:os";import"dotenv/config";import*as f from"@sentry/node";import p from"ps-list";import{deflateSync as m}from"node:zlib";import{randomUUID as h}from"node:crypto";import{URL as g}from"url";import _ from"node:http";import v from"node:process";var y=Object.create,b=Object.defineProperty,x=Object.getOwnPropertyDescriptor,S=Object.getOwnPropertyNames,C=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty,T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),E=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=S(t),a=0,o=i.length,s;a<o;a++)s=i[a],!w.call(e,s)&&s!==n&&b(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=x(t,s))||r.enumerable});return e},D=(e,t,n)=>(n=e==null?{}:y(C(e)),E(t||!e||!e.__esModule?b(n,`default`,{value:e,enumerable:!0}):n,e)),O=e(import.meta.url),k=class{events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){return`${e}_${Date.now()}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length>0?t[0]:``}},A;(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})(A||={});var ee;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(ee||={});const j=A.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),M=e=>{switch(typeof e){case`undefined`:return j.undefined;case`string`:return j.string;case`number`:return Number.isNaN(e)?j.nan:j.number;case`boolean`:return j.boolean;case`function`:return j.function;case`bigint`:return j.bigint;case`symbol`:return j.symbol;case`object`:return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?j.promise:typeof Map<`u`&&e instanceof Map?j.map:typeof Set<`u`&&e instanceof Set?j.set:typeof Date<`u`&&e instanceof Date?j.date:j.object;default:return j.unknown}},N=A.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`]);var P=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,A.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},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()}};P.create=e=>new P(e);var te=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===j.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,A.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${A.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${A.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${A.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.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}"`:A.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.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 N.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 N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,A.assertNever(e)}return{message:n}};let ne=te;function re(){return ne}const F=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 I(e,t){let n=re(),r=F({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===te?void 0:te].filter(e=>!!e)});e.common.issues.push(r)}var L=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 R;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 R;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}}};const R=Object.freeze({status:`aborted`}),ie=e=>({status:`dirty`,value:e}),z=e=>({status:`valid`,value:e}),B=e=>e.status===`aborted`,ae=e=>e.status===`dirty`,oe=e=>e.status===`valid`,V=e=>typeof Promise<`u`&&e instanceof Promise;var H;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(H||={});var se=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}};const ce=(e,t)=>{if(oe(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(){return this._error||=new P(e.common.issues),this._error}}};function U(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 W=class{get description(){return this._def.description}_getType(e){return M(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new L,ctx:{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(V(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:M(e)},r=this._parseSync({data:e,path:n.path,parent:n});return ce(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return oe(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=>oe(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:M(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(V(r)?r:Promise.resolve(r));return ce(n,i)}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:N.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 ut({schema:this,typeName:G.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 dt.create(this,this._def)}nullable(){return ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ge.create(this)}promise(){return lt.create(this,this._def)}or(e){return Je.create([this,e],this._def)}and(e){return Qe.create(this,e,this._def)}transform(e){return new ut({...U(this._def),schema:this,typeName:G.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new pt({...U(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new gt({typeName:G.ZodBranded,type:this,...U(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new mt({...U(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _t.create(this,e)}readonly(){return vt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const le=/^c[^\s-]{8,}$/i,ue=/^[0-9a-z]+$/,de=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fe=/^[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,pe=/^[a-z0-9_-]{21}$/i,me=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,he=/^[-+]?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)?)??$/,ge=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let _e;const ve=/^(?:(?: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])$/,ye=/^(?:(?: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])$/,be=/^(([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]))$/,xe=/^(([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])$/,Se=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ce=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,we=`((\\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])))`,Te=RegExp(`^${we}$`);function Ee(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 De(e){return RegExp(`^${Ee(e)}$`)}function Oe(e){let t=`${we}T${Ee(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ke(e,t){return!!((t===`v4`||!t)&&ve.test(e)||(t===`v6`||!t)&&be.test(e))}function Ae(e,t){if(!me.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 je(e,t){return!!((t===`v4`||!t)&&ye.test(e)||(t===`v6`||!t)&&xe.test(e))}var Me=class e extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.string,received:t.parsedType}),R}let t=new L,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:N.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),I(n,{code:N.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?I(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&I(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)ge.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)_e||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),_e.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)fe.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)pe.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ue.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)de.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),I(n,{validation:`url`,code:N.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),I(n,{validation:`regex`,code:N.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),I(n,{code:N.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),I(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Oe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Te.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?De(r).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?he.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ke(e.data,r.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ae(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?je(e.data,r.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Se.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ce.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):A.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...H.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...H.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...H.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...H.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...H.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...H.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...H.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...H.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...H.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...H.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...H.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...H.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,...H.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,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...H.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...H.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...H.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...H.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...H.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...H.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...H.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...H.errToObj(t)})}nonempty(e){return this.min(1,H.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}};Me.create=e=>new Me({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...U(e)});function Ne(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(`.`,``)),o=Number.parseInt(t.toFixed(i).replace(`.`,``));return a%o/10**i}var Pe=class e extends W{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)!==j.number){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.number,received:t.parsedType}),R}let t,n=new L;for(let r of this._def.checks)r.kind===`int`?A.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:N.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),I(t,{code:N.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),I(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ne(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),I(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:N.not_finite,message:r.message}),n.dirty()):A.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:H.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:H.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:H.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:H.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`&&A.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)}};Pe.create=e=>new Pe({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...U(e)});var Fe=class e extends W{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)!==j.bigint)return this._getInvalidInput(e);let t,n=new L;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),I(t,{code:N.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),I(t,{code:N.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),I(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):A.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.bigint,received:t.parsedType}),R}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.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:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.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}};Fe.create=e=>new Fe({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var Ie=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.boolean,received:t.parsedType}),R}return z(e.data)}};Ie.create=e=>new Ie({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var Le=class e extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.date,received:t.parsedType}),R}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_date}),R}let t=new L,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:N.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),I(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):A.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:H.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:H.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)}};Le.create=e=>new Le({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...U(e)});var Re=class extends W{_parse(e){if(this._getType(e)!==j.symbol){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.symbol,received:t.parsedType}),R}return z(e.data)}};Re.create=e=>new Re({typeName:G.ZodSymbol,...U(e)});var ze=class extends W{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.undefined,received:t.parsedType}),R}return z(e.data)}};ze.create=e=>new ze({typeName:G.ZodUndefined,...U(e)});var Be=class extends W{_parse(e){if(this._getType(e)!==j.null){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.null,received:t.parsedType}),R}return z(e.data)}};Be.create=e=>new Be({typeName:G.ZodNull,...U(e)});var Ve=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}};Ve.create=e=>new Ve({typeName:G.ZodAny,...U(e)});var He=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}};He.create=e=>new He({typeName:G.ZodUnknown,...U(e)});var Ue=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.never,received:t.parsedType}),R}};Ue.create=e=>new Ue({typeName:G.ZodNever,...U(e)});var We=class extends W{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.void,received:t.parsedType}),R}return z(e.data)}};We.create=e=>new We({typeName:G.ZodVoid,...U(e)});var Ge=class e extends W{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==j.array)return I(t,{code:N.invalid_type,expected:j.array,received:t.parsedType}),R;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(I(t,{code:e?N.too_big:N.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&&(I(t,{code:N.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&&(I(t,{code:N.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 se(t,e,t.path,n)))).then(e=>L.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new se(t,e,t.path,n)));return L.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:H.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:H.toString(n)}})}nonempty(e){return this.min(1,e)}};Ge.create=(e,t)=>new Ge({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...U(t)});function Ke(e){if(e instanceof qe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=dt.create(Ke(r))}return new qe({...e._def,shape:()=>t})}else if(e instanceof Ge)return new Ge({...e._def,type:Ke(e.element)});else if(e instanceof dt)return dt.create(Ke(e.unwrap()));else if(e instanceof ft)return ft.create(Ke(e.unwrap()));else if(e instanceof $e)return $e.create(e.items.map(e=>Ke(e)));else return e}var qe=class e extends W{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=A.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),R}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ue&&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 se(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ue){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&&(I(n,{code:N.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 se(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=>L.mergeObjectSync(t,e)):L.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return H.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:H.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:G.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 A.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 A.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ke(this)}partial(t){let n={};for(let e of A.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of A.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof dt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return ot(A.objectKeys(this.shape))}};qe.create=(e,t)=>new qe({shape:()=>e,unknownKeys:`strip`,catchall:Ue.create(),typeName:G.ZodObject,...U(t)}),qe.strictCreate=(e,t)=>new qe({shape:()=>e,unknownKeys:`strict`,catchall:Ue.create(),typeName:G.ZodObject,...U(t)}),qe.lazycreate=(e,t)=>new qe({shape:e,unknownKeys:`strip`,catchall:Ue.create(),typeName:G.ZodObject,...U(t)});var Je=class extends W{_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 P(e.ctx.common.issues));return I(t,{code:N.invalid_union,unionErrors:n}),R}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 P(e));return I(t,{code:N.invalid_union,unionErrors:i}),R}}get options(){return this._def.options}};Je.create=(e,t)=>new Je({options:e,typeName:G.ZodUnion,...U(t)});const Ye=e=>e instanceof it?Ye(e.schema):e instanceof ut?Ye(e.innerType()):e instanceof at?[e.value]:e instanceof st?e.options:e instanceof ct?A.objectValues(e.enum):e instanceof pt?Ye(e._def.innerType):e instanceof ze?[void 0]:e instanceof Be?[null]:e instanceof dt?[void 0,...Ye(e.unwrap())]:e instanceof ft?[null,...Ye(e.unwrap())]:e instanceof gt||e instanceof vt?Ye(e.unwrap()):e instanceof mt?Ye(e._def.innerType):[];var Xe=class e extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return I(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),R;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}):(I(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),R)}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=Ye(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:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...U(r)})}};function Ze(e,t){let n=M(e),r=M(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){let n=A.objectKeys(t),r=A.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ze(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===j.array&&r===j.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=Ze(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===j.date&&r===j.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Qe=class extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(B(e)||B(r))return R;let i=Ze(e.value,r.value);return i.valid?((ae(e)||ae(r))&&t.dirty(),{status:t.value,value:i.data}):(I(n,{code:N.invalid_intersection_types}),R)};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}))}};Qe.create=(e,t,n)=>new Qe({left:e,right:t,typeName:G.ZodIntersection,...U(n)});var $e=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return I(n,{code:N.invalid_type,expected:j.array,received:n.parsedType}),R;if(n.data.length<this._def.items.length)return I(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),R;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:N.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 se(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>L.mergeArray(t,e)):L.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};$e.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new $e({items:e,typeName:G.ZodTuple,rest:null,...U(t)})};var et=class e extends W{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!==j.object)return I(n,{code:N.invalid_type,expected:j.object,received:n.parsedType}),R;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new se(n,e,n.path,e)),value:a._parse(new se(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?L.mergeObjectAsync(t,r):L.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof W?new e({keyType:t,valueType:n,typeName:G.ZodRecord,...U(r)}):new e({keyType:Me.create(),valueType:t,typeName:G.ZodRecord,...U(n)})}},tt=class extends W{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!==j.map)return I(n,{code:N.invalid_type,expected:j.map,received:n.parsedType}),R;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new se(n,e,n.path,[a,`key`])),value:i._parse(new se(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 R;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return R;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};tt.create=(e,t,n)=>new tt({valueType:t,keyType:e,typeName:G.ZodMap,...U(n)});var nt=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return I(n,{code:N.invalid_type,expected:j.set,received:n.parsedType}),R;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(I(n,{code:N.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&&(I(n,{code:N.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 R;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 se(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:H.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:H.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};nt.create=(e,t)=>new nt({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...U(t)});var rt=class e extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return I(t,{code:N.invalid_type,expected:j.function,received:t.parsedType}),R;function n(e,n){return F({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),te].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return F({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),te].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof lt){let e=this;return z(async function(...t){let o=new P([]),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})})}else{let e=this;return z(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new P([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new P([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:$e.create(t).rest(He.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||$e.create([]).rest(He.create()),returns:n||He.create(),typeName:G.ZodFunction,...U(r)})}},it=class extends W{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})}};it.create=(e,t)=>new it({getter:e,typeName:G.ZodLazy,...U(t)});var at=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),R}return{status:`valid`,value:e.data}}get value(){return this._def.value}};at.create=(e,t)=>new at({value:e,typeName:G.ZodLiteral,...U(t)});function ot(e,t){return new st({values:e,typeName:G.ZodEnum,...U(t)})}var st=class e extends W{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{expected:A.joinValues(n),received:t.parsedType,code:N.invalid_type}),R}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{received:t.data,code:N.invalid_enum_value,options:n}),R}return z(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})}};st.create=ot;var ct=class extends W{_parse(e){let t=A.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let e=A.objectValues(t);return I(n,{expected:A.joinValues(e),received:n.parsedType,code:N.invalid_type}),R}if(this._cache||=new Set(A.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=A.objectValues(t);return I(n,{received:n.data,code:N.invalid_enum_value,options:e}),R}return z(e.data)}get enum(){return this._def.values}};ct.create=(e,t)=>new ct({values:e,typeName:G.ZodNativeEnum,...U(t)});var lt=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return I(t,{code:N.invalid_type,expected:j.promise,received:t.parsedType}),R;let n=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return z(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};lt.create=(e,t)=>new lt({type:e,typeName:G.ZodPromise,...U(t)});var ut=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.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=>{I(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 R;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?R:r.status===`dirty`||t.value===`dirty`?ie(r.value):r});{if(t.value===`aborted`)return R;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?R:r.status===`dirty`||t.value===`dirty`?ie(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`?R:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?R:(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(!oe(e))return R;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}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>oe(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):R);A.assertNever(r)}};ut.create=(e,t,n)=>new ut({schema:e,typeName:G.ZodEffects,effect:t,...U(n)}),ut.createWithPreprocess=(e,t,n)=>new ut({schema:t,effect:{type:`preprocess`,transform:e},typeName:G.ZodEffects,...U(n)});var dt=class extends W{_parse(e){return this._getType(e)===j.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:G.ZodOptional,...U(t)});var ft=class extends W{_parse(e){return this._getType(e)===j.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:G.ZodNullable,...U(t)});var pt=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...U(t)});var mt=class extends W{_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 V(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...U(t)});var ht=class extends W{_parse(e){if(this._getType(e)!==j.nan){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.nan,received:t.parsedType}),R}return{status:`valid`,value:e.data}}};ht.create=e=>new ht({typeName:G.ZodNaN,...U(e)});var gt=class extends W{_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}},_t=class e extends W{_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`?R:e.status===`dirty`?(t.dirty(),ie(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`?R: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:G.ZodPipeline})}},vt=class extends W{_parse(e){let t=this._def.innerType._parse(e),n=e=>(oe(e)&&(e.value=Object.freeze(e.value)),e);return V(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};vt.create=(e,t)=>new vt({innerType:e,typeName:G.ZodReadonly,...U(t)}),qe.lazycreate;var G;(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`})(G||={});const K=Me.create,yt=Pe.create;ht.create,Fe.create;const bt=Ie.create;Le.create,Re.create,ze.create,Be.create;const xt=Ve.create,St=He.create;Ue.create,We.create;const q=Ge.create,J=qe.create;qe.strictCreate;const Ct=Je.create,wt=Xe.create;Qe.create,$e.create;const Tt=et.create;tt.create,nt.create,rt.create,it.create;const Y=at.create,Et=st.create;ct.create,lt.create,ut.create;const X=dt.create;ft.create,ut.createWithPreprocess,_t.create;const Dt=R,Ot=`2025-06-18`,kt=[Ot,`2025-03-26`,`2024-11-05`,`2024-10-07`],At=Ct([K(),yt().int()]),jt=K(),Mt=J({progressToken:X(At)}).passthrough(),Nt=J({_meta:X(Mt)}).passthrough(),Pt=J({method:K(),params:X(Nt)}),Ft=J({_meta:X(J({}).passthrough())}).passthrough(),It=J({method:K(),params:X(Ft)}),Lt=J({_meta:X(J({}).passthrough())}).passthrough(),Rt=Ct([K(),yt().int()]),zt=J({jsonrpc:Y(`2.0`),id:Rt}).merge(Pt).strict(),Bt=e=>zt.safeParse(e).success,Vt=J({jsonrpc:Y(`2.0`)}).merge(It).strict(),Ht=e=>Vt.safeParse(e).success,Ut=J({jsonrpc:Y(`2.0`),id:Rt,result:Lt}).strict(),Wt=e=>Ut.safeParse(e).success;var Gt;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`})(Gt||={});const Kt=J({jsonrpc:Y(`2.0`),id:Rt,error:J({code:yt().int(),message:K(),data:X(St())})}).strict(),qt=e=>Kt.safeParse(e).success,Jt=Ct([zt,Vt,Ut,Kt]),Yt=Lt.strict(),Xt=It.extend({method:Y(`notifications/cancelled`),params:Ft.extend({requestId:Rt,reason:K().optional()})}),Zt=J({src:K(),mimeType:X(K()),sizes:X(K())}).passthrough(),Qt=J({name:K(),title:X(K())}).passthrough(),$t=Qt.extend({version:K(),websiteUrl:X(K()),icons:X(q(Zt))}),en=J({experimental:X(J({}).passthrough()),sampling:X(J({}).passthrough()),elicitation:X(J({}).passthrough()),roots:X(J({listChanged:X(bt())}).passthrough())}).passthrough(),tn=Pt.extend({method:Y(`initialize`),params:Nt.extend({protocolVersion:K(),capabilities:en,clientInfo:$t})}),nn=e=>tn.safeParse(e).success,rn=J({experimental:X(J({}).passthrough()),logging:X(J({}).passthrough()),completions:X(J({}).passthrough()),prompts:X(J({listChanged:X(bt())}).passthrough()),resources:X(J({subscribe:X(bt()),listChanged:X(bt())}).passthrough()),tools:X(J({listChanged:X(bt())}).passthrough())}).passthrough(),an=Lt.extend({protocolVersion:K(),capabilities:rn,serverInfo:$t,instructions:X(K())}),on=It.extend({method:Y(`notifications/initialized`)}),sn=e=>on.safeParse(e).success,cn=Pt.extend({method:Y(`ping`)}),ln=J({progress:yt(),total:X(yt()),message:X(K())}).passthrough(),un=It.extend({method:Y(`notifications/progress`),params:Ft.merge(ln).extend({progressToken:At})}),dn=Pt.extend({params:Nt.extend({cursor:X(jt)}).optional()}),fn=Lt.extend({nextCursor:X(jt)}),pn=J({uri:K(),mimeType:X(K()),_meta:X(J({}).passthrough())}).passthrough(),mn=pn.extend({text:K()}),hn=K().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),gn=pn.extend({blob:hn}),_n=Qt.extend({uri:K(),description:X(K()),mimeType:X(K()),icons:X(q(Zt)),_meta:X(J({}).passthrough())}),vn=Qt.extend({uriTemplate:K(),description:X(K()),mimeType:X(K()),_meta:X(J({}).passthrough())}),yn=dn.extend({method:Y(`resources/list`)}),bn=fn.extend({resources:q(_n)}),xn=dn.extend({method:Y(`resources/templates/list`)}),Sn=fn.extend({resourceTemplates:q(vn)}),Cn=Pt.extend({method:Y(`resources/read`),params:Nt.extend({uri:K()})}),wn=Lt.extend({contents:q(Ct([mn,gn]))}),Tn=It.extend({method:Y(`notifications/resources/list_changed`)}),En=Pt.extend({method:Y(`resources/subscribe`),params:Nt.extend({uri:K()})}),Dn=Pt.extend({method:Y(`resources/unsubscribe`),params:Nt.extend({uri:K()})}),On=It.extend({method:Y(`notifications/resources/updated`),params:Ft.extend({uri:K()})}),kn=J({name:K(),description:X(K()),required:X(bt())}).passthrough(),An=Qt.extend({description:X(K()),arguments:X(q(kn)),icons:X(q(Zt)),_meta:X(J({}).passthrough())}),jn=dn.extend({method:Y(`prompts/list`)}),Mn=fn.extend({prompts:q(An)}),Nn=Pt.extend({method:Y(`prompts/get`),params:Nt.extend({name:K(),arguments:X(Tt(K()))})}),Pn=J({type:Y(`text`),text:K(),_meta:X(J({}).passthrough())}).passthrough(),Fn=J({type:Y(`image`),data:hn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),In=J({type:Y(`audio`),data:hn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),Ln=J({type:Y(`resource`),resource:Ct([mn,gn]),_meta:X(J({}).passthrough())}).passthrough(),Rn=_n.extend({type:Y(`resource_link`)}),zn=Ct([Pn,Fn,In,Rn,Ln]),Bn=J({role:Et([`user`,`assistant`]),content:zn}).passthrough(),Vn=Lt.extend({description:X(K()),messages:q(Bn)}),Hn=It.extend({method:Y(`notifications/prompts/list_changed`)}),Un=J({title:X(K()),readOnlyHint:X(bt()),destructiveHint:X(bt()),idempotentHint:X(bt()),openWorldHint:X(bt())}).passthrough(),Wn=Qt.extend({description:X(K()),inputSchema:J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough(),outputSchema:X(J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough()),annotations:X(Un),icons:X(q(Zt)),_meta:X(J({}).passthrough())}),Gn=dn.extend({method:Y(`tools/list`)}),Kn=fn.extend({tools:q(Wn)}),qn=Lt.extend({content:q(zn).default([]),structuredContent:J({}).passthrough().optional(),isError:X(bt())});qn.or(Lt.extend({toolResult:St()}));const Jn=Pt.extend({method:Y(`tools/call`),params:Nt.extend({name:K(),arguments:X(Tt(St()))})}),Yn=It.extend({method:Y(`notifications/tools/list_changed`)}),Xn=Et([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Zn=Pt.extend({method:Y(`logging/setLevel`),params:Nt.extend({level:Xn})}),Qn=It.extend({method:Y(`notifications/message`),params:Ft.extend({level:Xn,logger:X(K()),data:St()})}),$n=J({name:K().optional()}).passthrough(),er=J({hints:X(q($n)),costPriority:X(yt().min(0).max(1)),speedPriority:X(yt().min(0).max(1)),intelligencePriority:X(yt().min(0).max(1))}).passthrough(),tr=J({role:Et([`user`,`assistant`]),content:Ct([Pn,Fn,In])}).passthrough(),nr=Pt.extend({method:Y(`sampling/createMessage`),params:Nt.extend({messages:q(tr),systemPrompt:X(K()),includeContext:X(Et([`none`,`thisServer`,`allServers`])),temperature:X(yt()),maxTokens:yt().int(),stopSequences:X(q(K())),metadata:X(J({}).passthrough()),modelPreferences:X(er)})}),rr=Lt.extend({model:K(),stopReason:X(Et([`endTurn`,`stopSequence`,`maxTokens`]).or(K())),role:Et([`user`,`assistant`]),content:wt(`type`,[Pn,Fn,In])}),ir=J({type:Y(`boolean`),title:X(K()),description:X(K()),default:X(bt())}).passthrough(),ar=J({type:Y(`string`),title:X(K()),description:X(K()),minLength:X(yt()),maxLength:X(yt()),format:X(Et([`email`,`uri`,`date`,`date-time`]))}).passthrough(),or=J({type:Et([`number`,`integer`]),title:X(K()),description:X(K()),minimum:X(yt()),maximum:X(yt())}).passthrough(),sr=J({type:Y(`string`),title:X(K()),description:X(K()),enum:q(K()),enumNames:X(q(K()))}).passthrough(),cr=Ct([ir,ar,or,sr]),lr=Pt.extend({method:Y(`elicitation/create`),params:Nt.extend({message:K(),requestedSchema:J({type:Y(`object`),properties:Tt(K(),cr),required:X(q(K()))}).passthrough()})}),ur=Lt.extend({action:Et([`accept`,`decline`,`cancel`]),content:X(Tt(K(),St()))}),dr=J({type:Y(`ref/resource`),uri:K()}).passthrough(),fr=J({type:Y(`ref/prompt`),name:K()}).passthrough(),pr=Pt.extend({method:Y(`completion/complete`),params:Nt.extend({ref:Ct([fr,dr]),argument:J({name:K(),value:K()}).passthrough(),context:X(J({arguments:X(Tt(K(),K()))}))})}),mr=Lt.extend({completion:J({values:q(K()).max(100),total:X(yt().int()),hasMore:X(bt())}).passthrough()}),hr=J({uri:K().startsWith(`file://`),name:X(K()),_meta:X(J({}).passthrough())}).passthrough(),gr=Pt.extend({method:Y(`roots/list`)}),_r=Lt.extend({roots:q(hr)}),vr=It.extend({method:Y(`notifications/roots/list_changed`)});Ct([cn,tn,pr,Zn,Nn,jn,yn,xn,Cn,En,Dn,Jn,Gn]),Ct([Xt,un,on,vr]),Ct([Yt,rr,ur,_r]),Ct([cn,nr,lr,gr]),Ct([Xt,un,Qn,On,Tn,Yn,Hn]),Ct([Yt,an,mr,Vn,Mn,bn,Sn,wn,qn,Kn]);var yr=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},br=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},xr=class extends br{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},Sr=class extends br{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},Cr=class extends br{constructor(e,t,n,r={}){super(`HTTPServerError`,e,{feature:`http`,module:`server`,operation:`request`},{endpoint:t,statusCode:n,...r})}},wr=class extends br{constructor(e,t,n,r={}){super(`ProcessSpawnError`,e,{feature:`stdio`,module:`transport`,operation:`spawn`},{argCount:n?.length,command:t,...r})}},Tr=class extends br{constructor(e,t,n,r={}){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r})}},Er=class extends br{constructor(e,t,n=`unknown`,r={}){super(`ProxyServerError`,e,{feature:`server`,module:`proxy`,operation:n},{handler:t,...r})}},Dr=class extends br{constructor(e,t=`unknown`,n=`unknown`,r={}){super(`TransportError`,e,{feature:t,module:`transport`,operation:n},r)}};const Or={APP_VERSION:`1.0.33`,NODE_ENV:`development`,OAUTH_PROVIDERS:[{authorizationEndpoint:`https://github.com/login/oauth/authorize`,clientId:`Ov23liDj6mzRyvM5n0yG`,id:`github`,name:`GitHub`,tokenEndpoint:`https://github.com/login/oauth/access_token`,urlPatterns:[`github.com`,`api.github.com`,`githubcopilot.com`,`api.githubcopilot.com`],clientSecret:`d467125f345a6edd5de0254a5a9b6bdde26fdd86`,scopes:[`read:user`,`repo`,`gist`,`notifications`,`project`,`public_repo`,`read:gpg_key`,`read:org`,`repo:status`,`repo_deployment`,`user`,`user:email`,`user:follow`],usePkce:!0,tokenEndpointAuthMethod:`client_secret_post`}],SENTRY_DSN:null,SENTRY_ENABLED:!1},kr=c.get,Ar=Or.APP_VERSION,jr=e=>{let t={};if(e){let n=e.split(`,`);for(let e of n){let[n,...r]=e.split(`:`);n&&r.length>0&&(t[n.trim()]=r.join(`:`).trim())}}return t},Mr=e=>{try{let t=new URL(e),n=`/guard/evaluate/v1`;return t.pathname.includes(n)?(t.pathname=t.pathname.replace(n,`/access-control/authorize`),t.toString()):(console.warn(`[mcp-gateway] Warning: SCANNER_URL does not contain expected path "${n}". Access control URL derivation skipped. Current path: "${t.pathname}". Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null)}catch(e){return console.warn(`[mcp-gateway] Warning: Failed to parse SCANNER_URL as valid URL: ${e instanceof Error?e.message:String(e)}. Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null}},Nr=t(),Pr=kr(`NODE_ENV`).default(Or.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Fr=kr(`MCP_GATEWAY_SENTRY_DSN`).default(Or.SENTRY_DSN||``).asString()||null,Ir=kr(`MCP_GATEWAY_SENTRY_ENABLED`).default(String(Or.SENTRY_ENABLED??!1)).asBool(),Lr=kr(`DEBUG`).default(`false`).asBool()||kr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Rr=kr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,zr=kr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Br=(()=>{let e=kr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?jr(e):{}})(),Vr=kr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),Hr=kr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Ur=kr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Wr=kr(`CLIENT_APP_NAME`).default(``).asString(),Gr=kr(`MCP_GATEWAY_LOG_DIR`).default(a(l(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Kr=kr(`MCP_GATEWAY_OAUTH_DIR`).default(a(l(),`.onyx`,`mcp-gateway`,`oauth`)).asString(),qr=(()=>kr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Rr?Mr(Rr):null))(),Jr=(()=>{let e=kr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?jr(e):{}})(),Yr=kr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),Xr={accessControl:{enabled:!!(qr&&zr),headers:Jr,timeoutMs:Yr,url:qr},appVersion:Ar,clientAppName:Wr,debug:Lr,environment:Pr,logDir:Gr,oauthDir:Kr,proxyCommand:Ur,scanner:{apiKey:zr,enabled:!!Rr,failOpen:Hr,headers:Br,timeoutMs:Vr,url:Rr},sentry:{debug:Lr&&Pr===`development`,dsn:Fr||void 0,enabled:Ir,environment:Pr,release:`mcp-gateway@${Ar}`,tracesSampleRate:Pr===`production`?1:0}},Zr=Xr.logDir,Qr=Xr.debug?`debug`:`info`;let $r=!1;try{n(Zr)||r(Zr,{recursive:!0}),$r=!0}catch(e){let t=e instanceof Error?e.message:String(e),n=t.includes(`EACCES`)||t.includes(`permission denied`);console.error(`[mcp-gateway] WARNING: Failed to create log directory: ${Zr}`),console.error(`[mcp-gateway] Error: ${t}`),n&&(console.error(`[mcp-gateway] This appears to be a permission issue. Possible solutions:`),console.error(`[mcp-gateway] 1. Fix directory permissions: sudo chown -R $USER ~/.onyx`),console.error(`[mcp-gateway] 2. Use a different log directory: export MCP_GATEWAY_LOG_DIR=/tmp/mcp-gateway-logs`)),console.error(`[mcp-gateway] File logging will be disabled. The gateway will continue to function.`)}const ei=o.format.combine(o.format.timestamp(),o.format.errors({stack:!0}),o.format.json());let ti=null;const ni=[];if($r){let e=new s({datePattern:`YYYY-MM-DD`,filename:a(Zr,`mcp-gateway-%DATE%.log`),format:ei,handleExceptions:!1,handleRejections:!1,level:Qr,maxFiles:10,maxSize:`10m`});ni.push(e)}const ri=o.createLogger({defaultMeta:{service:`mcp-gateway`,version:Xr.appVersion},format:o.format.combine(o.format.errors({stack:!0}),o.format.metadata()),level:Qr,transports:ni}),ii=e=>{let[t,...n]=e;if(typeof t!=`string`)throw Error(`First argument must be a string message`);if(n.length>0&&n[0]&&typeof n[0]==`object`&&`proxyType`in n[0]){let e=n[0],r=n[1];return{message:t,meta:r,sessionData:e}}let r=n[0];return{message:t,meta:r,sessionData:ti||void 0}},Z={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.error(t,{sessionData:r,...n})},getSessionData:()=>ti,info:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.info(t,{sessionData:r,...n})},setSessionData:e=>{ti=e,Z.debug(`Session data set for logger`,e)},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.warn(t,{sessionData:r,...n})}};Z.info(`MCP Gateway logger initialized`,{debug:Xr.debug,fileLoggingEnabled:$r,logDir:Zr,logLevel:Qr});let ai={"proxy.version":Xr.appVersion};function oi(e,t=`default`,n=`info`,r){try{if(!Xr.sentry.enabled){Z.debug(`Breadcrumb: [${t}] ${e}`,r);return}f.addBreadcrumb({category:t,data:r?ui(r):void 0,level:n,message:e,timestamp:Date.now()/1e3})}catch(e){Z.warn(`Failed to add breadcrumb to Sentry`,{error:e})}}function si(e){ai={...ai,...e}}function ci(e,t,n){try{let r=e instanceof br?{...e.tags,...n}:n,i=e instanceof br?{...e.extra,...t}:t;if(!Xr.sentry.enabled){let t=e instanceof Error?e.message:String(e);Z.error(`Exception captured: ${t}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r});return}let a=e instanceof Error?e.message:String(e);Z.error(`Sending exception to Sentry: ${a}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r}),f.withScope(t=>{r&&Object.entries(r).forEach(([e,n])=>{let r=e.startsWith(`mcp.gateway.`)?e:`mcp.gateway.${e}`;t.setTag(r,n)}),i&&Object.entries(ui(i)).forEach(([e,n])=>{t.setExtra(e,n)}),t.setLevel(`error`),f.captureException(e)})}catch(e){Z.warn(`Failed to capture exception to Sentry`,{sentryError:e instanceof Error?e.message:e})}}function li(){try{if(!Xr.sentry.enabled){Z.debug(`Sentry disabled (no DSN provided or in development mode)`);return}f.init({beforeSend(e){return e.tags={...e.tags,...ai},e.extra&&=ui(e.extra),e.contexts?.runtime?.name&&(e.contexts.runtime.name=`node`),e},beforeSendTransaction(e){return e.tags={...e.tags,...ai},e},debug:Xr.sentry.debug,dsn:Xr.sentry.dsn,environment:Xr.sentry.environment,release:Xr.sentry.release,tracesSampleRate:Xr.sentry.tracesSampleRate}),Z.debug(`Sentry initialized`,{dsn:Xr.sentry.dsn?`***configured***`:`not configured`,environment:Xr.sentry.environment,release:Xr.sentry.release})}catch(e){Z.warn(`Failed to initialize Sentry, continuing without error tracking`,{error:e})}}function ui(e){let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.toLowerCase();if(r.includes(`password`)||r.includes(`token`)||r.includes(`key`)||r.includes(`secret`)||r.includes(`auth`)||r===`env`||r===`environment`){t[e]=`[FILTERED]`;return}if(typeof n==`string`&&(r.includes(`url`)||n.startsWith(`http`)))try{let r=new URL(n);t[e]=`${r.protocol}//${r.host}${r.pathname}`}catch{t[e]=n}else t[e]=n}),t}function di(){return a(l(),`.claude.json`)}function fi(){try{return u()}catch{return`unknown-device`}}async function pi(e){try{return(await p()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}function mi(){try{let e=gi();return e?e.oauthAccount.emailAddress:void 0}catch{return}}function hi(){try{let e=d();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function gi(){try{let e=di();if(!n(e))return null;let t=i(e,`utf-8`);return JSON.parse(t)}catch{return null}}const _i=async()=>{let e=process.pid,t=process.ppid;try{let n=fi(),r=mi(),i=hi(),a=await pi(t);return{clientAppName:Wr||`unknown`,deviceName:n,email:r,parentProcessId:t,parentProcessName:a,processId:e,username:i}}catch{return{clientAppName:Wr||`unknown`,deviceName:`unknown-device`,email:void 0,parentProcessId:t,parentProcessName:`unknown`,processId:e,username:void 0}}};function vi(e){let t=m(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var yi=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),Z.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return Z.warn(`Request blocked by security policy`),t}catch(t){if(Z.error(`Scanning failed`,{error:t}),ci(t instanceof Error?t:Error(String(t)),{method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl},{feature:`traffic-scanner`,module:`evaluator`,operation:`scan`}),!this.config.scanFailOpen)return Z.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};Z.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.sessionData,method:e.method,originalRequestId:e.originalRequestId,type:e.type};Z.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return Z.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}getClientInfoBase64(){return vi(this.sessionData)}async sendScanRequest(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.scanTimeoutMs);try{let n=`${this.config.scanUrl}/${this.config.scanApiKey}/mcp/${this.clientInfoBase64}`,r={data:e.data,id:e.id,metadata:e.metadata,method:e.method,sessionId:Nr,...e.originalRequestId&&{original_request_id:String(e.originalRequestId)},type:e.type},i=await fetch(n,{body:JSON.stringify(r),headers:{"Content-Type":`application/json`,...this.config.scanHeaders},method:`POST`,signal:t.signal});if(!i.ok)throw Error(`Sanitization service returned ${i.status}: ${i.statusText}`);let a=await i.json();if(!a.action||![`allow`,`block`,`modify`].includes(a.action))throw Error(`Invalid scan response format: action="${a.action}"`);return a}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Scan request timed out after ${this.config.scanTimeoutMs}ms`):e}finally{clearTimeout(n)}}};let bi=null;const xi=async e=>{let t=await _i(),n=e.cliArgs.proxyType,r={...t,proxyType:n,remoteCliArgs:n===`remote`?e.cliArgs:void 0,stdioCliArgs:n===`stdio`?e.cliArgs:void 0};return Z.setSessionData(r),bi=new yi(e,r),bi},Si=()=>bi,Ci=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,wi=(e,n,r,i)=>async(...a)=>{let o=Si(),s=e,c=a[0],l=t(),u=Ci(a)?.toString();c&&typeof c==`object`&&`method`in c&&typeof c.method==`string`&&(s=c.method);let d=async(e,t,n)=>{try{if(!o?.isEnabled()&&!o?.isScanEnabled())return;let r;try{r=await o.evaluate({data:t,id:l,method:s,originalRequestId:u,timestamp:new Date().toISOString(),type:e})}catch(t){if(Z.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(Z.info(`${e} scan result`,{action:r.action,id:l,method:s,...e===`request`&&{originalRequestId:u}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?Z.warn(n):Z.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?Z.warn(a):Z.info(a),n(r.modified_data);return}return r.modified_data}Z.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(Z.error(`Unexpected error during ${e} processing`,{error:t}),ci(t),e===`request`&&t instanceof Error&&t.message===`Security scanning service unavailable`)throw t;return}},f;try{f=await d(`request`,c,e=>{a[0]=e})}catch(t){if(t instanceof Error&&t.message===`Security scanning service unavailable`){let r=new Er(`Security scanning unavailable (fail-closed)`,e,n,{errorMessage:t.message});throw ci(r),t}Z.error(`Unexpected error during request processing, continuing`,{error:t}),ci(t)}if(f!==void 0)return f;if(i&&!await i.isAllowed()){let t=i.getBlockReason();throw Z.warn(`MCP server blocked by access control`,{handlerName:e,operation:n,reason:t}),new xr(t,`policy_block`)}try{let e=await r(...a);try{if(e){let t=await d(`response`,e);if(t!==void 0)return t}}catch(e){Z.error(`Error during response processing, returning original result`,{error:e}),ci(e)}return e}catch(t){if(t instanceof xr)throw Z.info(`Request blocked by access control`,{error:t.message,handlerName:e,operation:n,reason:t.reason}),t;try{await d(`error`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}catch(e){Z.warn(`Failed to evaluate error`,{evalError:e})}let r=new Er(`Handler error: ${t}`,e,n,{argsCount:a.length,errorMessage:t instanceof Error?t.message:String(t)});throw ci(r),t}},Ti=async({authorizer:e,client:t,server:n,serverCapabilities:r})=>{r?.logging&&(n.setNotificationHandler(Qn,wi(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(Qn,wi(`notifications/message`,`client-to-server`,async e=>n.notification(e),e))),r?.prompts&&(n.setRequestHandler(Nn,wi(`prompts/get`,`get`,async e=>t.getPrompt(e.params),e)),n.setRequestHandler(jn,wi(`prompts/list`,`list`,async e=>t.listPrompts(e.params),e))),r?.resources&&(n.setRequestHandler(yn,wi(`resources/list`,`list`,async e=>t.listResources(e.params),e)),n.setRequestHandler(xn,wi(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params),e)),n.setRequestHandler(Cn,wi(`resources/read`,`read`,async e=>t.readResource(e.params),e)),r?.resources.subscribe&&(n.setNotificationHandler(On,wi(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),n.setRequestHandler(En,wi(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params),e)),n.setRequestHandler(Dn,wi(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params),e)))),r?.tools&&(n.setRequestHandler(Jn,wi(`tools/call`,`call`,async e=>t.callTool(e.params),e)),n.setRequestHandler(Gn,wi(`tools/list`,`list`,async e=>t.listTools(e.params),e))),n.setRequestHandler(pr,wi(`completion/complete`,`complete`,async e=>t.complete(e.params),e))};var Ei=T(((exports,t)=>{t.exports=o,t.exports.format=s,t.exports.parse=c;var n=/\B(?=(\d{3})+(?!\d))/g,r=/(?:\.0*|(\.[^0]+)0+)$/,i={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:1024**4,pb:1024**5},a=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function o(e,t){return typeof e==`string`?c(e):typeof e==`number`?s(e,t):null}function s(e,t){if(!Number.isFinite(e))return null;var a=Math.abs(e),o=t&&t.thousandsSeparator||``,s=t&&t.unitSeparator||``,c=t&&t.decimalPlaces!==void 0?t.decimalPlaces:2,l=!!(t&&t.fixedDecimals),u=t&&t.unit||``;(!u||!i[u.toLowerCase()])&&(u=a>=i.pb?`PB`:a>=i.tb?`TB`:a>=i.gb?`GB`:a>=i.mb?`MB`:a>=i.kb?`KB`:`B`);var d=(e/i[u.toLowerCase()]).toFixed(c);return l||(d=d.replace(r,`$1`)),o&&(d=d.split(`.`).map(function(e,t){return t===0?e.replace(n,o):e}).join(`.`)),d+s+u}function c(e){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e!=`string`)return null;var t=a.exec(e),n,r=`b`;return t?(n=parseFloat(t[1]),r=t[4].toLowerCase()):(n=parseInt(e,10),r=`b`),isNaN(n)?null:Math.floor(i[r]*n)}})),Di=T(((exports,t)=>{
|
|
1
|
+
import{createRequire as e}from"node:module";import{randomUUID as t}from"crypto";import{existsSync as n,mkdirSync as r,readFileSync as i}from"node:fs";import{join as a}from"node:path";import o from"winston";import s from"winston-daily-rotate-file";import c from"env-var";import{homedir as l,hostname as u,userInfo as d}from"node:os";import"dotenv/config";import*as f from"@sentry/node";import p from"ps-list";import{deflateSync as m}from"node:zlib";import{randomUUID as h}from"node:crypto";import{URL as g}from"url";import _ from"node:http";import v from"node:process";var y=Object.create,b=Object.defineProperty,x=Object.getOwnPropertyDescriptor,S=Object.getOwnPropertyNames,C=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty,T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),E=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=S(t),a=0,o=i.length,s;a<o;a++)s=i[a],!w.call(e,s)&&s!==n&&b(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=x(t,s))||r.enumerable});return e},D=(e,t,n)=>(n=e==null?{}:y(C(e)),E(t||!e||!e.__esModule?b(n,`default`,{value:e,enumerable:!0}):n,e)),O=e(import.meta.url),k=class{events=new Map;async replayEventsAfter(e,{send:t}){if(!e||!this.events.has(e))return``;let n=this.getStreamIdFromEventId(e);if(!n)return``;let r=!1,i=[...this.events.entries()].sort((e,t)=>e[0].localeCompare(t[0]));for(let[a,{message:o,streamId:s}]of i){if(s!==n)continue;if(a===e){r=!0;continue}r&&await t(a,o)}return n}async storeEvent(e,t){let n=this.generateEventId(e);return this.events.set(n,{message:t,streamId:e}),n}generateEventId(e){return`${e}_${Date.now()}_${Math.random().toString(36).substring(2,10)}`}getStreamIdFromEventId(e){let t=e.split(`_`);return t.length>0?t[0]:``}},A;(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})(A||={});var ee;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(ee||={});const j=A.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),M=e=>{switch(typeof e){case`undefined`:return j.undefined;case`string`:return j.string;case`number`:return Number.isNaN(e)?j.nan:j.number;case`boolean`:return j.boolean;case`function`:return j.function;case`bigint`:return j.bigint;case`symbol`:return j.symbol;case`object`:return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?j.promise:typeof Map<`u`&&e instanceof Map?j.map:typeof Set<`u`&&e instanceof Set?j.set:typeof Date<`u`&&e instanceof Date?j.date:j.object;default:return j.unknown}},N=A.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`]);var P=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,A.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},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()}};P.create=e=>new P(e);var te=(e,t)=>{let n;switch(e.code){case N.invalid_type:n=e.received===j.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,A.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${A.joinValues(e.keys,`, `)}`;break;case N.invalid_union:n=`Invalid input`;break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${A.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${A.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n=`Invalid function arguments`;break;case N.invalid_return_type:n=`Invalid function return type`;break;case N.invalid_date:n=`Invalid date`;break;case N.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}"`:A.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case N.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 N.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 N.custom:n=`Invalid input`;break;case N.invalid_intersection_types:n=`Intersection results could not be merged`;break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,A.assertNever(e)}return{message:n}};let ne=te;function re(){return ne}const F=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 I(e,t){let n=re(),r=F({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===te?void 0:te].filter(e=>!!e)});e.common.issues.push(r)}var L=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 R;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 R;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}}};const R=Object.freeze({status:`aborted`}),ie=e=>({status:`dirty`,value:e}),z=e=>({status:`valid`,value:e}),B=e=>e.status===`aborted`,ae=e=>e.status===`dirty`,oe=e=>e.status===`valid`,V=e=>typeof Promise<`u`&&e instanceof Promise;var H;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(H||={});var se=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}};const ce=(e,t)=>{if(oe(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(){return this._error||=new P(e.common.issues),this._error}}};function U(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 W=class{get description(){return this._def.description}_getType(e){return M(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new L,ctx:{common:e.parent.common,data:e.data,parsedType:M(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(V(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:M(e)},r=this._parseSync({data:e,path:n.path,parent:n});return ce(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:M(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return oe(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=>oe(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:M(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(V(r)?r:Promise.resolve(r));return ce(n,i)}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:N.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 ut({schema:this,typeName:G.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 dt.create(this,this._def)}nullable(){return ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ge.create(this)}promise(){return lt.create(this,this._def)}or(e){return Je.create([this,e],this._def)}and(e){return Qe.create(this,e,this._def)}transform(e){return new ut({...U(this._def),schema:this,typeName:G.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new pt({...U(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new gt({typeName:G.ZodBranded,type:this,...U(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new mt({...U(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _t.create(this,e)}readonly(){return vt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const le=/^c[^\s-]{8,}$/i,ue=/^[0-9a-z]+$/,de=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fe=/^[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,pe=/^[a-z0-9_-]{21}$/i,me=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,he=/^[-+]?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)?)??$/,ge=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let _e;const ve=/^(?:(?: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])$/,ye=/^(?:(?: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])$/,be=/^(([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]))$/,xe=/^(([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])$/,Se=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ce=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,we=`((\\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])))`,Te=RegExp(`^${we}$`);function Ee(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 De(e){return RegExp(`^${Ee(e)}$`)}function Oe(e){let t=`${we}T${Ee(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ke(e,t){return!!((t===`v4`||!t)&&ve.test(e)||(t===`v6`||!t)&&be.test(e))}function Ae(e,t){if(!me.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 je(e,t){return!!((t===`v4`||!t)&&ye.test(e)||(t===`v6`||!t)&&xe.test(e))}var Me=class e extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.string,received:t.parsedType}),R}let t=new L,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:N.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),I(n,{code:N.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?I(n,{code:N.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&I(n,{code:N.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)ge.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`email`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)_e||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),_e.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`emoji`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)fe.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`uuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)pe.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`nanoid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cuid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ue.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cuid2`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)de.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`ulid`,code:N.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),I(n,{validation:`url`,code:N.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),I(n,{validation:`regex`,code:N.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),I(n,{code:N.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),I(n,{code:N.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Oe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Te.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?De(r).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:N.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?he.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`duration`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ke(e.data,r.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`ip`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ae(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`jwt`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?je(e.data,r.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cidr`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Se.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`base64`,code:N.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ce.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`base64url`,code:N.invalid_string,message:r.message}),t.dirty()):A.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:N.invalid_string,...H.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...H.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...H.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...H.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...H.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...H.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...H.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...H.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...H.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...H.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...H.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...H.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,...H.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,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...H.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...H.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...H.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...H.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...H.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...H.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...H.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...H.errToObj(t)})}nonempty(e){return this.min(1,H.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}};Me.create=e=>new Me({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...U(e)});function Ne(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(`.`,``)),o=Number.parseInt(t.toFixed(i).replace(`.`,``));return a%o/10**i}var Pe=class e extends W{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)!==j.number){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.number,received:t.parsedType}),R}let t,n=new L;for(let r of this._def.checks)r.kind===`int`?A.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:N.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),I(t,{code:N.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),I(t,{code:N.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ne(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),I(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:N.not_finite,message:r.message}),n.dirty()):A.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:H.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:H.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:H.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:H.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`&&A.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)}};Pe.create=e=>new Pe({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...U(e)});var Fe=class e extends W{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)!==j.bigint)return this._getInvalidInput(e);let t,n=new L;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),I(t,{code:N.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),I(t,{code:N.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),I(t,{code:N.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):A.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.bigint,received:t.parsedType}),R}gte(e,t){return this.setLimit(`min`,e,!0,H.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,H.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,H.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,H.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:H.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:H.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:H.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}};Fe.create=e=>new Fe({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var Ie=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.boolean,received:t.parsedType}),R}return z(e.data)}};Ie.create=e=>new Ie({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var Le=class e extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.date,received:t.parsedType}),R}if(Number.isNaN(e.data.getTime())){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_date}),R}let t=new L,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:N.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),I(n,{code:N.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):A.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:H.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:H.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)}};Le.create=e=>new Le({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...U(e)});var Re=class extends W{_parse(e){if(this._getType(e)!==j.symbol){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.symbol,received:t.parsedType}),R}return z(e.data)}};Re.create=e=>new Re({typeName:G.ZodSymbol,...U(e)});var ze=class extends W{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.undefined,received:t.parsedType}),R}return z(e.data)}};ze.create=e=>new ze({typeName:G.ZodUndefined,...U(e)});var Be=class extends W{_parse(e){if(this._getType(e)!==j.null){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.null,received:t.parsedType}),R}return z(e.data)}};Be.create=e=>new Be({typeName:G.ZodNull,...U(e)});var Ve=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}};Ve.create=e=>new Ve({typeName:G.ZodAny,...U(e)});var He=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}};He.create=e=>new He({typeName:G.ZodUnknown,...U(e)});var Ue=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.never,received:t.parsedType}),R}};Ue.create=e=>new Ue({typeName:G.ZodNever,...U(e)});var We=class extends W{_parse(e){if(this._getType(e)!==j.undefined){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.void,received:t.parsedType}),R}return z(e.data)}};We.create=e=>new We({typeName:G.ZodVoid,...U(e)});var Ge=class e extends W{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==j.array)return I(t,{code:N.invalid_type,expected:j.array,received:t.parsedType}),R;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(I(t,{code:e?N.too_big:N.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&&(I(t,{code:N.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&&(I(t,{code:N.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 se(t,e,t.path,n)))).then(e=>L.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new se(t,e,t.path,n)));return L.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:H.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:H.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:H.toString(n)}})}nonempty(e){return this.min(1,e)}};Ge.create=(e,t)=>new Ge({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...U(t)});function Ke(e){if(e instanceof qe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=dt.create(Ke(r))}return new qe({...e._def,shape:()=>t})}else if(e instanceof Ge)return new Ge({...e._def,type:Ke(e.element)});else if(e instanceof dt)return dt.create(Ke(e.unwrap()));else if(e instanceof ft)return ft.create(Ke(e.unwrap()));else if(e instanceof $e)return $e.create(e.items.map(e=>Ke(e)));else return e}var qe=class e extends W{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=A.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),R}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ue&&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 se(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ue){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&&(I(n,{code:N.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 se(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=>L.mergeObjectSync(t,e)):L.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return H.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:H.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:G.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 A.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 A.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ke(this)}partial(t){let n={};for(let e of A.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of A.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof dt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return ot(A.objectKeys(this.shape))}};qe.create=(e,t)=>new qe({shape:()=>e,unknownKeys:`strip`,catchall:Ue.create(),typeName:G.ZodObject,...U(t)}),qe.strictCreate=(e,t)=>new qe({shape:()=>e,unknownKeys:`strict`,catchall:Ue.create(),typeName:G.ZodObject,...U(t)}),qe.lazycreate=(e,t)=>new qe({shape:e,unknownKeys:`strip`,catchall:Ue.create(),typeName:G.ZodObject,...U(t)});var Je=class extends W{_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 P(e.ctx.common.issues));return I(t,{code:N.invalid_union,unionErrors:n}),R}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 P(e));return I(t,{code:N.invalid_union,unionErrors:i}),R}}get options(){return this._def.options}};Je.create=(e,t)=>new Je({options:e,typeName:G.ZodUnion,...U(t)});const Ye=e=>e instanceof it?Ye(e.schema):e instanceof ut?Ye(e.innerType()):e instanceof at?[e.value]:e instanceof st?e.options:e instanceof ct?A.objectValues(e.enum):e instanceof pt?Ye(e._def.innerType):e instanceof ze?[void 0]:e instanceof Be?[null]:e instanceof dt?[void 0,...Ye(e.unwrap())]:e instanceof ft?[null,...Ye(e.unwrap())]:e instanceof gt||e instanceof vt?Ye(e.unwrap()):e instanceof mt?Ye(e._def.innerType):[];var Xe=class e extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return I(t,{code:N.invalid_type,expected:j.object,received:t.parsedType}),R;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}):(I(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),R)}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=Ye(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:G.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...U(r)})}};function Ze(e,t){let n=M(e),r=M(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){let n=A.objectKeys(t),r=A.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Ze(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===j.array&&r===j.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=Ze(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===j.date&&r===j.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Qe=class extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(B(e)||B(r))return R;let i=Ze(e.value,r.value);return i.valid?((ae(e)||ae(r))&&t.dirty(),{status:t.value,value:i.data}):(I(n,{code:N.invalid_intersection_types}),R)};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}))}};Qe.create=(e,t,n)=>new Qe({left:e,right:t,typeName:G.ZodIntersection,...U(n)});var $e=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return I(n,{code:N.invalid_type,expected:j.array,received:n.parsedType}),R;if(n.data.length<this._def.items.length)return I(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),R;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:N.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 se(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>L.mergeArray(t,e)):L.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};$e.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new $e({items:e,typeName:G.ZodTuple,rest:null,...U(t)})};var et=class e extends W{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!==j.object)return I(n,{code:N.invalid_type,expected:j.object,received:n.parsedType}),R;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new se(n,e,n.path,e)),value:a._parse(new se(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?L.mergeObjectAsync(t,r):L.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof W?new e({keyType:t,valueType:n,typeName:G.ZodRecord,...U(r)}):new e({keyType:Me.create(),valueType:t,typeName:G.ZodRecord,...U(n)})}},tt=class extends W{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!==j.map)return I(n,{code:N.invalid_type,expected:j.map,received:n.parsedType}),R;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new se(n,e,n.path,[a,`key`])),value:i._parse(new se(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 R;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return R;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};tt.create=(e,t,n)=>new tt({valueType:t,keyType:e,typeName:G.ZodMap,...U(n)});var nt=class e extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return I(n,{code:N.invalid_type,expected:j.set,received:n.parsedType}),R;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(I(n,{code:N.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&&(I(n,{code:N.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 R;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 se(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:H.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:H.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};nt.create=(e,t)=>new nt({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...U(t)});var rt=class e extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return I(t,{code:N.invalid_type,expected:j.function,received:t.parsedType}),R;function n(e,n){return F({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),te].filter(e=>!!e),issueData:{code:N.invalid_arguments,argumentsError:n}})}function r(e,n){return F({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),te].filter(e=>!!e),issueData:{code:N.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof lt){let e=this;return z(async function(...t){let o=new P([]),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})})}else{let e=this;return z(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new P([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new P([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:$e.create(t).rest(He.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||$e.create([]).rest(He.create()),returns:n||He.create(),typeName:G.ZodFunction,...U(r)})}},it=class extends W{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})}};it.create=(e,t)=>new it({getter:e,typeName:G.ZodLazy,...U(t)});var at=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),R}return{status:`valid`,value:e.data}}get value(){return this._def.value}};at.create=(e,t)=>new at({value:e,typeName:G.ZodLiteral,...U(t)});function ot(e,t){return new st({values:e,typeName:G.ZodEnum,...U(t)})}var st=class e extends W{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{expected:A.joinValues(n),received:t.parsedType,code:N.invalid_type}),R}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{received:t.data,code:N.invalid_enum_value,options:n}),R}return z(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})}};st.create=ot;var ct=class extends W{_parse(e){let t=A.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let e=A.objectValues(t);return I(n,{expected:A.joinValues(e),received:n.parsedType,code:N.invalid_type}),R}if(this._cache||=new Set(A.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=A.objectValues(t);return I(n,{received:n.data,code:N.invalid_enum_value,options:e}),R}return z(e.data)}get enum(){return this._def.values}};ct.create=(e,t)=>new ct({values:e,typeName:G.ZodNativeEnum,...U(t)});var lt=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return I(t,{code:N.invalid_type,expected:j.promise,received:t.parsedType}),R;let n=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return z(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};lt.create=(e,t)=>new lt({type:e,typeName:G.ZodPromise,...U(t)});var ut=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.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=>{I(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 R;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?R:r.status===`dirty`||t.value===`dirty`?ie(r.value):r});{if(t.value===`aborted`)return R;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?R:r.status===`dirty`||t.value===`dirty`?ie(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`?R:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?R:(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(!oe(e))return R;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}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>oe(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):R);A.assertNever(r)}};ut.create=(e,t,n)=>new ut({schema:e,typeName:G.ZodEffects,effect:t,...U(n)}),ut.createWithPreprocess=(e,t,n)=>new ut({schema:t,effect:{type:`preprocess`,transform:e},typeName:G.ZodEffects,...U(n)});var dt=class extends W{_parse(e){return this._getType(e)===j.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:G.ZodOptional,...U(t)});var ft=class extends W{_parse(e){return this._getType(e)===j.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:G.ZodNullable,...U(t)});var pt=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...U(t)});var mt=class extends W{_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 V(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new P(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...U(t)});var ht=class extends W{_parse(e){if(this._getType(e)!==j.nan){let t=this._getOrReturnCtx(e);return I(t,{code:N.invalid_type,expected:j.nan,received:t.parsedType}),R}return{status:`valid`,value:e.data}}};ht.create=e=>new ht({typeName:G.ZodNaN,...U(e)});var gt=class extends W{_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}},_t=class e extends W{_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`?R:e.status===`dirty`?(t.dirty(),ie(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`?R: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:G.ZodPipeline})}},vt=class extends W{_parse(e){let t=this._def.innerType._parse(e),n=e=>(oe(e)&&(e.value=Object.freeze(e.value)),e);return V(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};vt.create=(e,t)=>new vt({innerType:e,typeName:G.ZodReadonly,...U(t)}),qe.lazycreate;var G;(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`})(G||={});const K=Me.create,yt=Pe.create;ht.create,Fe.create;const bt=Ie.create;Le.create,Re.create,ze.create,Be.create;const xt=Ve.create,St=He.create;Ue.create,We.create;const q=Ge.create,J=qe.create;qe.strictCreate;const Ct=Je.create,wt=Xe.create;Qe.create,$e.create;const Tt=et.create;tt.create,nt.create,rt.create,it.create;const Y=at.create,Et=st.create;ct.create,lt.create,ut.create;const X=dt.create;ft.create,ut.createWithPreprocess,_t.create;const Dt=R,Ot=`2025-06-18`,kt=[Ot,`2025-03-26`,`2024-11-05`,`2024-10-07`],At=Ct([K(),yt().int()]),jt=K(),Mt=J({progressToken:X(At)}).passthrough(),Nt=J({_meta:X(Mt)}).passthrough(),Pt=J({method:K(),params:X(Nt)}),Ft=J({_meta:X(J({}).passthrough())}).passthrough(),It=J({method:K(),params:X(Ft)}),Lt=J({_meta:X(J({}).passthrough())}).passthrough(),Rt=Ct([K(),yt().int()]),zt=J({jsonrpc:Y(`2.0`),id:Rt}).merge(Pt).strict(),Bt=e=>zt.safeParse(e).success,Vt=J({jsonrpc:Y(`2.0`)}).merge(It).strict(),Ht=e=>Vt.safeParse(e).success,Ut=J({jsonrpc:Y(`2.0`),id:Rt,result:Lt}).strict(),Wt=e=>Ut.safeParse(e).success;var Gt;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`})(Gt||={});const Kt=J({jsonrpc:Y(`2.0`),id:Rt,error:J({code:yt().int(),message:K(),data:X(St())})}).strict(),qt=e=>Kt.safeParse(e).success,Jt=Ct([zt,Vt,Ut,Kt]),Yt=Lt.strict(),Xt=It.extend({method:Y(`notifications/cancelled`),params:Ft.extend({requestId:Rt,reason:K().optional()})}),Zt=J({src:K(),mimeType:X(K()),sizes:X(K())}).passthrough(),Qt=J({name:K(),title:X(K())}).passthrough(),$t=Qt.extend({version:K(),websiteUrl:X(K()),icons:X(q(Zt))}),en=J({experimental:X(J({}).passthrough()),sampling:X(J({}).passthrough()),elicitation:X(J({}).passthrough()),roots:X(J({listChanged:X(bt())}).passthrough())}).passthrough(),tn=Pt.extend({method:Y(`initialize`),params:Nt.extend({protocolVersion:K(),capabilities:en,clientInfo:$t})}),nn=e=>tn.safeParse(e).success,rn=J({experimental:X(J({}).passthrough()),logging:X(J({}).passthrough()),completions:X(J({}).passthrough()),prompts:X(J({listChanged:X(bt())}).passthrough()),resources:X(J({subscribe:X(bt()),listChanged:X(bt())}).passthrough()),tools:X(J({listChanged:X(bt())}).passthrough())}).passthrough(),an=Lt.extend({protocolVersion:K(),capabilities:rn,serverInfo:$t,instructions:X(K())}),on=It.extend({method:Y(`notifications/initialized`)}),sn=e=>on.safeParse(e).success,cn=Pt.extend({method:Y(`ping`)}),ln=J({progress:yt(),total:X(yt()),message:X(K())}).passthrough(),un=It.extend({method:Y(`notifications/progress`),params:Ft.merge(ln).extend({progressToken:At})}),dn=Pt.extend({params:Nt.extend({cursor:X(jt)}).optional()}),fn=Lt.extend({nextCursor:X(jt)}),pn=J({uri:K(),mimeType:X(K()),_meta:X(J({}).passthrough())}).passthrough(),mn=pn.extend({text:K()}),hn=K().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),gn=pn.extend({blob:hn}),_n=Qt.extend({uri:K(),description:X(K()),mimeType:X(K()),icons:X(q(Zt)),_meta:X(J({}).passthrough())}),vn=Qt.extend({uriTemplate:K(),description:X(K()),mimeType:X(K()),_meta:X(J({}).passthrough())}),yn=dn.extend({method:Y(`resources/list`)}),bn=fn.extend({resources:q(_n)}),xn=dn.extend({method:Y(`resources/templates/list`)}),Sn=fn.extend({resourceTemplates:q(vn)}),Cn=Pt.extend({method:Y(`resources/read`),params:Nt.extend({uri:K()})}),wn=Lt.extend({contents:q(Ct([mn,gn]))}),Tn=It.extend({method:Y(`notifications/resources/list_changed`)}),En=Pt.extend({method:Y(`resources/subscribe`),params:Nt.extend({uri:K()})}),Dn=Pt.extend({method:Y(`resources/unsubscribe`),params:Nt.extend({uri:K()})}),On=It.extend({method:Y(`notifications/resources/updated`),params:Ft.extend({uri:K()})}),kn=J({name:K(),description:X(K()),required:X(bt())}).passthrough(),An=Qt.extend({description:X(K()),arguments:X(q(kn)),icons:X(q(Zt)),_meta:X(J({}).passthrough())}),jn=dn.extend({method:Y(`prompts/list`)}),Mn=fn.extend({prompts:q(An)}),Nn=Pt.extend({method:Y(`prompts/get`),params:Nt.extend({name:K(),arguments:X(Tt(K()))})}),Pn=J({type:Y(`text`),text:K(),_meta:X(J({}).passthrough())}).passthrough(),Fn=J({type:Y(`image`),data:hn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),In=J({type:Y(`audio`),data:hn,mimeType:K(),_meta:X(J({}).passthrough())}).passthrough(),Ln=J({type:Y(`resource`),resource:Ct([mn,gn]),_meta:X(J({}).passthrough())}).passthrough(),Rn=_n.extend({type:Y(`resource_link`)}),zn=Ct([Pn,Fn,In,Rn,Ln]),Bn=J({role:Et([`user`,`assistant`]),content:zn}).passthrough(),Vn=Lt.extend({description:X(K()),messages:q(Bn)}),Hn=It.extend({method:Y(`notifications/prompts/list_changed`)}),Un=J({title:X(K()),readOnlyHint:X(bt()),destructiveHint:X(bt()),idempotentHint:X(bt()),openWorldHint:X(bt())}).passthrough(),Wn=Qt.extend({description:X(K()),inputSchema:J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough(),outputSchema:X(J({type:Y(`object`),properties:X(J({}).passthrough()),required:X(q(K()))}).passthrough()),annotations:X(Un),icons:X(q(Zt)),_meta:X(J({}).passthrough())}),Gn=dn.extend({method:Y(`tools/list`)}),Kn=fn.extend({tools:q(Wn)}),qn=Lt.extend({content:q(zn).default([]),structuredContent:J({}).passthrough().optional(),isError:X(bt())});qn.or(Lt.extend({toolResult:St()}));const Jn=Pt.extend({method:Y(`tools/call`),params:Nt.extend({name:K(),arguments:X(Tt(St()))})}),Yn=It.extend({method:Y(`notifications/tools/list_changed`)}),Xn=Et([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Zn=Pt.extend({method:Y(`logging/setLevel`),params:Nt.extend({level:Xn})}),Qn=It.extend({method:Y(`notifications/message`),params:Ft.extend({level:Xn,logger:X(K()),data:St()})}),$n=J({name:K().optional()}).passthrough(),er=J({hints:X(q($n)),costPriority:X(yt().min(0).max(1)),speedPriority:X(yt().min(0).max(1)),intelligencePriority:X(yt().min(0).max(1))}).passthrough(),tr=J({role:Et([`user`,`assistant`]),content:Ct([Pn,Fn,In])}).passthrough(),nr=Pt.extend({method:Y(`sampling/createMessage`),params:Nt.extend({messages:q(tr),systemPrompt:X(K()),includeContext:X(Et([`none`,`thisServer`,`allServers`])),temperature:X(yt()),maxTokens:yt().int(),stopSequences:X(q(K())),metadata:X(J({}).passthrough()),modelPreferences:X(er)})}),rr=Lt.extend({model:K(),stopReason:X(Et([`endTurn`,`stopSequence`,`maxTokens`]).or(K())),role:Et([`user`,`assistant`]),content:wt(`type`,[Pn,Fn,In])}),ir=J({type:Y(`boolean`),title:X(K()),description:X(K()),default:X(bt())}).passthrough(),ar=J({type:Y(`string`),title:X(K()),description:X(K()),minLength:X(yt()),maxLength:X(yt()),format:X(Et([`email`,`uri`,`date`,`date-time`]))}).passthrough(),or=J({type:Et([`number`,`integer`]),title:X(K()),description:X(K()),minimum:X(yt()),maximum:X(yt())}).passthrough(),sr=J({type:Y(`string`),title:X(K()),description:X(K()),enum:q(K()),enumNames:X(q(K()))}).passthrough(),cr=Ct([ir,ar,or,sr]),lr=Pt.extend({method:Y(`elicitation/create`),params:Nt.extend({message:K(),requestedSchema:J({type:Y(`object`),properties:Tt(K(),cr),required:X(q(K()))}).passthrough()})}),ur=Lt.extend({action:Et([`accept`,`decline`,`cancel`]),content:X(Tt(K(),St()))}),dr=J({type:Y(`ref/resource`),uri:K()}).passthrough(),fr=J({type:Y(`ref/prompt`),name:K()}).passthrough(),pr=Pt.extend({method:Y(`completion/complete`),params:Nt.extend({ref:Ct([fr,dr]),argument:J({name:K(),value:K()}).passthrough(),context:X(J({arguments:X(Tt(K(),K()))}))})}),mr=Lt.extend({completion:J({values:q(K()).max(100),total:X(yt().int()),hasMore:X(bt())}).passthrough()}),hr=J({uri:K().startsWith(`file://`),name:X(K()),_meta:X(J({}).passthrough())}).passthrough(),gr=Pt.extend({method:Y(`roots/list`)}),_r=Lt.extend({roots:q(hr)}),vr=It.extend({method:Y(`notifications/roots/list_changed`)});Ct([cn,tn,pr,Zn,Nn,jn,yn,xn,Cn,En,Dn,Jn,Gn]),Ct([Xt,un,on,vr]),Ct([Yt,rr,ur,_r]),Ct([cn,nr,lr,gr]),Ct([Xt,un,Qn,On,Tn,Yn,Hn]),Ct([Yt,an,mr,Vn,Mn,bn,Sn,wn,qn,Kn]);var yr=class extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}},br=class extends Error{extra;tags;constructor(e,t,n={},r={}){super(t),this.name=e,this.tags=n,this.extra=r}},xr=class extends br{constructor(e,t=`access_denied`,n={}){super(`AccessControlBlockError`,e,{feature:`access_control`,module:`security`,operation:`block`},{reason:t,...n}),this.reason=t}},Sr=class extends br{constructor(e,t,n={}){super(`ConfigurationError`,e,{feature:`configuration`,module:`cli`,operation:`validate`},{configKey:t,...n})}},Cr=class extends br{constructor(e,t,n,r={}){super(`HTTPServerError`,e,{feature:`http`,module:`server`,operation:`request`},{endpoint:t,statusCode:n,...r})}},wr=class extends br{constructor(e,t,n,r={}){super(`ProcessSpawnError`,e,{feature:`stdio`,module:`transport`,operation:`spawn`},{argCount:n?.length,command:t,...r})}},Tr=class extends br{constructor(e,t,n,r={}){super(`ProxyConnectionError`,e,{feature:`connection`,module:`proxy`,operation:`connect`,transport:n||`unknown`},{url:t?(()=>{try{return new URL(t).origin}catch{return t}})():void 0,...r})}},Er=class extends br{constructor(e,t,n=`unknown`,r={}){super(`ProxyServerError`,e,{feature:`server`,module:`proxy`,operation:n},{handler:t,...r})}},Dr=class extends br{constructor(e,t=`unknown`,n=`unknown`,r={}){super(`TransportError`,e,{feature:t,module:`transport`,operation:n},r)}};const Or={APP_VERSION:`1.0.34`,NODE_ENV:`development`,OAUTH_PROVIDERS:[{authorizationEndpoint:`https://github.com/login/oauth/authorize`,clientId:`Ov23liDj6mzRyvM5n0yG`,id:`github`,name:`GitHub`,tokenEndpoint:`https://github.com/login/oauth/access_token`,urlPatterns:[`github.com`,`api.github.com`,`githubcopilot.com`,`api.githubcopilot.com`],clientSecret:`d467125f345a6edd5de0254a5a9b6bdde26fdd86`,scopes:[`read:user`,`repo`,`gist`,`notifications`,`project`,`public_repo`,`read:gpg_key`,`read:org`,`repo:status`,`repo_deployment`,`user`,`user:email`,`user:follow`],usePkce:!0,tokenEndpointAuthMethod:`client_secret_post`}],SENTRY_DSN:null,SENTRY_ENABLED:!1},kr=c.get,Ar=Or.APP_VERSION,jr=e=>{let t={};if(e){let n=e.split(`,`);for(let e of n){let[n,...r]=e.split(`:`);n&&r.length>0&&(t[n.trim()]=r.join(`:`).trim())}}return t},Mr=e=>{try{let t=new URL(e),n=`/guard/evaluate/v1`;return t.pathname.includes(n)?(t.pathname=t.pathname.replace(n,`/access-control/authorize`),t.toString()):(console.warn(`[mcp-gateway] Warning: SCANNER_URL does not contain expected path "${n}". Access control URL derivation skipped. Current path: "${t.pathname}". Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null)}catch(e){return console.warn(`[mcp-gateway] Warning: Failed to parse SCANNER_URL as valid URL: ${e instanceof Error?e.message:String(e)}. Please set MCP_GATEWAY_ACCESS_CONTROL_URL explicitly.`),null}},Nr=t(),Pr=kr(`NODE_ENV`).default(Or.NODE_ENV||`development`).asEnum([`development`,`production`,`staging`,`test`]),Fr=kr(`MCP_GATEWAY_SENTRY_DSN`).default(Or.SENTRY_DSN||``).asString()||null,Ir=kr(`MCP_GATEWAY_SENTRY_ENABLED`).default(String(Or.SENTRY_ENABLED??!1)).asBool(),Lr=kr(`DEBUG`).default(`false`).asBool()||kr(`MCP_GATEWAY_DEBUG`).default(`false`).asBool(),Rr=kr(`MCP_GATEWAY_SCANNER_URL`).default(``).asString()||null,zr=kr(`MCP_GATEWAY_SCANNER_API_KEY`).default(``).asString()||void 0,Br=(()=>{let e=kr(`MCP_GATEWAY_SCANNER_HEADERS`).required(!1).asString();return e?jr(e):{}})(),Vr=kr(`MCP_GATEWAY_SCANNER_TIMEOUT_MS`).default(`20000`).asIntPositive(),Hr=kr(`MCP_GATEWAY_SCANNER_FAIL_OPEN`).default(`true`).asBool(),Ur=kr(`MCP_GATEWAY_COMMAND`).default(`mcp-gateway`).asString(),Wr=kr(`CLIENT_APP_NAME`).default(``).asString(),Gr=kr(`MCP_GATEWAY_LOG_DIR`).default(a(l(),`.onyx`,`mcp-gateway`,`logs`)).asString(),Kr=kr(`MCP_GATEWAY_OAUTH_DIR`).default(a(l(),`.onyx`,`mcp-gateway`,`oauth`)).asString(),qr=(()=>kr(`MCP_GATEWAY_ACCESS_CONTROL_URL`).default(``).asString()||(Rr?Mr(Rr):null))(),Jr=(()=>{let e=kr(`MCP_GATEWAY_ACCESS_CONTROL_HEADERS`).required(!1).asString();return e?jr(e):{}})(),Yr=kr(`MCP_GATEWAY_ACCESS_CONTROL_TIMEOUT_MS`).default(`3000`).asIntPositive(),Xr={accessControl:{enabled:!!(qr&&zr),headers:Jr,timeoutMs:Yr,url:qr},appVersion:Ar,clientAppName:Wr,debug:Lr,environment:Pr,logDir:Gr,oauthDir:Kr,proxyCommand:Ur,scanner:{apiKey:zr,enabled:!!Rr,failOpen:Hr,headers:Br,timeoutMs:Vr,url:Rr},sentry:{debug:Lr&&Pr===`development`,dsn:Fr||void 0,enabled:Ir,environment:Pr,release:`mcp-gateway@${Ar}`,tracesSampleRate:Pr===`production`?1:0}},Zr=Xr.logDir,Qr=Xr.debug?`debug`:`info`;let $r=!1;try{n(Zr)||r(Zr,{recursive:!0}),$r=!0}catch(e){let t=e instanceof Error?e.message:String(e),n=t.includes(`EACCES`)||t.includes(`permission denied`);console.error(`[mcp-gateway] WARNING: Failed to create log directory: ${Zr}`),console.error(`[mcp-gateway] Error: ${t}`),n&&(console.error(`[mcp-gateway] This appears to be a permission issue. Possible solutions:`),console.error(`[mcp-gateway] 1. Fix directory permissions: sudo chown -R $USER ~/.onyx`),console.error(`[mcp-gateway] 2. Use a different log directory: export MCP_GATEWAY_LOG_DIR=/tmp/mcp-gateway-logs`)),console.error(`[mcp-gateway] File logging will be disabled. The gateway will continue to function.`)}const ei=o.format.combine(o.format.timestamp(),o.format.errors({stack:!0}),o.format.json());let ti=null;const ni=[];if($r){let e=new s({datePattern:`YYYY-MM-DD`,filename:a(Zr,`mcp-gateway-%DATE%.log`),format:ei,handleExceptions:!1,handleRejections:!1,level:Qr,maxFiles:10,maxSize:`10m`});ni.push(e)}const ri=o.createLogger({defaultMeta:{service:`mcp-gateway`,version:Xr.appVersion},format:o.format.combine(o.format.errors({stack:!0}),o.format.metadata()),level:Qr,transports:ni}),ii=e=>{let[t,...n]=e;if(typeof t!=`string`)throw Error(`First argument must be a string message`);if(n.length>0&&n[0]&&typeof n[0]==`object`&&`proxyType`in n[0]){let e=n[0],r=n[1];return{message:t,meta:r,sessionData:e}}let r=n[0];return{message:t,meta:r,sessionData:ti||void 0}},Z={debug:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.debug(t,{sessionData:r,...n})},error:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.error(t,{sessionData:r,...n})},getSessionData:()=>ti,info:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.info(t,{sessionData:r,...n})},setSessionData:e=>{ti=e,Z.debug(`Session data set for logger`,e)},warn:(...e)=>{let{message:t,meta:n,sessionData:r}=ii(e);ri.warn(t,{sessionData:r,...n})}};Z.info(`MCP Gateway logger initialized`,{debug:Xr.debug,fileLoggingEnabled:$r,logDir:Zr,logLevel:Qr});let ai={"proxy.version":Xr.appVersion};function oi(e,t=`default`,n=`info`,r){try{if(!Xr.sentry.enabled){Z.debug(`Breadcrumb: [${t}] ${e}`,r);return}f.addBreadcrumb({category:t,data:r?ui(r):void 0,level:n,message:e,timestamp:Date.now()/1e3})}catch(e){Z.warn(`Failed to add breadcrumb to Sentry`,{error:e})}}function si(e){ai={...ai,...e}}function ci(e,t,n){try{let r=e instanceof br?{...e.tags,...n}:n,i=e instanceof br?{...e.extra,...t}:t;if(!Xr.sentry.enabled){let t=e instanceof Error?e.message:String(e);Z.error(`Exception captured: ${t}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r});return}let a=e instanceof Error?e.message:String(e);Z.error(`Sending exception to Sentry: ${a}`,{error:e instanceof Error?e.stack||e.message:e,extra:i,tags:r}),f.withScope(t=>{r&&Object.entries(r).forEach(([e,n])=>{let r=e.startsWith(`mcp.gateway.`)?e:`mcp.gateway.${e}`;t.setTag(r,n)}),i&&Object.entries(ui(i)).forEach(([e,n])=>{t.setExtra(e,n)}),t.setLevel(`error`),f.captureException(e)})}catch(e){Z.warn(`Failed to capture exception to Sentry`,{sentryError:e instanceof Error?e.message:e})}}function li(){try{if(!Xr.sentry.enabled){Z.debug(`Sentry disabled (no DSN provided or in development mode)`);return}f.init({beforeSend(e){return e.tags={...e.tags,...ai},e.extra&&=ui(e.extra),e.contexts?.runtime?.name&&(e.contexts.runtime.name=`node`),e},beforeSendTransaction(e){return e.tags={...e.tags,...ai},e},debug:Xr.sentry.debug,dsn:Xr.sentry.dsn,environment:Xr.sentry.environment,release:Xr.sentry.release,tracesSampleRate:Xr.sentry.tracesSampleRate}),Z.debug(`Sentry initialized`,{dsn:Xr.sentry.dsn?`***configured***`:`not configured`,environment:Xr.sentry.environment,release:Xr.sentry.release})}catch(e){Z.warn(`Failed to initialize Sentry, continuing without error tracking`,{error:e})}}function ui(e){let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.toLowerCase();if(r.includes(`password`)||r.includes(`token`)||r.includes(`key`)||r.includes(`secret`)||r.includes(`auth`)||r===`env`||r===`environment`){t[e]=`[FILTERED]`;return}if(typeof n==`string`&&(r.includes(`url`)||n.startsWith(`http`)))try{let r=new URL(n);t[e]=`${r.protocol}//${r.host}${r.pathname}`}catch{t[e]=n}else t[e]=n}),t}function di(){return a(l(),`.claude.json`)}function fi(){try{return u()}catch{return`unknown-device`}}async function pi(e){try{return(await p()).find(t=>t.pid===e)?.name||`unknown`}catch{return`unknown`}}function mi(){try{let e=gi();return e?e.oauthAccount.emailAddress:void 0}catch{return}}function hi(){try{let e=d();if(e.username)return e.username;throw Error(`userInfo() returned empty username`)}catch{return process.env.USER||process.env.USERNAME||process.env.LOGNAME}}function gi(){try{let e=di();if(!n(e))return null;let t=i(e,`utf-8`);return JSON.parse(t)}catch{return null}}const _i=async()=>{let e=process.pid,t=process.ppid;try{let n=fi(),r=mi(),i=hi(),a=await pi(t);return{clientAppName:Wr||`unknown`,deviceName:n,email:r,parentProcessId:t,parentProcessName:a,processId:e,username:i}}catch{return{clientAppName:Wr||`unknown`,deviceName:`unknown-device`,email:void 0,parentProcessId:t,parentProcessName:`unknown`,processId:e,username:void 0}}};function vi(e){let t=m(JSON.stringify(e));return Buffer.from(t).toString(`base64url`)}var yi=class{clientAppName;clientInfoBase64;sessionData;get scannerConfig(){return{apiKey:this.config.scanApiKey,enabled:this.config.scanEnabled,failOpen:this.config.scanFailOpen,headers:this.config.scanHeaders,timeoutMs:this.config.scanTimeoutMs,url:this.config.scanUrl}}config;constructor(e,t){this.config=e,this.sessionData=t,this.clientAppName=t.clientAppName||``,this.clientInfoBase64=this.getClientInfoBase64()}async evaluate(e){let t={action:`allow`};if(this.isScanEnabled())try{if(t=await this.scan({data:e.data,id:e.id,method:e.method,originalRequestId:e.originalRequestId,timestamp:e.timestamp,type:e.type}),Z.info(`Scan result`,{action:t.action,id:e.id,method:e.method,originalRequestId:e.originalRequestId}),t.action===`block`)return Z.warn(`Request blocked by security policy`),t}catch(t){if(Z.error(`Scanning failed`,{error:t}),ci(t instanceof Error?t:Error(String(t)),{method:e.method,requestType:e.type,scannerUrl:this.config.scanUrl},{feature:`traffic-scanner`,module:`evaluator`,operation:`scan`}),!this.config.scanFailOpen)return Z.warn(`Scanning service unavailable, blocking traffic (fail-closed)`),{action:`block`};Z.warn(`Scanning service unavailable, allowing traffic (fail-open)`)}return t}isEnabled(){return this.isScanEnabled()}isScanEnabled(){return this.config.scanEnabled&&!!this.config.scanUrl}async scan(e){if(!this.isScanEnabled())return{action:`allow`};let t={data:e.data,id:e.id,metadata:this.sessionData,method:e.method,originalRequestId:e.originalRequestId,type:e.type};Z.info(`Scanning traffic`,{id:e.id,method:e.method,originalRequestId:e.originalRequestId,type:e.type});let n=await this.sendScanRequest(t);return Z.info(`Scan result`,{action:n.action,blockReason:n.block_reason,hasModifiedData:!!n.modified_data,id:e.id,originalRequestId:e.originalRequestId}),n}updateConfig(e){this.config={...this.config,...e}}getClientInfoBase64(){return vi(this.sessionData)}async sendScanRequest(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.config.scanTimeoutMs);try{let n=`${this.config.scanUrl}/${this.config.scanApiKey}/mcp/${this.clientInfoBase64}`,r={data:e.data,id:e.id,metadata:e.metadata,method:e.method,sessionId:Nr,...e.originalRequestId&&{original_request_id:String(e.originalRequestId)},type:e.type},i=await fetch(n,{body:JSON.stringify(r),headers:{"Content-Type":`application/json`,...this.config.scanHeaders},method:`POST`,signal:t.signal});if(!i.ok)throw Error(`Sanitization service returned ${i.status}: ${i.statusText}`);let a=await i.json();if(!a.action||![`allow`,`block`,`modify`].includes(a.action))throw Error(`Invalid scan response format: action="${a.action}"`);return a}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Scan request timed out after ${this.config.scanTimeoutMs}ms`):e}finally{clearTimeout(n)}}};let bi=null;const xi=async e=>{let t=await _i(),n=e.cliArgs.proxyType,r={...t,proxyType:n,remoteCliArgs:n===`remote`?e.cliArgs:void 0,stdioCliArgs:n===`stdio`?e.cliArgs:void 0};return Z.setSessionData(r),bi=new yi(e,r),bi},Si=()=>bi,Ci=e=>e.length>1&&e[1]&&typeof e[1]==`object`&&`requestId`in e[1]?e[1].requestId:void 0,wi=(e,n,r,i)=>async(...a)=>{let o=Si(),s=e,c=a[0],l=t(),u=Ci(a)?.toString();c&&typeof c==`object`&&`method`in c&&typeof c.method==`string`&&(s=c.method);let d=async(e,t,n)=>{try{if(!o?.isEnabled()&&!o?.isScanEnabled())return;let r;try{r=await o.evaluate({data:t,id:l,method:s,originalRequestId:u,timestamp:new Date().toISOString(),type:e})}catch(t){if(Z.error(`${e} evaluation failed, applying fail-safe`,{error:t}),o?.isScanEnabled()&&!o.scannerConfig?.failOpen)throw Error(`Security scanning service unavailable`);return}if(Z.info(`${e} scan result`,{action:r.action,id:l,method:s,...e===`request`&&{originalRequestId:u}}),r.action===`block`||r.action===`modify`){let t=r.action===`block`?`blocked`:`modified`,i=r.action===`block`&&e===`request`?`warn`:`log`;if(r.modified_data){if(r.action===`block`){let n=`${e} ${t} by security policy${e===`request`?`, returning error response`:``}`;return i===`warn`?Z.warn(n):Z.info(n),r.modified_data}if(n){let a=`${e} ${t} by security policy`;i===`warn`?Z.warn(a):Z.info(a),n(r.modified_data);return}return r.modified_data}Z.warn(`${r.action} action without modified_data, allowing original ${e}`)}return}catch(t){if(Z.error(`Unexpected error during ${e} processing`,{error:t}),ci(t),e===`request`&&t instanceof Error&&t.message===`Security scanning service unavailable`)throw t;return}},f;try{f=await d(`request`,c,e=>{a[0]=e})}catch(t){if(t instanceof Error&&t.message===`Security scanning service unavailable`){let r=new Er(`Security scanning unavailable (fail-closed)`,e,n,{errorMessage:t.message});throw ci(r),t}Z.error(`Unexpected error during request processing, continuing`,{error:t}),ci(t)}if(f!==void 0)return f;if(i&&!await i.isAllowed()){let t=i.getBlockReason();throw Z.warn(`MCP server blocked by access control`,{handlerName:e,operation:n,reason:t}),new xr(t,`policy_block`)}try{let e=await r(...a);try{if(e){let t=await d(`response`,e);if(t!==void 0)return t}}catch(e){Z.error(`Error during response processing, returning original result`,{error:e}),ci(e)}return e}catch(t){if(t instanceof xr)throw Z.info(`Request blocked by access control`,{error:t.message,handlerName:e,operation:n,reason:t.reason}),t;try{await d(`error`,{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}catch(e){Z.warn(`Failed to evaluate error`,{evalError:e})}let r=new Er(`Handler error: ${t}`,e,n,{argsCount:a.length,errorMessage:t instanceof Error?t.message:String(t)});throw ci(r),t}},Ti=async({authorizer:e,client:t,server:n,serverCapabilities:r})=>{r?.logging&&(n.setNotificationHandler(Qn,wi(`notifications/message`,`server-to-client`,async e=>t.notification(e),e)),t.setNotificationHandler(Qn,wi(`notifications/message`,`client-to-server`,async e=>n.notification(e),e))),r?.prompts&&(n.setRequestHandler(Nn,wi(`prompts/get`,`get`,async e=>t.getPrompt(e.params),e)),n.setRequestHandler(jn,wi(`prompts/list`,`list`,async e=>t.listPrompts(e.params),e))),r?.resources&&(n.setRequestHandler(yn,wi(`resources/list`,`list`,async e=>t.listResources(e.params),e)),n.setRequestHandler(xn,wi(`resources/templates/list`,`list`,async e=>t.listResourceTemplates(e.params),e)),n.setRequestHandler(Cn,wi(`resources/read`,`read`,async e=>t.readResource(e.params),e)),r?.resources.subscribe&&(n.setNotificationHandler(On,wi(`notifications/resources/updated`,`notify`,async e=>t.notification(e),e)),n.setRequestHandler(En,wi(`resources/subscribe`,`subscribe`,async e=>t.subscribeResource(e.params),e)),n.setRequestHandler(Dn,wi(`resources/unsubscribe`,`unsubscribe`,async e=>t.unsubscribeResource(e.params),e)))),r?.tools&&(n.setRequestHandler(Jn,wi(`tools/call`,`call`,async e=>t.callTool(e.params),e)),n.setRequestHandler(Gn,wi(`tools/list`,`list`,async e=>t.listTools(e.params),e))),n.setRequestHandler(pr,wi(`completion/complete`,`complete`,async e=>t.complete(e.params),e))};var Ei=T(((exports,t)=>{t.exports=o,t.exports.format=s,t.exports.parse=c;var n=/\B(?=(\d{3})+(?!\d))/g,r=/(?:\.0*|(\.[^0]+)0+)$/,i={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:1024**4,pb:1024**5},a=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function o(e,t){return typeof e==`string`?c(e):typeof e==`number`?s(e,t):null}function s(e,t){if(!Number.isFinite(e))return null;var a=Math.abs(e),o=t&&t.thousandsSeparator||``,s=t&&t.unitSeparator||``,c=t&&t.decimalPlaces!==void 0?t.decimalPlaces:2,l=!!(t&&t.fixedDecimals),u=t&&t.unit||``;(!u||!i[u.toLowerCase()])&&(u=a>=i.pb?`PB`:a>=i.tb?`TB`:a>=i.gb?`GB`:a>=i.mb?`MB`:a>=i.kb?`KB`:`B`);var d=(e/i[u.toLowerCase()]).toFixed(c);return l||(d=d.replace(r,`$1`)),o&&(d=d.split(`.`).map(function(e,t){return t===0?e.replace(n,o):e}).join(`.`)),d+s+u}function c(e){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e!=`string`)return null;var t=a.exec(e),n,r=`b`;return t?(n=parseFloat(t[1]),r=t[4].toLowerCase()):(n=parseInt(e,10),r=`b`),isNaN(n)?null:Math.floor(i[r]*n)}})),Di=T(((exports,t)=>{
|
|
2
2
|
/*!
|
|
3
3
|
* depd
|
|
4
4
|
* Copyright(c) 2014-2018 Douglas Christopher Wilson
|
|
@@ -26,4 +26,4 @@ return fn.apply(this, arguments)
|
|
|
26
26
|
`&&r++}}return[t,n]}var xo=class extends Event{constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(wo(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(wo(this),t)}};function So(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Co(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Co).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Co(e.cause)}`:e.message:`${e}`}function wo(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var To=e=>{throw TypeError(e)},Eo=(e,t,n)=>t.has(e)||To(`Cannot `+n),Q=(e,t,n)=>(Eo(e,t,`read from private field`),n?n.call(e):t.get(e)),Do=(e,t,n)=>t.has(e)?To(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),$=(e,t,n,r)=>(Eo(e,t,`write to private field`),t.set(e,n),n),Oo=(e,t,n)=>(Eo(e,t,`access private method`),n),ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo,Go,Ko,qo,Jo,Yo,Xo,Zo,Qo=class extends EventTarget{constructor(e,t){super(),Do(this,Ho),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Do(this,ko),Do(this,Ao),Do(this,jo),Do(this,Mo),Do(this,No),Do(this,Po),Do(this,Fo),Do(this,Io,null),Do(this,Lo),Do(this,Ro),Do(this,zo,null),Do(this,Bo,null),Do(this,Vo,null),Do(this,Wo,async e=>{var t;Q(this,Ro).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Oo(this,Ho,Yo).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?$(this,jo,new URL(e.url)):$(this,jo,void 0),i!==200){Oo(this,Ho,Yo).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Oo(this,Ho,Yo).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(Q(this,ko)===this.CLOSED)return;$(this,ko,this.OPEN);let o=new Event(`open`);if((t=Q(this,Vo))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Oo(this,Ho,Yo).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&Q(this,Ro).feed(s.decode(t,{stream:!e})),e&&(l=!1,Q(this,Ro).reset(),Oo(this,Ho,Xo).call(this))}while(l)}),Do(this,Go,e=>{$(this,Lo,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&Oo(this,Ho,Xo).call(this,Co(e))}),Do(this,qo,e=>{typeof e.id==`string`&&$(this,Io,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:Q(this,jo)?Q(this,jo).origin:Q(this,Ao).origin,lastEventId:e.id||``});Q(this,Bo)&&(!e.event||e.event===`message`)&&Q(this,Bo).call(this,t),this.dispatchEvent(t)}),Do(this,Jo,e=>{$(this,Po,e)}),Do(this,Zo,()=>{$(this,Fo,void 0),Q(this,ko)===this.CONNECTING&&Oo(this,Ho,Uo).call(this)});try{if(e instanceof URL)$(this,Ao,e);else if(typeof e==`string`)$(this,Ao,new URL(e,$o()));else throw Error(`Invalid URL`)}catch{throw So(`An invalid or illegal string was specified`)}$(this,Ro,yo({onEvent:Q(this,qo),onRetry:Q(this,Jo)})),$(this,ko,this.CONNECTING),$(this,Po,3e3),$(this,No,t?.fetch??globalThis.fetch),$(this,Mo,t?.withCredentials??!1),Oo(this,Ho,Uo).call(this)}get readyState(){return Q(this,ko)}get url(){return Q(this,Ao).href}get withCredentials(){return Q(this,Mo)}get onerror(){return Q(this,zo)}set onerror(e){$(this,zo,e)}get onmessage(){return Q(this,Bo)}set onmessage(e){$(this,Bo,e)}get onopen(){return Q(this,Vo)}set onopen(e){$(this,Vo,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){Q(this,Fo)&&clearTimeout(Q(this,Fo)),Q(this,ko)!==this.CLOSED&&(Q(this,Lo)&&Q(this,Lo).abort(),$(this,ko,this.CLOSED),$(this,Lo,void 0))}};ko=new WeakMap,Ao=new WeakMap,jo=new WeakMap,Mo=new WeakMap,No=new WeakMap,Po=new WeakMap,Fo=new WeakMap,Io=new WeakMap,Lo=new WeakMap,Ro=new WeakMap,zo=new WeakMap,Bo=new WeakMap,Vo=new WeakMap,Ho=new WeakSet,Uo=function(){$(this,ko,this.CONNECTING),$(this,Lo,new AbortController),Q(this,No)(Q(this,Ao),Oo(this,Ho,Ko).call(this)).then(Q(this,Wo)).catch(Q(this,Go))},Wo=new WeakMap,Go=new WeakMap,Ko=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...Q(this,Io)?{"Last-Event-ID":Q(this,Io)}:void 0},cache:`no-store`,signal:Q(this,Lo)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},qo=new WeakMap,Jo=new WeakMap,Yo=function(e,t){var n;Q(this,ko)!==this.CLOSED&&$(this,ko,this.CLOSED);let r=new xo(`error`,{code:t,message:e});(n=Q(this,zo))==null||n.call(this,r),this.dispatchEvent(r)},Xo=function(e,t){var n;if(Q(this,ko)===this.CLOSED)return;$(this,ko,this.CONNECTING);let r=new xo(`error`,{code:t,message:e});(n=Q(this,zo))==null||n.call(this,r),this.dispatchEvent(r),$(this,Fo,setTimeout(Q(this,Zo),Q(this,Po)))},Zo=new WeakMap,Qo.CONNECTING=0,Qo.OPEN=1,Qo.CLOSED=2;function $o(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}let es;es=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ts(e){return(await es).getRandomValues(new Uint8Array(e))}async function ns(e){let t=``,n=await ts(e);for(let r=0;r<e;r++){let e=n[r]%66;t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e]}return t}async function rs(e){return await ns(e)}async function os(e){let t=await(await es).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function ss(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await rs(e),n=await os(t);return{code_verifier:t,code_challenge:n}}const cs=K().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:N.custom,message:`URL must be parseable`,fatal:!0}),Dt}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),ls=J({resource:K().url(),authorization_servers:q(cs).optional(),jwks_uri:K().url().optional(),scopes_supported:q(K()).optional(),bearer_methods_supported:q(K()).optional(),resource_signing_alg_values_supported:q(K()).optional(),resource_name:K().optional(),resource_documentation:K().optional(),resource_policy_uri:K().url().optional(),resource_tos_uri:K().url().optional(),tls_client_certificate_bound_access_tokens:bt().optional(),authorization_details_types_supported:q(K()).optional(),dpop_signing_alg_values_supported:q(K()).optional(),dpop_bound_access_tokens_required:bt().optional()}).passthrough(),us=J({issuer:K(),authorization_endpoint:cs,token_endpoint:cs,registration_endpoint:cs.optional(),scopes_supported:q(K()).optional(),response_types_supported:q(K()),response_modes_supported:q(K()).optional(),grant_types_supported:q(K()).optional(),token_endpoint_auth_methods_supported:q(K()).optional(),token_endpoint_auth_signing_alg_values_supported:q(K()).optional(),service_documentation:cs.optional(),revocation_endpoint:cs.optional(),revocation_endpoint_auth_methods_supported:q(K()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(K()).optional(),introspection_endpoint:K().optional(),introspection_endpoint_auth_methods_supported:q(K()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(K()).optional(),code_challenge_methods_supported:q(K()).optional()}).passthrough(),ds=J({issuer:K(),authorization_endpoint:cs,token_endpoint:cs,userinfo_endpoint:cs.optional(),jwks_uri:cs,registration_endpoint:cs.optional(),scopes_supported:q(K()).optional(),response_types_supported:q(K()),response_modes_supported:q(K()).optional(),grant_types_supported:q(K()).optional(),acr_values_supported:q(K()).optional(),subject_types_supported:q(K()),id_token_signing_alg_values_supported:q(K()),id_token_encryption_alg_values_supported:q(K()).optional(),id_token_encryption_enc_values_supported:q(K()).optional(),userinfo_signing_alg_values_supported:q(K()).optional(),userinfo_encryption_alg_values_supported:q(K()).optional(),userinfo_encryption_enc_values_supported:q(K()).optional(),request_object_signing_alg_values_supported:q(K()).optional(),request_object_encryption_alg_values_supported:q(K()).optional(),request_object_encryption_enc_values_supported:q(K()).optional(),token_endpoint_auth_methods_supported:q(K()).optional(),token_endpoint_auth_signing_alg_values_supported:q(K()).optional(),display_values_supported:q(K()).optional(),claim_types_supported:q(K()).optional(),claims_supported:q(K()).optional(),service_documentation:K().optional(),claims_locales_supported:q(K()).optional(),ui_locales_supported:q(K()).optional(),claims_parameter_supported:bt().optional(),request_parameter_supported:bt().optional(),request_uri_parameter_supported:bt().optional(),require_request_uri_registration:bt().optional(),op_policy_uri:cs.optional(),op_tos_uri:cs.optional()}).passthrough().merge(us.pick({code_challenge_methods_supported:!0})),fs=J({access_token:K(),id_token:K().optional(),token_type:K(),expires_in:yt().optional(),scope:K().optional(),refresh_token:K().optional()}).strip(),ps=J({error:K(),error_description:K().optional(),error_uri:K().optional()}),ms=J({redirect_uris:q(cs),token_endpoint_auth_method:K().optional(),grant_types:q(K()).optional(),response_types:q(K()).optional(),client_name:K().optional(),client_uri:cs.optional(),logo_uri:cs.optional(),scope:K().optional(),contacts:q(K()).optional(),tos_uri:cs.optional(),policy_uri:K().optional(),jwks_uri:cs.optional(),jwks:xt().optional(),software_id:K().optional(),software_version:K().optional(),software_statement:K().optional()}).strip(),hs=J({client_id:K(),client_secret:K().optional(),client_id_issued_at:yt().optional(),client_secret_expires_at:yt().optional()}).strip(),gs=ms.merge(hs);J({error:K(),error_description:K().optional()}).strip(),J({token:K(),token_type_hint:K().optional()}).strip();function _s(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function vs({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var ys=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},bs=class extends ys{};bs.errorCode=`invalid_request`;var xs=class extends ys{};xs.errorCode=`invalid_client`;var Ss=class extends ys{};Ss.errorCode=`invalid_grant`;var Cs=class extends ys{};Cs.errorCode=`unauthorized_client`;var ws=class extends ys{};ws.errorCode=`unsupported_grant_type`;var Ts=class extends ys{};Ts.errorCode=`invalid_scope`;var Es=class extends ys{};Es.errorCode=`access_denied`;var Ds=class extends ys{};Ds.errorCode=`server_error`;var Os=class extends ys{};Os.errorCode=`temporarily_unavailable`;var ks=class extends ys{};ks.errorCode=`unsupported_response_type`;var As=class extends ys{};As.errorCode=`unsupported_token_type`;var js=class extends ys{};js.errorCode=`invalid_token`;var Ms=class extends ys{};Ms.errorCode=`method_not_allowed`;var Ns=class extends ys{};Ns.errorCode=`too_many_requests`;var Ps=class extends ys{};Ps.errorCode=`invalid_client_metadata`;var Fs=class extends ys{};Fs.errorCode=`insufficient_scope`;const Is={[bs.errorCode]:bs,[xs.errorCode]:xs,[Ss.errorCode]:Ss,[Cs.errorCode]:Cs,[ws.errorCode]:ws,[Ts.errorCode]:Ts,[Es.errorCode]:Es,[Ds.errorCode]:Ds,[Os.errorCode]:Os,[ks.errorCode]:ks,[As.errorCode]:As,[js.errorCode]:js,[Ms.errorCode]:Ms,[Ns.errorCode]:Ns,[Ps.errorCode]:Ps,[Fs.errorCode]:Fs};var Ls=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Rs(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function zs(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Bs(i,a,n);return;case`client_secret_post`:Vs(i,a,r);return;case`none`:Hs(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Bs(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Vs(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Hs(e,t){t.set(`client_id`,e)}async function Us(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ps.parse(JSON.parse(n));return new(Is[e]||Ds)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new Ds(r)}}async function Ws(e,t){try{return await Gs(e,t)}catch(n){if(n instanceof xs||n instanceof Cs)return await e.invalidateCredentials?.call(e,`all`),await Gs(e,t);if(n instanceof Ss)return await e.invalidateCredentials?.call(e,`tokens`),await Gs(e,t);throw n}}async function Gs(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o,s;try{o=await Js(t,{resourceMetadataUrl:i},a),o.authorization_servers&&o.authorization_servers.length>0&&(s=o.authorization_servers[0])}catch{}s||=t;let c=await Ks(t,e,o),l=await tc(s,{fetchFn:a}),u=await Promise.resolve(e.clientInformation());if(!u){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await ac(s,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(t),u=t}if(n!==void 0){let t=await e.codeVerifier(),r=await rc(s,{metadata:l,clientInformation:u,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(r),`AUTHORIZED`}let d=await e.tokens();if(d?.refresh_token)try{let t=await ic(s,{metadata:l,clientInformation:u,refreshToken:d.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof ys)||e instanceof Ds))throw e}let f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:m}=await nc(s,{metadata:l,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:r||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(p),`REDIRECT`}async function Ks(e,t,n){let r=_s(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!vs({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function qs(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=/resource_metadata="([^"]*)"/.exec(t);if(i)try{return new URL(i[1])}catch{return}}async function Js(e,t,n=fetch){let r=await $s(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return ls.parse(await r.json())}async function Ys(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Ys(e,void 0,n):void 0;throw r}}function Xs(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Zs(e,t,n=fetch){return await Ys(e,{"MCP-Protocol-Version":t},n)}function Qs(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function $s(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??Ot,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Xs(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await Zs(o,a,n);if(!r?.metadataUrl&&Qs(s,i.pathname)){let e=new URL(`/.well-known/${t}`,i);s=await Zs(e,a,n)}return s}function ec(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function tc(e,{fetchFn:t=fetch,protocolVersion:n=Ot}={}){let r={"MCP-Protocol-Version":n},i=ec(e);for(let{url:e,type:n}of i){let i=await Ys(e,r,t);if(!i)continue;if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return us.parse(await i.json());{let t=ds.parse(await i.json());if(!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}async function nc(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await ss(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,o.href),{authorizationUrl:l,codeVerifier:d}}async function rc(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});if(s)s(d,f,e,t);else{let e=t?.token_endpoint_auth_methods_supported??[],r=Rs(n,e);zs(r,n,d,f)}o&&f.set(`resource`,o.href);let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Us(p);return fs.parse(await p.json())}async function ic(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`}),u=new URLSearchParams({grant_type:s,refresh_token:r});if(a)a(l,u,e,t);else{let e=t?.token_endpoint_auth_methods_supported??[],r=Rs(n,e);zs(r,n,l,u)}i&&u.set(`resource`,i.href);let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Us(d);return fs.parse({refresh_token:r,...await d.json()})}async function ac(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Us(a);return gs.parse(await a.json())}var oc=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},sc=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Ls(`No auth provider`);let t;try{t=await Ws(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}if(t!==`AUTHORIZED`)throw new Ls;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}return this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion),new Headers({...e,...this._requestInit?.headers})}_startOrAuth(){let e=(this===null||this===void 0?void 0:this._eventSourceInit)?.fetch??this._fetch??fetch;return new Promise((t,n)=>{this._eventSource=new Qo(this._url.href,{...this._eventSourceInit,fetch:async(t,n)=>{let r=await this._commonHeaders();r.set(`Accept`,`text/event-stream`);let i=await e(t,{...n,headers:r});return i.status===401&&i.headers.has(`www-authenticate`)&&(this._resourceMetadataUrl=qs(i)),i}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{var r;if(e.code===401&&this._authProvider){this._authThenStart().then(t,n);return}let i=new oc(e.code,e.message,e);n(i),(r=this.onerror)==null||r.call(this,i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,e=>{var r;let i=e;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){n(e),(r=this.onerror)==null||r.call(this,e),this.close();return}t()}),this._eventSource.onmessage=e=>{var t,n;let r=e,i;try{i=Jt.parse(JSON.parse(r.data))}catch(e){(t=this.onerror)==null||t.call(this,e);return}(n=this.onmessage)==null||n.call(this,i)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Ls(`No auth provider`);if(await Ws(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ls(`Failed to authorize`)}async close(){var e,t,n;(e=this._abortController)==null||e.abort(),(t=this._eventSource)==null||t.close(),(n=this.onclose)==null||n.call(this)}async send(e){var t;if(!this._endpoint)throw Error(`Not connected`);try{let t=await this._commonHeaders();t.set(`content-type`,`application/json`);let n={...this._requestInit,method:`POST`,headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._endpoint,n);if(!r.ok){if(r.status===401&&this._authProvider){if(this._resourceMetadataUrl=qs(r),await Ws(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ls;return this.send(e)}let t=await r.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${r.status}): ${t}`)}}catch(e){throw(t=this.onerror)==null||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}},cc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=yo({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const lc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var uc=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},dc=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??lc}async _authThenStart(){var e;if(!this._authProvider)throw new Ls(`No auth provider`);let t;try{t=await Ws(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}if(t!==`AUTHORIZED`)throw new Ls;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=this._normalizeHeaders(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){var t;let{resumptionToken:n}=e;try{let t=await this._commonHeaders();t.set(`Accept`,`text/event-stream`),n&&t.set(`last-event-id`,n);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:t,signal:this._abortController?.signal});if(!r.ok){if(r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new uc(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw(t=this.onerror)==null||t.call(this,e),e}}_getNextReconnectionDelay(e){let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,t=0){var n;let r=this._reconnectionOptions.maxRetries;if(r>0&&t>=r){(n=this.onerror)==null||n.call(this,Error(`Maximum reconnection attempts (${r}) exceeded.`));return}let i=this._getNextReconnectionDelay(t);setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{var r;(r=this.onerror)==null||r.call(this,Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a;(async()=>{var t,o,s,c;try{let n=e.pipeThrough(new TextDecoderStream).pipeThrough(new cc).getReader();for(;;){let{value:e,done:s}=await n.read();if(s)break;if(e.id&&(a=e.id,r?.(e.id)),!e.event||e.event===`message`)try{let n=Jt.parse(JSON.parse(e.data));i!==void 0&&Wt(n)&&(n.id=i),(t=this.onmessage)==null||t.call(this,n)}catch(e){(o=this.onerror)==null||o.call(this,e)}}}catch(e){if((s=this.onerror)==null||s.call(this,Error(`SSE stream disconnected: ${e}`)),n&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){(c=this.onerror)==null||c.call(this,Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Ls(`No auth provider`);if(await Ws(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ls(`Failed to authorize`)}async close(){var e,t;(e=this._abortController)==null||e.abort(),(t=this.onclose)==null||t.call(this)}async send(e,t){var n,r;try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:Bt(e)?e.id:void 0}).catch(e=>this.onerror?.call(this,e));return}let a=await this._commonHeaders();a.set(`content-type`,`application/json`),a.set(`accept`,`application/json, text/event-stream`);let o={...this._requestInit,method:`POST`,headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,o),c=s.headers.get(`mcp-session-id`);if(c&&(this._sessionId=c),!s.ok){if(s.status===401&&this._authProvider){if(this._resourceMetadataUrl=qs(s),await Ws(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Ls;return this.send(e)}let t=await s.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${s.status}): ${t}`)}if(s.status===202){sn(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.call(this,e));return}let l=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,u=s.headers.get(`content-type`);if(l)if(u?.includes(`text/event-stream`))this._handleSseStream(s.body,{onresumptiontoken:i},!1);else if(u?.includes(`application/json`)){let e=await s.json(),t=Array.isArray(e)?e.map(e=>Jt.parse(e)):[Jt.parse(e)];for(let e of t)(n=this.onmessage)==null||n.call(this,e)}else throw new uc(-1,`Unexpected content type: ${u}`)}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e;if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(!n.ok&&n.status!==405)throw new uc(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw(e=this.onerror)==null||e.call(this,t),t}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}},fc=D(mo(),1),pc=class extends ba{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Xn.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.setRequestHandler(tn,e=>this._oninitialize(e)),this.setNotificationHandler(on,()=>this.oninitialized?.call(this)),this._capabilities.logging&&this.setRequestHandler(Zn,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Xn.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=xa(this._capabilities,e)}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})`);break;case`ping`:break}}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/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw Error(`Server does not support sampling (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`ping`:case`initialize`:break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:kt.includes(t)?t:Ot,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`},Yt)}async createMessage(e,t){return this.request({method:`sampling/createMessage`,params:e},rr,t)}async elicitInput(e,t){let n=await this.request({method:`elicitation/create`,params:e},ur,t);if(n.action===`accept`&&n.content)try{let t=new fc.default,r=t.compile(e.requestedSchema);if(!r(n.content))throw new yr(Gt.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(r.errors)}`)}catch(e){throw e instanceof yr?e:new yr(Gt.InternalError,`Error validating elicitation response: ${e}`)}return n}async listRoots(e,t){return this.request({method:`roots/list`,params:e},_r,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`})}},mc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
27
27
|
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),hc(t)}clear(){this._buffer=void 0}};function hc(e){return Jt.parse(JSON.parse(e))}function gc(e){return JSON.stringify(e)+`
|
|
28
28
|
`}var _c=class{constructor(e=v.stdin,t=v.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new mc,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;(t=this.onerror)==null||t.call(this,e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(var e,t;;)try{let t=this._readBuffer.readMessage();if(t===null)break;(e=this.onmessage)==null||e.call(this,t)}catch(e){(t=this.onerror)==null||t.call(this,e)}}async close(){var e;this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)==null||e.call(this)}send(e){return new Promise(t=>{let n=gc(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};export{xr as AccessControlBlockError,Or as BUILD_TIME_CONFIG,go as Client,Sr as ConfigurationError,k as InMemoryEventStore,wr as ProcessSpawnError,Tr as ProxyConnectionError,mc as ReadBuffer,sc as SSEClientTransport,pc as Server,_c as StdioServerTransport,dc as StreamableHTTPClientTransport,Dr as TransportError,Ls as UnauthorizedError,T as __commonJSMin,D as __toESM,oi as addBreadcrumbSafe,si as addGlobalTags,ci as captureExceptionSafe,vi as compressClientInfo,Xr as config,yo as createParser,tc as discoverAuthorizationServerMetadata,Js as discoverOAuthProtectedResourceMetadata,rc as exchangeAuthorization,_i as getSessionData,li as initSentrySafe,xi as initializeTrafficMirror,Z as logger,Ti as proxyServer,ic as refreshAuthorization,ac as registerClient,gc as serializeMessage,nc as startAuthorization,ya as startHTTPServer};
|
|
29
|
-
//# sourceMappingURL=stdio-
|
|
29
|
+
//# sourceMappingURL=stdio-Bk0V_i6g.js.map
|