@mcpcloud/runtime 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.19.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.19.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var{create:Ih,defineProperty:$n,getOwnPropertyDescriptor:Oh,getOwnPropertyNames:Nh,getPrototypeOf:jh}=Object,qh=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),fu=(e,t)=>{let r={};for(var o in e)$n(r,o,{get:e[o],enumerable:!0});if(t)$n(r,Symbol.toStringTag,{value:"Module"});return r},xh=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=Nh(t),s=0,a=n.length,i;s<a;s++)if(i=n[s],!qh.call(e,i)&&i!==r)$n(e,i,{get:((c)=>t[c]).bind(null,i),enumerable:!(o=Oh(t,i))||o.enumerable})}return e},Rn=(e,t,r)=>(r=e!=null?Ih(jh(e)):{},xh(t||!e||!e.__esModule?$n(r,"default",{value:e,enumerable:!0}):r,e));var Ah=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),gu=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Mh=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Lh=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function _u(e){return typeof e==="string"&&gu.has(e.replace(/#$/,""))}function Su(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(Ah.has(r))return"2020-12";if(gu.has(r))return"2019-09";if(Mh.has(r)||Lh.has(r))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var yu,Ga=Object.freeze({status:"aborted"});function M(e,t,r){function o(i,c){if(!i._zod)Object.defineProperty(i,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1});if(i._zod.traits.has(e))return;i._zod.traits.add(e),t(i,c);let l=a.prototype,m=Object.keys(l);for(let g=0;g<m.length;g++){let z=m[g];if(!(z in i))i[z]=l[z].bind(i)}}let n=r?.Parent??Object;class s extends n{}Object.defineProperty(s,"name",{value:e});function a(i){var c;let l=r?.Parent?new s:this;o(l,i),(c=l._zod).deferred??(c.deferred=[]);for(let m of l._zod.deferred)m();return l}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:(i)=>{if(r?.Parent&&i instanceof r.Parent)return!0;return i?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}var Zh=Symbol("zod_brand");class ut extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class uo extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(yu=globalThis).__zod_globalConfig??(yu.__zod_globalConfig={});var lr=globalThis.__zod_globalConfig;function Ke(e){if(e)Object.assign(lr,e);return lr}function Pn(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Ya(e,t="|"){return e.map((r)=>ti(r)).join(t)}function lo(e,t){if(typeof t==="bigint")return t.toString();return t}function mo(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function En(e){return e===null||e===void 0}function Tn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function bu(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var vu=Symbol("evaluating");function _e(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===vu)return;if(o===void 0)o=vu,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Vt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function St(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Xa(e){return JSON.stringify(e)}function zu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Qa="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function dr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var $u=mo(()=>{if(lr.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ft(e){if(dr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(dr(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function ei(e){if(Ft(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Ru=new Set(["string","number","symbol"]);function yt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function X(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function ti(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function wu(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Pu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Dh(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=St(e._zod.def,{get shape(){let a={};for(let i in t){if(!(i in r.shape))throw Error(`Unrecognized key: "${i}"`);if(!t[i])continue;a[i]=r.shape[i]}return Vt(this,"shape",a),a},checks:[]});return rt(e,s)}function Uh(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=St(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let i in t){if(!(i in r.shape))throw Error(`Unrecognized key: "${i}"`);if(!t[i])continue;delete a[i]}return Vt(this,"shape",a),a},checks:[]});return rt(e,s)}function Vh(e,t){if(!Ft(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=St(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Vt(this,"shape",s),s}});return rt(e,n)}function Fh(e,t){if(!Ft(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=St(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Vt(this,"shape",o),o}});return rt(e,r)}function Hh(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=St(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return Vt(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return rt(e,r)}function Jh(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=St(t._zod.def,{get shape(){let i=t._zod.def.shape,c={...i};if(r)for(let l in r){if(!(l in i))throw Error(`Unrecognized key: "${l}"`);if(!r[l])continue;c[l]=e?new e({type:"optional",innerType:i[l]}):i[l]}else for(let l in i)c[l]=e?new e({type:"optional",innerType:i[l]}):i[l];return Vt(this,"shape",c),c},checks:[]});return rt(t,a)}function Bh(e,t,r){let o=St(t._zod.def,{get shape(){let n=t._zod.def.shape,s={...n};if(r)for(let a in r){if(!(a in s))throw Error(`Unrecognized key: "${a}"`);if(!r[a])continue;s[a]=new e({type:"nonoptional",innerType:n[a]})}else for(let a in n)s[a]=new e({type:"nonoptional",innerType:n[a]});return Vt(this,"shape",s),s}});return rt(t,o)}function Ht(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Eu(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function vt(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function wn(e){return typeof e==="string"?e:e?.message}function ot(e,t,r){let o=e.message?e.message:wn(e.inst?._zod.def?.error?.(e))??wn(t?.error?.(e))??wn(r.customError?.(e))??wn(r.localeError?.(e))??"Invalid input",{inst:n,continue:s,input:a,...i}=e;if(i.path??(i.path=[]),i.message=o,t?.reportInput)i.input=a;return i}function kn(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Tu(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Jt(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var ku=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,lo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cn=M("$ZodError",ku),ri=M("$ZodError",ku,{Parent:Error});function oi(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function ni(e,t=(r)=>r.message){let r={_errors:[]},o=(n,s=[])=>{for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((i)=>o({issues:i},[...s,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...s,...a.path]);else{let i=[...s,...a.path];if(i.length===0)r._errors.push(t(a));else{let c=r,l=0;while(l<i.length){let m=i[l];if(l!==i.length-1)c[m]=c[m]||{_errors:[]};else c[m]=c[m]||{_errors:[]},c[m]._errors.push(t(a));c=c[m],l++}}}};return o(e),r}var In=(e)=>(t,r,o,n)=>{let s=o?{...o,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new ut;if(a.issues.length){let i=new(n?.Err??e)(a.issues.map((c)=>ot(c,s,Ke())));throw Qa(i,n?.callee),i}return a.value};var On=(e)=>async(t,r,o,n)=>{let s=o?{...o,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let i=new(n?.Err??e)(a.issues.map((c)=>ot(c,s,Ke())));throw Qa(i,n?.callee),i}return a.value};var po=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new ut;return s.issues.length?{success:!1,error:new(e??Cn)(s.issues.map((a)=>ot(a,n,Ke())))}:{success:!0,data:s.value}},Cu=po(ri),ho=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((a)=>ot(a,n,Ke())))}:{success:!0,data:s.value}},Iu=ho(ri),Ou=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return In(e)(t,r,n)};var Nu=(e)=>(t,r,o)=>In(e)(t,r,o);var ju=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return On(e)(t,r,n)};var qu=(e)=>async(t,r,o)=>On(e)(t,r,o);var xu=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return po(e)(t,r,n)};var Au=(e)=>(t,r,o)=>po(e)(t,r,o);var Mu=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ho(e)(t,r,n)};var Lu=(e)=>async(t,r,o)=>ho(e)(t,r,o);var Zu=/^[cC][0-9a-z]{6,}$/,Du=/^[0-9a-z]+$/,Uu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Vu=/^[0-9a-vA-V]{20}$/,Fu=/^[A-Za-z0-9]{27}$/,Hu=/^[a-zA-Z0-9_-]{21}$/,Ju=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Bu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,si=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var Ku=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Gh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Gu(){return new RegExp(Gh,"u")}var Wu=/^(?:(?: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])$/,Yu=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var Xu=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Qu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,el=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ai=/^[A-Za-z0-9_-]*$/;var tl=/^https?$/,rl=/^\+[1-9]\d{6,14}$/,ol="(?:(?:\\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])))",nl=new RegExp(`^${ol}$`);function sl(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function al(e){return new RegExp(`^${sl(e)}$`)}function il(e){let t=sl({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${ol}T(?:${o})$`)}var cl=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var ul=/^-?\d+$/,ii=/^-?\d+(?:\.\d+)?$/,ll=/^(?:true|false)$/i,dl=/^null$/i;var ml=/^[^A-Z]*$/,pl=/^[^a-z]*$/;var Me=M("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),hl={number:"number",bigint:"bigint",object:"date"},ci=M("$ZodCheckLessThan",(e,t)=>{Me.init(e,t);let r=hl[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ui=M("$ZodCheckGreaterThan",(e,t)=>{Me.init(e,t);let r=hl[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),fl=M("$ZodCheckMultipleOf",(e,t)=>{Me.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):bu(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),gl=M("$ZodCheckNumberFormat",(e,t)=>{Me.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,s]=Pu[t.format];e._zod.onattach.push((a)=>{let i=a._zod.bag;if(i.format=t.format,i.minimum=n,i.maximum=s,r)i.pattern=ul}),e._zod.check=(a)=>{let i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:i,inst:e});return}if(!Number.isSafeInteger(i)){if(i>0)a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(i<n)a.issues.push({origin:"number",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(i>s)a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var _l=M("$ZodCheckMaxLength",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!En(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let a=kn(n);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Sl=M("$ZodCheckMinLength",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!En(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let a=kn(n);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),yl=M("$ZodCheckLengthEquals",(e,t)=>{var r;Me.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!En(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,s=n.length;if(s===t.length)return;let a=kn(n),i=s>t.length;o.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),go=M("$ZodCheckStringFormat",(e,t)=>{var r,o;if(Me.init(e,t),e._zod.onattach.push((n)=>{let s=n._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),vl=M("$ZodCheckRegex",(e,t)=>{go.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),bl=M("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ml),go.init(e,t)}),zl=M("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=pl),go.init(e,t)}),$l=M("$ZodCheckIncludes",(e,t)=>{Me.init(e,t);let r=yt(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Rl=M("$ZodCheckStartsWith",(e,t)=>{Me.init(e,t);let r=new RegExp(`^${yt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),wl=M("$ZodCheckEndsWith",(e,t)=>{Me.init(e,t);let r=new RegExp(`.*${yt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var Pl=M("$ZodCheckOverwrite",(e,t)=>{Me.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class li{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
3
3
  `).filter((s)=>s),o=Math.min(...r.map((s)=>s.length-s.trimStart().length)),n=r.map((s)=>s.slice(o)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of n)this.content.push(s)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
4
4
  `))}}var Tl={major:4,minor:4,patch:3};var Se=M("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Tl;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let s of n._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(a,i,c)=>{let l=Ht(a),m;for(let g of i){if(g._zod.def.when){if(Eu(a))continue;if(!g._zod.def.when(a))continue}else if(l)continue;let z=a.issues.length,w=g._zod.check(a);if(w instanceof Promise&&c?.async===!1)throw new ut;if(m||w instanceof Promise)m=(m??Promise.resolve()).then(async()=>{if(await w,a.issues.length===z)return;if(!l)l=Ht(a,z)});else{if(a.issues.length===z)continue;if(!l)l=Ht(a,z)}}if(m)return m.then(()=>a);return a},s=(a,i,c)=>{if(Ht(a))return a.aborted=!0,a;let l=n(i,o,c);if(l instanceof Promise){if(c.async===!1)throw new ut;return l.then((m)=>e._zod.parse(m,c))}return e._zod.parse(l,c)};e._zod.run=(a,i)=>{if(i.skipChecks)return e._zod.parse(a,i);if(i.direction==="backward"){let l=e._zod.parse({value:a.value,issues:[]},{...i,skipChecks:!0});if(l instanceof Promise)return l.then((m)=>s(m,a,i));return s(l,a,i)}let c=e._zod.parse(a,i);if(c instanceof Promise){if(i.async===!1)throw new ut;return c.then((l)=>n(l,o,i))}return n(c,o,i)}}_e(e,"~standard",()=>({validate:(n)=>{try{let s=Cu(e,n);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Iu(e,n).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),qn=M("$ZodString",(e,t)=>{Se.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??cl(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$e=M("$ZodStringFormat",(e,t)=>{go.init(e,t),qn.init(e,t)}),Al=M("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Bu),$e.init(e,t)}),Ml=M("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=si(o))}else t.pattern??(t.pattern=si());$e.init(e,t)}),Ll=M("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ku),$e.init(e,t)}),Zl=M("$ZodURL",(e,t)=>{$e.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===tl.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Dl=M("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Gu()),$e.init(e,t)}),Ul=M("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Hu),$e.init(e,t)}),Vl=M("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Zu),$e.init(e,t)}),Fl=M("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Du),$e.init(e,t)}),Hl=M("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Uu),$e.init(e,t)}),Jl=M("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Vu),$e.init(e,t)}),Bl=M("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Fu),$e.init(e,t)}),Kl=M("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=il(t)),$e.init(e,t)}),Gl=M("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=nl),$e.init(e,t)}),Wl=M("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=al(t)),$e.init(e,t)}),Yl=M("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ju),$e.init(e,t)}),Xl=M("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Wu),$e.init(e,t),e._zod.bag.format="ipv4"}),Ql=M("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Yu),$e.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var ed=M("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Xu),$e.init(e,t)}),td=M("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Qu),$e.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,s]=o;if(!s)throw Error();let a=Number(s);if(`${a}`!==s)throw Error();if(a<0||a>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function rd(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var od=M("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=el),$e.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(rd(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Wh(e){if(!ai.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return rd(r)}var nd=M("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ai),$e.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(Wh(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),sd=M("$ZodE164",(e,t)=>{t.pattern??(t.pattern=rl),$e.init(e,t)});function Yh(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var ad=M("$ZodJWT",(e,t)=>{$e.init(e,t),e._zod.check=(r)=>{if(Yh(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var mi=M("$ZodNumber",(e,t)=>{Se.init(e,t),e._zod.pattern=e._zod.bag.pattern??ii,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(a){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...s?{received:s}:{}}),r}}),id=M("$ZodNumberFormat",(e,t)=>{gl.init(e,t),mi.init(e,t)}),cd=M("$ZodBoolean",(e,t)=>{Se.init(e,t),e._zod.pattern=ll,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var ud=M("$ZodNull",(e,t)=>{Se.init(e,t),e._zod.pattern=dl,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),ld=M("$ZodAny",(e,t)=>{Se.init(e,t),e._zod.parse=(r)=>r}),dd=M("$ZodUnknown",(e,t)=>{Se.init(e,t),e._zod.parse=(r)=>r}),md=M("$ZodNever",(e,t)=>{Se.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function kl(e,t,r){if(e.issues.length)t.issues.push(...vt(r,e.issues));t.value[r]=e.value}var pd=M("$ZodArray",(e,t)=>{Se.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let s=[];for(let a=0;a<n.length;a++){let i=n[a],c=t.element._zod.run({value:i,issues:[]},o);if(c instanceof Promise)s.push(c.then((l)=>kl(l,r,a)));else kl(c,r,a)}if(s.length)return Promise.all(s).then(()=>r);return r}});function jn(e,t,r,o,n,s){let a=r in o;if(e.issues.length){if(n&&s&&!a)return;t.issues.push(...vt(r,e.issues))}if(!a&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(a)t.value[r]=void 0}else t.value[r]=e.value}function hd(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=wu(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function fd(e,t,r,o,n,s){let a=[],i=n.keySet,c=n.catchall._zod,l=c.def.type,m=c.optin==="optional",g=c.optout==="optional";for(let z in t){if(z==="__proto__")continue;if(i.has(z))continue;if(l==="never"){a.push(z);continue}let w=c.run({value:t[z],issues:[]},o);if(w instanceof Promise)e.push(w.then((_)=>jn(_,r,z,t,m,g)));else jn(w,r,z,t,m,g)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}var Xh=M("$ZodObject",(e,t)=>{if(Se.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let i=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...i};return Object.defineProperty(t,"shape",{value:c}),c}})}let o=mo(()=>hd(t));_e(e._zod,"propValues",()=>{let i=t.shape,c={};for(let l in i){let m=i[l]._zod;if(m.values){c[l]??(c[l]=new Set);for(let g of m.values)c[l].add(g)}}return c});let n=dr,s=t.catchall,a;e._zod.parse=(i,c)=>{a??(a=o.value);let l=i.value;if(!n(l))return i.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),i;i.value={};let m=[],g=a.shape;for(let z of a.keys){let w=g[z],_=w._zod.optin==="optional",b=w._zod.optout==="optional",f=w._zod.run({value:l[z],issues:[]},c);if(f instanceof Promise)m.push(f.then((d)=>jn(d,i,z,l,_,b)));else jn(f,i,z,l,_,b)}if(!s)return m.length?Promise.all(m).then(()=>i):i;return fd(m,l,i,c,o.value,e)}}),gd=M("$ZodObjectJIT",(e,t)=>{Xh.init(e,t);let r=e._zod.parse,o=mo(()=>hd(t)),n=(z)=>{let w=new li(["shape","payload","ctx"]),_=o.value,b=(p)=>{let S=Xa(p);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};w.write("const input = payload.value;");let f=Object.create(null),d=0;for(let p of _.keys)f[p]=`key_${d++}`;w.write("const newResult = {};");for(let p of _.keys){let S=f[p],P=Xa(p),y=z[p],h=y?._zod?.optin==="optional",E=y?._zod?.optout==="optional";if(w.write(`const ${S} = ${b(p)};`),h&&E)w.write(`
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.19.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.19.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var wk=Object.create;var{getPrototypeOf:Rk,defineProperty:Hd,getOwnPropertyNames:xk}=Object;var CS=Object.prototype.hasOwnProperty;function kk(e){return this[e]}var Ik,Pk,Ek=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var r=t?Ik??=new WeakMap:Pk??=new WeakMap,i=r.get(e);if(i)return i}n=e!=null?wk(Rk(e)):{};let a=t||!e||!e.__esModule||!CS.call(e,"default")?Hd(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of xk(e))if(!CS.call(a,s))Hd(a,s,{get:kk.bind(e,s),enumerable:!0})}if(o)r.set(e,a);return a};var U=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Tk=(e)=>e;function jk(e,t){this[e]=Tk.bind(null,t)}var tr=(e,t)=>{for(var n in t)Hd(e,n,{get:t[n],enumerable:!0,configurable:!0,set:jk.bind(t,n)})};var Va=U(function(uz){Object.defineProperty(uz,"__esModule",{value:!0});uz.regexpCode=uz.getEsmExportName=uz.getProperty=uz.safeStringify=uz.stringify=uz.strConcat=uz.addCodeArg=uz.str=uz._=uz.nil=uz._Code=uz.Name=uz.IDENTIFIER=uz._CodeOrName=void 0;class ld{}uz._CodeOrName=ld;uz.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Uo extends ld{constructor(e){super();if(!uz.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}uz.Name=Uo;class Et extends ld{constructor(e){super();this._items=typeof e==="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>{if(n instanceof Uo)t[n.str]=(t[n.str]||0)+1;return t},{})}}uz._Code=Et;uz.nil=new Et("");function cz(e,...t){let n=[e[0]],o=0;while(o<t.length)Z_(n,t[o]),n.push(e[++o]);return new Et(n)}uz._=cz;var L_=new Et("+");function lz(e,...t){let n=[Za(e[0])],o=0;while(o<t.length)n.push(L_),Z_(n,t[o]),n.push(L_,Za(e[++o]));return UT(n),new Et(n)}uz.str=lz;function Z_(e,t){if(t instanceof Et)e.push(...t._items);else if(t instanceof Uo)e.push(t);else e.push(ZT(t))}uz.addCodeArg=Z_;function UT(e){let t=1;while(t<e.length-1){if(e[t]===L_){let n=DT(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function DT(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof Uo||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Uo))return`"${e}${t.slice(1)}`;return}function LT(e,t){return t.emptyStr()?e:e.emptyStr()?t:lz`${e}${t}`}uz.strConcat=LT;function ZT(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Za(Array.isArray(e)?e.join(","):e)}function VT(e){return new Et(Za(e))}uz.stringify=VT;function Za(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}uz.safeStringify=Za;function FT(e){return typeof e=="string"&&uz.IDENTIFIER.test(e)?new Et(`.${e}`):cz`[${e}]`}uz.getProperty=FT;function JT(e){if(typeof e=="string"&&uz.IDENTIFIER.test(e))return new Et(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}uz.getEsmExportName=JT;function HT(e){return new Et(e.toString())}uz.regexpCode=HT});var H_=U(function(fz){Object.defineProperty(fz,"__esModule",{value:!0});fz.ValueScope=fz.ValueScopeName=fz.Scope=fz.varKinds=fz.UsedValueState=void 0;var ot=Va();class mz extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var dd;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(dd||(fz.UsedValueState=dd={}));fz.varKinds={const:new ot.Name("const"),let:new ot.Name("let"),var:new ot.Name("var")};class F_{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ot.Name?e:this.name(e)}name(e){return new ot.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0?void 0:n.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}fz.Scope=F_;class J_ extends ot.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=ot._`.${new ot.Name(t)}[${n}]`}}fz.ValueScopeName=J_;var i1=ot._`\n`;class pz extends F_{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?i1:ot.nil}}get(){return this._scope}name(e){return new J_(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:r}=o,i=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[r];if(a){let l=a.get(i);if(l)return l}else a=this._values[r]=new Map;a.set(i,o);let s=this._scope[r]||(this._scope[r]=[]),c=s.length;return s[c]=t.ref,o.setValue(t,{property:r,itemIndex:c}),o}getValue(e,t){let n=this._values[e];if(!n)return;return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(n)=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return ot._`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,(o)=>{if(o.value===void 0)throw Error(`CodeGen: name "${o}" has no value`);return o.value.code},t,n)}_reduceValues(e,t,n={},o){let r=ot.nil;for(let i in e){let a=e[i];if(!a)continue;let s=n[i]=n[i]||new Map;a.forEach((c)=>{if(s.has(c))return;s.set(c,dd.Started);let l=t(c);if(l){let d=this.opts.es5?fz.varKinds.var:fz.varKinds.const;r=ot._`${r}${d} ${c} = ${l};${this.opts._n}`}else if(l=o===null||o===void 0?void 0:o(c))r=ot._`${r}${l}${this.opts._n}`;else throw new mz(c);s.set(c,dd.Completed)})}return r}}fz.ValueScope=pz});var ce=U(function(it){Object.defineProperty(it,"__esModule",{value:!0});it.or=it.and=it.not=it.CodeGen=it.operators=it.varKinds=it.ValueScopeName=it.ValueScope=it.Scope=it.Name=it.regexpCode=it.stringify=it.getProperty=it.nil=it.strConcat=it.str=it._=void 0;var le=Va(),Tt=H_(),Vr=Va();Object.defineProperty(it,"_",{enumerable:!0,get:function(){return Vr._}});Object.defineProperty(it,"str",{enumerable:!0,get:function(){return Vr.str}});Object.defineProperty(it,"strConcat",{enumerable:!0,get:function(){return Vr.strConcat}});Object.defineProperty(it,"nil",{enumerable:!0,get:function(){return Vr.nil}});Object.defineProperty(it,"getProperty",{enumerable:!0,get:function(){return Vr.getProperty}});Object.defineProperty(it,"stringify",{enumerable:!0,get:function(){return Vr.stringify}});Object.defineProperty(it,"regexpCode",{enumerable:!0,get:function(){return Vr.regexpCode}});Object.defineProperty(it,"Name",{enumerable:!0,get:function(){return Vr.Name}});var vd=H_();Object.defineProperty(it,"Scope",{enumerable:!0,get:function(){return vd.Scope}});Object.defineProperty(it,"ValueScope",{enumerable:!0,get:function(){return vd.ValueScope}});Object.defineProperty(it,"ValueScopeName",{enumerable:!0,get:function(){return vd.ValueScopeName}});Object.defineProperty(it,"varKinds",{enumerable:!0,get:function(){return vd.varKinds}});it.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};class Fr{optimizeNodes(){return this}optimizeNames(e,t){return this}}class gz extends Fr{constructor(e,t,n){super();this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Tt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=Lo(this.rhs,e,t);return this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}}class B_ extends Fr{constructor(e,t,n){super();this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof le.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=Lo(this.rhs,e,t),this}get names(){let e=this.lhs instanceof le.Name?{}:{...this.lhs.names};return gd(e,this.rhs)}}class vz extends B_{constructor(e,t,n,o){super(e,n,o);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class _z extends Fr{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class Sz extends Fr{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class yz extends Fr{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class bz extends Fr{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=Lo(this.code,e,t),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}}class _d extends Fr{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let n=e[t].optimizeNodes();if(Array.isArray(n))e.splice(t,1,...n);else if(n)e[t]=n;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,o=n.length;while(o--){let r=n[o];if(r.optimizeNames(e,t))continue;l1(e,r.names),n.splice(o,1)}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>xn(e,t.names),{})}}class Jr extends _d{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class $z extends _d{}class Fa extends Jr{}Fa.kind="else";class dr extends Jr{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Fa(n):n}if(t){if(e===!1)return t instanceof dr?t:t.nodes;if(this.nodes.length)return this;return new dr(kz(e),t instanceof dr?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=Lo(this.condition,e,t),this}get names(){let e=super.names;if(gd(e,this.condition),this.else)xn(e,this.else.names);return e}}dr.kind="if";class Do extends Jr{}Do.kind="for";class zz extends Do{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=Lo(this.iteration,e,t),this}get names(){return xn(super.names,this.iteration.names)}}class wz extends Do{constructor(e,t,n,o){super();this.varKind=e,this.name=t,this.from=n,this.to=o}render(e){let t=e.es5?Tt.varKinds.var:this.varKind,{name:n,from:o,to:r}=this;return`for(${t} ${n}=${o}; ${n}<${r}; ${n}++)`+super.render(e)}get names(){let e=gd(super.names,this.from);return gd(e,this.to)}}class K_ extends Do{constructor(e,t,n,o){super();this.loop=e,this.varKind=t,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=Lo(this.iterable,e,t),this}get names(){return xn(super.names,this.iterable.names)}}class md extends Jr{constructor(e,t,n){super();this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}md.kind="func";class pd extends _d{render(e){return"return "+super.render(e)}}pd.kind="return";class Rz extends Jr{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,o;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(o=this.finally)===null||o===void 0||o.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)xn(e,this.catch.names);if(this.finally)xn(e,this.finally.names);return e}}class fd extends Jr{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}fd.kind="catch";class hd extends Jr{render(e){return"finally"+super.render(e)}}hd.kind="finally";class xz{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
3
3
  `:""},this._extScope=e,this._scope=new Tt.Scope({parent:e}),this._nodes=[new $z]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,o){let r=this._scope.toName(t);if(n!==void 0&&o)this._constants[r.str]=n;return this._leafNode(new gz(e,r,n)),r}const(e,t,n){return this._def(Tt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Tt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Tt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new B_(e,t,n))}add(e,t){return this._leafNode(new vz(e,it.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==le.nil)this._leafNode(new bz(e));return this}object(...e){let t=["{"];for(let[n,o]of e){if(t.length>1)t.push(",");if(t.push(n),n!==o||this.opts.es5)t.push(":"),le.addCodeArg(t,o)}return t.push("}"),new le._Code(t)}if(e,t,n){if(this._blockNode(new dr(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new dr(e))}else(){return this._elseNode(new Fa)}endIf(){return this._endBlockNode(dr,Fa)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new zz(e),t)}forRange(e,t,n,o,r=this.opts.es5?Tt.varKinds.var:Tt.varKinds.let){let i=this._scope.toName(e);return this._for(new wz(r,i,t,n),()=>o(i))}forOf(e,t,n,o=Tt.varKinds.const){let r=this._scope.toName(e);if(this.opts.es5){let i=t instanceof le.Name?t:this.var("_arr",t);return this.forRange("_i",0,le._`${i}.length`,(a)=>{this.var(r,le._`${i}[${a}]`),n(r)})}return this._for(new K_("of",o,r,t),()=>n(r))}forIn(e,t,n,o=this.opts.es5?Tt.varKinds.var:Tt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,le._`Object.keys(${t})`,n);let r=this._scope.toName(e);return this._for(new K_("in",o,r,t),()=>n(r))}endFor(){return this._endBlockNode(Do)}label(e){return this._leafNode(new _z(e))}break(e){return this._leafNode(new Sz(e))}return(e){let t=new pd;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(pd)}try(e,t,n){if(!t&&!n)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new Rz;if(this._blockNode(o),this.code(e),t){let r=this.name("e");this._currNode=o.catch=new fd(r),t(r)}if(n)this._currNode=o.finally=new hd,this.code(n);return this._endBlockNode(fd,hd)}throw(e){return this._leafNode(new yz(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=le.nil,n,o){if(this._blockNode(new md(e,t,n)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(md)}optimize(e=1){while(e-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof dr))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}it.CodeGen=xz;function xn(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function gd(e,t){return t instanceof le._CodeOrName?xn(e,t.names):e}function Lo(e,t,n){if(e instanceof le.Name)return o(e);if(!r(e))return e;return new le._Code(e._items.reduce((i,a)=>{if(a instanceof le.Name)a=o(a);if(a instanceof le._Code)i.push(...a._items);else i.push(a);return i},[]));function o(i){let a=n[i.str];if(a===void 0||t[i.str]!==1)return i;return delete t[i.str],a}function r(i){return i instanceof le._Code&&i._items.some((a)=>a instanceof le.Name&&t[a.str]===1&&n[a.str]!==void 0)}}function l1(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function kz(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:le._`!${G_(e)}`}it.not=kz;var u1=Iz(it.operators.AND);function d1(...e){return e.reduce(u1)}it.and=d1;var m1=Iz(it.operators.OR);function p1(...e){return e.reduce(m1)}it.or=p1;function Iz(e){return(t,n)=>t===le.nil?n:n===le.nil?t:le._`${G_(t)} ${e} ${G_(n)}`}function G_(e){return e instanceof le.Name?e:le._`(${e})`}});var de=U(function(Az){Object.defineProperty(Az,"__esModule",{value:!0});Az.checkStrictMode=Az.getErrorPath=Az.Type=Az.useFunc=Az.setEvaluated=Az.evaluatedPropsToName=Az.mergeEvaluated=Az.eachItem=Az.unescapeJsonPointer=Az.escapeJsonPointer=Az.escapeFragment=Az.unescapeFragment=Az.schemaRefOrVal=Az.schemaHasRulesButRef=Az.schemaHasRules=Az.checkUnknownRules=Az.alwaysValidSchema=Az.toHash=void 0;var ve=ce(),v1=Va();function _1(e){let t={};for(let n of e)t[n]=!0;return t}Az.toHash=_1;function S1(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return jz(e,t),!Oz(t,e.self.RULES.all)}Az.alwaysValidSchema=S1;function jz(e,t=e.schema){let{opts:n,self:o}=e;if(!n.strictSchema)return;if(typeof t==="boolean")return;let r=o.RULES.keywords;for(let i in t)if(!r[i])qz(e,`unknown keyword: "${i}"`)}Az.checkUnknownRules=jz;function Oz(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}Az.schemaHasRules=Oz;function y1(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}Az.schemaHasRulesButRef=y1;function b1({topSchemaRef:e,schemaPath:t},n,o,r){if(!r){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return ve._`${n}`}return ve._`${e}${t}${ve.getProperty(o)}`}Az.schemaRefOrVal=b1;function $1(e){return Nz(decodeURIComponent(e))}Az.unescapeFragment=$1;function z1(e){return encodeURIComponent(Y_(e))}Az.escapeFragment=z1;function Y_(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}Az.escapeJsonPointer=Y_;function Nz(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Az.unescapeJsonPointer=Nz;function w1(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}Az.eachItem=w1;function Ez({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:o}){return(r,i,a,s)=>{let c=a===void 0?i:a instanceof ve.Name?(i instanceof ve.Name?e(r,i,a):t(r,i,a),a):i instanceof ve.Name?(t(r,a,i),i):n(i,a);return s===ve.Name&&!(c instanceof ve.Name)?o(r,c):c}}Az.mergeEvaluated={props:Ez({mergeNames:(e,t,n)=>e.if(ve._`${n} !== true && ${t} !== undefined`,()=>{e.if(ve._`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,ve._`${n} || {}`).code(ve._`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if(ve._`${n} !== true`,()=>{if(t===!0)e.assign(n,!0);else e.assign(n,ve._`${n} || {}`),X_(e,n,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Cz}),items:Ez({mergeNames:(e,t,n)=>e.if(ve._`${n} !== true && ${t} !== undefined`,()=>e.assign(n,ve._`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if(ve._`${n} !== true`,()=>e.assign(n,t===!0?!0:ve._`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Cz(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",ve._`{}`);if(t!==void 0)X_(e,n,t);return n}Az.evaluatedPropsToName=Cz;function X_(e,t,n){Object.keys(n).forEach((o)=>e.assign(ve._`${t}${ve.getProperty(o)}`,!0))}Az.setEvaluated=X_;var Tz={};function R1(e,t){return e.scopeValue("func",{ref:t,code:Tz[t.code]||(Tz[t.code]=new v1._Code(t.code))})}Az.useFunc=R1;var W_;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(W_||(Az.Type=W_={}));function x1(e,t,n){if(e instanceof ve.Name){let o=t===W_.Num;return n?o?ve._`"[" + ${e} + "]"`:ve._`"['" + ${e} + "']"`:o?ve._`"/" + ${e}`:ve._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?ve.getProperty(e).toString():"/"+Y_(e)}Az.getErrorPath=x1;function qz(e,t,n=e.opts.strictSchema){if(!n)return;if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}Az.checkStrictMode=qz});var mr=U(function(Uz){Object.defineProperty(Uz,"__esModule",{value:!0});var De=ce(),F1={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};Uz.default=F1});var Ja=U(function(Vz){Object.defineProperty(Vz,"__esModule",{value:!0});Vz.extendErrors=Vz.resetErrorsCount=Vz.reportExtraError=Vz.reportError=Vz.keyword$DataError=Vz.keywordError=void 0;var me=ce(),yd=de(),Be=mr();Vz.keywordError={message:({keyword:e})=>me.str`must pass "${e}" keyword validation`};Vz.keyword$DataError={message:({keyword:e,schemaType:t})=>t?me.str`"${e}" keyword must be ${t} ($data)`:me.str`"${e}" keyword is invalid ($data)`};function H1(e,t=Vz.keywordError,n,o){let{it:r}=e,{gen:i,compositeRule:a,allErrors:s}=r,c=Zz(e,t,n);if(o!==null&&o!==void 0?o:a||s)Dz(i,c);else Lz(r,me._`[${c}]`)}Vz.reportError=H1;function K1(e,t=Vz.keywordError,n){let{it:o}=e,{gen:r,compositeRule:i,allErrors:a}=o,s=Zz(e,t,n);if(Dz(r,s),!(i||a))Lz(o,Be.default.vErrors)}Vz.reportExtraError=K1;function G1(e,t){e.assign(Be.default.errors,t),e.if(me._`${Be.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(me._`${Be.default.vErrors}.length`,t),()=>e.assign(Be.default.vErrors,null)))}Vz.resetErrorsCount=G1;function B1({gen:e,keyword:t,schemaValue:n,data:o,errsCount:r,it:i}){if(r===void 0)throw Error("ajv implementation error");let a=e.name("err");e.forRange("i",r,Be.default.errors,(s)=>{if(e.const(a,me._`${Be.default.vErrors}[${s}]`),e.if(me._`${a}.instancePath === undefined`,()=>e.assign(me._`${a}.instancePath`,me.strConcat(Be.default.instancePath,i.errorPath))),e.assign(me._`${a}.schemaPath`,me.str`${i.errSchemaPath}/${t}`),i.opts.verbose)e.assign(me._`${a}.schema`,n),e.assign(me._`${a}.data`,o)})}Vz.extendErrors=B1;function Dz(e,t){let n=e.const("err",t);e.if(me._`${Be.default.vErrors} === null`,()=>e.assign(Be.default.vErrors,me._`[${n}]`),me._`${Be.default.vErrors}.push(${n})`),e.code(me._`${Be.default.errors}++`)}function Lz(e,t){let{gen:n,validateName:o,schemaEnv:r}=e;if(r.$async)n.throw(me._`new ${e.ValidationError}(${t})`);else n.assign(me._`${o}.errors`,t),n.return(!1)}var kn={keyword:new me.Name("keyword"),schemaPath:new me.Name("schemaPath"),params:new me.Name("params"),propertyName:new me.Name("propertyName"),message:new me.Name("message"),schema:new me.Name("schema"),parentSchema:new me.Name("parentSchema")};function Zz(e,t,n){let{createErrors:o}=e.it;if(o===!1)return me._`{}`;return W1(e,t,n)}function W1(e,t,n={}){let{gen:o,it:r}=e,i=[Y1(r,n),X1(e,n)];return Q1(e,t,i),o.object(...i)}function Y1({errorPath:e},{instancePath:t}){let n=t?me.str`${e}${yd.getErrorPath(t,yd.Type.Str)}`:e;return[Be.default.instancePath,me.strConcat(Be.default.instancePath,n)]}function X1({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:o}){let r=o?t:me.str`${t}/${e}`;if(n)r=me.str`${r}${yd.getErrorPath(n,yd.Type.Str)}`;return[kn.schemaPath,r]}function Q1(e,{params:t,message:n},o){let{keyword:r,data:i,schemaValue:a,it:s}=e,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:m}=s;if(o.push([kn.keyword,r],[kn.params,typeof t=="function"?t(e):t||me._`{}`]),c.messages)o.push([kn.message,typeof n=="function"?n(e):n]);if(c.verbose)o.push([kn.schema,a],[kn.parentSchema,me._`${d}${m}`],[Be.default.data,i]);if(l)o.push([kn.propertyName,l])}});var Gz=U(function(Hz){Object.defineProperty(Hz,"__esModule",{value:!0});Hz.boolOrEmptySchema=Hz.topBoolOrEmptySchema=void 0;var oj=Ja(),ij=ce(),aj=mr(),sj={message:"boolean schema is false"};function cj(e){let{gen:t,schema:n,validateName:o}=e;if(n===!1)Jz(e,!1);else if(typeof n=="object"&&n.$async===!0)t.return(aj.default.data);else t.assign(ij._`${o}.errors`,null),t.return(!0)}Hz.topBoolOrEmptySchema=cj;function lj(e,t){let{gen:n,schema:o}=e;if(o===!1)n.var(t,!1),Jz(e);else n.var(t,!0)}Hz.boolOrEmptySchema=lj;function Jz(e,t){let{gen:n,data:o}=e;oj.reportError({gen:n,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e},sj,void 0,t)}});var eS=U(function(Bz){Object.defineProperty(Bz,"__esModule",{value:!0});Bz.getRules=Bz.isJSONType=void 0;var dj=["string","number","integer","boolean","null","object","array"],mj=new Set(dj);function pj(e){return typeof e=="string"&&mj.has(e)}Bz.isJSONType=pj;function fj(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Bz.getRules=fj});var tS=U(function(Qz){Object.defineProperty(Qz,"__esModule",{value:!0});Qz.shouldUseRule=Qz.shouldUseGroup=Qz.schemaHasRulesForType=void 0;function gj({schema:e,self:t},n){let o=t.RULES.types[n];return o&&o!==!0&&Yz(e,o)}Qz.schemaHasRulesForType=gj;function Yz(e,t){return t.rules.some((n)=>Xz(e,n))}Qz.shouldUseGroup=Yz;function Xz(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some((o)=>e[o]!==void 0))}Qz.shouldUseRule=Xz});var Ha=U(function(ow){Object.defineProperty(ow,"__esModule",{value:!0});ow.reportTypeError=ow.checkDataTypes=ow.checkDataType=ow.coerceAndCheckDataType=ow.getJSONTypes=ow.getSchemaTypes=ow.DataType=void 0;var Sj=eS(),yj=tS(),bj=Ja(),ie=ce(),tw=de(),Zo;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Zo||(ow.DataType=Zo={}));function $j(e){let t=rw(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}ow.getSchemaTypes=$j;function rw(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Sj.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ow.getJSONTypes=rw;function zj(e,t){let{gen:n,data:o,opts:r}=e,i=wj(t,r.coerceTypes),a=t.length>0&&!(i.length===0&&t.length===1&&yj.schemaHasRulesForType(e,t[0]));if(a){let s=nS(t,o,r.strictNumbers,Zo.Wrong);n.if(s,()=>{if(i.length)Rj(e,t,i);else oS(e)})}return a}ow.coerceAndCheckDataType=zj;var nw=new Set(["string","number","integer","boolean","null"]);function wj(e,t){return t?e.filter((n)=>nw.has(n)||t==="array"&&n==="array"):[]}function Rj(e,t,n){let{gen:o,data:r,opts:i}=e,a=o.let("dataType",ie._`typeof ${r}`),s=o.let("coerced",ie._`undefined`);if(i.coerceTypes==="array")o.if(ie._`${a} == 'object' && Array.isArray(${r}) && ${r}.length == 1`,()=>o.assign(r,ie._`${r}[0]`).assign(a,ie._`typeof ${r}`).if(nS(t,r,i.strictNumbers),()=>o.assign(s,r)));o.if(ie._`${s} !== undefined`);for(let l of n)if(nw.has(l)||l==="array"&&i.coerceTypes==="array")c(l);o.else(),oS(e),o.endIf(),o.if(ie._`${s} !== undefined`,()=>{o.assign(r,s),xj(e,s)});function c(l){switch(l){case"string":o.elseIf(ie._`${a} == "number" || ${a} == "boolean"`).assign(s,ie._`"" + ${r}`).elseIf(ie._`${r} === null`).assign(s,ie._`""`);return;case"number":o.elseIf(ie._`${a} == "boolean" || ${r} === null
4
4
  || (${a} == "string" && ${r} && ${r} == +${r})`).assign(s,ie._`+${r}`);return;case"integer":o.elseIf(ie._`${a} === "boolean" || ${r} === null
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.19.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.19.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var bt=Object.create;var{getPrototypeOf:Pt,defineProperty:re,getOwnPropertyNames:Ot}=Object;var Qe=Object.prototype.hasOwnProperty;function vt(e){return this[e]}var Mt,xt,Nt=(e,t,r)=>{var o=e!=null&&typeof e==="object";if(o){var l=t?Mt??=new WeakMap:xt??=new WeakMap,d=l.get(e);if(d)return d}r=e!=null?bt(Pt(e)):{};let f=t||!e||!e.__esModule||!Qe.call(e,"default")?re(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let s of Ot(e))if(!Qe.call(f,s))re(f,s,{get:vt.bind(e,s),enumerable:!0})}if(o)l.set(e,f);return f};var Ct=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var kt=(e)=>e;function It(e,t){this[e]=kt.bind(null,t)}var Lt=(e,t)=>{for(var r in t)re(e,r,{get:t[r],enumerable:!0,configurable:!0,set:It.bind(t,r)})};var ne=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(o){r=[o]}if(r)throw r[0];return t};var U,ie,j,K,F;var V=ne(()=>{U={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},ie={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},j={Pending:0,Fulfilled:1,Rejected:2},K={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},F={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function H(...e){ce&&console.log("quickjs-emscripten:",...e)}function*ot(e){return yield e}function Jt(e){return ot(de(e))}function $e(e,t){return(...r)=>{let o=t.call(e,he,...r);return de(o)}}function Dt(e,t){let r=t.call(e,he);return de(r)}function de(e){function t(r){return r.done?r.value:r.value instanceof Promise?r.value.then((o)=>t(e.next(o)),(o)=>t(e.throw(o))):t(e.next(r.value))}return t(e.next())}function se(e,t){let r;try{e.dispose()}catch(o){r=o}if(t&&r)throw Object.assign(t,{message:`${t.message}
3
3
  Then, failed to dispose scope: ${r.message}`,disposeError:r}),t;if(t||r)throw t||r}function Qt(e){let t=e?Array.from(e):[];function r(){return t.forEach((l)=>l.alive?l.dispose():void 0)}function o(){return t.some((l)=>l.alive)}return Object.defineProperty(t,le,{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:o}),t}function W(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Gt(e){if(!e)return 0;let t=0;for(let[r,o]of Object.entries(e)){if(!(r in ie))throw new rt(r);o&&(t|=ie[r])}return t}function Wt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:r,strip:o,compileOnly:l,backtraceBarrier:d}=e,f=0;return t==="global"&&(f|=U.JS_EVAL_TYPE_GLOBAL),t==="module"&&(f|=U.JS_EVAL_TYPE_MODULE),r&&(f|=U.JS_EVAL_FLAG_STRICT),o&&(f|=U.JS_EVAL_FLAG_STRIP),l&&(f|=U.JS_EVAL_FLAG_COMPILE_ONLY),d&&(f|=U.JS_EVAL_FLAG_BACKTRACE_BARRIER),f}function qt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:r,quickjsPrivate:o,onlyEnumerable:l,numbers:d,numbersAsStrings:f}=e,s=0;return t&&(s|=K.JS_GPN_STRING_MASK),r&&(s|=K.JS_GPN_SYMBOL_MASK),o&&(s|=K.JS_GPN_PRIVATE_MASK),l&&(s|=K.JS_GPN_ENUM_ONLY),d&&(s|=K.QTS_GPN_NUMBER_MASK),f&&(s|=K.QTS_STANDARD_COMPLIANT_NUMBER),s}function zt(...e){let t=[];for(let r of e)r!==void 0&&(t=t.concat(r));return t}function oe(e){return e>>8}function pe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function _e(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var Kt,Bt=(e,t)=>{for(var r in t)Kt(e,r,{get:t[r],enumerable:!0})},ce=!1,Yt,ae,Xe,ue,Ze,et,tt,Ft,Ht,rt,nt,it,st,I,he,N,le,Ve,A,B,Ge,M,fe,jt,$t,Y,Vt,at=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((l)=>l.value)),r=t.length*t.BYTES_PER_ELEMENT,o=this.module._malloc(r);return new Uint8Array(this.module.HEAPU8.buffer,o,r).set(new Uint8Array(t.buffer)),new A(o,void 0,(l)=>this.module._free(l))}newTypedArray(e,t){let r=new e(Array(t).fill(0)),o=r.length*r.BYTES_PER_ELEMENT,l=this.module._malloc(o),d=new e(this.module.HEAPU8.buffer,l,t);return d.set(r),new A({typedArray:d,ptr:l},void 0,(f)=>this.module._free(f.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),r=t+1,o=this.module._malloc(r);return this.module.stringToUTF8(e,o,r),new A({ptr:o,strlen:t},void 0,(l)=>this.module._free(l.ptr))}newHeapBufferPointer(e){let t=e.byteLength,r=this.module._malloc(t);return this.module.HEAPU8.set(e,r),new A({pointer:r,numBytes:t},void 0,(o)=>this.module._free(o.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Lr,Ur,Xt,We=-2147483648,qe=2147483647,G=0,Zt=class{constructor(){this.nextId=We,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),r=oe(t),o=this.groups.get(r);return o||(o=new Map,this.groups.set(r,o)),o.set(t,e),t}get(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),r=this.groups.get(t);if(!r)throw new I(`host reference id ${e} is not defined`);let o=r.get(e);if(!o)throw new I(`host reference id ${e} is not defined`);return o}delete(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),r=this.groups.get(t);if(!r)throw new I(`host reference id ${e} is not defined`);r.delete(e),r.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===G&&this.nextId++,this.nextId>qe)throw new st(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${qe-We}`);return this.nextId++}},ze,er,tr,rr,nr=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},me=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new nr({freeHostRef:(t,r,o)=>{let l=this.runtimeCallbacks.get(r);if(!l)throw Error(`QuickJSRuntime(rt = ${r}) not found when trying to free HostRef(id = ${o})`);l.freeHostRef(r,o)},callFunction:(t,r,o,l,d,f)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(r);if(!s)throw Error(`QuickJSContext(ctx = ${r}) not found for C function call "${f}"`);return s.callFunction(r,o,l,d,f)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,r)=>this.handleAsyncify(t,()=>{try{let o=this.runtimeCallbacks.get(r);if(!o)throw Error(`QuickJSRuntime(rt = ${r}) not found for C interrupt`);return o.shouldInterrupt(r)}catch(o){return console.error("[C to host interrupt: returning error]",o),1}}),loadModuleSource:(t,r,o,l)=>this.handleAsyncify(t,()=>{try{let d=this.runtimeCallbacks.get(r);if(!d)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let f=d.loadModuleSource;if(!f)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return f(r,o,l)}catch(d){return console.error("[C to host module loader error: returning null]",d),0}}),normalizeModule:(t,r,o,l,d)=>this.handleAsyncify(t,()=>{try{let f=this.runtimeCallbacks.get(r);if(!f)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let s=f.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return s(r,o,l,d)}catch(f){return console.error("[C to host module loader error: returning null]",f),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((o)=>{try{let l=t();if(!(l instanceof Promise)){H("asyncify.handleSleep: not suspending:",l),o(l);return}if(this.suspended)throw new et(`Already suspended at: ${this.suspended.stack}
4
4
  Attempted to suspend at:`);this.suspended=new tt(`(${this.suspendedCount++})`),H("asyncify.handleSleep: suspending:",this.suspended),l.then((d)=>{this.suspended=void 0,H("asyncify.handleSleep: resolved:",d),o(d)},(d)=>{H("asyncify.handleSleep: rejected:",d),console.error("QuickJS: cannot handle error in suspended function",d),this.suspended=void 0})}catch(l){throw H("asyncify.handleSleep: error:",l),this.suspended=void 0,l}});let r=t();if(r instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return r}},ut=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new me(e)}newRuntime(e={}){let t=new A(this.ffi.QTS_NewRuntime(),void 0,(o)=>{this.ffi.QTS_FreeRuntime(o),this.callbacks.deleteRuntime(o)}),r=new rr({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return pe(r,e),e.moduleLoader&&r.setModuleLoader(e.moduleLoader),r}newContext(e={}){let t=this.newRuntime(),r=t.newContext({...e,ownedLifetimes:zt(t,e.ownedLifetimes)});return t.context=r,r}evalCode(e,t={}){return M.withScope((r)=>{let o=r.manage(this.newContext());_e(o.runtime,t);let l=o.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&o.runtime.setMemoryLimit(-1),l.error)throw o.dump(r.manage(l.error));return o.dump(r.manage(l.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var lt=ne(()=>{V();V();Kt=Object.defineProperty;Yt={};Bt(Yt,{QuickJSAsyncifyError:()=>et,QuickJSAsyncifySuspended:()=>tt,QuickJSEmptyGetOwnPropertyNames:()=>it,QuickJSEmscriptenModuleError:()=>Ht,QuickJSHostRefInvalid:()=>I,QuickJSHostRefRangeExceeded:()=>st,QuickJSMemoryLeakDetected:()=>Ft,QuickJSNotImplemented:()=>Ze,QuickJSPromisePending:()=>nt,QuickJSUnknownIntrinsic:()=>rt,QuickJSUnwrapError:()=>ae,QuickJSUseAfterFree:()=>ue,QuickJSWrongOwner:()=>Xe});ae=class extends Error{constructor(e,t){let r=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(r);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},Xe=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},ue=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},Ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},et=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},tt=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},Ft=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Ht=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},rt=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},nt=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},it=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},st=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},I=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};he=ot;he.of=Jt;N=class{[Symbol.dispose](){return this.dispose()}},le=Symbol.dispose??Symbol.for("Symbol.dispose"),Ve=N.prototype;Ve[le]||(Ve[le]=function(){return this.dispose()});A=class e extends N{constructor(t,r,o,l){super();this._value=t,this.copier=r,this.disposer=o,this._owner=l,this._alive=!0,this._constructorStack=ce?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let r=t(this);return this.dispose(),r}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ue(`Lifetime not alive
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.19.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.19.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var _R=Object.defineProperty;var SR=(e)=>e;function yR(e,t){this[e]=SR.bind(null,t)}var Ut=(e,t)=>{for(var n in t)_R(e,n,{get:t[n],enumerable:!0,configurable:!0,set:yR.bind(t,n)})};function Uu(){return typeof process>"u"?{}:process.env}var Mu=null,Aa=null;function bR(e){if(!e?.trim())return{};let t=JSON.parse(e);if(!t||typeof t!=="object"||Array.isArray(t))throw Error("UPSTREAM_CUSTOM_HEADERS must be a JSON object.");return Object.entries(t).reduce((n,[o,r])=>{if(typeof r==="string"&&r.trim())n[o]=r;return n},{})}function $R(e){if(!e?.trim())return{};try{let t=JSON.parse(e);if(!t||typeof t!=="object"||Array.isArray(t))return{};return Object.entries(t).reduce((n,[o,r])=>{if(r==="on"||r==="off")n[o]=r;return n},{})}catch{return{}}}function Ur(e,t){let n=t?.trim();if(!n)throw Error(`Set ${e} before starting the generated MCP server.`);return n}function RR(e){let t=Number.parseInt(Ur("MCP_RUNTIME_AUTH_DEPLOYMENT_VERSION",e),10);if(!Number.isFinite(t)||t<=0)throw Error("MCP_RUNTIME_AUTH_DEPLOYMENT_VERSION must be a positive integer.");return t}function Ma(e=Uu()){let t=e.MCP_RUNTIME_AUTH_ACCESS_MODE?.trim();return t==="privateOrg"||t==="unlisted"?t:"public"}function Ua(e,t=Uu()){let n=t.UPSTREAM_BASE_URL?.trim()||e.defaultUpstreamBaseUrl||"";if(e.defaultUpstreamBaseUrl&&!n)throw Error("Set UPSTREAM_BASE_URL before starting the generated MCP server.");let o=Ma(t);Mu=t.MCP_OAUTH_RUNTIME_TOKEN?.trim()||null,Aa=t.MCP_MEMBER_KEY_RUNTIME_TOKEN?.trim()||null;let r=t.MCP_MEMBER_KEY_MODE?.trim()==="perMember"&&Boolean(t.MCP_MEMBER_KEY_RUNTIME_URL?.trim())&&Boolean(Aa);return{serverName:e.serverName,serverVersion:e.serverVersion,upstreamBaseUrl:n,apiKey:t.UPSTREAM_API_KEY?.trim()||null,apiKeyHeader:t.UPSTREAM_API_KEY_HEADER?.trim()||e.apiKeyHeader,apiKeyPrefix:t.UPSTREAM_API_KEY_PREFIX??e.apiKeyPrefix,customHeaders:bR(t.UPSTREAM_CUSTOM_HEADERS),forwardClientIdentity:t.MCP_FORWARD_CLIENT_IDENTITY?.trim()==="true",catalogSessions:t.MCP_CATALOG_SESSIONS?.trim()==="true",accessMode:o,oauth:t.MCP_OAUTH_RUNTIME_URL?.trim()&&t.MCP_OAUTH_CONNECTION_ID?.trim()&&t.MCP_OAUTH_RUNTIME_TOKEN?.trim()?{runtimeUrl:t.MCP_OAUTH_RUNTIME_URL.trim(),connectionId:t.MCP_OAUTH_CONNECTION_ID.trim(),mode:t.MCP_OAUTH_MODE?.trim()==="perMember"?"perMember":"shared",applyToAllTools:t.MCP_OAUTH_APPLY_ALL?.trim()==="true",toolOverrides:$R(t.MCP_OAUTH_TOOL_OVERRIDES)}:null,memberKey:r?{runtimeUrl:t.MCP_MEMBER_KEY_RUNTIME_URL.trim(),connectPageUrl:t.MCP_MEMBER_KEY_CONNECT_URL?.trim()||null}:null,runtimeAuth:o==="public"?null:{audience:Ur("MCP_RUNTIME_AUTH_AUDIENCE",t.MCP_RUNTIME_AUTH_AUDIENCE),deploymentId:Ur("MCP_RUNTIME_AUTH_DEPLOYMENT_ID",t.MCP_RUNTIME_AUTH_DEPLOYMENT_ID),deploymentVersion:RR(t.MCP_RUNTIME_AUTH_DEPLOYMENT_VERSION),issuer:Ur("MCP_RUNTIME_AUTH_ISSUER",t.MCP_RUNTIME_AUTH_ISSUER),organizationId:Ur("MCP_RUNTIME_AUTH_ORGANIZATION_ID",t.MCP_RUNTIME_AUTH_ORGANIZATION_ID),publicKey:Ur("MCP_RUNTIME_AUTH_PUBLIC_KEY",t.MCP_RUNTIME_AUTH_PUBLIC_KEY),publicKeyPrevious:t.MCP_RUNTIME_AUTH_PUBLIC_KEY_PREVIOUS?.trim()||null,publicKeyPreviousUntil:t.MCP_RUNTIME_AUTH_PUBLIC_KEY_PREVIOUS_UNTIL?.trim()||null,serverId:Ur("MCP_RUNTIME_AUTH_SERVER_ID",t.MCP_RUNTIME_AUTH_SERVER_ID)}}}async function qu(e,t){if(!e.oauth)throw Error("OAuth runtime settings are not available for this generated server.");if(!Mu)throw Error("OAuth runtime credentials are not configured for this deployment.");return fetch(e.oauth.runtimeUrl,{method:"POST",headers:new Headers({"Content-Type":"application/json","x-mcpcloud-runtime-token":Mu}),body:JSON.stringify(t)})}async function f_(e,t){if(!e.memberKey)throw Error("Per-member upstream key settings are not available for this generated server.");if(!Aa)throw Error("Per-member upstream key credentials are not configured for this deployment.");return fetch(e.memberKey.runtimeUrl,{method:"POST",headers:new Headers({"Content-Type":"application/json","x-mcpcloud-runtime-token":Aa}),body:JSON.stringify(t)})}var{create:zR,defineProperty:qa,getOwnPropertyDescriptor:TR,getOwnPropertyNames:xR,getPrototypeOf:kR}=Object,ER=Object.prototype.hasOwnProperty,h_=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),g_=(e,t)=>{let n={};for(var o in e)qa(n,o,{get:e[o],enumerable:!0});if(t)qa(n,Symbol.toStringTag,{value:"Module"});return n},wR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var r=xR(t),i=0,a=r.length,s;i<a;i++)if(s=r[i],!ER.call(e,s)&&s!==n)qa(e,s,{get:((c)=>t[c]).bind(null,s),enumerable:!(o=TR(t,s))||o.enumerable})}return e},v_=(e,t,n)=>(n=e!=null?zR(kR(e)):{},wR(t||!e||!e.__esModule?qa(n,"default",{value:e,enumerable:!0}):n,e));var IR=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),__=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),PR=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),OR=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function S_(e){return typeof e==="string"&&__.has(e.replace(/#$/,""))}function y_(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let n=e.$schema.replace(/#$/,"");if(IR.has(n))return"2020-12";if(__.has(n))return"2019-09";if(PR.has(n)||OR.has(n))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var Ti={};Ut(Ti,{$brand:()=>Lu,$input:()=>Qp,$output:()=>Xp,NEVER:()=>Ko,TimePrecision:()=>of,ZodAny:()=>Fh,ZodArray:()=>Bh,ZodBase64:()=>uc,ZodBase64URL:()=>dc,ZodBigInt:()=>Hn,ZodBigIntFormat:()=>fc,ZodBoolean:()=>Bn,ZodCIDRv4:()=>cc,ZodCIDRv6:()=>lc,ZodCUID:()=>tc,ZodCUID2:()=>rc,ZodCatch:()=>pg,ZodCodec:()=>Ri,ZodCustom:()=>zi,ZodCustomStringFormat:()=>Jn,ZodDate:()=>Si,ZodDefault:()=>sg,ZodDiscriminatedUnion:()=>Yh,ZodE164:()=>mc,ZodEmail:()=>Ws,ZodEmoji:()=>Qs,ZodEnum:()=>Zn,ZodError:()=>QT,ZodExactOptional:()=>og,ZodFile:()=>rg,ZodFirstPartyTypeKind:()=>Tg,ZodFunction:()=>$g,ZodGUID:()=>hi,ZodIPv4:()=>ac,ZodIPv6:()=>sc,ZodISODate:()=>Ks,ZodISODateTime:()=>Fs,ZodISODuration:()=>Bs,ZodISOTime:()=>Vs,ZodIntersection:()=>Gh,ZodIssueCode:()=>xg,ZodJWT:()=>pc,ZodKSUID:()=>ic,ZodLazy:()=>yg,ZodLiteral:()=>tg,ZodMAC:()=>qh,ZodMap:()=>Qh,ZodNaN:()=>hg,ZodNanoID:()=>ec,ZodNever:()=>Jh,ZodNonOptional:()=>Sc,ZodNull:()=>Zh,ZodNullable:()=>ag,ZodNumber:()=>Vn,ZodNumberFormat:()=>Yr,ZodObject:()=>yi,ZodOptional:()=>_c,ZodPipe:()=>$i,ZodPrefault:()=>lg,ZodPreprocess:()=>gg,ZodPromise:()=>bg,ZodReadonly:()=>vg,ZodRealError:()=>He,ZodRecord:()=>Dn,ZodSet:()=>eg,ZodString:()=>Fn,ZodStringFormat:()=>pe,ZodSuccess:()=>mg,ZodSymbol:()=>Lh,ZodTemplateLiteral:()=>Sg,ZodTransform:()=>ng,ZodTuple:()=>Wh,ZodType:()=>se,ZodULID:()=>nc,ZodURL:()=>_i,ZodUUID:()=>It,ZodUndefined:()=>Dh,ZodUnion:()=>bi,ZodUnknown:()=>Kh,ZodVoid:()=>Vh,ZodXID:()=>oc,ZodXor:()=>Hh,_ZodString:()=>Gs,_default:()=>cg,_function:()=>vy,any:()=>hc,array:()=>v,base64:()=>AS,base64url:()=>MS,bigint:()=>HS,boolean:()=>j,catch:()=>fg,check:()=>_y,cidrv4:()=>NS,cidrv6:()=>jS,clone:()=>Ue,codec:()=>py,coerce:()=>yc,config:()=>ge,core:()=>Dt,cuid:()=>xS,cuid2:()=>kS,custom:()=>Sy,date:()=>ey,decode:()=>Oh,decodeAsync:()=>Nh,describe:()=>yy,discriminatedUnion:()=>dr,e164:()=>US,email:()=>Xs,emoji:()=>zS,encode:()=>Ph,encodeAsync:()=>Ch,endsWith:()=>On,enum:()=>Q,exactOptional:()=>ig,file:()=>ly,flattenError:()=>Qo,float32:()=>KS,float64:()=>JS,formatError:()=>ei,fromJSONSchema:()=>xy,function:()=>vy,getErrorMap:()=>rx,globalRegistry:()=>xe,gt:()=>Et,gte:()=>Le,guid:()=>_S,hash:()=>FS,hex:()=>ZS,hostname:()=>DS,httpUrl:()=>RS,includes:()=>In,instanceof:()=>$y,int:()=>Hs,int32:()=>VS,int64:()=>YS,intersection:()=>ft,invertCodec:()=>fy,ipv4:()=>PS,ipv6:()=>CS,iso:()=>ur,json:()=>zy,jwt:()=>qS,keyof:()=>ty,ksuid:()=>IS,lazy:()=>mr,length:()=>Vr,literal:()=>S,locales:()=>ui,looseObject:()=>H,looseRecord:()=>iy,lowercase:()=>En,lt:()=>kt,lte:()=>et,mac:()=>OS,map:()=>ay,maxLength:()=>Jr,maxSize:()=>ar,meta:()=>by,mime:()=>Cn,minLength:()=>Lt,minSize:()=>wt,multipleOf:()=>ir,nan:()=>my,nanoid:()=>TS,nativeEnum:()=>cy,negative:()=>js,never:()=>gc,nonnegative:()=>Ms,nonoptional:()=>dg,nonpositive:()=>As,normalize:()=>Nn,null:()=>pt,nullable:()=>gi,nullish:()=>uy,number:()=>x,object:()=>f,optional:()=>K,overwrite:()=>mt,parse:()=>Eh,parseAsync:()=>wh,partialRecord:()=>oy,pipe:()=>Ys,positive:()=>Ns,prefault:()=>ug,preprocess:()=>Zt,prettifyError:()=>Wu,promise:()=>gy,property:()=>Us,readonly:()=>_g,record:()=>C,refine:()=>Rg,regex:()=>kn,regexes:()=>qt,registry:()=>ps,safeDecode:()=>Ah,safeDecodeAsync:()=>Uh,safeEncode:()=>jh,safeEncodeAsync:()=>Mh,safeParse:()=>fi,safeParseAsync:()=>Ih,set:()=>sy,setErrorMap:()=>tx,size:()=>Kr,slugify:()=>Un,startsWith:()=>Pn,strictObject:()=>ry,string:()=>l,stringFormat:()=>LS,stringbool:()=>Ry,success:()=>dy,superRefine:()=>zg,symbol:()=>WS,templateLiteral:()=>hy,toJSONSchema:()=>Br,toLowerCase:()=>An,toUpperCase:()=>Mn,transform:()=>vc,treeifyError:()=>Gu,trim:()=>jn,tuple:()=>Xh,uint32:()=>BS,uint64:()=>GS,ulid:()=>ES,undefined:()=>XS,union:()=>A,unknown:()=>Z,uppercase:()=>wn,url:()=>Kn,util:()=>V,uuid:()=>SS,uuidv4:()=>yS,uuidv6:()=>bS,uuidv7:()=>$S,void:()=>QS,xid:()=>wS,xor:()=>ny});var Dt={};Ut(Dt,{$ZodAny:()=>Tm,$ZodArray:()=>Im,$ZodAsyncError:()=>Tt,$ZodBase64:()=>hm,$ZodBase64URL:()=>gm,$ZodBigInt:()=>ls,$ZodBigIntFormat:()=>bm,$ZodBoolean:()=>ni,$ZodCIDRv4:()=>mm,$ZodCIDRv6:()=>pm,$ZodCUID:()=>em,$ZodCUID2:()=>tm,$ZodCatch:()=>Hm,$ZodCheck:()=>fe,$ZodCheckBigIntFormat:()=>Id,$ZodCheckEndsWith:()=>Zd,$ZodCheckGreaterThan:()=>rs,$ZodCheckIncludes:()=>Ld,$ZodCheckLengthEquals:()=>Ad,$ZodCheckLessThan:()=>ts,$ZodCheckLowerCase:()=>Ud,$ZodCheckMaxLength:()=>Nd,$ZodCheckMaxSize:()=>Pd,$ZodCheckMimeType:()=>Kd,$ZodCheckMinLength:()=>jd,$ZodCheckMinSize:()=>Od,$ZodCheckMultipleOf:()=>Ed,$ZodCheckNumberFormat:()=>wd,$ZodCheckOverwrite:()=>Jd,$ZodCheckProperty:()=>Fd,$ZodCheckRegex:()=>Md,$ZodCheckSizeEquals:()=>Cd,$ZodCheckStartsWith:()=>Dd,$ZodCheckStringFormat:()=>Tn,$ZodCheckUpperCase:()=>qd,$ZodCodec:()=>ii,$ZodCustom:()=>rp,$ZodCustomStringFormat:()=>Sm,$ZodDate:()=>wm,$ZodDefault:()=>Km,$ZodDiscriminatedUnion:()=>Cm,$ZodE164:()=>vm,$ZodEmail:()=>Gd,$ZodEmoji:()=>Xd,$ZodEncodeError:()=>Lr,$ZodEnum:()=>Um,$ZodError:()=>Xo,$ZodExactOptional:()=>Zm,$ZodFile:()=>Lm,$ZodFunction:()=>Qm,$ZodGUID:()=>Hd,$ZodIPv4:()=>lm,$ZodIPv6:()=>um,$ZodISODate:()=>am,$ZodISODateTime:()=>im,$ZodISODuration:()=>cm,$ZodISOTime:()=>sm,$ZodIntersection:()=>Nm,$ZodJWT:()=>_m,$ZodKSUID:()=>om,$ZodLazy:()=>tp,$ZodLiteral:()=>qm,$ZodMAC:()=>dm,$ZodMap:()=>Am,$ZodNaN:()=>Ym,$ZodNanoID:()=>Qd,$ZodNever:()=>km,$ZodNonOptional:()=>Vm,$ZodNull:()=>zm,$ZodNullable:()=>Fm,$ZodNumber:()=>cs,$ZodNumberFormat:()=>ym,$ZodObject:()=>cS,$ZodObjectJIT:()=>Pm,$ZodOptional:()=>ds,$ZodPipe:()=>ms,$ZodPrefault:()=>Jm,$ZodPreprocess:()=>Gm,$ZodPromise:()=>ep,$ZodReadonly:()=>Wm,$ZodRealError:()=>Be,$ZodRecord:()=>jm,$ZodRegistry:()=>ef,$ZodSet:()=>Mm,$ZodString:()=>Fr,$ZodStringFormat:()=>me,$ZodSuccess:()=>Bm,$ZodSymbol:()=>$m,$ZodTemplateLiteral:()=>Xm,$ZodTransform:()=>Dm,$ZodTuple:()=>us,$ZodType:()=>re,$ZodULID:()=>rm,$ZodURL:()=>Wd,$ZodUUID:()=>Yd,$ZodUndefined:()=>Rm,$ZodUnion:()=>oi,$ZodUnknown:()=>xm,$ZodVoid:()=>Em,$ZodXID:()=>nm,$ZodXor:()=>Om,$brand:()=>Lu,$constructor:()=>g,$input:()=>Qp,$output:()=>Xp,Doc:()=>ns,JSONSchema:()=>hS,JSONSchemaGenerator:()=>Th,NEVER:()=>Ko,TimePrecision:()=>of,_any:()=>xf,_array:()=>Cf,_base64:()=>Is,_base64url:()=>Ps,_bigint:()=>Sf,_boolean:()=>vf,_catch:()=>JT,_check:()=>fS,_cidrv4:()=>Es,_cidrv6:()=>ws,_coercedBigint:()=>yf,_coercedBoolean:()=>_f,_coercedDate:()=>Pf,_coercedNumber:()=>df,_coercedString:()=>rf,_cuid:()=>bs,_cuid2:()=>$s,_custom:()=>jf,_date:()=>If,_decode:()=>Ja,_decodeAsync:()=>Ba,_default:()=>ZT,_discriminatedUnion:()=>IT,_e164:()=>Os,_email:()=>fs,_emoji:()=>Ss,_encode:()=>Ka,_encodeAsync:()=>Va,_endsWith:()=>On,_enum:()=>AT,_file:()=>Nf,_float32:()=>pf,_float64:()=>ff,_gt:()=>Et,_gte:()=>Le,_guid:()=>di,_includes:()=>In,_int:()=>mf,_int32:()=>hf,_int64:()=>bf,_intersection:()=>PT,_ipv4:()=>xs,_ipv6:()=>ks,_isoDate:()=>sf,_isoDateTime:()=>af,_isoDuration:()=>lf,_isoTime:()=>cf,_jwt:()=>Cs,_ksuid:()=>Ts,_lazy:()=>YT,_length:()=>Vr,_literal:()=>UT,_lowercase:()=>En,_lt:()=>kt,_lte:()=>et,_mac:()=>nf,_map:()=>NT,_max:()=>et,_maxLength:()=>Jr,_maxSize:()=>ar,_mime:()=>Cn,_min:()=>Le,_minLength:()=>Lt,_minSize:()=>wt,_multipleOf:()=>ir,_nan:()=>Of,_nanoid:()=>ys,_nativeEnum:()=>MT,_negative:()=>js,_never:()=>Ef,_nonnegative:()=>Ms,_nonoptional:()=>FT,_nonpositive:()=>As,_normalize:()=>Nn,_null:()=>Tf,_nullable:()=>DT,_number:()=>uf,_optional:()=>LT,_overwrite:()=>mt,_parse:()=>bn,_parseAsync:()=>$n,_pipe:()=>VT,_positive:()=>Ns,_promise:()=>GT,_property:()=>Us,_readonly:()=>BT,_record:()=>CT,_refine:()=>Af,_regex:()=>kn,_safeDecode:()=>Ya,_safeDecodeAsync:()=>Wa,_safeEncode:()=>Ha,_safeEncodeAsync:()=>Ga,_safeParse:()=>Rn,_safeParseAsync:()=>zn,_set:()=>jT,_size:()=>Kr,_slugify:()=>Un,_startsWith:()=>Pn,_string:()=>tf,_stringFormat:()=>qn,_stringbool:()=>Lf,_success:()=>KT,_superRefine:()=>Mf,_symbol:()=>Rf,_templateLiteral:()=>HT,_toLowerCase:()=>An,_toUpperCase:()=>Mn,_transform:()=>qT,_trim:()=>jn,_tuple:()=>OT,_uint32:()=>gf,_uint64:()=>$f,_ulid:()=>Rs,_undefined:()=>zf,_union:()=>ET,_unknown:()=>kf,_uppercase:()=>wn,_url:()=>mi,_uuid:()=>hs,_uuidv4:()=>gs,_uuidv6:()=>vs,_uuidv7:()=>_s,_void:()=>wf,_xid:()=>zs,_xor:()=>wT,clone:()=>Ue,config:()=>ge,createStandardJSONSchemaMethod:()=>Ln,createToJSONSchemaMethod:()=>Df,decode:()=>QR,decodeAsync:()=>tz,describe:()=>Uf,encode:()=>XR,encodeAsync:()=>ez,extractDefs:()=>cr,finalize:()=>lr,flattenError:()=>Qo,formatError:()=>ei,globalConfig:()=>qr,globalRegistry:()=>xe,initializeContext:()=>sr,isValidBase64:()=>fm,isValidBase64URL:()=>oS,isValidJWT:()=>iS,locales:()=>ui,meta:()=>qf,parse:()=>Za,parseAsync:()=>Fa,prettifyError:()=>Wu,process:()=>de,regexes:()=>qt,registry:()=>ps,safeDecode:()=>nz,safeDecodeAsync:()=>iz,safeEncode:()=>rz,safeEncodeAsync:()=>oz,safeParse:()=>Xu,safeParseAsync:()=>Qu,toDotPath:()=>N_,toJSONSchema:()=>Br,treeifyError:()=>Gu,util:()=>V,version:()=>Vd});var b_,Ko=Object.freeze({status:"aborted"});function g(e,t,n){function o(s,c){if(!s._zod)Object.defineProperty(s,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1});if(s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,c);let u=a.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let p=d[m];if(!(p in s))s[p]=u[p].bind(s)}}let r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function a(s){var c;let u=n?.Parent?new i:this;o(u,s),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:(s)=>{if(n?.Parent&&s instanceof n.Parent)return!0;return s?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}var Lu=Symbol("zod_brand");class Tt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Lr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(b_=globalThis).__zod_globalConfig??(b_.__zod_globalConfig={});var qr=globalThis.__zod_globalConfig;function ge(e){if(e)Object.assign(qr,e);return qr}var V={};Ut(V,{BIGINT_FORMAT_RANGES:()=>Hu,Class:()=>O_,NUMBER_FORMAT_RANGES:()=>Bu,aborted:()=>nr,allowsEval:()=>Ku,assert:()=>MR,assertEqual:()=>CR,assertIs:()=>jR,assertNever:()=>AR,assertNotEqual:()=>NR,assignProp:()=>tr,base64ToUint8Array:()=>I_,base64urlToUint8Array:()=>BR,cached:()=>yn,captureStackTrace:()=>Da,cleanEnum:()=>VR,cleanRegex:()=>Bo,clone:()=>Ue,cloneDef:()=>qR,createTransparentProxy:()=>JR,defineLazy:()=>le,esc:()=>La,escapeRegex:()=>st,explicitlyAborted:()=>Yu,extend:()=>T_,finalizeIssue:()=>qe,floatSafeRemainder:()=>Zu,getElementAtPath:()=>LR,getEnumValues:()=>Vo,getLengthableOrigin:()=>Wo,getParsedType:()=>KR,getSizableOrigin:()=>Go,hexToUint8Array:()=>YR,isObject:()=>Dr,isPlainObject:()=>rr,issue:()=>or,joinValues:()=>y,jsonStringifyReplacer:()=>Sn,merge:()=>k_,mergeDefs:()=>xt,normalizeParams:()=>T,nullish:()=>er,numKeys:()=>FR,objectClone:()=>UR,omit:()=>z_,optionalKeys:()=>Vu,parsedType:()=>w,partial:()=>E_,pick:()=>R_,prefixIssues:()=>Ve,primitiveTypes:()=>Ju,promiseAllObject:()=>DR,propertyKeyTypes:()=>Yo,randomString:()=>ZR,required:()=>w_,safeExtend:()=>x_,shallowClone:()=>Ho,slugify:()=>Fu,stringifyPrimitive:()=>k,uint8ArrayToBase64:()=>P_,uint8ArrayToBase64url:()=>HR,uint8ArrayToHex:()=>GR,unwrapMessage:()=>Jo});function CR(e){return e}function NR(e){return e}function jR(e){}function AR(e){throw Error("Unexpected value in exhaustive check")}function MR(e){}function Vo(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,r])=>t.indexOf(+o)===-1).map(([o,r])=>r)}function y(e,t="|"){return e.map((n)=>k(n)).join(t)}function Sn(e,t){if(typeof t==="bigint")return t.toString();return t}function yn(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function er(e){return e===null||e===void 0}function Bo(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Zu(e,t){let n=e/t,o=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-o)<r)return 0;return n-o}var $_=Symbol("evaluating");function le(e,t,n){let o=void 0;Object.defineProperty(e,t,{get(){if(o===$_)return;if(o===void 0)o=$_,o=n();return o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function UR(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function tr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function xt(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function qR(e){return xt(e._zod.def)}function LR(e,t){if(!t)return e;return t.reduce((n,o)=>n?.[o],e)}function DR(e){let t=Object.keys(e),n=t.map((o)=>e[o]);return Promise.all(n).then((o)=>{let r={};for(let i=0;i<t.length;i++)r[t[i]]=o[i];return r})}function ZR(e=10){let n="";for(let o=0;o<e;o++)n+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return n}function La(e){return JSON.stringify(e)}function Fu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Da="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Dr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Ku=yn(()=>{if(qr.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function rr(e){if(Dr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Dr(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Ho(e){if(rr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function FR(e){let t=0;for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n))t++;return t}var KR=(e)=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(e===null)return"null";if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return"promise";if(typeof Map<"u"&&e instanceof Map)return"map";if(typeof Set<"u"&&e instanceof Set)return"set";if(typeof Date<"u"&&e instanceof Date)return"date";if(typeof File<"u"&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},Yo=new Set(["string","number","symbol"]),Ju=new Set(["string","number","bigint","boolean","symbol","undefined"]);function st(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ue(e,t,n){let o=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)o._zod.parent=e;return o}function T(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function JR(e){let t;return new Proxy({},{get(n,o,r){return t??(t=e()),Reflect.get(t,o,r)},set(n,o,r,i){return t??(t=e()),Reflect.set(t,o,r,i)},has(n,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(n,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(n,o,r){return t??(t=e()),Reflect.defineProperty(t,o,r)}})}function k(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Vu(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Bu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Hu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function R_(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=xt(e._zod.def,{get shape(){let a={};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;a[s]=n.shape[s]}return tr(this,"shape",a),a},checks:[]});return Ue(e,i)}function z_(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=xt(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let s in t){if(!(s in n.shape))throw Error(`Unrecognized key: "${s}"`);if(!t[s])continue;delete a[s]}return tr(this,"shape",a),a},checks:[]});return Ue(e,i)}function T_(e,t){if(!rr(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=xt(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return tr(this,"shape",i),i}});return Ue(e,r)}function x_(e,t){if(!rr(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=xt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return tr(this,"shape",o),o}});return Ue(e,n)}function k_(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=xt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return tr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ue(e,n)}function E_(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=xt(t._zod.def,{get shape(){let s=t._zod.def.shape,c={...s};if(n)for(let u in n){if(!(u in s))throw Error(`Unrecognized key: "${u}"`);if(!n[u])continue;c[u]=e?new e({type:"optional",innerType:s[u]}):s[u]}else for(let u in s)c[u]=e?new e({type:"optional",innerType:s[u]}):s[u];return tr(this,"shape",c),c},checks:[]});return Ue(t,a)}function w_(e,t,n){let o=xt(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let a in n){if(!(a in i))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;i[a]=new e({type:"nonoptional",innerType:r[a]})}else for(let a in r)i[a]=new e({type:"nonoptional",innerType:r[a]});return tr(this,"shape",i),i}});return Ue(t,o)}function nr(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Yu(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Ve(e,t){return t.map((n)=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function Jo(e){return typeof e==="string"?e:e?.message}function qe(e,t,n){let o=e.message?e.message:Jo(e.inst?._zod.def?.error?.(e))??Jo(t?.error?.(e))??Jo(n.customError?.(e))??Jo(n.localeError?.(e))??"Invalid input",{inst:r,continue:i,input:a,...s}=e;if(s.path??(s.path=[]),s.message=o,t?.reportInput)s.input=a;return s}function Go(e){if(e instanceof Set)return"set";if(e instanceof Map)return"map";if(e instanceof File)return"file";return"unknown"}function Wo(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function w(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function or(...e){let[t,n,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:o};return{...t}}function VR(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map((t)=>t[1])}function I_(e){let t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}function P_(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function BR(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return I_(t+n)}function HR(e){return P_(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function YR(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)n[o/2]=Number.parseInt(t.slice(o,o+2),16);return n}function GR(e){return Array.from(e).map((t)=>t.toString(16).padStart(2,"0")).join("")}class O_{constructor(...e){}}var C_=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Sn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Xo=g("$ZodError",C_),Be=g("$ZodError",C_,{Parent:Error});function Qo(e,t=(n)=>n.message){let n={},o=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else o.push(t(r));return{formErrors:o,fieldErrors:n}}function ei(e,t=(n)=>n.message){let n={_errors:[]},o=(r,i=[])=>{for(let a of r.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((s)=>o({issues:s},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let s=[...i,...a.path];if(s.length===0)n._errors.push(t(a));else{let c=n,u=0;while(u<s.length){let d=s[u];if(u!==s.length-1)c[d]=c[d]||{_errors:[]};else c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(a));c=c[d],u++}}}};return o(e),n}function Gu(e,t=(n)=>n.message){let n={errors:[]},o=(r,i=[])=>{var a,s;for(let c of r.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map((u)=>o({issues:u},[...i,...c.path]));else if(c.code==="invalid_key")o({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")o({issues:c.issues},[...i,...c.path]);else{let u=[...i,...c.path];if(u.length===0){n.errors.push(t(c));continue}let d=n,m=0;while(m<u.length){let p=u[m],h=m===u.length-1;if(typeof p==="string")d.properties??(d.properties={}),(a=d.properties)[p]??(a[p]={errors:[]}),d=d.properties[p];else d.items??(d.items=[]),(s=d.items)[p]??(s[p]={errors:[]}),d=d.items[p];if(h)d.errors.push(t(c));m++}}};return o(e),n}function N_(e){let t=[],n=e.map((o)=>typeof o==="object"?o.key:o);for(let o of n)if(typeof o==="number")t.push(`[${o}]`);else if(typeof o==="symbol")t.push(`[${JSON.stringify(String(o))}]`);else if(/[^\w$]/.test(o))t.push(`[${JSON.stringify(o)}]`);else{if(t.length)t.push(".");t.push(o)}return t.join("")}function Wu(e){let t=[],n=[...e.issues].sort((o,r)=>(o.path??[]).length-(r.path??[]).length);for(let o of n)if(t.push(`✖ ${o.message}`),o.path?.length)t.push(` → at ${N_(o.path)}`);return t.join(`
3
3
  `)}var bn=(e)=>(t,n,o,r)=>{let i=o?{...o,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Tt;if(a.issues.length){let s=new(r?.Err??e)(a.issues.map((c)=>qe(c,i,ge())));throw Da(s,r?.callee),s}return a.value},Za=bn(Be),$n=(e)=>async(t,n,o,r)=>{let i=o?{...o,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)a=await a;if(a.issues.length){let s=new(r?.Err??e)(a.issues.map((c)=>qe(c,i,ge())));throw Da(s,r?.callee),s}return a.value},Fa=$n(Be),Rn=(e)=>(t,n,o)=>{let r=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Tt;return i.issues.length?{success:!1,error:new(e??Xo)(i.issues.map((a)=>qe(a,r,ge())))}:{success:!0,data:i.value}},Xu=Rn(Be),zn=(e)=>async(t,n,o)=>{let r=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((a)=>qe(a,r,ge())))}:{success:!0,data:i.value}},Qu=zn(Be),Ka=(e)=>(t,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return bn(e)(t,n,r)},XR=Ka(Be),Ja=(e)=>(t,n,o)=>bn(e)(t,n,o),QR=Ja(Be),Va=(e)=>async(t,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return $n(e)(t,n,r)},ez=Va(Be),Ba=(e)=>async(t,n,o)=>$n(e)(t,n,o),tz=Ba(Be),Ha=(e)=>(t,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return Rn(e)(t,n,r)},rz=Ha(Be),Ya=(e)=>(t,n,o)=>Rn(e)(t,n,o),nz=Ya(Be),Ga=(e)=>async(t,n,o)=>{let r=o?{...o,direction:"backward"}:{direction:"backward"};return zn(e)(t,n,r)},oz=Ga(Be),Wa=(e)=>async(t,n,o)=>zn(e)(t,n,o),iz=Wa(Be);var qt={};Ut(qt,{base64:()=>hd,base64url:()=>Xa,bigint:()=>bd,boolean:()=>Rd,browserEmail:()=>pz,cidrv4:()=>pd,cidrv6:()=>fd,cuid:()=>ed,cuid2:()=>td,date:()=>vd,datetime:()=>Sd,domain:()=>M_,duration:()=>ad,e164:()=>gd,email:()=>cd,emoji:()=>ld,extendedDuration:()=>az,guid:()=>sd,hex:()=>L_,hostname:()=>A_,html5Email:()=>uz,httpProtocol:()=>Qa,idnEmail:()=>mz,integer:()=>$d,ipv4:()=>ud,ipv6:()=>dd,ksuid:()=>od,lowercase:()=>xd,mac:()=>md,md5_base64:()=>gz,md5_base64url:()=>vz,md5_hex:()=>hz,nanoid:()=>id,null:()=>zd,number:()=>es,rfc5322Email:()=>dz,sha1_base64:()=>Sz,sha1_base64url:()=>yz,sha1_hex:()=>_z,sha256_base64:()=>$z,sha256_base64url:()=>Rz,sha256_hex:()=>bz,sha384_base64:()=>Tz,sha384_base64url:()=>xz,sha384_hex:()=>zz,sha512_base64:()=>Ez,sha512_base64url:()=>wz,sha512_hex:()=>kz,string:()=>yd,time:()=>_d,ulid:()=>rd,undefined:()=>Td,unicodeEmail:()=>j_,uppercase:()=>kd,uuid:()=>Zr,uuid4:()=>sz,uuid6:()=>cz,uuid7:()=>lz,xid:()=>nd});var ed=/^[cC][0-9a-z]{6,}$/,td=/^[0-9a-z]+$/,rd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nd=/^[0-9a-vA-V]{20}$/,od=/^[A-Za-z0-9]{27}$/,id=/^[a-zA-Z0-9_-]{21}$/,ad=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,az=/^[-+]?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)?)??$/,sd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Zr=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},sz=Zr(4),cz=Zr(6),lz=Zr(7),cd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,dz=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,j_=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,mz=j_,pz=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,fz="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ld(){return new RegExp(fz,"u")}var ud=/^(?:(?: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])$/,dd=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,md=(e)=>{let t=st(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},pd=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,fd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xa=/^[A-Za-z0-9_-]*$/,A_=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,M_=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Qa=/^https?$/,gd=/^\+[1-9]\d{6,14}$/,U_="(?:(?:\\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])))",vd=new RegExp(`^${U_}$`);function q_(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function _d(e){return new RegExp(`^${q_(e)}$`)}function Sd(e){let t=q_({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${n.join("|")})`;return new RegExp(`^${U_}T(?:${o})$`)}var yd=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},bd=/^-?\d+n?$/,$d=/^-?\d+$/,es=/^-?\d+(?:\.\d+)?$/,Rd=/^(?:true|false)$/i,zd=/^null$/i;var Td=/^undefined$/i;var xd=/^[^A-Z]*$/,kd=/^[^a-z]*$/,L_=/^[0-9a-fA-F]*$/;function ti(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function ri(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var hz=/^[0-9a-fA-F]{32}$/,gz=ti(22,"=="),vz=ri(22),_z=/^[0-9a-fA-F]{40}$/,Sz=ti(27,"="),yz=ri(27),bz=/^[0-9a-fA-F]{64}$/,$z=ti(43,"="),Rz=ri(43),zz=/^[0-9a-fA-F]{96}$/,Tz=ti(64,""),xz=ri(64),kz=/^[0-9a-fA-F]{128}$/,Ez=ti(86,"=="),wz=ri(86);var fe=g("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Z_={number:"number",bigint:"bigint",object:"date"},ts=g("$ZodCheckLessThan",(e,t)=>{fe.init(e,t);let n=Z_[typeof t.value];e._zod.onattach.push((o)=>{let r=o._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rs=g("$ZodCheckGreaterThan",(e,t)=>{fe.init(e,t);let n=Z_[typeof t.value];e._zod.onattach.push((o)=>{let r=o._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ed=g("$ZodCheckMultipleOf",(e,t)=>{fe.init(e,t),e._zod.onattach.push((n)=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):Zu(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),wd=g("$ZodCheckNumberFormat",(e,t)=>{fe.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),o=n?"int":"number",[r,i]=Bu[t.format];e._zod.onattach.push((a)=>{let s=a._zod.bag;if(s.format=t.format,s.minimum=r,s.maximum=i,n)s.pattern=$d}),e._zod.check=(a)=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){if(s>0)a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(s<r)a.issues.push({origin:"number",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(s>i)a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Id=g("$ZodCheckBigIntFormat",(e,t)=>{fe.init(e,t);let[n,o]=Hu[t.format];e._zod.onattach.push((r)=>{let i=r._zod.bag;i.format=t.format,i.minimum=n,i.maximum=o}),e._zod.check=(r)=>{let i=r.value;if(i<n)r.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(i>o)r.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Pd=g("$ZodCheckMaxSize",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!er(r)&&r.size!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let r=o.value;if(r.size<=t.maximum)return;o.issues.push({origin:Go(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Od=g("$ZodCheckMinSize",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!er(r)&&r.size!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let r=o.value;if(r.size>=t.minimum)return;o.issues.push({origin:Go(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Cd=g("$ZodCheckSizeEquals",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!er(r)&&r.size!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=(o)=>{let r=o.value,i=r.size;if(i===t.size)return;let a=i>t.size;o.issues.push({origin:Go(r),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Nd=g("$ZodCheckMaxLength",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!er(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let r=o.value;if(r.length<=t.maximum)return;let a=Wo(r);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),jd=g("$ZodCheckMinLength",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!er(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let r=o.value;if(r.length>=t.minimum)return;let a=Wo(r);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ad=g("$ZodCheckLengthEquals",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!er(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(o)=>{let r=o.value,i=r.length;if(i===t.length)return;let a=Wo(r),s=i>t.length;o.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Tn=g("$ZodCheckStringFormat",(e,t)=>{var n,o;if(fe.init(e,t),e._zod.onattach.push((r)=>{let i=r._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),Md=g("$ZodCheckRegex",(e,t)=>{Tn.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ud=g("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=xd),Tn.init(e,t)}),qd=g("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=kd),Tn.init(e,t)}),Ld=g("$ZodCheckIncludes",(e,t)=>{fe.init(e,t);let n=st(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=o,e._zod.onattach.push((r)=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Dd=g("$ZodCheckStartsWith",(e,t)=>{fe.init(e,t);let n=new RegExp(`^${st(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Zd=g("$ZodCheckEndsWith",(e,t)=>{fe.init(e,t);let n=new RegExp(`.*${st(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});function D_(e,t,n){if(e.issues.length)t.issues.push(...Ve(n,e.issues))}var Fd=g("$ZodCheckProperty",(e,t)=>{fe.init(e,t),e._zod.check=(n)=>{let o=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then((r)=>D_(r,n,t.property));D_(o,n,t.property);return}}),Kd=g("$ZodCheckMimeType",(e,t)=>{fe.init(e,t);let n=new Set(t.mime);e._zod.onattach.push((o)=>{o._zod.bag.mime=t.mime}),e._zod.check=(o)=>{if(n.has(o.value.type))return;o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),Jd=g("$ZodCheckOverwrite",(e,t)=>{fe.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class ns{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
4
4
  `).filter((i)=>i),o=Math.min(...n.map((i)=>i.length-i.trimStart().length)),r=n.map((i)=>i.slice(o)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of r)this.content.push(i)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((r)=>` ${r}`)];return new e(...t,o.join(`
@@ -98,7 +98,7 @@ data:
98
98
  `;if(o)r+=`id: ${o}
99
99
  `;return r+=`data: ${JSON.stringify(n)}
100
100
 
101
- `,e.enqueue(t.encode(r)),!0}catch(r){return this.onerror?.(r),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!Cv(e.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let o=e,r;if(t?.parsedBody===void 0)try{r=await e.json()}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else r=t.parsedBody;let i;try{i=Array.isArray(r)?r.map((R)=>Wn.parse(R)):[Wn.parse(r)]}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let a=i.some((R)=>Rv(R));if(a){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(i.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!a){let R=this.validateSession(e);if(R)return R;let z=this.validateProtocolVersion(e);if(z)return z}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!i.some((R)=>Bt(R))){for(let R of i)this.onmessage?.(R,{authInfo:t?.authInfo,request:o});return new Response(null,{status:202})}let s=crypto.randomUUID(),c=i.find((R)=>Rv(R)),u=c?c.params.protocolVersion:e.headers.get("mcp-protocol-version")??bc;if(this._enableJsonResponse)return new Promise((R)=>{this._streamMapping.set(s,{resolveJson:R,cleanup:()=>{this._streamMapping.delete(s)}});for(let z of i)if(Bt(z))this._requestToStreamMapping.set(z.id,s);for(let z of i)this.onmessage?.(z,{authInfo:t?.authInfo,request:o})});let d=new TextEncoder,m,p,h=new ReadableStream({start:(R)=>{m=R},cancel:()=>{if(p!==void 0)clearInterval(p);if(this._streamMapping.get(s)?.controller===m)this._streamMapping.delete(s)}}),b={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};if(this.sessionId!==void 0)b["mcp-session-id"]=this.sessionId;for(let R of i)if(Bt(R))this._streamMapping.set(s,{controller:m,encoder:d,cleanup:()=>{if(p!==void 0)clearInterval(p);this._streamMapping.delete(s);try{m.close()}catch{}}}),this._requestToStreamMapping.set(R.id,s);await this.writePrimingEvent(m,d,s,u);for(let R of i){let z,N;if(Bt(R)&&this._eventStore&&this.supportsEmptySSEData(u))z=()=>{this.closeSSEStream(R.id)},N=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(R,{authInfo:t?.authInfo,request:o,closeSSEStream:z,closeStandaloneSSEStream:N})}if(this._streamMapping.get(s)?.controller===m)p=this.startKeepAlive(m,d);return new Response(h,{status:200,headers:b})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let t=e.headers.get("mcp-session-id");if(!t)return this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(t!==this.sessionId)return this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let t=e.headers.get("mcp-protocol-version");if(t!==null&&!this._supportedProtocolVersions.includes(t)){let n=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(n)),this.createJsonErrorResponse(400,-32000,n)}}async close(){if(this._closed)return;this._closed=!0;for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);if(n)n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);if(e)e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if(Jt(e)||Ht(e))n=e.id;if(n===void 0){if(Jt(e)||Ht(e))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;if(this._eventStore)i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e);let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;if(a.controller&&a.encoder&&(i===void 0||!a.replayedEventIds?.has(i)))this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw Error(`No connection established for request ID: ${String(n)}`);let r=this._streamMapping.get(o);if(!this._enableJsonResponse){let i;if(this._eventStore)i=await this._eventStore.storeEvent(o,e),r=this._streamMapping.get(o);if(r?.controller&&r?.encoder&&(i===void 0||!r.replayedEventIds?.has(i)))this.writeSSEEvent(r.controller,r.encoder,e,i)}if(Jt(e)||Ht(e)){this._requestResponseMap.set(n,e);let i=[...this._requestToStreamMapping.entries()].filter(([a,s])=>s===o).map(([a])=>a);if(i.every((a)=>this._requestResponseMap.has(a))){if(!r){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let a of i)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}for(let a of i)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}if(this._enableJsonResponse&&r.resolveJson){let a={"Content-Type":"application/json"};if(this.sessionId!==void 0)a["mcp-session-id"]=this.sessionId;let s=i.map((c)=>this._requestResponseMap.get(c));if(s.length===1)r.resolveJson(Response.json(s[0],{status:200,headers:a}));else r.resolveJson(Response.json(s,{status:200,headers:a}));r.cleanup()}else r.cleanup();for(let a of i)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a)}}}};function Tr(e){if(e===null||typeof e!=="object"||Array.isArray(e))return null;let{method:t,id:n}=e;if(typeof t!=="string")return null;return typeof n==="string"||typeof n==="number"?n:null}function xr(e,t,n,o,r=null){return Response.json({jsonrpc:"2.0",error:{code:t,message:n,...o!==void 0&&{data:o}},id:r},{status:e})}function Tu(e,t=null){return xr(e.httpStatus,e.code,e.message,e.data,t)}function xu(e){return e instanceof Error?e:Error(String(e))}function ku(e=null){return xr(500,-32603,"Internal server error",void 0,e)}function LE(e,t,n){return async(o,r)=>{if(o.method.toUpperCase()!=="POST")return xr(405,-32000,"Method not allowed.");try{let i=await e({era:"legacy",...r?.authInfo!==void 0&&{authInfo:r.authInfo},requestInfo:o}),a=new Eu({sessionIdGenerator:void 0,...n!==void 0&&{keepAliveMs:n}});await i.connect(a);let s=()=>{a.close().catch(()=>{}),i.close().catch(()=>{})};o.signal?.addEventListener("abort",s,{once:!0});let c=await a.handleRequest(o,{...r?.authInfo!==void 0&&{authInfo:r.authInfo},...r?.parsedBody!==void 0&&{parsedBody:r.parsedBody}});if(c.body===null||Ov(c.headers.get("content-type"))!=="text/event-stream")return s(),c;let u=c.body.getReader(),d=!1,m=()=>{if(!d)d=!0,s()},p=new ReadableStream({pull:async(h)=>{try{let{done:b,value:R}=await u.read();if(b){m(),h.close();return}if(R!==void 0)h.enqueue(R)}catch(b){m(),h.error(b)}},cancel:(h)=>(m(),u.cancel(h).catch(()=>{}))});return new Response(p,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(i){try{t?.(xu(i))}catch{}return ku(Tr(r?.parsedBody))}}}async function i$(e,t,n=!0){let o=e.method.toUpperCase(),r,i=t,a=e,s=!1;if(o==="POST"){if(i===void 0){if(n)a=e.clone();let c;try{c=await e.text()}catch{return{step:"unreadable-body"}}try{r=c.length===0?void 0:JSON.parse(c)}catch{s=!0}if(!s&&r!==void 0)i=r}else r=i;if(s||r===void 0)return{step:"no-json-body",forwardRequest:a}}return{step:"classified",outcome:bb({httpMethod:o,protocolVersionHeader:e.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:e.headers.get("mcp-method")??void 0,mcpNameHeader:e.headers.get("mcp-name")??void 0,...r!==void 0&&{body:r}}),body:r,parsedBody:i,forwardRequest:a}}async function a$(e,t){let n=await i$(t===void 0&&e.method.toUpperCase()==="POST"?e.clone():e,t,!1);return n.step==="no-json-body"||n.step==="classified"&&n.outcome.kind==="legacy"}function s$(e,t={}){let{legacy:n,onerror:o,responseMode:r}=t;if(typeof n==="function")throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let i=new Set,a=!1,s=(z)=>{try{o?.(z)}catch{}},c=t.bus??new Hb(s),u=Yb(c),d=Gb({bus:c,maxSubscriptions:t.maxSubscriptions??Mv,keepAliveMs:t.keepAliveMs??da,onerror:s});if(r==="json")console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let m=n==="reject"?void 0:LE(e,s,t.keepAliveMs);async function p(z,N,B){let P=z.classification.revision;if(P===void 0||!ia.includes(P)){let ce=new vu({supported:[...ia],requested:P??"unknown"});return s(ce),xr(400,ce.code,ce.message,ce.data,Tr(z.message))}let O=Sb({httpMethod:N.method,mcpMethodHeader:N.headers.get("mcp-method")??void 0,mcpNameHeader:N.headers.get("mcp-name")??void 0},z);if(O!==void 0)return s(Error(`Rejected inbound request (${O.cell}): ${O.message}`)),Tu(O,Tr(z.message));let J=z.messageKind==="request"?Rr(z.message.params):void 0,Y=J?.[Ot];if(z.messageKind==="request"){let ce=Wy(z.message.method);if(ce!==void 0){let ue=oa(ce,Y);if(ue!==void 0){let Te=new aa({requiredCapabilities:ue});return s(Te),xr(_b(Te.code,"ladder"),Te.code,Te.message,Te.data,z.message.id)}}}let ee=await e({era:"modern",...B!==void 0&&{authInfo:B},requestInfo:N}),ne=ee instanceof po?ee.server:ee;if(z.messageKind==="request"&&z.message.method==="subscriptions/listen"){let ce=ne.getCapabilities(),ue=n$(ne);return ee.close().catch(s),d.serve(z.message,N.signal,ce,ue)}if(z.messageKind==="request"&&z.message.method==="tools/call"&&ee instanceof po){let ce=z.message.params,ue=typeof ce?.name==="string"?ce.name:void 0,Te=ue===void 0?void 0:ee.toolInputSchemaJson(ue);if(Te!==void 0){let tt=yu(Te);if(tt.valid&&tt.declarations.length>0){let Ne=vb(tt.declarations,ce?.arguments,N.headers);if(Ne!==void 0)return ee.close().catch(s),s(Error(`Rejected inbound request (${Ne.cell}): ${Ne.message}`)),Tu(Ne,z.message.id)}}}if(Nb(ne,P),r$(ne,ia),J!==void 0)t$(ne,{clientInfo:J[Xr],clientCapabilities:Y});let ae=ne.onclose;i.add(ne),ne.onclose=()=>{i.delete(ne),ae?.()};try{let ce=await qE(ee,z.message,{classification:z.classification,request:N,...B!==void 0&&{authInfo:B},...r!==void 0&&{responseMode:r},...t.keepAliveMs!==void 0&&{keepAliveMs:t.keepAliveMs}});if(z.messageKind==="notification")queueMicrotask(()=>void ne.close().catch(()=>{}));return ce}catch(ce){if(ce instanceof te&&ce.code===ie.ConnectionClosed)return new Response(null,{status:499});return await ne.close().catch(()=>{}),i.delete(ne),s(xu(ce)),ku(Tr(z.message))}}async function h(z,N,B,P){if(m!==void 0)return m(N,{...B!==void 0&&{authInfo:B},...P!==void 0&&{parsedBody:P}});let O=$b(z,ia);if(O===void 0)return new Response(null,{status:202});return s(Error(`Rejected 2025-era request on a modern-only endpoint (${O.cell}): ${O.message}`)),Tu(O,Tr(P))}async function b(z,N){let B=N?.authInfo;if(z.method.toUpperCase()==="POST"&&!Cv(z.headers.get("content-type")))return s(Error("Unsupported Media Type: Content-Type must be application/json")),xr(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let P=await i$(z,N?.parsedBody);if(P.step==="unreadable-body")return xr(400,-32700,"Parse error: the request body could not be read");if(P.step==="no-json-body"){if(m!==void 0)return m(P.forwardRequest,{...B!==void 0&&{authInfo:B}});return xr(400,-32700,"Parse error: the request body is not valid JSON")}let{outcome:O,body:J,parsedBody:Y,forwardRequest:ee}=P;try{switch(O.kind){case"reject":return s(Error(`Rejected inbound request (${O.cell}): ${O.message}`)),Tu(O,Tr(J));case"modern":return await p(O,z,B);case"legacy":return await h(O,ee,B,Y)}}catch(ne){return s(xu(ne)),ku(Tr(J))}}return{fetch:async(z,N)=>{if(a)throw Error("This MCP handler has been closed");try{return await b(z,N)}catch(B){return s(xu(B)),ku(Tr(N?.parsedBody))}},notify:u,bus:c,close:async()=>{a=!0,d.closeAll();let z=[...i].map((N)=>N.close().catch(()=>{}));i.clear(),await Promise.all(z)}}}function Uv(e){if(typeof e!=="string")return null;let t=e.replace(/[^\x20-\x7e]/g," ").replace(/\s+/g," ").trim();if(!t)return null;return t.slice(0,128).trim()}function c$(e,t,n){if(!t)return;let o=Uv(n.clientName);if(o)e.set("X-MCP-Client-Name",o);let r=n.clientInfo?.(),i=Uv(r?.name);if(i)e.set("X-MCP-Client-Info-Name",i);let a=Uv(r?.version);if(a)e.set("X-MCP-Client-Info-Version",a)}var DE=new Map([["oauth_connection_revoked","The upstream account for this server was disconnected. Reconnect it in MCPCloud to use this tool."],["oauth_refresh_failed","The upstream account for this server could not be refreshed. Reconnect it in MCPCloud to use this tool."],["oauth_refresh_token_missing","The upstream account for this server cannot be refreshed. Reconnect it in MCPCloud to use this tool."],["oauth_elicitation_required","Authentication is required to use this tool."],["oauth_rate_limited","Too many credential requests for this server. Wait a moment and retry."],["oauth_runtime_grant_invalid","MCPCloud rejected this server's credential request. Redeploy the server if this keeps happening."]]);function ZE(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.error;if(!t||typeof t!=="object")return null;let n=t.code;return typeof n==="string"&&n?n:null}function qv(e,t){let n=ZE(e);return n&&DE.get(n)||t}var l$=-32042;function u$(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.elicitation;if(!t||typeof t!=="object")return null;let n=t;if(typeof n.url!=="string"||!n.url)return null;return{url:n.url,message:typeof n.message==="string"&&n.message?n.message:"Authentication is required to use this tool.",elicitationId:typeof n.elicitationId==="string"?n.elicitationId:""}}async function FE(e,t,n){if(!e.oauth)throw Error("OAuth runtime settings are not available for this generated server.");let o=e.oauth.mode==="perMember"?t.runtimeToken:null,r=await qu(e,{connectionId:e.oauth.connectionId,forceRefresh:n,callerRuntimeToken:o}),i=await r.json().catch(()=>null);if(!r.ok){let s=u$(i);if(s)throw new D(l$,s.message,{elicitations:[{mode:"url",message:s.message,url:s.url,elicitationId:s.elicitationId}]});throw Error(qv(i,"Unable to resolve the delegated OAuth access token from MCPCloud."))}if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Unable to resolve the delegated OAuth access token from MCPCloud.");let a=typeof i.accessToken==="string"&&i.accessToken.trim()?i.accessToken.trim():null;if(!a)throw Error("MCPCloud did not return an OAuth access token for this request.");return{accessToken:a,tokenType:typeof i.tokenType==="string"&&i.tokenType.trim()?i.tokenType.trim():null}}async function KE(e,t,n){if(!t.runtimeToken)throw Error("Per-member upstream keys require a protected deployment with a verified caller identity.");let o=await f_(e,{callerRuntimeToken:t.runtimeToken,reportInvalid:n}),r=await o.json().catch(()=>null);if(!o.ok){let a=u$(r);if(a)throw new D(l$,a.message,{elicitations:[{mode:"url",message:a.message,url:a.url,elicitationId:a.elicitationId}]});throw Error(qv(r,"Unable to resolve your upstream API key from MCPCloud."))}let i=r&&typeof r.apiKey==="string"&&r.apiKey.trim()?r.apiKey.trim():null;if(!i)throw Error("MCPCloud did not return an upstream API key for this request.");return i}function d$(e){return e.some((t)=>t.type==="oauth2"||t.type==="openIdConnect")}function m$(e,t,n){if(!n)return!1;let o=n.toolOverrides[e];if(o==="on")return!0;if(o==="off")return!1;return n.applyToAllTools||d$(t)}async function ma(e,t,n,o,r=!1){let i=new Headers;c$(i,e.forwardClientIdentity,o);for(let[u,d]of Object.entries(e.customHeaders))i.set(u,d);if(m$(t,n,e.oauth)&&e.oauth){let u=await FE(e,o,r);return i.set("Authorization",`${u.tokenType||"Bearer"} ${u.accessToken}`),i}let a=e.memberKey?await KE(e,o,r):e.apiKey;if(!a)return i;let s=n.find((u)=>u.type==="apiKey"&&u.in==="header");if(s)return i.set(s.name||e.apiKeyHeader,`${e.apiKeyPrefix}${a}`),i;if(n.find((u)=>u.type==="http"&&u.scheme?.toLowerCase()==="bearer"))return i.set("Authorization",`Bearer ${a}`),i;return i.set(e.apiKeyHeader,`${e.apiKeyPrefix}${a}`),i}var JE=new Set([408,429,500,502,503,504]);function p$(e){return JE.has(e)}class pa extends Error{status;retryable;retryAfterSeconds;constructor(e,t,n=null){super(e);this.name="UpstreamHttpError",this.status=t,this.retryable=p$(t),this.retryAfterSeconds=n}}class an extends Error{toolName;issues;constructor(e,t){super(`Invalid input for ${e}: ${t.join("; ")}`);this.name="ToolInputError",this.toolName=e,this.issues=t}}function Lv(e){if(e instanceof pa)return{error:e.message,errorClass:"UPSTREAM",httpStatus:e.status,retryable:e.retryable,...e.retryAfterSeconds!==null?{retryAfterSeconds:e.retryAfterSeconds}:{}};if(e instanceof an)return{error:e.message,errorClass:"BINDING_MISUSE",retryable:!1};return{error:e instanceof Error?e.message:typeof e==="string"?e:"Tool execution failed.",errorClass:"INTERNAL",retryable:!1}}function VE(e){return typeof e==="object"&&e!==null&&e.code===-32042}function f$(e){let t=Lv(e);return{content:[{type:"text",text:t.error}],isError:!0,_meta:{...t}}}function h$(e){let n=e.data?.elicitations;if(!Array.isArray(n))return[];return n.filter((o)=>Boolean(o)&&typeof o==="object"&&typeof o.url==="string")}function BE(e,t){let n=h$(e);if(n.length===0)return null;let o=e instanceof Error&&e.message||"Authorization is required.",r=Object.fromEntries(n.map((i,a)=>[i.elicitationId||`elicitation_${a}`,t.elicitUrl({url:i.url,message:i.message||o})]));return t({inputRequests:r})}function HE(e,t){if(!t)return null;if(t.elicitation)return null;let n=h$(e);if(n.length===0)return null;let o=e instanceof Error&&e.message||"Authorization is required.",r=n.map((i)=>`${i.message||o} Open this page to continue, then run the tool again: ${i.url}`);return r.push("Reconnecting or signing in to MCPCloud again will not resolve this — the credential has to be provided at the link above."),{content:[{type:"text",text:r.join(" ")}],isError:!0,_meta:{...Lv(e),errorClass:"POLICY_DENIED",retryable:!1,elicitationUndeliverable:!0,elicitationUrls:n.map((i)=>i.url)}}}async function fa(e,t){try{return await e()}catch(n){if(VE(n)){let o=HE(n,t?.clientCapabilities?.());if(o)return o;if(t?.era==="modern"&&t.inputRequired){let r=BE(n,t.inputRequired);if(r)return r}throw n}return f$(n)}}var YE=/^(?:invalid|missing|expired|revoked|bad)[_-]?(?:token|api[_-]?key|key|credentials?|auth)$|^(?:token|api[_-]?key|key|credentials?)[_-]?(?:expired|revoked|invalid|missing)$|^unauthenticated$/i;function g$(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function v$(e){if(!g$(e))return{code:null,message:null};let t=g$(e.error)?e.error:null,n=(...o)=>{for(let r of o)if(typeof r==="string"&&r.trim())return r.trim();return null};return{code:n(t?.code,t?.type,e.code,e.error_code,e.errorCode,typeof e.error==="string"?e.error:null),message:n(t?.message,e.message,e.error_description,e.detail)}}function _$(e){let{code:t}=v$(e);return t!==null&&YE.test(t)}function S$(e,t){if(e!==403)return null;let{code:n,message:o}=v$(t);if(!n&&!o)return null;return`The upstream API refused this action: ${[n,o].filter(Boolean).join(" — ")}. This is a permission decision, not a connection problem — reconnecting will not change it.`}function ha(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function GE(e,t){let n=e.properties;if(!n||typeof n!=="object"||Array.isArray(n))return null;let o=n[t];if(!o||typeof o!=="object"||Array.isArray(o))return null;let r=o["x-location"];return typeof r==="string"&&r.trim()?r:null}function b$(e){return e.endpoint.protocol==="graphql"&&Boolean(e.endpoint.document)}function y$(e,t){if(/^https?:\/\//i.test(t))return new URL(t);let n=e.replace(/\/+$/,"");if(!/^https?:\/\//i.test(n))throw Error(`Upstream base URL is not configured for this server — set UPSTREAM_BASE_URL to an absolute http(s) URL in Settings → General (got ${n?`"${n}"`:"an empty value"}).`);return new URL(t?`${n}/${t.replace(/^\/+/,"")}`:n)}async function WE(e,t,n,o,r=!1){let i=y$(n.upstreamBaseUrl,e.endpoint.path),a=await ma(n,e.name,e.auth,o,r);if(b$(e)){a.set("Accept","application/json"),a.set("Content-Type","application/json");let m=Object.fromEntries(Object.entries(t).filter(([,h])=>h!==void 0)),p=JSON.stringify({query:e.endpoint.document,operationName:e.endpoint.operationId??e.endpoint.rootField??void 0,variables:m});return{url:i.toString(),init:{method:"POST",headers:a,body:p}}}let s=e.endpoint.path.replace(/\{([^}]+)\}/g,(m,p)=>encodeURIComponent(String(t[p]??"")));i.pathname=y$(n.upstreamBaseUrl,s).pathname;let c,u;for(let[m,p]of Object.entries(t)){let h=GE(e.inputSchema,m);if(h==="path")continue;if(h==="query"){if(Array.isArray(p))for(let b of p)i.searchParams.append(m,String(b));else if(p!==void 0&&p!==null)i.searchParams.set(m,String(p));continue}if(h==="header"&&p!==void 0&&p!==null){a.set(m,String(p));continue}if(m==="body"&&p!==void 0)u=p}let d=!["GET","HEAD"].includes(e.endpoint.method.toUpperCase());if(u!==void 0&&d)if(e.endpoint.requestBodyContentType==="application/x-www-form-urlencoded")c=$$(u),a.set("Content-Type","application/x-www-form-urlencoded");else c=JSON.stringify(u),a.set("Content-Type","application/json");return{url:i.toString(),init:{method:e.endpoint.method,headers:a,body:c}}}function $$(e){let t=new URLSearchParams;return Dv(t,null,e),t.toString()}function Dv(e,t,n){if(n===void 0||n===null)return;if(Array.isArray(n)){n.forEach((o,r)=>{Dv(e,t?`${t}[${r}]`:String(r),o)});return}if(ha(n)){for(let[o,r]of Object.entries(n)){let i=t?`${t}[${o}]`:o;Dv(e,i,r)}return}if(t===null)return;e.append(t,typeof n==="string"?n:String(n))}async function XE(e){if((e.headers.get("content-type")||"").includes("application/json"))return await e.json();let n=await e.text();if(!n)return null;try{return JSON.parse(n)}catch{return n}}function R$(e){if(!ha(e)||!Array.isArray(e.errors)||!e.errors.length)return null;let t=e.errors.map((n)=>ha(n)&&typeof n.message==="string"?n.message.trim():null).filter((n)=>Boolean(n));return t.length?t.join(" "):"GraphQL execution failed."}function QE(e){if(!e)return null;let t=e.trim();if(!t)return null;let n=Number(t);if(Number.isFinite(n))return n>=0?Math.ceil(n):null;let o=Date.parse(t);if(Number.isNaN(o))return null;return Math.max(0,Math.ceil((o-Date.now())/1000))}function z$(e,t,n){if(!t?.memberKey)return null;if(e!==401&&!(e===403&&_$(n)))return null;let r=`The credential you connected for ${t.serverName?`“${t.serverName}”`:"this server"} was refused by the upstream API — it was most likely revoked, rotated or expired.`;return t.memberKey.connectPageUrl?`${r} Reconnect at ${t.memberKey.connectPageUrl} — signing in to MCPCloud again will not fix it.`:`${r} Reconnect it on this server's MCPCloud connect page — signing in to MCPCloud again will not fix it.`}function Zv(e,t,n,o=null,r){let i=R$(n),a=e.errorMappings.find((h)=>h.statusCode===String(t)),s=i||(typeof n==="string"?n:n?JSON.stringify(n,null,2):"No response body was returned."),c=a?.message?`${a.message} (HTTP ${t})`:`Upstream request failed with status ${t}.`,u=z$(t,r,n),d=u?null:S$(t,n),m=u??d,p=m?`${c} ${m} ${s}`:`${c} ${s}`;return new pa(p,t,o)}function ew(e,t,n,o){if(!t.ok)throw Zv(e,t.status,n,QE(t.headers.get("retry-after")),o);if(!b$(e))return n;if(R$(n))throw Zv(e,t.status||200,n);if(!ha(n)||!ha(n.data))throw Error("GraphQL execution did not return a data payload.");if(e.endpoint.rootField&&Object.prototype.hasOwnProperty.call(n.data,e.endpoint.rootField))return n.data[e.endpoint.rootField];return n.data}function tw(e,t){if(t===null)return`${e.title} completed successfully.`;if(typeof t==="string")return t;return JSON.stringify(t,null,2)}function T$(e){let t=e.previousPem?.trim();if(!t)return{usable:!1,reason:"absent"};let n=e.previousUntil?.trim();if(!n)return{usable:!1,reason:"no-window"};let o=Number(n);if(!Number.isFinite(o))return{usable:!1,reason:"malformed-window"};if(o<=e.nowMs)return{usable:!1,reason:"expired"};return{usable:!0,pem:t,expiresAtMs:o}}var x$=null,k$=null;function rw(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function E$(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function w$(e){return e==="privateOrg"||e==="unlisted"}function Kv(e){if(e==="privateOrg")return{protected:!0,summary:"This MCP endpoint requires an MCPCloud runtime token for callers in the deployment organization."};if(e==="unlisted")return{protected:!0,summary:"This MCP endpoint requires an MCPCloud runtime token and does not rely on URL secrecy as the primary control."};return{protected:!1,summary:"This MCP endpoint is public."}}function Fv(e,t,n){return Response.json({error:t,message:n},{status:e})}function nw(e){let t=e.get("authorization")?.trim();if(!t)return null;return t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function I$(e){let t=atob(e);return Uint8Array.from(t,(n)=>n.charCodeAt(0))}function P$(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4);return I$(n)}function O$(e){let t=e.replace(/-----BEGIN[^-]+-----/g,"").replace(/-----END[^-]+-----/g,"").replace(/\s+/g,"");return E$(I$(t))}function ow(e){return JSON.parse(new TextDecoder().decode(P$(e)))}async function iw(e){return x$||=crypto.subtle.importKey("spki",O$(e.publicKey),{hash:"SHA-256",name:"RSASSA-PKCS1-v1_5"},!1,["verify"]),await x$}async function aw(e){return k$||=crypto.subtle.importKey("spki",O$(e),{hash:"SHA-256",name:"RSASSA-PKCS1-v1_5"},!1,["verify"]),await k$}async function sw(e,t,n){let[o,r,i]=e.split(".");if(!o||!r||!i)throw Error("Runtime token is malformed.");let a=ow(r);if(!rw(a))throw Error("Runtime token payload is invalid.");let s=E$(P$(i)),c=new TextEncoder().encode(`${o}.${r}`),u=await crypto.subtle.verify("RSASSA-PKCS1-v1_5",await iw(n),s,c);if(!u){let m=T$({previousPem:n.publicKeyPrevious,previousUntil:n.publicKeyPreviousUntil,nowMs:Date.now()});if(m.usable)try{u=await crypto.subtle.verify("RSASSA-PKCS1-v1_5",await aw(m.pem),s,c)}catch{u=!1}}if(!u)throw Error("Runtime token signature is invalid.");let d=Math.floor(Date.now()/1000);if(a.aud!==n.audience||a.iss!==n.issuer||a.deploymentId!==n.deploymentId||a.deploymentVersion!==n.deploymentVersion||a.accessMode!==t||a.orgId!==n.organizationId||a.serverId!==n.serverId||typeof a.exp!=="number"||a.exp<=d||typeof a.iat!=="number"||typeof a.jti!=="string"||typeof a.sub!=="string")throw Error("Runtime token claims are invalid.");return{sub:a.sub,clientName:typeof a.clientName==="string"?a.clientName:null}}async function Jv(e,t){if(!w$(t.accessMode))return{response:null,callerUserId:null,rawToken:null};if(!t.runtimeAuth)return{response:Fv(500,"runtime_auth_misconfigured","Runtime auth is not configured for this deployment."),callerUserId:null,rawToken:null};let n=nw(e.headers);if(!n)return{response:Fv(401,"runtime_auth_required","This MCP endpoint requires an MCPCloud runtime access token."),callerUserId:null,rawToken:null};try{let o=await sw(n,t.accessMode,t.runtimeAuth);return{response:null,callerUserId:o.sub,rawToken:n,callerClientName:o.clientName}}catch{return{response:Fv(401,"runtime_auth_invalid","This MCP endpoint requires a valid MCPCloud runtime access token."),callerUserId:null,rawToken:null}}}function N$(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;let o=Array.from({length:t.length+1},(r,i)=>i);for(let r=1;r<=e.length;r+=1){let i=[r],a=r;for(let s=1;s<=t.length;s+=1){let c=e[r-1]===t[s-1]?0:1;i[s]=Math.min(o[s]+1,i[s-1]+1,o[s-1]+c),a=Math.min(a,i[s])}if(a>n)return n+1;o=i}return o[t.length]}function cw(e,t){if(!t.length)return null;let n=Math.max(1,Math.floor(e.length/3)),o=e.toLowerCase(),r=null,i=n+1;for(let a of t){if(a.toLowerCase()===o)return a;let s=N$(o,a.toLowerCase(),n);if(s<=n&&s<i)r=a,i=s}return r}function j$(e,t,n){if(!t.length)return{suggestion:null,nearest:[]};let o=e.toLowerCase(),r=Math.max(1,e.length),i=t.map((c)=>({name:c,distance:N$(o,c.toLowerCase(),r)}));i.sort((c,u)=>c.distance-u.distance||(c.name<u.name?-1:1));let a=Math.max(1,Math.ceil(e.length/2)),[s]=i;return{suggestion:s.distance<=a?s.name:null,nearest:i.slice(0,n).map((c)=>c.name)}}function sn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $e(e){return e.length?`/${e.join("/")}`:"/"}function A$(e){let t=e.type;if(typeof t==="string")return[t];if(Array.isArray(t))return t.filter((n)=>typeof n==="string");return[]}function lw(e){return e.nullable===!0||A$(e).includes("null")}function Iu(e,t,n){let o=[];return wu(e,t,n,o),o}function M$(e,t){return Iu(e,t,[]).map((n)=>`${n.path} ${n.message}`)}function C$(e,t,n,o,r){let i=t[e];if(!Array.isArray(i)||!i.length)return!1;if(i.filter((s)=>sn(s)&&Iu(s,n,o).length===0).length>0)return!0;return r.push({path:$e(o),message:"must match at least one allowed schema"}),!0}function uw(e,t,n,o){if(!sn(t))return o.push({path:$e(n),message:"must be an object"}),!0;let r=sn(e.properties)?e.properties:{},i=Array.isArray(e.required)?e.required.filter((s)=>typeof s==="string"):[],a=sn(e.additionalProperties)?e.additionalProperties:null;for(let s of i)if(!(s in t)||t[s]===void 0)o.push({path:$e([...n,s]),message:"is required"});if(e.additionalProperties===!1){for(let s of Object.keys(t))if(!(s in r)){let c=cw(s,Object.keys(r));o.push({path:$e([...n,s]),message:c?`is not allowed (did you mean "${c}"?)`:"is not allowed"})}}else if(a)for(let[s,c]of Object.entries(t)){if(s in r)continue;wu(a,c,[...n,s],o)}for(let[s,c]of Object.entries(r)){if(!(s in t)||t[s]===void 0)continue;if(sn(c))wu(c,t[s],[...n,s],o)}return!0}function dw(e,t,n,o){if(!Array.isArray(t))return o.push({path:$e(n),message:"must be an array"}),!0;if(typeof e.minItems==="number"&&t.length<e.minItems)o.push({path:$e(n),message:`must contain at least ${e.minItems} items`});if(typeof e.maxItems==="number"&&t.length>e.maxItems)o.push({path:$e(n),message:`must contain no more than ${e.maxItems} items`});if(sn(e.items))t.forEach((r,i)=>wu(e.items,r,[...n,String(i)],o));return!0}function mw(e,t,n,o){if(typeof t!=="string")return o.push({path:$e(n),message:"must be a string"}),!0;if(typeof e.minLength==="number"&&t.length<e.minLength)o.push({path:$e(n),message:`must have length at least ${e.minLength}`});if(typeof e.maxLength==="number"&&t.length>e.maxLength)o.push({path:$e(n),message:`must have length no greater than ${e.maxLength}`});if(typeof e.pattern==="string"){if(!new RegExp(e.pattern).test(t))o.push({path:$e(n),message:`must match pattern ${e.pattern}`})}return!0}function pw(e,t,n,o,r){if(typeof n!=="number"||Number.isNaN(n))return r.push({path:$e(o),message:e==="integer"?"must be an integer":"must be a number"}),!0;if(e==="integer"&&!Number.isInteger(n))r.push({path:$e(o),message:"must be an integer"});if(typeof t.minimum==="number"&&n<t.minimum)r.push({path:$e(o),message:`must be at least ${t.minimum}`});if(typeof t.maximum==="number"&&n>t.maximum)r.push({path:$e(o),message:`must be no greater than ${t.maximum}`});return!0}function wu(e,t,n,o){if(t===null&&lw(e))return;if(C$("anyOf",e,t,n,o)||C$("oneOf",e,t,n,o))return;if(Object.prototype.hasOwnProperty.call(e,"const")&&t!==e.const){o.push({path:$e(n),message:`must equal ${JSON.stringify(e.const)}`});return}if(Array.isArray(e.enum)&&!e.enum.some((s)=>s===t)){o.push({path:$e(n),message:`must be one of ${e.enum.map((s)=>JSON.stringify(s)).join(", ")}`});return}let r=A$(e).filter((s)=>s!=="null"),i=r.length?r:Array.isArray(e.items)?["array"]:sn(e.properties)?["object"]:[];if(!i.length)return;if(i.length>1){if(!i.find((c)=>Iu({...e,type:c},t,n).length===0))o.push({path:$e(n),message:`must match one of the allowed types: ${i.join(", ")}`});return}let[a]=i;switch(a){case"object":uw(e,t,n,o);return;case"array":dw(e,t,n,o);return;case"string":mw(e,t,n,o);return;case"integer":case"number":pw(a,e,t,n,o);return;case"boolean":if(typeof t!=="boolean")o.push({path:$e(n),message:"must be a boolean"});return;case"null":if(t!==null)o.push({path:$e(n),message:"must be null"});return;default:return}}function fw(e,t,n){let o=Iu(t,n,[]);if(o.length)throw new an(e,o.map((r)=>`${r.path} ${r.message}`));return n}var fo=(e)=>e!==null&&Object.prototype.toString.call(e)==="[object Object]",Ou=(e,t)=>{if(e===t)return!0;if(typeof e!==typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Ou(e[n],t[n]))return!1;return!0}if(fo(e)&&fo(t)){let n=Object.entries(e),o=new Set(Object.keys(t));if(n.length!==o.size)return!1;for(let[r,i]of n){if(!Ou(i,t[r]))return!1;o.delete(r)}return o.size===0}return!1},Pu=(e)=>{if(e===""||e===!1||e===null||e===void 0)return!0;if(Array.isArray(e)&&e.length===0)return!0;if(fo(e)){for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}return!1},hw=(e)=>e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_",U$=(e)=>e>="0"&&e<="9"||e==="-",gw=(e)=>e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||e==="_",_;(function(e){e.TOK_EOF="EOF",e.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",e.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",e.TOK_RBRACKET="Rbracket",e.TOK_RPAREN="Rparen",e.TOK_COMMA="Comma",e.TOK_COLON="Colon",e.TOK_RBRACE="Rbrace",e.TOK_NUMBER="Number",e.TOK_CURRENT="Current",e.TOK_ROOT="Root",e.TOK_EXPREF="Expref",e.TOK_PIPE="Pipe",e.TOK_OR="Or",e.TOK_AND="And",e.TOK_EQ="EQ",e.TOK_GT="GT",e.TOK_LT="LT",e.TOK_GTE="GTE",e.TOK_LTE="LTE",e.TOK_NE="NE",e.TOK_FLATTEN="Flatten",e.TOK_STAR="Star",e.TOK_FILTER="Filter",e.TOK_DOT="Dot",e.TOK_NOT="Not",e.TOK_LBRACE="Lbrace",e.TOK_LBRACKET="Lbracket",e.TOK_LPAREN="Lparen",e.TOK_LITERAL="Literal"})(_||(_={}));var q$={"(":_.TOK_LPAREN,")":_.TOK_RPAREN,"*":_.TOK_STAR,",":_.TOK_COMMA,".":_.TOK_DOT,":":_.TOK_COLON,"@":_.TOK_CURRENT,["$"]:_.TOK_ROOT,"]":_.TOK_RBRACKET,"{":_.TOK_LBRACE,"}":_.TOK_RBRACE},vw={"!":!0,"<":!0,"=":!0,">":!0},_w={"\t":!0,"\n":!0,"\r":!0," ":!0};class L${constructor(){this._current=0}tokenize(e){let t=[];this._current=0;let n,o,r;while(this._current<e.length)if(hw(e[this._current]))n=this._current,o=this.consumeUnquotedIdentifier(e),t.push({start:n,type:_.TOK_UNQUOTEDIDENTIFIER,value:o});else if(q$[e[this._current]]!==void 0)t.push({start:this._current,type:q$[e[this._current]],value:e[this._current]}),this._current+=1;else if(U$(e[this._current]))r=this.consumeNumber(e),t.push(r);else if(e[this._current]==="[")r=this.consumeLBracket(e),t.push(r);else if(e[this._current]==='"')n=this._current,o=this.consumeQuotedIdentifier(e),t.push({start:n,type:_.TOK_QUOTEDIDENTIFIER,value:o});else if(e[this._current]==="'")n=this._current,o=this.consumeRawStringLiteral(e),t.push({start:n,type:_.TOK_LITERAL,value:o});else if(e[this._current]==="`"){n=this._current;let i=this.consumeLiteral(e);t.push({start:n,type:_.TOK_LITERAL,value:i})}else if(vw[e[this._current]]!==void 0)r=this.consumeOperator(e),r&&t.push(r);else if(_w[e[this._current]]!==void 0)this._current+=1;else if(e[this._current]==="&")if(n=this._current,this._current+=1,e[this._current]==="&")this._current+=1,t.push({start:n,type:_.TOK_AND,value:"&&"});else t.push({start:n,type:_.TOK_EXPREF,value:"&"});else if(e[this._current]==="|")if(n=this._current,this._current+=1,e[this._current]==="|")this._current+=1,t.push({start:n,type:_.TOK_OR,value:"||"});else t.push({start:n,type:_.TOK_PIPE,value:"|"});else{let i=Error(`Unknown character: ${e[this._current]}`);throw i.name="LexerError",i}return t}consumeUnquotedIdentifier(e){let t=this._current;this._current+=1;while(this._current<e.length&&gw(e[this._current]))this._current+=1;return e.slice(t,this._current)}consumeQuotedIdentifier(e){let t=this._current;this._current+=1;let n=e.length;while(e[this._current]!=='"'&&this._current<n){let o=this._current;if(e[o]==="\\"&&(e[o+1]==="\\"||e[o+1]==='"'))o+=2;else o+=1;this._current=o}return this._current+=1,JSON.parse(e.slice(t,this._current))}consumeRawStringLiteral(e){let t=this._current;this._current+=1;let n=e.length;while(e[this._current]!=="'"&&this._current<n){let r=this._current;if(e[r]==="\\"&&(e[r+1]==="\\"||e[r+1]==="'"))r+=2;else r+=1;this._current=r}return this._current+=1,e.slice(t+1,this._current-1).replace("\\'","'")}consumeNumber(e){let t=this._current;this._current+=1;let n=e.length;while(U$(e[this._current])&&this._current<n)this._current+=1;let o=parseInt(e.slice(t,this._current),10);return{start:t,value:o,type:_.TOK_NUMBER}}consumeLBracket(e){let t=this._current;if(this._current+=1,e[this._current]==="?")return this._current+=1,{start:t,type:_.TOK_FILTER,value:"[?"};if(e[this._current]==="]")return this._current+=1,{start:t,type:_.TOK_FLATTEN,value:"[]"};return{start:t,type:_.TOK_LBRACKET,value:"["}}consumeOperator(e){let t=this._current,n=e[t];if(this._current+=1,n==="!"){if(e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_NE,value:"!="};return{start:t,type:_.TOK_NOT,value:"!"}}if(n==="<"){if(e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_LTE,value:"<="};return{start:t,type:_.TOK_LT,value:"<"}}if(n===">"){if(e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_GTE,value:">="};return{start:t,type:_.TOK_GT,value:">"}}if(n==="="&&e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_EQ,value:"=="}}consumeLiteral(e){this._current+=1;let t=this._current,n=e.length;while(e[this._current]!=="`"&&this._current<n){let i=this._current;if(e[i]==="\\"&&(e[i+1]==="\\"||e[i+1]==="`"))i+=2;else i+=1;this._current=i}let o=e.slice(t,this._current).trimLeft();o=o.replace("\\`","`");let r=this.looksLikeJSON(o)?JSON.parse(o):JSON.parse(`"${o}"`);return this._current+=1,r}looksLikeJSON(e){let n=["true","false","null"],o="-0123456789";if(e==="")return!1;if('[{"'.includes(e[0]))return!0;if(n.includes(e))return!0;if("-0123456789".includes(e[0]))try{return JSON.parse(e),!0}catch(r){return!1}return!1}}var Sw=new L$,Ce={[_.TOK_EOF]:0,[_.TOK_UNQUOTEDIDENTIFIER]:0,[_.TOK_QUOTEDIDENTIFIER]:0,[_.TOK_RBRACKET]:0,[_.TOK_RPAREN]:0,[_.TOK_COMMA]:0,[_.TOK_RBRACE]:0,[_.TOK_NUMBER]:0,[_.TOK_CURRENT]:0,[_.TOK_EXPREF]:0,[_.TOK_ROOT]:0,[_.TOK_PIPE]:1,[_.TOK_OR]:2,[_.TOK_AND]:3,[_.TOK_EQ]:5,[_.TOK_GT]:5,[_.TOK_LT]:5,[_.TOK_GTE]:5,[_.TOK_LTE]:5,[_.TOK_NE]:5,[_.TOK_FLATTEN]:9,[_.TOK_STAR]:20,[_.TOK_FILTER]:21,[_.TOK_DOT]:40,[_.TOK_NOT]:45,[_.TOK_LBRACE]:50,[_.TOK_LBRACKET]:55,[_.TOK_LPAREN]:60};class D${constructor(){this.index=0,this.tokens=[]}parse(e){this.loadTokens(e),this.index=0;let t=this.expression(0);if(this.lookahead(0)!==_.TOK_EOF){let n=this.lookaheadToken(0);this.errorToken(n,`Unexpected token type: ${n.type}, value: ${n.value}`)}return t}loadTokens(e){this.tokens=[...Sw.tokenize(e),{type:_.TOK_EOF,value:"",start:e.length}]}expression(e){let t=this.lookaheadToken(0);this.advance();let n=this.nud(t),o=this.lookahead(0);while(e<Ce[o])this.advance(),n=this.led(o,n),o=this.lookahead(0);return n}lookahead(e){return this.tokens[this.index+e].type}lookaheadToken(e){return this.tokens[this.index+e]}advance(){this.index+=1}nud(e){let t,n,o;switch(e.type){case _.TOK_LITERAL:return{type:"Literal",value:e.value};case _.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:e.value};case _.TOK_QUOTEDIDENTIFIER:let r={type:"Field",name:e.value};if(this.lookahead(0)===_.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return r;case _.TOK_NOT:return n=this.expression(Ce.Not),{type:"NotExpression",children:[n]};case _.TOK_STAR:return t={type:"Identity"},n=this.lookahead(0)===_.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(Ce.Star),{type:"ValueProjection",children:[t,n]};case _.TOK_FILTER:return this.led(e.type,{type:"Identity"});case _.TOK_LBRACE:return this.parseMultiselectHash();case _.TOK_FLATTEN:return t={type:_.TOK_FLATTEN,children:[{type:"Identity"}]},n=this.parseProjectionRHS(Ce.Flatten),{type:"Projection",children:[t,n]};case _.TOK_LBRACKET:if(this.lookahead(0)===_.TOK_NUMBER||this.lookahead(0)===_.TOK_COLON)return n=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},n);if(this.lookahead(0)===_.TOK_STAR&&this.lookahead(1)===_.TOK_RBRACKET)return this.advance(),this.advance(),n=this.parseProjectionRHS(Ce.Star),{children:[{type:"Identity"},n],type:"Projection"};return this.parseMultiselectList();case _.TOK_CURRENT:return{type:_.TOK_CURRENT};case _.TOK_ROOT:return{type:_.TOK_ROOT};case _.TOK_EXPREF:return o=this.expression(Ce.Expref),{type:"ExpressionReference",children:[o]};case _.TOK_LPAREN:let i=[];while(this.lookahead(0)!==_.TOK_RPAREN){if(this.lookahead(0)===_.TOK_CURRENT)o={type:_.TOK_CURRENT},this.advance();else o=this.expression(0);i.push(o)}return this.match(_.TOK_RPAREN),i[0];default:this.errorToken(e)}}led(e,t){let n;switch(e){case _.TOK_DOT:let o=Ce.Dot;if(this.lookahead(0)!==_.TOK_STAR)return n=this.parseDotRHS(o),{type:"Subexpression",children:[t,n]};return this.advance(),n=this.parseProjectionRHS(o),{type:"ValueProjection",children:[t,n]};case _.TOK_PIPE:return n=this.expression(Ce.Pipe),{type:_.TOK_PIPE,children:[t,n]};case _.TOK_OR:return n=this.expression(Ce.Or),{type:"OrExpression",children:[t,n]};case _.TOK_AND:return n=this.expression(Ce.And),{type:"AndExpression",children:[t,n]};case _.TOK_LPAREN:let r=t.name,i=[],a;while(this.lookahead(0)!==_.TOK_RPAREN){if(this.lookahead(0)===_.TOK_CURRENT)a={type:_.TOK_CURRENT},this.advance();else a=this.expression(0);if(this.lookahead(0)===_.TOK_COMMA)this.match(_.TOK_COMMA);i.push(a)}return this.match(_.TOK_RPAREN),{name:r,type:"Function",children:i};case _.TOK_FILTER:let c=this.expression(0);return this.match(_.TOK_RBRACKET),n=this.lookahead(0)===_.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(Ce.Filter),{type:"FilterProjection",children:[t,n,c]};case _.TOK_FLATTEN:let u={type:_.TOK_FLATTEN,children:[t]},d=this.parseProjectionRHS(Ce.Flatten);return{type:"Projection",children:[u,d]};case _.TOK_EQ:case _.TOK_NE:case _.TOK_GT:case _.TOK_GTE:case _.TOK_LT:case _.TOK_LTE:return this.parseComparator(t,e);case _.TOK_LBRACKET:let m=this.lookaheadToken(0);if(m.type===_.TOK_NUMBER||m.type===_.TOK_COLON)return n=this.parseIndexExpression(),this.projectIfSlice(t,n);return this.match(_.TOK_STAR),this.match(_.TOK_RBRACKET),n=this.parseProjectionRHS(Ce.Star),{type:"Projection",children:[t,n]};default:return this.errorToken(this.lookaheadToken(0))}}match(e){if(this.lookahead(0)===e){this.advance();return}else{let t=this.lookaheadToken(0);this.errorToken(t,`Expected ${e}, got: ${t.type}`)}}errorToken(e,t=""){let n=Error(t||`Invalid token (${e.type}): "${e.value}"`);throw n.name="ParserError",n}parseIndexExpression(){if(this.lookahead(0)===_.TOK_COLON||this.lookahead(1)===_.TOK_COLON)return this.parseSliceExpression();let e={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(_.TOK_RBRACKET),e}projectIfSlice(e,t){let n={type:"IndexExpression",children:[e,t]};if(t.type==="Slice")return{children:[n,this.parseProjectionRHS(Ce.Star)],type:"Projection"};return n}parseSliceExpression(){let e=[null,null,null],t=0,n=this.lookahead(0);while(n!==_.TOK_RBRACKET&&t<3){if(n===_.TOK_COLON)t+=1,this.advance();else if(n===_.TOK_NUMBER)e[t]=this.lookaheadToken(0).value,this.advance();else{let o=this.lookaheadToken(0);this.errorToken(o,`Syntax error, unexpected token: ${o.value}(${o.type})`)}n=this.lookahead(0)}return this.match(_.TOK_RBRACKET),{children:e,type:"Slice"}}parseComparator(e,t){let n=this.expression(Ce[t]);return{type:"Comparator",name:t,children:[e,n]}}parseDotRHS(e){let t=this.lookahead(0);if([_.TOK_UNQUOTEDIDENTIFIER,_.TOK_QUOTEDIDENTIFIER,_.TOK_STAR].includes(t))return this.expression(e);if(t===_.TOK_LBRACKET)return this.match(_.TOK_LBRACKET),this.parseMultiselectList();if(t===_.TOK_LBRACE)return this.match(_.TOK_LBRACE),this.parseMultiselectHash();let o=this.lookaheadToken(0);this.errorToken(o,`Syntax error, unexpected token: ${o.value}(${o.type})`)}parseProjectionRHS(e){if(Ce[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===_.TOK_LBRACKET)return this.expression(e);if(this.lookahead(0)===_.TOK_FILTER)return this.expression(e);if(this.lookahead(0)===_.TOK_DOT)return this.match(_.TOK_DOT),this.parseDotRHS(e);let t=this.lookaheadToken(0);this.errorToken(t,`Syntax error, unexpected token: ${t.value}(${t.type})`)}parseMultiselectList(){let e=[];while(this.lookahead(0)!==_.TOK_RBRACKET){let t=this.expression(0);if(e.push(t),this.lookahead(0)===_.TOK_COMMA){if(this.match(_.TOK_COMMA),this.lookahead(0)===_.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(_.TOK_RBRACKET),{type:"MultiSelectList",children:e}}parseMultiselectHash(){let e=[],t=[_.TOK_UNQUOTEDIDENTIFIER,_.TOK_QUOTEDIDENTIFIER],n,o,r;for(;;){if(n=this.lookaheadToken(0),!t.includes(n.type))throw Error(`Expecting an identifier token, got: ${n.type}`);if(o=n.value,this.advance(),this.match(_.TOK_COLON),r=this.expression(0),e.push({value:r,type:"KeyValuePair",name:o}),this.lookahead(0)===_.TOK_COMMA)this.match(_.TOK_COMMA);else if(this.lookahead(0)===_.TOK_RBRACE){this.match(_.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:e}}}var yw=new D$,E;(function(e){e[e.TYPE_NUMBER=0]="TYPE_NUMBER",e[e.TYPE_ANY=1]="TYPE_ANY",e[e.TYPE_STRING=2]="TYPE_STRING",e[e.TYPE_ARRAY=3]="TYPE_ARRAY",e[e.TYPE_OBJECT=4]="TYPE_OBJECT",e[e.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",e[e.TYPE_EXPREF=6]="TYPE_EXPREF",e[e.TYPE_NULL=7]="TYPE_NULL",e[e.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",e[e.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(E||(E={}));class Z${constructor(e){this.TYPE_NAME_TABLE={[E.TYPE_NUMBER]:"number",[E.TYPE_ANY]:"any",[E.TYPE_STRING]:"string",[E.TYPE_ARRAY]:"array",[E.TYPE_OBJECT]:"object",[E.TYPE_BOOLEAN]:"boolean",[E.TYPE_EXPREF]:"expression",[E.TYPE_NULL]:"null",[E.TYPE_ARRAY_NUMBER]:"Array<number>",[E.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([t])=>Math.abs(t),this.functionAvg=([t])=>{let n=0;for(let o=0;o<t.length;o+=1)n+=t[o];return n/t.length},this.functionCeil=([t])=>Math.ceil(t),this.functionContains=(t)=>{let[n,o]=t;return n.includes(o)},this.functionEndsWith=(t)=>{let[n,o]=t;return n.includes(o,n.length-o.length)},this.functionFloor=([t])=>Math.floor(t),this.functionJoin=(t)=>{let[n,o]=t;return o.join(n)},this.functionKeys=([t])=>Object.keys(t),this.functionLength=([t])=>{if(!fo(t))return t.length;return Object.keys(t).length},this.functionMap=(t)=>{if(!this._interpreter)return[];let n=[],o=this._interpreter,r=t[0],i=t[1];for(let a=0;a<i.length;a+=1)n.push(o.visit(r,i[a]));return n},this.functionMax=([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===E.TYPE_NUMBER)return Math.max(...t);let o=t,r=o[0];for(let i=1;i<o.length;i+=1)if(r.localeCompare(o[i])<0)r=o[i];return r},this.functionMaxBy=(t)=>{let n=t[1],o=t[0],r=this.createKeyFunction(n,[E.TYPE_NUMBER,E.TYPE_STRING]),i=-1/0,a,s;for(let c=0;c<o.length;c+=1)if(s=r&&r(o[c]),s!==void 0&&s>i)i=s,a=o[c];return a},this.functionMerge=(t)=>{let n={};for(let o=0;o<t.length;o+=1){let r=t[o];n=Object.assign(n,r)}return n},this.functionMin=([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===E.TYPE_NUMBER)return Math.min(...t);let o=t,r=o[0];for(let i=1;i<o.length;i+=1)if(o[i].localeCompare(r)<0)r=o[i];return r},this.functionMinBy=(t)=>{let n=t[1],o=t[0],r=this.createKeyFunction(n,[E.TYPE_NUMBER,E.TYPE_STRING]),i=1/0,a,s;for(let c=0;c<o.length;c+=1)if(s=r&&r(o[c]),s!==void 0&&s<i)i=s,a=o[c];return a},this.functionNotNull=(t)=>{for(let n=0;n<t.length;n+=1)if(this.getTypeName(t[n])!==E.TYPE_NULL)return t[n];return null},this.functionReverse=([t])=>{if(this.getTypeName(t)===E.TYPE_STRING){let r=t,i="";for(let a=r.length-1;a>=0;a-=1)i+=r[a];return i}let o=t.slice(0);return o.reverse(),o},this.functionSort=([t])=>[...t].sort(),this.functionSortBy=(t)=>{if(!this._interpreter)return[];let n=t[0].slice(0);if(n.length===0)return n;let o=this._interpreter,r=t[1],i=this.getTypeName(o.visit(r,n[0]));if(i!==void 0&&![E.TYPE_NUMBER,E.TYPE_STRING].includes(i))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[i]})`);let a=[];for(let s=0;s<n.length;s+=1)a.push([s,n[s]]);a.sort((s,c)=>{let u=o.visit(r,s[1]),d=o.visit(r,c[1]);if(this.getTypeName(u)!==i)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[i]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(u)]}`);else if(this.getTypeName(d)!==i)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[i]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(d)]}`);if(u>d)return 1;return u<d?-1:s[0]-c[0]});for(let s=0;s<a.length;s+=1)n[s]=a[s][1];return n},this.functionStartsWith=([t,n])=>t.startsWith(n),this.functionSum=([t])=>t.reduce((n,o)=>n+o,0),this.functionToArray=([t])=>{if(this.getTypeName(t)===E.TYPE_ARRAY)return t;return[t]},this.functionToNumber=([t])=>{let n=this.getTypeName(t),o;if(n===E.TYPE_NUMBER)return t;if(n===E.TYPE_STRING){if(o=+t,!isNaN(o))return o}return null},this.functionToString=([t])=>{if(this.getTypeName(t)===E.TYPE_STRING)return t;return JSON.stringify(t)},this.functionType=([t])=>{switch(this.getTypeName(t)){case E.TYPE_NUMBER:return"number";case E.TYPE_STRING:return"string";case E.TYPE_ARRAY:return"array";case E.TYPE_OBJECT:return"object";case E.TYPE_BOOLEAN:return"boolean";case E.TYPE_EXPREF:return"expref";case E.TYPE_NULL:return"null";default:return}},this.functionValues=([t])=>Object.values(t),this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[E.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[E.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[E.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[E.TYPE_STRING,E.TYPE_ARRAY]},{types:[E.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[E.TYPE_STRING]},{types:[E.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[E.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[E.TYPE_STRING]},{types:[E.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[E.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[E.TYPE_STRING,E.TYPE_ARRAY,E.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[E.TYPE_EXPREF]},{types:[E.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[E.TYPE_ARRAY_NUMBER,E.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[E.TYPE_ARRAY]},{types:[E.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[E.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[E.TYPE_ARRAY_NUMBER,E.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[E.TYPE_ARRAY]},{types:[E.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[E.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[E.TYPE_STRING,E.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[E.TYPE_ARRAY_STRING,E.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[E.TYPE_ARRAY]},{types:[E.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[E.TYPE_STRING]},{types:[E.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[E.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[E.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[E.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[E.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[E.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[E.TYPE_OBJECT]}]}},this._interpreter=e}registerFunction(e,t,n){if(e in this.functionTable)throw Error(`Function already defined: ${e}()`);this.functionTable[e]={_func:t.bind(this),_signature:n}}callFunction(e,t){let n=this.functionTable[e];if(n===void 0)throw Error(`Unknown function: ${e}()`);return this.validateArgs(e,t,n._signature),n._func.call(this,t)}validateInputSignatures(e,t){for(let n=0;n<t.length;n+=1)if("variadic"in t[n]&&n!==t.length-1)throw Error(`ArgumentError: ${e}() 'variadic' argument ${n+1} must occur last`)}validateArgs(e,t,n){var o,r;let i;this.validateInputSignatures(e,n);let a=n.filter((b)=>{var R;return(R=!b.optional)!==null&&R!==void 0?R:!1}).length,s=(r=(o=n[n.length-1])===null||o===void 0?void 0:o.variadic)!==null&&r!==void 0?r:!1,c=t.length<a,u=t.length>n.length,d=c&&(!s&&a>1||s)?"at least ":"";if(s&&c||!s&&(c||u))throw i=n.length>1,Error(`ArgumentError: ${e}() takes ${d}${a} argument${i&&"s"||""} but received ${t.length}`);let m,p,h;for(let b=0;b<n.length;b+=1){h=!1,m=n[b].types,p=this.getTypeName(t[b]);let R;for(R=0;R<m.length;R+=1)if(p!==void 0&&this.typeMatches(p,m[R],t[b])){h=!0;break}if(!h&&p!==void 0){let z=m.map((N)=>this.TYPE_NAME_TABLE[N]).join(" | ");throw Error(`TypeError: ${e}() expected argument ${b+1} to be type (${z}) but received type ${this.TYPE_NAME_TABLE[p]} instead.`)}}}typeMatches(e,t,n){if(t===E.TYPE_ANY)return!0;if(t===E.TYPE_ARRAY_STRING||t===E.TYPE_ARRAY_NUMBER||t===E.TYPE_ARRAY){if(t===E.TYPE_ARRAY)return e===E.TYPE_ARRAY;if(e===E.TYPE_ARRAY){let o;if(t===E.TYPE_ARRAY_NUMBER)o=E.TYPE_NUMBER;else if(t===E.TYPE_ARRAY_STRING)o=E.TYPE_STRING;for(let r=0;r<n.length;r+=1){let i=this.getTypeName(n[r]);if(i!==void 0&&o!==void 0&&!this.typeMatches(i,o,n[r]))return!1}return!0}}else return e===t;return!1}getTypeName(e){switch(Object.prototype.toString.call(e)){case"[object String]":return E.TYPE_STRING;case"[object Number]":return E.TYPE_NUMBER;case"[object Array]":return E.TYPE_ARRAY;case"[object Boolean]":return E.TYPE_BOOLEAN;case"[object Null]":return E.TYPE_NULL;case"[object Object]":if(e.jmespathType===_.TOK_EXPREF)return E.TYPE_EXPREF;return E.TYPE_OBJECT;default:return}}createKeyFunction(e,t){if(!this._interpreter)return;let n=this._interpreter;return(r)=>{let i=n.visit(e,r);if(!t.includes(this.getTypeName(i))){let a=`TypeError: expected one of (${t.map((s)=>this.TYPE_NAME_TABLE[s]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(i)]}`;throw Error(a)}return i}}}class F${constructor(){this._rootValue=null,this.runtime=new Z$(this)}search(e,t){return this._rootValue=t,this.visit(e,t)}visit(e,t){let n,o,r,i,a,s,c,u,d,m,p;switch(e.type){case"Field":if(t===null)return null;if(fo(t)){if(s=t[e.name],s===void 0)return null;return s}return null;case"Subexpression":r=this.visit(e.children[0],t);for(m=1;m<e.children.length;m+=1)if(r=this.visit(e.children[1],r),r===null)return null;return r;case"IndexExpression":return c=this.visit(e.children[0],t),u=this.visit(e.children[1],c),u;case"Index":if(!Array.isArray(t))return null;let h=e.value;if(h<0)h=t.length+h;if(r=t[h],r===void 0)r=null;return r;case"Slice":if(!Array.isArray(t))return null;let b=[...e.children],R=this.computeSliceParams(t.length,b),[z,N,B]=R;if(r=[],B>0)for(m=z;m<N;m+=B)r.push(t[m]);else for(m=z;m>N;m+=B)r.push(t[m]);return r;case"Projection":if(p=this.visit(e.children[0],t),!Array.isArray(p))return null;d=[];for(m=0;m<p.length;m+=1)if(o=this.visit(e.children[1],p[m]),o!==null)d.push(o);return d;case"ValueProjection":if(p=this.visit(e.children[0],t),!fo(p))return null;d=[];let P=Object.values(p);for(m=0;m<P.length;m+=1)if(o=this.visit(e.children[1],P[m]),o!==null)d.push(o);return d;case"FilterProjection":if(p=this.visit(e.children[0],t),!Array.isArray(p))return null;let O=[],J=[];for(m=0;m<p.length;m+=1)if(n=this.visit(e.children[2],p[m]),!Pu(n))O.push(p[m]);for(let ue=0;ue<O.length;ue+=1)if(o=this.visit(e.children[1],O[ue]),o!==null)J.push(o);return J;case"Comparator":switch(i=this.visit(e.children[0],t),a=this.visit(e.children[1],t),e.name){case _.TOK_EQ:r=Ou(i,a);break;case _.TOK_NE:r=!Ou(i,a);break;case _.TOK_GT:r=i>a;break;case _.TOK_GTE:r=i>=a;break;case _.TOK_LT:r=i<a;break;case _.TOK_LTE:r=i<=a;break;default:throw Error(`Unknown comparator: ${e.name}`)}return r;case _.TOK_FLATTEN:let Y=this.visit(e.children[0],t);if(!Array.isArray(Y))return null;let ee=[];for(m=0;m<Y.length;m+=1)if(o=Y[m],Array.isArray(o))ee=[...ee,...o];else ee.push(o);return ee;case"Identity":return t;case"MultiSelectList":if(t===null)return null;d=[];for(m=0;m<e.children.length;m+=1)d.push(this.visit(e.children[m],t));return d;case"MultiSelectHash":if(t===null)return null;d={};let ne;for(m=0;m<e.children.length;m+=1)ne=e.children[m],d[ne.name]=this.visit(ne.value,t);return d;case"OrExpression":if(n=this.visit(e.children[0],t),Pu(n))n=this.visit(e.children[1],t);return n;case"AndExpression":if(i=this.visit(e.children[0],t),Pu(i))return i;return this.visit(e.children[1],t);case"NotExpression":return i=this.visit(e.children[0],t),Pu(i);case"Literal":return e.value;case _.TOK_PIPE:return c=this.visit(e.children[0],t),this.visit(e.children[1],c);case _.TOK_CURRENT:return t;case _.TOK_ROOT:return this._rootValue;case"Function":let ae=[];for(let ue=0;ue<e.children.length;ue+=1)ae.push(this.visit(e.children[ue],t));return this.runtime.callFunction(e.name,ae);case"ExpressionReference":let ce=e.children[0];return ce.jmespathType=_.TOK_EXPREF,ce;default:throw Error(`Unknown node type: ${e.type}`)}}computeSliceParams(e,t){let[n,o,r]=t;if(r===null)r=1;else if(r===0){let a=Error("Invalid slice, step cannot be 0");throw a.name="RuntimeError",a}let i=r<0?!0:!1;return n=n===null?i?e-1:0:this.capSliceRange(e,n,r),o=o===null?i?-1:e:this.capSliceRange(e,o,r),[n,o,r]}capSliceRange(e,t,n){let o=t;if(o<0){if(o+=e,o<0)o=n<0?-1:0}else if(o>=e)o=n<0?e-1:e;return o}}var bw=new F$,CC=E.TYPE_ANY,NC=E.TYPE_ARRAY,jC=E.TYPE_ARRAY_NUMBER,AC=E.TYPE_ARRAY_STRING,MC=E.TYPE_BOOLEAN,UC=E.TYPE_EXPREF,qC=E.TYPE_NULL,LC=E.TYPE_NUMBER,DC=E.TYPE_OBJECT,ZC=E.TYPE_STRING;function K$(e,t){let n=yw.parse(t);return bw.search(n,e)}function V$(e,t){return Vv(e.responseProjection,t)}function Vv(e,t){if(!e||typeof e!=="string"||!e.trim())return t;if(t===null||typeof t!=="object")return t;try{let n=K$(t,e);return n===void 0?null:n}catch{return t}}function J$(e){if(e===void 0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)??"").length}catch{return 0}}function $w(e,t,n){let o=V$(e,t),r=n?.projectionUsage;if(!r)return o;let i=e.responseProjection;if(!(Boolean(i&&typeof i==="string"&&i.trim())&&t!==null&&typeof t==="object"))return o;let s=J$(t),c=J$(o);return r.preBytes+=s,r.postBytes+=c,r.applied=r.applied||o!==t,o}function ho(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function gt(e,t){if(typeof e.description!=="string"||!e.description)return t;return t.describe(e.description)}function Rw(e){let t=e.map((n)=>S(n));if(!t.length)return Z();if(t.length===1)return t[0];return A(t)}function jt(e,t){let n=e.type;if(!(e.nullable===!0||Array.isArray(n)&&n.includes("null")))return t;return t.nullable()}function ga(e){if(!ho(e))return Z();if(Array.isArray(e.enum)&&e.enum.length)return jt(e,gt(e,Rw(e.enum)));if(Object.prototype.hasOwnProperty.call(e,"const"))return jt(e,gt(e,S(e.const)));for(let n of["oneOf","anyOf"]){let o=e[n];if(Array.isArray(o)&&o.length){let r=o.map((a)=>ga(a)),i=r.length===1?r[0]:A(r);return jt(e,gt(e,i))}}let t=typeof e.type==="string"?e.type:Array.isArray(e.type)?e.type.find((n)=>n!=="null"):null;if(t==="object"||!t&&(ho(e.properties)||Object.prototype.hasOwnProperty.call(e,"additionalProperties")))return B$(e);if(t==="array"){let n=ho(e.items)?ga(e.items):Z();return jt(e,gt(e,v(n)))}if(t==="string"){let n=l();if(typeof e.minLength==="number")n=n.min(e.minLength);if(typeof e.maxLength==="number")n=n.max(e.maxLength);return jt(e,gt(e,n))}if(t==="integer"){let n=x().int();if(typeof e.minimum==="number")n=n.min(e.minimum);if(typeof e.maximum==="number")n=n.max(e.maximum);return jt(e,gt(e,n))}if(t==="number"){let n=x();if(typeof e.minimum==="number")n=n.min(e.minimum);if(typeof e.maximum==="number")n=n.max(e.maximum);return jt(e,gt(e,n))}if(t==="boolean")return jt(e,gt(e,j()));if(t==="null")return gt(e,pt());return jt(e,gt(e,Z()))}function B$(e){if(!ho(e))return f({}).passthrough();let t=ho(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter((i)=>typeof i==="string"):[]),o=Object.fromEntries(Object.entries(t).map(([i,a])=>{let s=ga(a),c=n.has(i)?s:s.optional();return[i,c]})),r=e.additionalProperties===!1?f(o).strict():ho(e.additionalProperties)?f(o).catchall(ga(e.additionalProperties)):f(o).passthrough();return jt(e,gt(e,r))}var go=new Map;function zw(e,t){let n=go.get(e)??{};go.set(e,{...n,...t})}function Tw(){go.clear()}function xw(){let e={};for(let[t,n]of go)e[t]={...n};return e}function Bv(e,t){return go.get(e)?.description??t}function Hv(e,t){return go.get(e)?.title??t}function Y$(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter((t)=>t.length>0)}function Yv(e){return[e.name,e.title,e.description,e.tags.join(" ")].join(" ")}function kw(e){let t=e.map((i)=>Y$(Yv(i))),n=new Map;for(let i of t)for(let a of new Set(i))n.set(a,(n.get(a)??0)+1);let o=t.reduce((i,a)=>i+a.length,0),r=t.length?o/t.length:0;return{entries:e,docTokens:t,docFrequency:n,averageDocLength:r}}var H$=new WeakMap;function Ew(e){let t=H$.get(e);if(t)return t;let n=kw(e);return H$.set(e,n),n}function ww(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}function Iw(e,t,n){let o=e.docTokens[t];if(!o.length)return 0;let r=ww(o),i=o.length,a=e.entries.length,s=e.averageDocLength||1,c=0;for(let u of n){let d=r.get(u);if(!d)continue;let m=e.docFrequency.get(u)??0,p=Math.log(1+(a-m+0.5)/(m+0.5)),h=d+1.5*(0.25+0.75*i/s);c+=p*(d*2.5/h)}return c}function Pw(e){let t=e.match(/^\/(.+)\/([a-z]*)$/);if(!t)return null;try{return new RegExp(t[1],t[2])}catch{return null}}function Cu(e,t){return{name:e.name,title:e.title,description:e.description,score:t}}function Ow(e,t,n){let o=[];for(let r of e){let i=t.flags.includes("g")?t.flags:`${t.flags}g`;if(new RegExp(t.source,i).test(Yv(r)))o.push(Cu(r,1));if(o.length>=n)break}return o}function Cw(e,t,n){let o=t.toLowerCase().trim();if(!o)return[];let r=[];for(let i of e){if(Yv(i).toLowerCase().includes(o))r.push(Cu(i,1));if(r.length>=n)break}return r}function Gv(e,t,n=10){let o=Math.max(1,Math.min(Math.floor(n)||10,100)),r=t.trim();if(!r)return e.slice(0,o).map((u)=>Cu(u,0));let i=Pw(r);if(i)return Ow(e,i,o);let a=Ew(e),s=Y$(r),c=a.entries.map((u,d)=>({entry:u,score:Iw(a,d,s)})).filter((u)=>u.score>0).sort((u,d)=>d.score-u.score).slice(0,o).map((u)=>Cu(u.entry,Number(u.score.toFixed(4))));if(c.length>0)return c;return Cw(e,r,o)}var Wv="0.19.0";function Nw(e){let t=3735928559,n=1103547991;for(let o=0;o<e.length;o++){let r=e.charCodeAt(o);t=Math.imul(t^r,2654435761),n=Math.imul(n^r,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&n)+(t>>>0)).toString(16)}function G$(e){let t=JSON.stringify(e,(n,o)=>typeof o==="function"?void 0:o);return`mcpc-${Nw(t??"")}`}function W$(e,t){let n=e.headers.get("mcp-session-id")?.trim();if(!n||!n.startsWith("mcpc-"))return!1;return n!==t}async function X$(e){if(e.method!=="POST")return!1;try{let t=await e.clone().json();return(Array.isArray(t)?t:[t]).some((o)=>typeof o==="object"&&o!==null&&o.method==="initialize")}catch{return!1}}function Q$(){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32001,message:"Session not found: this server's tools changed since you connected. Reconnect to load the current tools."}},{status:404})}function eR(e,t){if(!e.ok)return e;let n=new Headers(e.headers);return n.set("Mcp-Session-Id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}var Xv={maxDepth:2,maxKeys:12,maxVariants:3};function jw(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;if(t==="object"&&e instanceof Date)return"Date";return t}function tR(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function Aw(e,t){let n=[...new Set(e)];if(n.length===0)return"unknown";if(n.length===1)return n[0];let o=[...n].sort();if(o.length>t)return`${o.slice(0,t).join(" | ")} | …${o.length-t} more`;return o.join(" | ")}function Qv(e,t,n,o){if(!tR(e)&&!Array.isArray(e))return jw(e);if(Array.isArray(e)){if(e.length===0)return"unknown[0]";let s=e.slice(0,200).map((c)=>Qv(c,t,n,o));return`${Aw(s,o.maxVariants)}[${e.length}]`}let r=Object.keys(e);if(t<=0&&n.length===0)return"object";let i=r.slice(0,o.maxKeys),a=i.map((s)=>{let c=n[0]===s,u=c?n.slice(1):[],d=c?Math.max(t,1):t-1;return`${s}: ${Qv(e[s],d,u,o)}`});if(r.length>i.length)a.push(`…+${r.length-i.length} more`);return`{${a.join(", ")}}`}function va(e,t={}){let n={maxDepth:t.maxDepth??Xv.maxDepth,maxKeys:t.maxKeys??Xv.maxKeys,maxVariants:t.maxVariants??Xv.maxVariants};return Qv(e,n.maxDepth,t.focusPath??[],n)}function e_(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.filter(tR);if(n.length===0)return[];let o=n.length,r=new Map,i=new Set;for(let a of n)for(let s of Object.keys(a))i.add(s);for(let a of i){let s=0;for(let c of n){let u=c[a];if(u===null||u===void 0)s+=1}if(s>0)r.set(a,s)}return[...r.entries()].map(([a,s])=>({field:a,missing:s,total:o,text:`${s}/${o} items have ${a} === null`})).sort((a,s)=>s.missing-a.missing||a.field.localeCompare(s.field)).slice(0,t.limit??3)}var Mw=["read","write"],r_="__mcpcloud_call_tool",Uw=`globalThis.tool = (name, args) =>
101
+ `,e.enqueue(t.encode(r)),!0}catch(r){return this.onerror?.(r),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!Cv(e.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let o=e,r;if(t?.parsedBody===void 0)try{r=await e.json()}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else r=t.parsedBody;let i;try{i=Array.isArray(r)?r.map((R)=>Wn.parse(R)):[Wn.parse(r)]}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let a=i.some((R)=>Rv(R));if(a){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(i.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!a){let R=this.validateSession(e);if(R)return R;let z=this.validateProtocolVersion(e);if(z)return z}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!i.some((R)=>Bt(R))){for(let R of i)this.onmessage?.(R,{authInfo:t?.authInfo,request:o});return new Response(null,{status:202})}let s=crypto.randomUUID(),c=i.find((R)=>Rv(R)),u=c?c.params.protocolVersion:e.headers.get("mcp-protocol-version")??bc;if(this._enableJsonResponse)return new Promise((R)=>{this._streamMapping.set(s,{resolveJson:R,cleanup:()=>{this._streamMapping.delete(s)}});for(let z of i)if(Bt(z))this._requestToStreamMapping.set(z.id,s);for(let z of i)this.onmessage?.(z,{authInfo:t?.authInfo,request:o})});let d=new TextEncoder,m,p,h=new ReadableStream({start:(R)=>{m=R},cancel:()=>{if(p!==void 0)clearInterval(p);if(this._streamMapping.get(s)?.controller===m)this._streamMapping.delete(s)}}),b={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};if(this.sessionId!==void 0)b["mcp-session-id"]=this.sessionId;for(let R of i)if(Bt(R))this._streamMapping.set(s,{controller:m,encoder:d,cleanup:()=>{if(p!==void 0)clearInterval(p);this._streamMapping.delete(s);try{m.close()}catch{}}}),this._requestToStreamMapping.set(R.id,s);await this.writePrimingEvent(m,d,s,u);for(let R of i){let z,N;if(Bt(R)&&this._eventStore&&this.supportsEmptySSEData(u))z=()=>{this.closeSSEStream(R.id)},N=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(R,{authInfo:t?.authInfo,request:o,closeSSEStream:z,closeStandaloneSSEStream:N})}if(this._streamMapping.get(s)?.controller===m)p=this.startKeepAlive(m,d);return new Response(h,{status:200,headers:b})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let t=e.headers.get("mcp-session-id");if(!t)return this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(t!==this.sessionId)return this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let t=e.headers.get("mcp-protocol-version");if(t!==null&&!this._supportedProtocolVersions.includes(t)){let n=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(n)),this.createJsonErrorResponse(400,-32000,n)}}async close(){if(this._closed)return;this._closed=!0;for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);if(n)n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);if(e)e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if(Jt(e)||Ht(e))n=e.id;if(n===void 0){if(Jt(e)||Ht(e))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;if(this._eventStore)i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e);let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;if(a.controller&&a.encoder&&(i===void 0||!a.replayedEventIds?.has(i)))this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw Error(`No connection established for request ID: ${String(n)}`);let r=this._streamMapping.get(o);if(!this._enableJsonResponse){let i;if(this._eventStore)i=await this._eventStore.storeEvent(o,e),r=this._streamMapping.get(o);if(r?.controller&&r?.encoder&&(i===void 0||!r.replayedEventIds?.has(i)))this.writeSSEEvent(r.controller,r.encoder,e,i)}if(Jt(e)||Ht(e)){this._requestResponseMap.set(n,e);let i=[...this._requestToStreamMapping.entries()].filter(([a,s])=>s===o).map(([a])=>a);if(i.every((a)=>this._requestResponseMap.has(a))){if(!r){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let a of i)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}for(let a of i)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}if(this._enableJsonResponse&&r.resolveJson){let a={"Content-Type":"application/json"};if(this.sessionId!==void 0)a["mcp-session-id"]=this.sessionId;let s=i.map((c)=>this._requestResponseMap.get(c));if(s.length===1)r.resolveJson(Response.json(s[0],{status:200,headers:a}));else r.resolveJson(Response.json(s,{status:200,headers:a}));r.cleanup()}else r.cleanup();for(let a of i)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a)}}}};function Tr(e){if(e===null||typeof e!=="object"||Array.isArray(e))return null;let{method:t,id:n}=e;if(typeof t!=="string")return null;return typeof n==="string"||typeof n==="number"?n:null}function xr(e,t,n,o,r=null){return Response.json({jsonrpc:"2.0",error:{code:t,message:n,...o!==void 0&&{data:o}},id:r},{status:e})}function Tu(e,t=null){return xr(e.httpStatus,e.code,e.message,e.data,t)}function xu(e){return e instanceof Error?e:Error(String(e))}function ku(e=null){return xr(500,-32603,"Internal server error",void 0,e)}function LE(e,t,n){return async(o,r)=>{if(o.method.toUpperCase()!=="POST")return xr(405,-32000,"Method not allowed.");try{let i=await e({era:"legacy",...r?.authInfo!==void 0&&{authInfo:r.authInfo},requestInfo:o}),a=new Eu({sessionIdGenerator:void 0,...n!==void 0&&{keepAliveMs:n}});await i.connect(a);let s=()=>{a.close().catch(()=>{}),i.close().catch(()=>{})};o.signal?.addEventListener("abort",s,{once:!0});let c=await a.handleRequest(o,{...r?.authInfo!==void 0&&{authInfo:r.authInfo},...r?.parsedBody!==void 0&&{parsedBody:r.parsedBody}});if(c.body===null||Ov(c.headers.get("content-type"))!=="text/event-stream")return s(),c;let u=c.body.getReader(),d=!1,m=()=>{if(!d)d=!0,s()},p=new ReadableStream({pull:async(h)=>{try{let{done:b,value:R}=await u.read();if(b){m(),h.close();return}if(R!==void 0)h.enqueue(R)}catch(b){m(),h.error(b)}},cancel:(h)=>(m(),u.cancel(h).catch(()=>{}))});return new Response(p,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(i){try{t?.(xu(i))}catch{}return ku(Tr(r?.parsedBody))}}}async function i$(e,t,n=!0){let o=e.method.toUpperCase(),r,i=t,a=e,s=!1;if(o==="POST"){if(i===void 0){if(n)a=e.clone();let c;try{c=await e.text()}catch{return{step:"unreadable-body"}}try{r=c.length===0?void 0:JSON.parse(c)}catch{s=!0}if(!s&&r!==void 0)i=r}else r=i;if(s||r===void 0)return{step:"no-json-body",forwardRequest:a}}return{step:"classified",outcome:bb({httpMethod:o,protocolVersionHeader:e.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:e.headers.get("mcp-method")??void 0,mcpNameHeader:e.headers.get("mcp-name")??void 0,...r!==void 0&&{body:r}}),body:r,parsedBody:i,forwardRequest:a}}async function a$(e,t){let n=await i$(t===void 0&&e.method.toUpperCase()==="POST"?e.clone():e,t,!1);return n.step==="no-json-body"||n.step==="classified"&&n.outcome.kind==="legacy"}function s$(e,t={}){let{legacy:n,onerror:o,responseMode:r}=t;if(typeof n==="function")throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let i=new Set,a=!1,s=(z)=>{try{o?.(z)}catch{}},c=t.bus??new Hb(s),u=Yb(c),d=Gb({bus:c,maxSubscriptions:t.maxSubscriptions??Mv,keepAliveMs:t.keepAliveMs??da,onerror:s});if(r==="json")console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let m=n==="reject"?void 0:LE(e,s,t.keepAliveMs);async function p(z,N,B){let P=z.classification.revision;if(P===void 0||!ia.includes(P)){let ce=new vu({supported:[...ia],requested:P??"unknown"});return s(ce),xr(400,ce.code,ce.message,ce.data,Tr(z.message))}let O=Sb({httpMethod:N.method,mcpMethodHeader:N.headers.get("mcp-method")??void 0,mcpNameHeader:N.headers.get("mcp-name")??void 0},z);if(O!==void 0)return s(Error(`Rejected inbound request (${O.cell}): ${O.message}`)),Tu(O,Tr(z.message));let J=z.messageKind==="request"?Rr(z.message.params):void 0,Y=J?.[Ot];if(z.messageKind==="request"){let ce=Wy(z.message.method);if(ce!==void 0){let ue=oa(ce,Y);if(ue!==void 0){let Te=new aa({requiredCapabilities:ue});return s(Te),xr(_b(Te.code,"ladder"),Te.code,Te.message,Te.data,z.message.id)}}}let ee=await e({era:"modern",...B!==void 0&&{authInfo:B},requestInfo:N}),ne=ee instanceof po?ee.server:ee;if(z.messageKind==="request"&&z.message.method==="subscriptions/listen"){let ce=ne.getCapabilities(),ue=n$(ne);return ee.close().catch(s),d.serve(z.message,N.signal,ce,ue)}if(z.messageKind==="request"&&z.message.method==="tools/call"&&ee instanceof po){let ce=z.message.params,ue=typeof ce?.name==="string"?ce.name:void 0,Te=ue===void 0?void 0:ee.toolInputSchemaJson(ue);if(Te!==void 0){let tt=yu(Te);if(tt.valid&&tt.declarations.length>0){let Ne=vb(tt.declarations,ce?.arguments,N.headers);if(Ne!==void 0)return ee.close().catch(s),s(Error(`Rejected inbound request (${Ne.cell}): ${Ne.message}`)),Tu(Ne,z.message.id)}}}if(Nb(ne,P),r$(ne,ia),J!==void 0)t$(ne,{clientInfo:J[Xr],clientCapabilities:Y});let ae=ne.onclose;i.add(ne),ne.onclose=()=>{i.delete(ne),ae?.()};try{let ce=await qE(ee,z.message,{classification:z.classification,request:N,...B!==void 0&&{authInfo:B},...r!==void 0&&{responseMode:r},...t.keepAliveMs!==void 0&&{keepAliveMs:t.keepAliveMs}});if(z.messageKind==="notification")queueMicrotask(()=>void ne.close().catch(()=>{}));return ce}catch(ce){if(ce instanceof te&&ce.code===ie.ConnectionClosed)return new Response(null,{status:499});return await ne.close().catch(()=>{}),i.delete(ne),s(xu(ce)),ku(Tr(z.message))}}async function h(z,N,B,P){if(m!==void 0)return m(N,{...B!==void 0&&{authInfo:B},...P!==void 0&&{parsedBody:P}});let O=$b(z,ia);if(O===void 0)return new Response(null,{status:202});return s(Error(`Rejected 2025-era request on a modern-only endpoint (${O.cell}): ${O.message}`)),Tu(O,Tr(P))}async function b(z,N){let B=N?.authInfo;if(z.method.toUpperCase()==="POST"&&!Cv(z.headers.get("content-type")))return s(Error("Unsupported Media Type: Content-Type must be application/json")),xr(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let P=await i$(z,N?.parsedBody);if(P.step==="unreadable-body")return xr(400,-32700,"Parse error: the request body could not be read");if(P.step==="no-json-body"){if(m!==void 0)return m(P.forwardRequest,{...B!==void 0&&{authInfo:B}});return xr(400,-32700,"Parse error: the request body is not valid JSON")}let{outcome:O,body:J,parsedBody:Y,forwardRequest:ee}=P;try{switch(O.kind){case"reject":return s(Error(`Rejected inbound request (${O.cell}): ${O.message}`)),Tu(O,Tr(J));case"modern":return await p(O,z,B);case"legacy":return await h(O,ee,B,Y)}}catch(ne){return s(xu(ne)),ku(Tr(J))}}return{fetch:async(z,N)=>{if(a)throw Error("This MCP handler has been closed");try{return await b(z,N)}catch(B){return s(xu(B)),ku(Tr(N?.parsedBody))}},notify:u,bus:c,close:async()=>{a=!0,d.closeAll();let z=[...i].map((N)=>N.close().catch(()=>{}));i.clear(),await Promise.all(z)}}}function Uv(e){if(typeof e!=="string")return null;let t=e.replace(/[^\x20-\x7e]/g," ").replace(/\s+/g," ").trim();if(!t)return null;return t.slice(0,128).trim()}function c$(e,t,n){if(!t)return;let o=Uv(n.clientName);if(o)e.set("X-MCP-Client-Name",o);let r=n.clientInfo?.(),i=Uv(r?.name);if(i)e.set("X-MCP-Client-Info-Name",i);let a=Uv(r?.version);if(a)e.set("X-MCP-Client-Info-Version",a)}var DE=new Map([["oauth_connection_revoked","The upstream account for this server was disconnected. Reconnect it in MCPCloud to use this tool."],["oauth_refresh_failed","The upstream account for this server could not be refreshed. Reconnect it in MCPCloud to use this tool."],["oauth_refresh_token_missing","The upstream account for this server cannot be refreshed. Reconnect it in MCPCloud to use this tool."],["oauth_elicitation_required","Authentication is required to use this tool."],["oauth_rate_limited","Too many credential requests for this server. Wait a moment and retry."],["oauth_runtime_grant_invalid","MCPCloud rejected this server's credential request. Redeploy the server if this keeps happening."]]);function ZE(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.error;if(!t||typeof t!=="object")return null;let n=t.code;return typeof n==="string"&&n?n:null}function qv(e,t){let n=ZE(e);return n&&DE.get(n)||t}var l$=-32042;function u$(e){if(!e||typeof e!=="object"||Array.isArray(e))return null;let t=e.elicitation;if(!t||typeof t!=="object")return null;let n=t;if(typeof n.url!=="string"||!n.url)return null;return{url:n.url,message:typeof n.message==="string"&&n.message?n.message:"Authentication is required to use this tool.",elicitationId:typeof n.elicitationId==="string"?n.elicitationId:""}}async function FE(e,t,n){if(!e.oauth)throw Error("OAuth runtime settings are not available for this generated server.");let o=e.oauth.mode==="perMember"?t.runtimeToken:null,r=await qu(e,{connectionId:e.oauth.connectionId,forceRefresh:n,callerRuntimeToken:o}),i=await r.json().catch(()=>null);if(!r.ok){let s=u$(i);if(s)throw new D(l$,s.message,{elicitations:[{mode:"url",message:s.message,url:s.url,elicitationId:s.elicitationId}]});throw Error(qv(i,"Unable to resolve the delegated OAuth access token from MCPCloud."))}if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Unable to resolve the delegated OAuth access token from MCPCloud.");let a=typeof i.accessToken==="string"&&i.accessToken.trim()?i.accessToken.trim():null;if(!a)throw Error("MCPCloud did not return an OAuth access token for this request.");return{accessToken:a,tokenType:typeof i.tokenType==="string"&&i.tokenType.trim()?i.tokenType.trim():null}}async function KE(e,t,n){if(!t.runtimeToken)throw Error("Per-member upstream keys require a protected deployment with a verified caller identity.");let o=await f_(e,{callerRuntimeToken:t.runtimeToken,reportInvalid:n}),r=await o.json().catch(()=>null);if(!o.ok){let a=u$(r);if(a)throw new D(l$,a.message,{elicitations:[{mode:"url",message:a.message,url:a.url,elicitationId:a.elicitationId}]});throw Error(qv(r,"Unable to resolve your upstream API key from MCPCloud."))}let i=r&&typeof r.apiKey==="string"&&r.apiKey.trim()?r.apiKey.trim():null;if(!i)throw Error("MCPCloud did not return an upstream API key for this request.");return i}function d$(e){return e.some((t)=>t.type==="oauth2"||t.type==="openIdConnect")}function m$(e,t,n){if(!n)return!1;let o=n.toolOverrides[e];if(o==="on")return!0;if(o==="off")return!1;return n.applyToAllTools||d$(t)}async function ma(e,t,n,o,r=!1){let i=new Headers;c$(i,e.forwardClientIdentity,o);for(let[u,d]of Object.entries(e.customHeaders))i.set(u,d);if(m$(t,n,e.oauth)&&e.oauth){let u=await FE(e,o,r);return i.set("Authorization",`${u.tokenType||"Bearer"} ${u.accessToken}`),i}let a=e.memberKey?await KE(e,o,r):e.apiKey;if(!a)return i;let s=n.find((u)=>u.type==="apiKey"&&u.in==="header");if(s)return i.set(s.name||e.apiKeyHeader,`${e.apiKeyPrefix}${a}`),i;if(n.find((u)=>u.type==="http"&&u.scheme?.toLowerCase()==="bearer"))return i.set("Authorization",`Bearer ${a}`),i;return i.set(e.apiKeyHeader,`${e.apiKeyPrefix}${a}`),i}var JE=new Set([408,429,500,502,503,504]);function p$(e){return JE.has(e)}class pa extends Error{status;retryable;retryAfterSeconds;constructor(e,t,n=null){super(e);this.name="UpstreamHttpError",this.status=t,this.retryable=p$(t),this.retryAfterSeconds=n}}class an extends Error{toolName;issues;constructor(e,t){super(`Invalid input for ${e}: ${t.join("; ")}`);this.name="ToolInputError",this.toolName=e,this.issues=t}}function Lv(e){if(e instanceof pa)return{error:e.message,errorClass:"UPSTREAM",httpStatus:e.status,retryable:e.retryable,...e.retryAfterSeconds!==null?{retryAfterSeconds:e.retryAfterSeconds}:{}};if(e instanceof an)return{error:e.message,errorClass:"BINDING_MISUSE",retryable:!1};return{error:e instanceof Error?e.message:typeof e==="string"?e:"Tool execution failed.",errorClass:"INTERNAL",retryable:!1}}function VE(e){return typeof e==="object"&&e!==null&&e.code===-32042}function f$(e){let t=Lv(e);return{content:[{type:"text",text:t.error}],isError:!0,_meta:{...t}}}function h$(e){let n=e.data?.elicitations;if(!Array.isArray(n))return[];return n.filter((o)=>Boolean(o)&&typeof o==="object"&&typeof o.url==="string")}function BE(e,t){let n=h$(e);if(n.length===0)return null;let o=e instanceof Error&&e.message||"Authorization is required.",r=Object.fromEntries(n.map((i,a)=>[i.elicitationId||`elicitation_${a}`,t.elicitUrl({url:i.url,message:i.message||o})]));return t({inputRequests:r})}function HE(e,t){if(!t)return null;if(t.elicitation)return null;let n=h$(e);if(n.length===0)return null;let o=e instanceof Error&&e.message||"Authorization is required.",r=n.map((i)=>`${i.message||o} Open this page to continue, then run the tool again: ${i.url}`);return r.push("Reconnecting or signing in to MCPCloud again will not resolve this — the credential has to be provided at the link above."),{content:[{type:"text",text:r.join(" ")}],isError:!0,_meta:{...Lv(e),errorClass:"POLICY_DENIED",retryable:!1,elicitationUndeliverable:!0,elicitationUrls:n.map((i)=>i.url)}}}async function fa(e,t){try{return await e()}catch(n){if(VE(n)){let o=HE(n,t?.clientCapabilities?.());if(o)return o;if(t?.era==="modern"&&t.inputRequired){let r=BE(n,t.inputRequired);if(r)return r}throw n}return f$(n)}}var YE=/^(?:invalid|missing|expired|revoked|bad)[_-]?(?:token|api[_-]?key|key|credentials?|auth)$|^(?:token|api[_-]?key|key|credentials?)[_-]?(?:expired|revoked|invalid|missing)$|^unauthenticated$/i;function g$(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function v$(e){if(!g$(e))return{code:null,message:null};let t=g$(e.error)?e.error:null,n=(...o)=>{for(let r of o)if(typeof r==="string"&&r.trim())return r.trim();return null};return{code:n(t?.code,t?.type,e.code,e.error_code,e.errorCode,typeof e.error==="string"?e.error:null),message:n(t?.message,e.message,e.error_description,e.detail)}}function _$(e){let{code:t}=v$(e);return t!==null&&YE.test(t)}function S$(e,t){if(e!==403)return null;let{code:n,message:o}=v$(t);if(!n&&!o)return null;return`The upstream API refused this action: ${[n,o].filter(Boolean).join(" — ")}. This is a permission decision, not a connection problem — reconnecting will not change it.`}function ha(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function GE(e,t){let n=e.properties;if(!n||typeof n!=="object"||Array.isArray(n))return null;let o=n[t];if(!o||typeof o!=="object"||Array.isArray(o))return null;let r=o["x-location"];return typeof r==="string"&&r.trim()?r:null}function b$(e){return e.endpoint.protocol==="graphql"&&Boolean(e.endpoint.document)}function y$(e,t){if(/^https?:\/\//i.test(t))return new URL(t);let n=e.replace(/\/+$/,"");if(!/^https?:\/\//i.test(n))throw Error(`Upstream base URL is not configured for this server — set UPSTREAM_BASE_URL to an absolute http(s) URL in Settings → General (got ${n?`"${n}"`:"an empty value"}).`);return new URL(t?`${n}/${t.replace(/^\/+/,"")}`:n)}async function WE(e,t,n,o,r=!1){let i=y$(n.upstreamBaseUrl,e.endpoint.path),a=await ma(n,e.name,e.auth,o,r);if(b$(e)){a.set("Accept","application/json"),a.set("Content-Type","application/json");let m=Object.fromEntries(Object.entries(t).filter(([,h])=>h!==void 0)),p=JSON.stringify({query:e.endpoint.document,operationName:e.endpoint.operationId??e.endpoint.rootField??void 0,variables:m});return{url:i.toString(),init:{method:"POST",headers:a,body:p}}}let s=e.endpoint.path.replace(/\{([^}]+)\}/g,(m,p)=>encodeURIComponent(String(t[p]??"")));i.pathname=y$(n.upstreamBaseUrl,s).pathname;let c,u;for(let[m,p]of Object.entries(t)){let h=GE(e.inputSchema,m);if(h==="path")continue;if(h==="query"){if(Array.isArray(p))for(let b of p)i.searchParams.append(m,String(b));else if(p!==void 0&&p!==null)i.searchParams.set(m,String(p));continue}if(h==="header"&&p!==void 0&&p!==null){a.set(m,String(p));continue}if(m==="body"&&p!==void 0)u=p}let d=!["GET","HEAD"].includes(e.endpoint.method.toUpperCase());if(u!==void 0&&d)if(e.endpoint.requestBodyContentType==="application/x-www-form-urlencoded")c=$$(u),a.set("Content-Type","application/x-www-form-urlencoded");else c=JSON.stringify(u),a.set("Content-Type","application/json");return{url:i.toString(),init:{method:e.endpoint.method,headers:a,body:c}}}function $$(e){let t=new URLSearchParams;return Dv(t,null,e),t.toString()}function Dv(e,t,n){if(n===void 0||n===null)return;if(Array.isArray(n)){n.forEach((o,r)=>{Dv(e,t?`${t}[${r}]`:String(r),o)});return}if(ha(n)){for(let[o,r]of Object.entries(n)){let i=t?`${t}[${o}]`:o;Dv(e,i,r)}return}if(t===null)return;e.append(t,typeof n==="string"?n:String(n))}async function XE(e){if((e.headers.get("content-type")||"").includes("application/json"))return await e.json();let n=await e.text();if(!n)return null;try{return JSON.parse(n)}catch{return n}}function R$(e){if(!ha(e)||!Array.isArray(e.errors)||!e.errors.length)return null;let t=e.errors.map((n)=>ha(n)&&typeof n.message==="string"?n.message.trim():null).filter((n)=>Boolean(n));return t.length?t.join(" "):"GraphQL execution failed."}function QE(e){if(!e)return null;let t=e.trim();if(!t)return null;let n=Number(t);if(Number.isFinite(n))return n>=0?Math.ceil(n):null;let o=Date.parse(t);if(Number.isNaN(o))return null;return Math.max(0,Math.ceil((o-Date.now())/1000))}function z$(e,t,n){if(!t?.memberKey)return null;if(e!==401&&!(e===403&&_$(n)))return null;let r=`The credential you connected for ${t.serverName?`“${t.serverName}”`:"this server"} was refused by the upstream API — it was most likely revoked, rotated or expired.`;return t.memberKey.connectPageUrl?`${r} Reconnect at ${t.memberKey.connectPageUrl} — signing in to MCPCloud again will not fix it.`:`${r} Reconnect it on this server's MCPCloud connect page — signing in to MCPCloud again will not fix it.`}function Zv(e,t,n,o=null,r){let i=R$(n),a=e.errorMappings.find((h)=>h.statusCode===String(t)),s=i||(typeof n==="string"?n:n?JSON.stringify(n,null,2):"No response body was returned."),c=a?.message?`${a.message} (HTTP ${t})`:`Upstream request failed with status ${t}.`,u=z$(t,r,n),d=u?null:S$(t,n),m=u??d,p=m?`${c} ${m} ${s}`:`${c} ${s}`;return new pa(p,t,o)}function ew(e,t,n,o){if(!t.ok)throw Zv(e,t.status,n,QE(t.headers.get("retry-after")),o);if(!b$(e))return n;if(R$(n))throw Zv(e,t.status||200,n);if(!ha(n)||!ha(n.data))throw Error("GraphQL execution did not return a data payload.");if(e.endpoint.rootField&&Object.prototype.hasOwnProperty.call(n.data,e.endpoint.rootField))return n.data[e.endpoint.rootField];return n.data}function tw(e,t){if(t===null)return`${e.title} completed successfully.`;if(typeof t==="string")return t;return JSON.stringify(t,null,2)}function T$(e){let t=e.previousPem?.trim();if(!t)return{usable:!1,reason:"absent"};let n=e.previousUntil?.trim();if(!n)return{usable:!1,reason:"no-window"};let o=Number(n);if(!Number.isFinite(o))return{usable:!1,reason:"malformed-window"};if(o<=e.nowMs)return{usable:!1,reason:"expired"};return{usable:!0,pem:t,expiresAtMs:o}}var x$=null,k$=null;function rw(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function E$(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function w$(e){return e==="privateOrg"||e==="unlisted"}function Kv(e){if(e==="privateOrg")return{protected:!0,summary:"This MCP endpoint requires an MCPCloud runtime token for callers in the deployment organization."};if(e==="unlisted")return{protected:!0,summary:"This MCP endpoint requires an MCPCloud runtime token and does not rely on URL secrecy as the primary control."};return{protected:!1,summary:"This MCP endpoint is public."}}function Fv(e,t,n){return Response.json({error:t,message:n},{status:e})}function nw(e){let t=e.get("authorization")?.trim();if(!t)return null;return t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function I$(e){let t=atob(e);return Uint8Array.from(t,(n)=>n.charCodeAt(0))}function P$(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4);return I$(n)}function O$(e){let t=e.replace(/-----BEGIN[^-]+-----/g,"").replace(/-----END[^-]+-----/g,"").replace(/\s+/g,"");return E$(I$(t))}function ow(e){return JSON.parse(new TextDecoder().decode(P$(e)))}async function iw(e){return x$||=crypto.subtle.importKey("spki",O$(e.publicKey),{hash:"SHA-256",name:"RSASSA-PKCS1-v1_5"},!1,["verify"]),await x$}async function aw(e){return k$||=crypto.subtle.importKey("spki",O$(e),{hash:"SHA-256",name:"RSASSA-PKCS1-v1_5"},!1,["verify"]),await k$}async function sw(e,t,n){let[o,r,i]=e.split(".");if(!o||!r||!i)throw Error("Runtime token is malformed.");let a=ow(r);if(!rw(a))throw Error("Runtime token payload is invalid.");let s=E$(P$(i)),c=new TextEncoder().encode(`${o}.${r}`),u=await crypto.subtle.verify("RSASSA-PKCS1-v1_5",await iw(n),s,c);if(!u){let m=T$({previousPem:n.publicKeyPrevious,previousUntil:n.publicKeyPreviousUntil,nowMs:Date.now()});if(m.usable)try{u=await crypto.subtle.verify("RSASSA-PKCS1-v1_5",await aw(m.pem),s,c)}catch{u=!1}}if(!u)throw Error("Runtime token signature is invalid.");let d=Math.floor(Date.now()/1000);if(a.aud!==n.audience||a.iss!==n.issuer||a.accessMode!==t||a.orgId!==n.organizationId||a.serverId!==n.serverId||typeof a.exp!=="number"||a.exp<=d||typeof a.iat!=="number"||typeof a.jti!=="string"||typeof a.sub!=="string")throw Error("Runtime token claims are invalid.");return{sub:a.sub,clientName:typeof a.clientName==="string"?a.clientName:null}}async function Jv(e,t){if(!w$(t.accessMode))return{response:null,callerUserId:null,rawToken:null};if(!t.runtimeAuth)return{response:Fv(500,"runtime_auth_misconfigured","Runtime auth is not configured for this deployment."),callerUserId:null,rawToken:null};let n=nw(e.headers);if(!n)return{response:Fv(401,"runtime_auth_required","This MCP endpoint requires an MCPCloud runtime access token."),callerUserId:null,rawToken:null};try{let o=await sw(n,t.accessMode,t.runtimeAuth);return{response:null,callerUserId:o.sub,rawToken:n,callerClientName:o.clientName}}catch{return{response:Fv(401,"runtime_auth_invalid","This MCP endpoint requires a valid MCPCloud runtime access token."),callerUserId:null,rawToken:null}}}function N$(e,t,n){if(Math.abs(e.length-t.length)>n)return n+1;let o=Array.from({length:t.length+1},(r,i)=>i);for(let r=1;r<=e.length;r+=1){let i=[r],a=r;for(let s=1;s<=t.length;s+=1){let c=e[r-1]===t[s-1]?0:1;i[s]=Math.min(o[s]+1,i[s-1]+1,o[s-1]+c),a=Math.min(a,i[s])}if(a>n)return n+1;o=i}return o[t.length]}function cw(e,t){if(!t.length)return null;let n=Math.max(1,Math.floor(e.length/3)),o=e.toLowerCase(),r=null,i=n+1;for(let a of t){if(a.toLowerCase()===o)return a;let s=N$(o,a.toLowerCase(),n);if(s<=n&&s<i)r=a,i=s}return r}function j$(e,t,n){if(!t.length)return{suggestion:null,nearest:[]};let o=e.toLowerCase(),r=Math.max(1,e.length),i=t.map((c)=>({name:c,distance:N$(o,c.toLowerCase(),r)}));i.sort((c,u)=>c.distance-u.distance||(c.name<u.name?-1:1));let a=Math.max(1,Math.ceil(e.length/2)),[s]=i;return{suggestion:s.distance<=a?s.name:null,nearest:i.slice(0,n).map((c)=>c.name)}}function sn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $e(e){return e.length?`/${e.join("/")}`:"/"}function A$(e){let t=e.type;if(typeof t==="string")return[t];if(Array.isArray(t))return t.filter((n)=>typeof n==="string");return[]}function lw(e){return e.nullable===!0||A$(e).includes("null")}function Iu(e,t,n){let o=[];return wu(e,t,n,o),o}function M$(e,t){return Iu(e,t,[]).map((n)=>`${n.path} ${n.message}`)}function C$(e,t,n,o,r){let i=t[e];if(!Array.isArray(i)||!i.length)return!1;if(i.filter((s)=>sn(s)&&Iu(s,n,o).length===0).length>0)return!0;return r.push({path:$e(o),message:"must match at least one allowed schema"}),!0}function uw(e,t,n,o){if(!sn(t))return o.push({path:$e(n),message:"must be an object"}),!0;let r=sn(e.properties)?e.properties:{},i=Array.isArray(e.required)?e.required.filter((s)=>typeof s==="string"):[],a=sn(e.additionalProperties)?e.additionalProperties:null;for(let s of i)if(!(s in t)||t[s]===void 0)o.push({path:$e([...n,s]),message:"is required"});if(e.additionalProperties===!1){for(let s of Object.keys(t))if(!(s in r)){let c=cw(s,Object.keys(r));o.push({path:$e([...n,s]),message:c?`is not allowed (did you mean "${c}"?)`:"is not allowed"})}}else if(a)for(let[s,c]of Object.entries(t)){if(s in r)continue;wu(a,c,[...n,s],o)}for(let[s,c]of Object.entries(r)){if(!(s in t)||t[s]===void 0)continue;if(sn(c))wu(c,t[s],[...n,s],o)}return!0}function dw(e,t,n,o){if(!Array.isArray(t))return o.push({path:$e(n),message:"must be an array"}),!0;if(typeof e.minItems==="number"&&t.length<e.minItems)o.push({path:$e(n),message:`must contain at least ${e.minItems} items`});if(typeof e.maxItems==="number"&&t.length>e.maxItems)o.push({path:$e(n),message:`must contain no more than ${e.maxItems} items`});if(sn(e.items))t.forEach((r,i)=>wu(e.items,r,[...n,String(i)],o));return!0}function mw(e,t,n,o){if(typeof t!=="string")return o.push({path:$e(n),message:"must be a string"}),!0;if(typeof e.minLength==="number"&&t.length<e.minLength)o.push({path:$e(n),message:`must have length at least ${e.minLength}`});if(typeof e.maxLength==="number"&&t.length>e.maxLength)o.push({path:$e(n),message:`must have length no greater than ${e.maxLength}`});if(typeof e.pattern==="string"){if(!new RegExp(e.pattern).test(t))o.push({path:$e(n),message:`must match pattern ${e.pattern}`})}return!0}function pw(e,t,n,o,r){if(typeof n!=="number"||Number.isNaN(n))return r.push({path:$e(o),message:e==="integer"?"must be an integer":"must be a number"}),!0;if(e==="integer"&&!Number.isInteger(n))r.push({path:$e(o),message:"must be an integer"});if(typeof t.minimum==="number"&&n<t.minimum)r.push({path:$e(o),message:`must be at least ${t.minimum}`});if(typeof t.maximum==="number"&&n>t.maximum)r.push({path:$e(o),message:`must be no greater than ${t.maximum}`});return!0}function wu(e,t,n,o){if(t===null&&lw(e))return;if(C$("anyOf",e,t,n,o)||C$("oneOf",e,t,n,o))return;if(Object.prototype.hasOwnProperty.call(e,"const")&&t!==e.const){o.push({path:$e(n),message:`must equal ${JSON.stringify(e.const)}`});return}if(Array.isArray(e.enum)&&!e.enum.some((s)=>s===t)){o.push({path:$e(n),message:`must be one of ${e.enum.map((s)=>JSON.stringify(s)).join(", ")}`});return}let r=A$(e).filter((s)=>s!=="null"),i=r.length?r:Array.isArray(e.items)?["array"]:sn(e.properties)?["object"]:[];if(!i.length)return;if(i.length>1){if(!i.find((c)=>Iu({...e,type:c},t,n).length===0))o.push({path:$e(n),message:`must match one of the allowed types: ${i.join(", ")}`});return}let[a]=i;switch(a){case"object":uw(e,t,n,o);return;case"array":dw(e,t,n,o);return;case"string":mw(e,t,n,o);return;case"integer":case"number":pw(a,e,t,n,o);return;case"boolean":if(typeof t!=="boolean")o.push({path:$e(n),message:"must be a boolean"});return;case"null":if(t!==null)o.push({path:$e(n),message:"must be null"});return;default:return}}function fw(e,t,n){let o=Iu(t,n,[]);if(o.length)throw new an(e,o.map((r)=>`${r.path} ${r.message}`));return n}var fo=(e)=>e!==null&&Object.prototype.toString.call(e)==="[object Object]",Ou=(e,t)=>{if(e===t)return!0;if(typeof e!==typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Ou(e[n],t[n]))return!1;return!0}if(fo(e)&&fo(t)){let n=Object.entries(e),o=new Set(Object.keys(t));if(n.length!==o.size)return!1;for(let[r,i]of n){if(!Ou(i,t[r]))return!1;o.delete(r)}return o.size===0}return!1},Pu=(e)=>{if(e===""||e===!1||e===null||e===void 0)return!0;if(Array.isArray(e)&&e.length===0)return!0;if(fo(e)){for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}return!1},hw=(e)=>e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_",U$=(e)=>e>="0"&&e<="9"||e==="-",gw=(e)=>e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||e==="_",_;(function(e){e.TOK_EOF="EOF",e.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",e.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",e.TOK_RBRACKET="Rbracket",e.TOK_RPAREN="Rparen",e.TOK_COMMA="Comma",e.TOK_COLON="Colon",e.TOK_RBRACE="Rbrace",e.TOK_NUMBER="Number",e.TOK_CURRENT="Current",e.TOK_ROOT="Root",e.TOK_EXPREF="Expref",e.TOK_PIPE="Pipe",e.TOK_OR="Or",e.TOK_AND="And",e.TOK_EQ="EQ",e.TOK_GT="GT",e.TOK_LT="LT",e.TOK_GTE="GTE",e.TOK_LTE="LTE",e.TOK_NE="NE",e.TOK_FLATTEN="Flatten",e.TOK_STAR="Star",e.TOK_FILTER="Filter",e.TOK_DOT="Dot",e.TOK_NOT="Not",e.TOK_LBRACE="Lbrace",e.TOK_LBRACKET="Lbracket",e.TOK_LPAREN="Lparen",e.TOK_LITERAL="Literal"})(_||(_={}));var q$={"(":_.TOK_LPAREN,")":_.TOK_RPAREN,"*":_.TOK_STAR,",":_.TOK_COMMA,".":_.TOK_DOT,":":_.TOK_COLON,"@":_.TOK_CURRENT,["$"]:_.TOK_ROOT,"]":_.TOK_RBRACKET,"{":_.TOK_LBRACE,"}":_.TOK_RBRACE},vw={"!":!0,"<":!0,"=":!0,">":!0},_w={"\t":!0,"\n":!0,"\r":!0," ":!0};class L${constructor(){this._current=0}tokenize(e){let t=[];this._current=0;let n,o,r;while(this._current<e.length)if(hw(e[this._current]))n=this._current,o=this.consumeUnquotedIdentifier(e),t.push({start:n,type:_.TOK_UNQUOTEDIDENTIFIER,value:o});else if(q$[e[this._current]]!==void 0)t.push({start:this._current,type:q$[e[this._current]],value:e[this._current]}),this._current+=1;else if(U$(e[this._current]))r=this.consumeNumber(e),t.push(r);else if(e[this._current]==="[")r=this.consumeLBracket(e),t.push(r);else if(e[this._current]==='"')n=this._current,o=this.consumeQuotedIdentifier(e),t.push({start:n,type:_.TOK_QUOTEDIDENTIFIER,value:o});else if(e[this._current]==="'")n=this._current,o=this.consumeRawStringLiteral(e),t.push({start:n,type:_.TOK_LITERAL,value:o});else if(e[this._current]==="`"){n=this._current;let i=this.consumeLiteral(e);t.push({start:n,type:_.TOK_LITERAL,value:i})}else if(vw[e[this._current]]!==void 0)r=this.consumeOperator(e),r&&t.push(r);else if(_w[e[this._current]]!==void 0)this._current+=1;else if(e[this._current]==="&")if(n=this._current,this._current+=1,e[this._current]==="&")this._current+=1,t.push({start:n,type:_.TOK_AND,value:"&&"});else t.push({start:n,type:_.TOK_EXPREF,value:"&"});else if(e[this._current]==="|")if(n=this._current,this._current+=1,e[this._current]==="|")this._current+=1,t.push({start:n,type:_.TOK_OR,value:"||"});else t.push({start:n,type:_.TOK_PIPE,value:"|"});else{let i=Error(`Unknown character: ${e[this._current]}`);throw i.name="LexerError",i}return t}consumeUnquotedIdentifier(e){let t=this._current;this._current+=1;while(this._current<e.length&&gw(e[this._current]))this._current+=1;return e.slice(t,this._current)}consumeQuotedIdentifier(e){let t=this._current;this._current+=1;let n=e.length;while(e[this._current]!=='"'&&this._current<n){let o=this._current;if(e[o]==="\\"&&(e[o+1]==="\\"||e[o+1]==='"'))o+=2;else o+=1;this._current=o}return this._current+=1,JSON.parse(e.slice(t,this._current))}consumeRawStringLiteral(e){let t=this._current;this._current+=1;let n=e.length;while(e[this._current]!=="'"&&this._current<n){let r=this._current;if(e[r]==="\\"&&(e[r+1]==="\\"||e[r+1]==="'"))r+=2;else r+=1;this._current=r}return this._current+=1,e.slice(t+1,this._current-1).replace("\\'","'")}consumeNumber(e){let t=this._current;this._current+=1;let n=e.length;while(U$(e[this._current])&&this._current<n)this._current+=1;let o=parseInt(e.slice(t,this._current),10);return{start:t,value:o,type:_.TOK_NUMBER}}consumeLBracket(e){let t=this._current;if(this._current+=1,e[this._current]==="?")return this._current+=1,{start:t,type:_.TOK_FILTER,value:"[?"};if(e[this._current]==="]")return this._current+=1,{start:t,type:_.TOK_FLATTEN,value:"[]"};return{start:t,type:_.TOK_LBRACKET,value:"["}}consumeOperator(e){let t=this._current,n=e[t];if(this._current+=1,n==="!"){if(e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_NE,value:"!="};return{start:t,type:_.TOK_NOT,value:"!"}}if(n==="<"){if(e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_LTE,value:"<="};return{start:t,type:_.TOK_LT,value:"<"}}if(n===">"){if(e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_GTE,value:">="};return{start:t,type:_.TOK_GT,value:">"}}if(n==="="&&e[this._current]==="=")return this._current+=1,{start:t,type:_.TOK_EQ,value:"=="}}consumeLiteral(e){this._current+=1;let t=this._current,n=e.length;while(e[this._current]!=="`"&&this._current<n){let i=this._current;if(e[i]==="\\"&&(e[i+1]==="\\"||e[i+1]==="`"))i+=2;else i+=1;this._current=i}let o=e.slice(t,this._current).trimLeft();o=o.replace("\\`","`");let r=this.looksLikeJSON(o)?JSON.parse(o):JSON.parse(`"${o}"`);return this._current+=1,r}looksLikeJSON(e){let n=["true","false","null"],o="-0123456789";if(e==="")return!1;if('[{"'.includes(e[0]))return!0;if(n.includes(e))return!0;if("-0123456789".includes(e[0]))try{return JSON.parse(e),!0}catch(r){return!1}return!1}}var Sw=new L$,Ce={[_.TOK_EOF]:0,[_.TOK_UNQUOTEDIDENTIFIER]:0,[_.TOK_QUOTEDIDENTIFIER]:0,[_.TOK_RBRACKET]:0,[_.TOK_RPAREN]:0,[_.TOK_COMMA]:0,[_.TOK_RBRACE]:0,[_.TOK_NUMBER]:0,[_.TOK_CURRENT]:0,[_.TOK_EXPREF]:0,[_.TOK_ROOT]:0,[_.TOK_PIPE]:1,[_.TOK_OR]:2,[_.TOK_AND]:3,[_.TOK_EQ]:5,[_.TOK_GT]:5,[_.TOK_LT]:5,[_.TOK_GTE]:5,[_.TOK_LTE]:5,[_.TOK_NE]:5,[_.TOK_FLATTEN]:9,[_.TOK_STAR]:20,[_.TOK_FILTER]:21,[_.TOK_DOT]:40,[_.TOK_NOT]:45,[_.TOK_LBRACE]:50,[_.TOK_LBRACKET]:55,[_.TOK_LPAREN]:60};class D${constructor(){this.index=0,this.tokens=[]}parse(e){this.loadTokens(e),this.index=0;let t=this.expression(0);if(this.lookahead(0)!==_.TOK_EOF){let n=this.lookaheadToken(0);this.errorToken(n,`Unexpected token type: ${n.type}, value: ${n.value}`)}return t}loadTokens(e){this.tokens=[...Sw.tokenize(e),{type:_.TOK_EOF,value:"",start:e.length}]}expression(e){let t=this.lookaheadToken(0);this.advance();let n=this.nud(t),o=this.lookahead(0);while(e<Ce[o])this.advance(),n=this.led(o,n),o=this.lookahead(0);return n}lookahead(e){return this.tokens[this.index+e].type}lookaheadToken(e){return this.tokens[this.index+e]}advance(){this.index+=1}nud(e){let t,n,o;switch(e.type){case _.TOK_LITERAL:return{type:"Literal",value:e.value};case _.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:e.value};case _.TOK_QUOTEDIDENTIFIER:let r={type:"Field",name:e.value};if(this.lookahead(0)===_.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return r;case _.TOK_NOT:return n=this.expression(Ce.Not),{type:"NotExpression",children:[n]};case _.TOK_STAR:return t={type:"Identity"},n=this.lookahead(0)===_.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(Ce.Star),{type:"ValueProjection",children:[t,n]};case _.TOK_FILTER:return this.led(e.type,{type:"Identity"});case _.TOK_LBRACE:return this.parseMultiselectHash();case _.TOK_FLATTEN:return t={type:_.TOK_FLATTEN,children:[{type:"Identity"}]},n=this.parseProjectionRHS(Ce.Flatten),{type:"Projection",children:[t,n]};case _.TOK_LBRACKET:if(this.lookahead(0)===_.TOK_NUMBER||this.lookahead(0)===_.TOK_COLON)return n=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},n);if(this.lookahead(0)===_.TOK_STAR&&this.lookahead(1)===_.TOK_RBRACKET)return this.advance(),this.advance(),n=this.parseProjectionRHS(Ce.Star),{children:[{type:"Identity"},n],type:"Projection"};return this.parseMultiselectList();case _.TOK_CURRENT:return{type:_.TOK_CURRENT};case _.TOK_ROOT:return{type:_.TOK_ROOT};case _.TOK_EXPREF:return o=this.expression(Ce.Expref),{type:"ExpressionReference",children:[o]};case _.TOK_LPAREN:let i=[];while(this.lookahead(0)!==_.TOK_RPAREN){if(this.lookahead(0)===_.TOK_CURRENT)o={type:_.TOK_CURRENT},this.advance();else o=this.expression(0);i.push(o)}return this.match(_.TOK_RPAREN),i[0];default:this.errorToken(e)}}led(e,t){let n;switch(e){case _.TOK_DOT:let o=Ce.Dot;if(this.lookahead(0)!==_.TOK_STAR)return n=this.parseDotRHS(o),{type:"Subexpression",children:[t,n]};return this.advance(),n=this.parseProjectionRHS(o),{type:"ValueProjection",children:[t,n]};case _.TOK_PIPE:return n=this.expression(Ce.Pipe),{type:_.TOK_PIPE,children:[t,n]};case _.TOK_OR:return n=this.expression(Ce.Or),{type:"OrExpression",children:[t,n]};case _.TOK_AND:return n=this.expression(Ce.And),{type:"AndExpression",children:[t,n]};case _.TOK_LPAREN:let r=t.name,i=[],a;while(this.lookahead(0)!==_.TOK_RPAREN){if(this.lookahead(0)===_.TOK_CURRENT)a={type:_.TOK_CURRENT},this.advance();else a=this.expression(0);if(this.lookahead(0)===_.TOK_COMMA)this.match(_.TOK_COMMA);i.push(a)}return this.match(_.TOK_RPAREN),{name:r,type:"Function",children:i};case _.TOK_FILTER:let c=this.expression(0);return this.match(_.TOK_RBRACKET),n=this.lookahead(0)===_.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(Ce.Filter),{type:"FilterProjection",children:[t,n,c]};case _.TOK_FLATTEN:let u={type:_.TOK_FLATTEN,children:[t]},d=this.parseProjectionRHS(Ce.Flatten);return{type:"Projection",children:[u,d]};case _.TOK_EQ:case _.TOK_NE:case _.TOK_GT:case _.TOK_GTE:case _.TOK_LT:case _.TOK_LTE:return this.parseComparator(t,e);case _.TOK_LBRACKET:let m=this.lookaheadToken(0);if(m.type===_.TOK_NUMBER||m.type===_.TOK_COLON)return n=this.parseIndexExpression(),this.projectIfSlice(t,n);return this.match(_.TOK_STAR),this.match(_.TOK_RBRACKET),n=this.parseProjectionRHS(Ce.Star),{type:"Projection",children:[t,n]};default:return this.errorToken(this.lookaheadToken(0))}}match(e){if(this.lookahead(0)===e){this.advance();return}else{let t=this.lookaheadToken(0);this.errorToken(t,`Expected ${e}, got: ${t.type}`)}}errorToken(e,t=""){let n=Error(t||`Invalid token (${e.type}): "${e.value}"`);throw n.name="ParserError",n}parseIndexExpression(){if(this.lookahead(0)===_.TOK_COLON||this.lookahead(1)===_.TOK_COLON)return this.parseSliceExpression();let e={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(_.TOK_RBRACKET),e}projectIfSlice(e,t){let n={type:"IndexExpression",children:[e,t]};if(t.type==="Slice")return{children:[n,this.parseProjectionRHS(Ce.Star)],type:"Projection"};return n}parseSliceExpression(){let e=[null,null,null],t=0,n=this.lookahead(0);while(n!==_.TOK_RBRACKET&&t<3){if(n===_.TOK_COLON)t+=1,this.advance();else if(n===_.TOK_NUMBER)e[t]=this.lookaheadToken(0).value,this.advance();else{let o=this.lookaheadToken(0);this.errorToken(o,`Syntax error, unexpected token: ${o.value}(${o.type})`)}n=this.lookahead(0)}return this.match(_.TOK_RBRACKET),{children:e,type:"Slice"}}parseComparator(e,t){let n=this.expression(Ce[t]);return{type:"Comparator",name:t,children:[e,n]}}parseDotRHS(e){let t=this.lookahead(0);if([_.TOK_UNQUOTEDIDENTIFIER,_.TOK_QUOTEDIDENTIFIER,_.TOK_STAR].includes(t))return this.expression(e);if(t===_.TOK_LBRACKET)return this.match(_.TOK_LBRACKET),this.parseMultiselectList();if(t===_.TOK_LBRACE)return this.match(_.TOK_LBRACE),this.parseMultiselectHash();let o=this.lookaheadToken(0);this.errorToken(o,`Syntax error, unexpected token: ${o.value}(${o.type})`)}parseProjectionRHS(e){if(Ce[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===_.TOK_LBRACKET)return this.expression(e);if(this.lookahead(0)===_.TOK_FILTER)return this.expression(e);if(this.lookahead(0)===_.TOK_DOT)return this.match(_.TOK_DOT),this.parseDotRHS(e);let t=this.lookaheadToken(0);this.errorToken(t,`Syntax error, unexpected token: ${t.value}(${t.type})`)}parseMultiselectList(){let e=[];while(this.lookahead(0)!==_.TOK_RBRACKET){let t=this.expression(0);if(e.push(t),this.lookahead(0)===_.TOK_COMMA){if(this.match(_.TOK_COMMA),this.lookahead(0)===_.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(_.TOK_RBRACKET),{type:"MultiSelectList",children:e}}parseMultiselectHash(){let e=[],t=[_.TOK_UNQUOTEDIDENTIFIER,_.TOK_QUOTEDIDENTIFIER],n,o,r;for(;;){if(n=this.lookaheadToken(0),!t.includes(n.type))throw Error(`Expecting an identifier token, got: ${n.type}`);if(o=n.value,this.advance(),this.match(_.TOK_COLON),r=this.expression(0),e.push({value:r,type:"KeyValuePair",name:o}),this.lookahead(0)===_.TOK_COMMA)this.match(_.TOK_COMMA);else if(this.lookahead(0)===_.TOK_RBRACE){this.match(_.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:e}}}var yw=new D$,E;(function(e){e[e.TYPE_NUMBER=0]="TYPE_NUMBER",e[e.TYPE_ANY=1]="TYPE_ANY",e[e.TYPE_STRING=2]="TYPE_STRING",e[e.TYPE_ARRAY=3]="TYPE_ARRAY",e[e.TYPE_OBJECT=4]="TYPE_OBJECT",e[e.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",e[e.TYPE_EXPREF=6]="TYPE_EXPREF",e[e.TYPE_NULL=7]="TYPE_NULL",e[e.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",e[e.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(E||(E={}));class Z${constructor(e){this.TYPE_NAME_TABLE={[E.TYPE_NUMBER]:"number",[E.TYPE_ANY]:"any",[E.TYPE_STRING]:"string",[E.TYPE_ARRAY]:"array",[E.TYPE_OBJECT]:"object",[E.TYPE_BOOLEAN]:"boolean",[E.TYPE_EXPREF]:"expression",[E.TYPE_NULL]:"null",[E.TYPE_ARRAY_NUMBER]:"Array<number>",[E.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([t])=>Math.abs(t),this.functionAvg=([t])=>{let n=0;for(let o=0;o<t.length;o+=1)n+=t[o];return n/t.length},this.functionCeil=([t])=>Math.ceil(t),this.functionContains=(t)=>{let[n,o]=t;return n.includes(o)},this.functionEndsWith=(t)=>{let[n,o]=t;return n.includes(o,n.length-o.length)},this.functionFloor=([t])=>Math.floor(t),this.functionJoin=(t)=>{let[n,o]=t;return o.join(n)},this.functionKeys=([t])=>Object.keys(t),this.functionLength=([t])=>{if(!fo(t))return t.length;return Object.keys(t).length},this.functionMap=(t)=>{if(!this._interpreter)return[];let n=[],o=this._interpreter,r=t[0],i=t[1];for(let a=0;a<i.length;a+=1)n.push(o.visit(r,i[a]));return n},this.functionMax=([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===E.TYPE_NUMBER)return Math.max(...t);let o=t,r=o[0];for(let i=1;i<o.length;i+=1)if(r.localeCompare(o[i])<0)r=o[i];return r},this.functionMaxBy=(t)=>{let n=t[1],o=t[0],r=this.createKeyFunction(n,[E.TYPE_NUMBER,E.TYPE_STRING]),i=-1/0,a,s;for(let c=0;c<o.length;c+=1)if(s=r&&r(o[c]),s!==void 0&&s>i)i=s,a=o[c];return a},this.functionMerge=(t)=>{let n={};for(let o=0;o<t.length;o+=1){let r=t[o];n=Object.assign(n,r)}return n},this.functionMin=([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===E.TYPE_NUMBER)return Math.min(...t);let o=t,r=o[0];for(let i=1;i<o.length;i+=1)if(o[i].localeCompare(r)<0)r=o[i];return r},this.functionMinBy=(t)=>{let n=t[1],o=t[0],r=this.createKeyFunction(n,[E.TYPE_NUMBER,E.TYPE_STRING]),i=1/0,a,s;for(let c=0;c<o.length;c+=1)if(s=r&&r(o[c]),s!==void 0&&s<i)i=s,a=o[c];return a},this.functionNotNull=(t)=>{for(let n=0;n<t.length;n+=1)if(this.getTypeName(t[n])!==E.TYPE_NULL)return t[n];return null},this.functionReverse=([t])=>{if(this.getTypeName(t)===E.TYPE_STRING){let r=t,i="";for(let a=r.length-1;a>=0;a-=1)i+=r[a];return i}let o=t.slice(0);return o.reverse(),o},this.functionSort=([t])=>[...t].sort(),this.functionSortBy=(t)=>{if(!this._interpreter)return[];let n=t[0].slice(0);if(n.length===0)return n;let o=this._interpreter,r=t[1],i=this.getTypeName(o.visit(r,n[0]));if(i!==void 0&&![E.TYPE_NUMBER,E.TYPE_STRING].includes(i))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[i]})`);let a=[];for(let s=0;s<n.length;s+=1)a.push([s,n[s]]);a.sort((s,c)=>{let u=o.visit(r,s[1]),d=o.visit(r,c[1]);if(this.getTypeName(u)!==i)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[i]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(u)]}`);else if(this.getTypeName(d)!==i)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[i]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(d)]}`);if(u>d)return 1;return u<d?-1:s[0]-c[0]});for(let s=0;s<a.length;s+=1)n[s]=a[s][1];return n},this.functionStartsWith=([t,n])=>t.startsWith(n),this.functionSum=([t])=>t.reduce((n,o)=>n+o,0),this.functionToArray=([t])=>{if(this.getTypeName(t)===E.TYPE_ARRAY)return t;return[t]},this.functionToNumber=([t])=>{let n=this.getTypeName(t),o;if(n===E.TYPE_NUMBER)return t;if(n===E.TYPE_STRING){if(o=+t,!isNaN(o))return o}return null},this.functionToString=([t])=>{if(this.getTypeName(t)===E.TYPE_STRING)return t;return JSON.stringify(t)},this.functionType=([t])=>{switch(this.getTypeName(t)){case E.TYPE_NUMBER:return"number";case E.TYPE_STRING:return"string";case E.TYPE_ARRAY:return"array";case E.TYPE_OBJECT:return"object";case E.TYPE_BOOLEAN:return"boolean";case E.TYPE_EXPREF:return"expref";case E.TYPE_NULL:return"null";default:return}},this.functionValues=([t])=>Object.values(t),this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[E.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[E.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[E.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[E.TYPE_STRING,E.TYPE_ARRAY]},{types:[E.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[E.TYPE_STRING]},{types:[E.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[E.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[E.TYPE_STRING]},{types:[E.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[E.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[E.TYPE_STRING,E.TYPE_ARRAY,E.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[E.TYPE_EXPREF]},{types:[E.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[E.TYPE_ARRAY_NUMBER,E.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[E.TYPE_ARRAY]},{types:[E.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[E.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[E.TYPE_ARRAY_NUMBER,E.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[E.TYPE_ARRAY]},{types:[E.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[E.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[E.TYPE_STRING,E.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[E.TYPE_ARRAY_STRING,E.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[E.TYPE_ARRAY]},{types:[E.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[E.TYPE_STRING]},{types:[E.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[E.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[E.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[E.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[E.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[E.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[E.TYPE_OBJECT]}]}},this._interpreter=e}registerFunction(e,t,n){if(e in this.functionTable)throw Error(`Function already defined: ${e}()`);this.functionTable[e]={_func:t.bind(this),_signature:n}}callFunction(e,t){let n=this.functionTable[e];if(n===void 0)throw Error(`Unknown function: ${e}()`);return this.validateArgs(e,t,n._signature),n._func.call(this,t)}validateInputSignatures(e,t){for(let n=0;n<t.length;n+=1)if("variadic"in t[n]&&n!==t.length-1)throw Error(`ArgumentError: ${e}() 'variadic' argument ${n+1} must occur last`)}validateArgs(e,t,n){var o,r;let i;this.validateInputSignatures(e,n);let a=n.filter((b)=>{var R;return(R=!b.optional)!==null&&R!==void 0?R:!1}).length,s=(r=(o=n[n.length-1])===null||o===void 0?void 0:o.variadic)!==null&&r!==void 0?r:!1,c=t.length<a,u=t.length>n.length,d=c&&(!s&&a>1||s)?"at least ":"";if(s&&c||!s&&(c||u))throw i=n.length>1,Error(`ArgumentError: ${e}() takes ${d}${a} argument${i&&"s"||""} but received ${t.length}`);let m,p,h;for(let b=0;b<n.length;b+=1){h=!1,m=n[b].types,p=this.getTypeName(t[b]);let R;for(R=0;R<m.length;R+=1)if(p!==void 0&&this.typeMatches(p,m[R],t[b])){h=!0;break}if(!h&&p!==void 0){let z=m.map((N)=>this.TYPE_NAME_TABLE[N]).join(" | ");throw Error(`TypeError: ${e}() expected argument ${b+1} to be type (${z}) but received type ${this.TYPE_NAME_TABLE[p]} instead.`)}}}typeMatches(e,t,n){if(t===E.TYPE_ANY)return!0;if(t===E.TYPE_ARRAY_STRING||t===E.TYPE_ARRAY_NUMBER||t===E.TYPE_ARRAY){if(t===E.TYPE_ARRAY)return e===E.TYPE_ARRAY;if(e===E.TYPE_ARRAY){let o;if(t===E.TYPE_ARRAY_NUMBER)o=E.TYPE_NUMBER;else if(t===E.TYPE_ARRAY_STRING)o=E.TYPE_STRING;for(let r=0;r<n.length;r+=1){let i=this.getTypeName(n[r]);if(i!==void 0&&o!==void 0&&!this.typeMatches(i,o,n[r]))return!1}return!0}}else return e===t;return!1}getTypeName(e){switch(Object.prototype.toString.call(e)){case"[object String]":return E.TYPE_STRING;case"[object Number]":return E.TYPE_NUMBER;case"[object Array]":return E.TYPE_ARRAY;case"[object Boolean]":return E.TYPE_BOOLEAN;case"[object Null]":return E.TYPE_NULL;case"[object Object]":if(e.jmespathType===_.TOK_EXPREF)return E.TYPE_EXPREF;return E.TYPE_OBJECT;default:return}}createKeyFunction(e,t){if(!this._interpreter)return;let n=this._interpreter;return(r)=>{let i=n.visit(e,r);if(!t.includes(this.getTypeName(i))){let a=`TypeError: expected one of (${t.map((s)=>this.TYPE_NAME_TABLE[s]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(i)]}`;throw Error(a)}return i}}}class F${constructor(){this._rootValue=null,this.runtime=new Z$(this)}search(e,t){return this._rootValue=t,this.visit(e,t)}visit(e,t){let n,o,r,i,a,s,c,u,d,m,p;switch(e.type){case"Field":if(t===null)return null;if(fo(t)){if(s=t[e.name],s===void 0)return null;return s}return null;case"Subexpression":r=this.visit(e.children[0],t);for(m=1;m<e.children.length;m+=1)if(r=this.visit(e.children[1],r),r===null)return null;return r;case"IndexExpression":return c=this.visit(e.children[0],t),u=this.visit(e.children[1],c),u;case"Index":if(!Array.isArray(t))return null;let h=e.value;if(h<0)h=t.length+h;if(r=t[h],r===void 0)r=null;return r;case"Slice":if(!Array.isArray(t))return null;let b=[...e.children],R=this.computeSliceParams(t.length,b),[z,N,B]=R;if(r=[],B>0)for(m=z;m<N;m+=B)r.push(t[m]);else for(m=z;m>N;m+=B)r.push(t[m]);return r;case"Projection":if(p=this.visit(e.children[0],t),!Array.isArray(p))return null;d=[];for(m=0;m<p.length;m+=1)if(o=this.visit(e.children[1],p[m]),o!==null)d.push(o);return d;case"ValueProjection":if(p=this.visit(e.children[0],t),!fo(p))return null;d=[];let P=Object.values(p);for(m=0;m<P.length;m+=1)if(o=this.visit(e.children[1],P[m]),o!==null)d.push(o);return d;case"FilterProjection":if(p=this.visit(e.children[0],t),!Array.isArray(p))return null;let O=[],J=[];for(m=0;m<p.length;m+=1)if(n=this.visit(e.children[2],p[m]),!Pu(n))O.push(p[m]);for(let ue=0;ue<O.length;ue+=1)if(o=this.visit(e.children[1],O[ue]),o!==null)J.push(o);return J;case"Comparator":switch(i=this.visit(e.children[0],t),a=this.visit(e.children[1],t),e.name){case _.TOK_EQ:r=Ou(i,a);break;case _.TOK_NE:r=!Ou(i,a);break;case _.TOK_GT:r=i>a;break;case _.TOK_GTE:r=i>=a;break;case _.TOK_LT:r=i<a;break;case _.TOK_LTE:r=i<=a;break;default:throw Error(`Unknown comparator: ${e.name}`)}return r;case _.TOK_FLATTEN:let Y=this.visit(e.children[0],t);if(!Array.isArray(Y))return null;let ee=[];for(m=0;m<Y.length;m+=1)if(o=Y[m],Array.isArray(o))ee=[...ee,...o];else ee.push(o);return ee;case"Identity":return t;case"MultiSelectList":if(t===null)return null;d=[];for(m=0;m<e.children.length;m+=1)d.push(this.visit(e.children[m],t));return d;case"MultiSelectHash":if(t===null)return null;d={};let ne;for(m=0;m<e.children.length;m+=1)ne=e.children[m],d[ne.name]=this.visit(ne.value,t);return d;case"OrExpression":if(n=this.visit(e.children[0],t),Pu(n))n=this.visit(e.children[1],t);return n;case"AndExpression":if(i=this.visit(e.children[0],t),Pu(i))return i;return this.visit(e.children[1],t);case"NotExpression":return i=this.visit(e.children[0],t),Pu(i);case"Literal":return e.value;case _.TOK_PIPE:return c=this.visit(e.children[0],t),this.visit(e.children[1],c);case _.TOK_CURRENT:return t;case _.TOK_ROOT:return this._rootValue;case"Function":let ae=[];for(let ue=0;ue<e.children.length;ue+=1)ae.push(this.visit(e.children[ue],t));return this.runtime.callFunction(e.name,ae);case"ExpressionReference":let ce=e.children[0];return ce.jmespathType=_.TOK_EXPREF,ce;default:throw Error(`Unknown node type: ${e.type}`)}}computeSliceParams(e,t){let[n,o,r]=t;if(r===null)r=1;else if(r===0){let a=Error("Invalid slice, step cannot be 0");throw a.name="RuntimeError",a}let i=r<0?!0:!1;return n=n===null?i?e-1:0:this.capSliceRange(e,n,r),o=o===null?i?-1:e:this.capSliceRange(e,o,r),[n,o,r]}capSliceRange(e,t,n){let o=t;if(o<0){if(o+=e,o<0)o=n<0?-1:0}else if(o>=e)o=n<0?e-1:e;return o}}var bw=new F$,CC=E.TYPE_ANY,NC=E.TYPE_ARRAY,jC=E.TYPE_ARRAY_NUMBER,AC=E.TYPE_ARRAY_STRING,MC=E.TYPE_BOOLEAN,UC=E.TYPE_EXPREF,qC=E.TYPE_NULL,LC=E.TYPE_NUMBER,DC=E.TYPE_OBJECT,ZC=E.TYPE_STRING;function K$(e,t){let n=yw.parse(t);return bw.search(n,e)}function V$(e,t){return Vv(e.responseProjection,t)}function Vv(e,t){if(!e||typeof e!=="string"||!e.trim())return t;if(t===null||typeof t!=="object")return t;try{let n=K$(t,e);return n===void 0?null:n}catch{return t}}function J$(e){if(e===void 0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)??"").length}catch{return 0}}function $w(e,t,n){let o=V$(e,t),r=n?.projectionUsage;if(!r)return o;let i=e.responseProjection;if(!(Boolean(i&&typeof i==="string"&&i.trim())&&t!==null&&typeof t==="object"))return o;let s=J$(t),c=J$(o);return r.preBytes+=s,r.postBytes+=c,r.applied=r.applied||o!==t,o}function ho(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function gt(e,t){if(typeof e.description!=="string"||!e.description)return t;return t.describe(e.description)}function Rw(e){let t=e.map((n)=>S(n));if(!t.length)return Z();if(t.length===1)return t[0];return A(t)}function jt(e,t){let n=e.type;if(!(e.nullable===!0||Array.isArray(n)&&n.includes("null")))return t;return t.nullable()}function ga(e){if(!ho(e))return Z();if(Array.isArray(e.enum)&&e.enum.length)return jt(e,gt(e,Rw(e.enum)));if(Object.prototype.hasOwnProperty.call(e,"const"))return jt(e,gt(e,S(e.const)));for(let n of["oneOf","anyOf"]){let o=e[n];if(Array.isArray(o)&&o.length){let r=o.map((a)=>ga(a)),i=r.length===1?r[0]:A(r);return jt(e,gt(e,i))}}let t=typeof e.type==="string"?e.type:Array.isArray(e.type)?e.type.find((n)=>n!=="null"):null;if(t==="object"||!t&&(ho(e.properties)||Object.prototype.hasOwnProperty.call(e,"additionalProperties")))return B$(e);if(t==="array"){let n=ho(e.items)?ga(e.items):Z();return jt(e,gt(e,v(n)))}if(t==="string"){let n=l();if(typeof e.minLength==="number")n=n.min(e.minLength);if(typeof e.maxLength==="number")n=n.max(e.maxLength);return jt(e,gt(e,n))}if(t==="integer"){let n=x().int();if(typeof e.minimum==="number")n=n.min(e.minimum);if(typeof e.maximum==="number")n=n.max(e.maximum);return jt(e,gt(e,n))}if(t==="number"){let n=x();if(typeof e.minimum==="number")n=n.min(e.minimum);if(typeof e.maximum==="number")n=n.max(e.maximum);return jt(e,gt(e,n))}if(t==="boolean")return jt(e,gt(e,j()));if(t==="null")return gt(e,pt());return jt(e,gt(e,Z()))}function B$(e){if(!ho(e))return f({}).passthrough();let t=ho(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter((i)=>typeof i==="string"):[]),o=Object.fromEntries(Object.entries(t).map(([i,a])=>{let s=ga(a),c=n.has(i)?s:s.optional();return[i,c]})),r=e.additionalProperties===!1?f(o).strict():ho(e.additionalProperties)?f(o).catchall(ga(e.additionalProperties)):f(o).passthrough();return jt(e,gt(e,r))}var go=new Map;function zw(e,t){let n=go.get(e)??{};go.set(e,{...n,...t})}function Tw(){go.clear()}function xw(){let e={};for(let[t,n]of go)e[t]={...n};return e}function Bv(e,t){return go.get(e)?.description??t}function Hv(e,t){return go.get(e)?.title??t}function Y$(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter((t)=>t.length>0)}function Yv(e){return[e.name,e.title,e.description,e.tags.join(" ")].join(" ")}function kw(e){let t=e.map((i)=>Y$(Yv(i))),n=new Map;for(let i of t)for(let a of new Set(i))n.set(a,(n.get(a)??0)+1);let o=t.reduce((i,a)=>i+a.length,0),r=t.length?o/t.length:0;return{entries:e,docTokens:t,docFrequency:n,averageDocLength:r}}var H$=new WeakMap;function Ew(e){let t=H$.get(e);if(t)return t;let n=kw(e);return H$.set(e,n),n}function ww(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}function Iw(e,t,n){let o=e.docTokens[t];if(!o.length)return 0;let r=ww(o),i=o.length,a=e.entries.length,s=e.averageDocLength||1,c=0;for(let u of n){let d=r.get(u);if(!d)continue;let m=e.docFrequency.get(u)??0,p=Math.log(1+(a-m+0.5)/(m+0.5)),h=d+1.5*(0.25+0.75*i/s);c+=p*(d*2.5/h)}return c}function Pw(e){let t=e.match(/^\/(.+)\/([a-z]*)$/);if(!t)return null;try{return new RegExp(t[1],t[2])}catch{return null}}function Cu(e,t){return{name:e.name,title:e.title,description:e.description,score:t}}function Ow(e,t,n){let o=[];for(let r of e){let i=t.flags.includes("g")?t.flags:`${t.flags}g`;if(new RegExp(t.source,i).test(Yv(r)))o.push(Cu(r,1));if(o.length>=n)break}return o}function Cw(e,t,n){let o=t.toLowerCase().trim();if(!o)return[];let r=[];for(let i of e){if(Yv(i).toLowerCase().includes(o))r.push(Cu(i,1));if(r.length>=n)break}return r}function Gv(e,t,n=10){let o=Math.max(1,Math.min(Math.floor(n)||10,100)),r=t.trim();if(!r)return e.slice(0,o).map((u)=>Cu(u,0));let i=Pw(r);if(i)return Ow(e,i,o);let a=Ew(e),s=Y$(r),c=a.entries.map((u,d)=>({entry:u,score:Iw(a,d,s)})).filter((u)=>u.score>0).sort((u,d)=>d.score-u.score).slice(0,o).map((u)=>Cu(u.entry,Number(u.score.toFixed(4))));if(c.length>0)return c;return Cw(e,r,o)}var Wv="0.19.1";function Nw(e){let t=3735928559,n=1103547991;for(let o=0;o<e.length;o++){let r=e.charCodeAt(o);t=Math.imul(t^r,2654435761),n=Math.imul(n^r,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&n)+(t>>>0)).toString(16)}function G$(e){let t=JSON.stringify(e,(n,o)=>typeof o==="function"?void 0:o);return`mcpc-${Nw(t??"")}`}function W$(e,t){let n=e.headers.get("mcp-session-id")?.trim();if(!n||!n.startsWith("mcpc-"))return!1;return n!==t}async function X$(e){if(e.method!=="POST")return!1;try{let t=await e.clone().json();return(Array.isArray(t)?t:[t]).some((o)=>typeof o==="object"&&o!==null&&o.method==="initialize")}catch{return!1}}function Q$(){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32001,message:"Session not found: this server's tools changed since you connected. Reconnect to load the current tools."}},{status:404})}function eR(e,t){if(!e.ok)return e;let n=new Headers(e.headers);return n.set("Mcp-Session-Id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}var Xv={maxDepth:2,maxKeys:12,maxVariants:3};function jw(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;if(t==="object"&&e instanceof Date)return"Date";return t}function tR(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof Date)}function Aw(e,t){let n=[...new Set(e)];if(n.length===0)return"unknown";if(n.length===1)return n[0];let o=[...n].sort();if(o.length>t)return`${o.slice(0,t).join(" | ")} | …${o.length-t} more`;return o.join(" | ")}function Qv(e,t,n,o){if(!tR(e)&&!Array.isArray(e))return jw(e);if(Array.isArray(e)){if(e.length===0)return"unknown[0]";let s=e.slice(0,200).map((c)=>Qv(c,t,n,o));return`${Aw(s,o.maxVariants)}[${e.length}]`}let r=Object.keys(e);if(t<=0&&n.length===0)return"object";let i=r.slice(0,o.maxKeys),a=i.map((s)=>{let c=n[0]===s,u=c?n.slice(1):[],d=c?Math.max(t,1):t-1;return`${s}: ${Qv(e[s],d,u,o)}`});if(r.length>i.length)a.push(`…+${r.length-i.length} more`);return`{${a.join(", ")}}`}function va(e,t={}){let n={maxDepth:t.maxDepth??Xv.maxDepth,maxKeys:t.maxKeys??Xv.maxKeys,maxVariants:t.maxVariants??Xv.maxVariants};return Qv(e,n.maxDepth,t.focusPath??[],n)}function e_(e,t={}){if(!Array.isArray(e)||e.length===0)return[];let n=e.filter(tR);if(n.length===0)return[];let o=n.length,r=new Map,i=new Set;for(let a of n)for(let s of Object.keys(a))i.add(s);for(let a of i){let s=0;for(let c of n){let u=c[a];if(u===null||u===void 0)s+=1}if(s>0)r.set(a,s)}return[...r.entries()].map(([a,s])=>({field:a,missing:s,total:o,text:`${s}/${o} items have ${a} === null`})).sort((a,s)=>s.missing-a.missing||a.field.localeCompare(s.field)).slice(0,t.limit??3)}var Mw=["read","write"],r_="__mcpcloud_call_tool",Uw=`globalThis.tool = (name, args) =>
102
102
  globalThis.${r_}(String(name), JSON.stringify(args ?? {}))
103
103
  .then((json) => JSON.parse(json));`;function rR(e,t,n,o){let r=[],i=!1,a=!1,s=!1,c=t.newFunction(r_,(d,m)=>{let p=t.newPromise(),h="<unknown>";try{h=t.getString(d);let b=t.getString(m);if(r.length>=o){i=!0;let O=t.newString(`Tool-call budget exhausted: ${o} calls per execution.`);return p.reject(O),O.dispose(),p.settled.then(()=>e.executePendingJobs()),p.handle}if(n.isKnownTool&&!n.isKnownTool(h)){let O=n.describeUnknownTool?n.describeUnknownTool(h):`Unknown tool "${h}".`;r.push({name:h,args:t_(b),durationMs:0,mutates:!1,error:O});let J=t.newString(O);return p.reject(J),J.dispose(),p.settled.then(()=>e.executePendingJobs()),p.handle}let R=n.refuseToolCall?.(h)??null;if(R){a=!0,r.push({name:h,args:t_(b),durationMs:0,mutates:!0,error:R});let O=t.newString(R);return p.reject(O),O.dispose(),p.settled.then(()=>e.executePendingJobs()),p.handle}if(n.effectClassFor){let O=n.allowedEffects??Mw,J=n.effectClassFor(h)??null;if(J===null||!O.includes(J)){a=!0;let Y=J===null?`Tool "${h}" has no classified effect and cannot be called from Code Mode.`:`Tool "${h}" is a ${J} operation, which Code Mode does not permit. Call it directly instead.`;r.push({name:h,args:t_(b),durationMs:0,mutates:J!=="read",error:Y});let ee=t.newString(Y);return p.reject(ee),ee.dispose(),p.settled.then(()=>e.executePendingJobs()),p.handle}}let z={};try{z=JSON.parse(b)}catch{z={}}let N=n.isMutation?n.isMutation(h)!==!1:!0,B=Date.now(),P={name:h,args:z,durationMs:0,mutates:N};return r.push(P),n.callTool({name:h,args:z}).then((O)=>{P.durationMs=Date.now()-B;let J=n.projectionFor?.(h),Y=Vv(J,O);if(J){let ae=JSON.stringify(O??null).length,ce=JSON.stringify(Y??null).length;P.preProjectionBytes=ae,P.postProjectionBytes=ce}P.resultShape=va(Y);let ee=e_(Y);if(ee.length)P.facts=ee.map((ae)=>ae.text);let ne=t.newString(JSON.stringify(Y??null));p.resolve(ne),ne.dispose()}).catch((O)=>{P.durationMs=Date.now()-B,P.error=O instanceof Error?O.message:String(O);let J=t.newString(P.error);p.reject(J),J.dispose()}).finally(()=>{e.executePendingJobs()}),p.handle}catch(b){let R=b instanceof Error?b.message:String(b),z=`Tool "${h}" could not be dispatched: ${R}`;r.push({name:h,args:{},durationMs:0,mutates:!0,error:z}),s=!0;let N=t.newString(z);return p.reject(N),N.dispose(),p.settled.then(()=>e.executePendingJobs()),p.handle}});t.setProp(t.global,r_,c),c.dispose();let u=t.evalCode(Uw,"mcpcloud:shim");if(u.error){let d=t.dump(u.error);throw u.error.dispose(),Error(`Failed to install the guest tool shim: ${String(d)}`)}return u.value.dispose(),{spans:r,exceededCap:()=>i,deniedByPolicy:()=>a,hostThrew:()=>s}}function t_(e){try{return JSON.parse(e)}catch{return{}}}var qw=40,_a=200,Lw=6,nR=["log","warn","error","info","debug"],n_="__mcpcloud_console",Dw=`globalThis.console = {
104
104
  ${nR.map((e)=>` ${e}: (...args) => globalThis.${n_}(${JSON.stringify(e)}, JSON.stringify(args.slice(0, ${Lw}).map((value) => (value instanceof Error ? { __mcpcloudError: value.name + ': ' + value.message } : value)))),`).join(`
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.19.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.19.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var Tt=Object.create;var{getPrototypeOf:yt,defineProperty:re,getOwnPropertyNames:St}=Object;var De=Object.prototype.hasOwnProperty;function Rt(e){return this[e]}var wt,Pt,At=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var l=t?wt??=new WeakMap:Pt??=new WeakMap,d=l.get(e);if(d)return d}n=e!=null?Tt(yt(e)):{};let m=t||!e||!e.__esModule||!De.call(e,"default")?re(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of St(e))if(!De.call(m,s))re(m,s,{get:Rt.bind(e,s),enumerable:!0})}if(o)l.set(e,m);return m};var bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ot=(e)=>e;function Mt(e,t){this[e]=Ot.bind(null,t)}var vt=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Mt.bind(t,n)})};var ne=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(o){n=[o]}if(n)throw n[0];return t};var U,ie,j,K,J;var G=ne(()=>{U={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},ie={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},j={Pending:0,Fulfilled:1,Rejected:2},K={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},J={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function F(...e){ce&&console.log("quickjs-emscripten:",...e)}function*st(e){return yield e}function Ut(e){return st(de(e))}function je(e,t){return(...n)=>{let o=t.call(e,he,...n);return de(o)}}function Kt(e,t){let n=t.call(e,he);return de(n)}function de(e){function t(n){return n.done?n.value:n.value instanceof Promise?n.value.then((o)=>t(e.next(o)),(o)=>t(e.throw(o))):t(e.next(n.value))}return t(e.next())}function se(e,t){let n;try{e.dispose()}catch(o){n=o}if(t&&n)throw Object.assign(t,{message:`${t.message}
3
3
  Then, failed to dispose scope: ${n.message}`,disposeError:n}),t;if(t||n)throw t||n}function Yt(e){let t=e?Array.from(e):[];function n(){return t.forEach((l)=>l.alive?l.dispose():void 0)}function o(){return t.some((l)=>l.alive)}return Object.defineProperty(t,le,{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:o}),t}function W(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Ht(e){if(!e)return 0;let t=0;for(let[n,o]of Object.entries(e)){if(!(n in ie))throw new tt(n);o&&(t|=ie[n])}return t}function Dt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:n,strip:o,compileOnly:l,backtraceBarrier:d}=e,m=0;return t==="global"&&(m|=U.JS_EVAL_TYPE_GLOBAL),t==="module"&&(m|=U.JS_EVAL_TYPE_MODULE),n&&(m|=U.JS_EVAL_FLAG_STRICT),o&&(m|=U.JS_EVAL_FLAG_STRIP),l&&(m|=U.JS_EVAL_FLAG_COMPILE_ONLY),d&&(m|=U.JS_EVAL_FLAG_BACKTRACE_BARRIER),m}function Qt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:n,quickjsPrivate:o,onlyEnumerable:l,numbers:d,numbersAsStrings:m}=e,s=0;return t&&(s|=K.JS_GPN_STRING_MASK),n&&(s|=K.JS_GPN_SYMBOL_MASK),o&&(s|=K.JS_GPN_PRIVATE_MASK),l&&(s|=K.JS_GPN_ENUM_ONLY),d&&(s|=K.QTS_GPN_NUMBER_MASK),m&&(s|=K.QTS_STANDARD_COMPLIANT_NUMBER),s}function jt(...e){let t=[];for(let n of e)n!==void 0&&(t=t.concat(n));return t}function oe(e){return e>>8}function pe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function _e(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var Nt,Ct=(e,t)=>{for(var n in t)Nt(e,n,{get:t[n],enumerable:!0})},ce=!1,kt,ae,ze,ue,Xe,Ze,et,It,Lt,tt,rt,nt,it,I,he,N,le,$e,P,Y,Ge,v,fe,Bt,Jt,B,Ft,ot=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((l)=>l.value)),n=t.length*t.BYTES_PER_ELEMENT,o=this.module._malloc(n);return new Uint8Array(this.module.HEAPU8.buffer,o,n).set(new Uint8Array(t.buffer)),new P(o,void 0,(l)=>this.module._free(l))}newTypedArray(e,t){let n=new e(Array(t).fill(0)),o=n.length*n.BYTES_PER_ELEMENT,l=this.module._malloc(o),d=new e(this.module.HEAPU8.buffer,l,t);return d.set(n),new P({typedArray:d,ptr:l},void 0,(m)=>this.module._free(m.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),n=t+1,o=this.module._malloc(n);return this.module.stringToUTF8(e,o,n),new P({ptr:o,strlen:t},void 0,(l)=>this.module._free(l.ptr))}newHeapBufferPointer(e){let t=e.byteLength,n=this.module._malloc(t);return this.module.HEAPU8.set(e,n),new P({pointer:n,numBytes:t},void 0,(o)=>this.module._free(o.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Sr,Rr,$t,Ve=-2147483648,We=2147483647,V=0,Gt=class{constructor(){this.nextId=Ve,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),n=oe(t),o=this.groups.get(n);return o||(o=new Map,this.groups.set(n,o)),o.set(t,e),t}get(e){if(e===V)throw new I("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new I(`host reference id ${e} is not defined`);let o=n.get(e);if(!o)throw new I(`host reference id ${e} is not defined`);return o}delete(e){if(e===V)throw new I("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new I(`host reference id ${e} is not defined`);n.delete(e),n.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===V&&this.nextId++,this.nextId>We)throw new it(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${We-Ve}`);return this.nextId++}},qe,Vt,Wt,qt,zt=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},me=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new zt({freeHostRef:(t,n,o)=>{let l=this.runtimeCallbacks.get(n);if(!l)throw Error(`QuickJSRuntime(rt = ${n}) not found when trying to free HostRef(id = ${o})`);l.freeHostRef(n,o)},callFunction:(t,n,o,l,d,m)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(n);if(!s)throw Error(`QuickJSContext(ctx = ${n}) not found for C function call "${m}"`);return s.callFunction(n,o,l,d,m)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,n)=>this.handleAsyncify(t,()=>{try{let o=this.runtimeCallbacks.get(n);if(!o)throw Error(`QuickJSRuntime(rt = ${n}) not found for C interrupt`);return o.shouldInterrupt(n)}catch(o){return console.error("[C to host interrupt: returning error]",o),1}}),loadModuleSource:(t,n,o,l)=>this.handleAsyncify(t,()=>{try{let d=this.runtimeCallbacks.get(n);if(!d)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let m=d.loadModuleSource;if(!m)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return m(n,o,l)}catch(d){return console.error("[C to host module loader error: returning null]",d),0}}),normalizeModule:(t,n,o,l,d)=>this.handleAsyncify(t,()=>{try{let m=this.runtimeCallbacks.get(n);if(!m)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let s=m.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return s(n,o,l,d)}catch(m){return console.error("[C to host module loader error: returning null]",m),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((o)=>{try{let l=t();if(!(l instanceof Promise)){F("asyncify.handleSleep: not suspending:",l),o(l);return}if(this.suspended)throw new Ze(`Already suspended at: ${this.suspended.stack}
4
4
  Attempted to suspend at:`);this.suspended=new et(`(${this.suspendedCount++})`),F("asyncify.handleSleep: suspending:",this.suspended),l.then((d)=>{this.suspended=void 0,F("asyncify.handleSleep: resolved:",d),o(d)},(d)=>{F("asyncify.handleSleep: rejected:",d),console.error("QuickJS: cannot handle error in suspended function",d),this.suspended=void 0})}catch(l){throw F("asyncify.handleSleep: error:",l),this.suspended=void 0,l}});let n=t();if(n instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return n}},at=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new me(e)}newRuntime(e={}){let t=new P(this.ffi.QTS_NewRuntime(),void 0,(o)=>{this.ffi.QTS_FreeRuntime(o),this.callbacks.deleteRuntime(o)}),n=new qt({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return pe(n,e),e.moduleLoader&&n.setModuleLoader(e.moduleLoader),n}newContext(e={}){let t=this.newRuntime(),n=t.newContext({...e,ownedLifetimes:jt(t,e.ownedLifetimes)});return t.context=n,n}evalCode(e,t={}){return v.withScope((n)=>{let o=n.manage(this.newContext());_e(o.runtime,t);let l=o.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&o.runtime.setMemoryLimit(-1),l.error)throw o.dump(n.manage(l.error));return o.dump(n.manage(l.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var ut=ne(()=>{G();G();Nt=Object.defineProperty;kt={};Ct(kt,{QuickJSAsyncifyError:()=>Ze,QuickJSAsyncifySuspended:()=>et,QuickJSEmptyGetOwnPropertyNames:()=>nt,QuickJSEmscriptenModuleError:()=>Lt,QuickJSHostRefInvalid:()=>I,QuickJSHostRefRangeExceeded:()=>it,QuickJSMemoryLeakDetected:()=>It,QuickJSNotImplemented:()=>Xe,QuickJSPromisePending:()=>rt,QuickJSUnknownIntrinsic:()=>tt,QuickJSUnwrapError:()=>ae,QuickJSUseAfterFree:()=>ue,QuickJSWrongOwner:()=>ze});ae=class extends Error{constructor(e,t){let n=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(n);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},ue=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},Xe=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},Ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},et=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},It=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Lt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},tt=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},rt=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},nt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},it=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},I=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};he=st;he.of=Ut;N=class{[Symbol.dispose](){return this.dispose()}},le=Symbol.dispose??Symbol.for("Symbol.dispose"),$e=N.prototype;$e[le]||($e[le]=function(){return this.dispose()});P=class e extends N{constructor(t,n,o,l){super();this._value=t,this.copier=n,this.disposer=o,this._owner=l,this._alive=!0,this._constructorStack=ce?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let n=t(this);return this.dispose(),n}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ue(`Lifetime not alive
@@ -16,4 +16,4 @@
16
16
  * question: not "what did we intend to deploy?" but "what is running?".
17
17
  * Comparing the two makes a failed-but-successful-looking deploy detectable.
18
18
  */
19
- export declare const RUNTIME_VERSION = "0.19.0";
19
+ export declare const RUNTIME_VERSION = "0.19.1";
package/dist/stdio.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.19.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.19.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var Df=Object.create;var{getPrototypeOf:Uf,defineProperty:la,getOwnPropertyNames:Ff}=Object;var Ku=Object.prototype.hasOwnProperty;function Zf(e){return this[e]}var Vf,Jf,Hf=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?Vf??=new WeakMap:Jf??=new WeakMap,i=o.get(e);if(i)return i}r=e!=null?Df(Uf(e)):{};let a=t||!e||!e.__esModule||!Ku.call(e,"default")?la(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let s of Ff(e))if(!Ku.call(a,s))la(a,s,{get:Zf.bind(e,s),enumerable:!0})}if(n)o.set(e,a);return a};var Kf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Bf=(e)=>e;function Yf(e,t){this[e]=Bf.bind(null,t)}var Gf=(e,t)=>{for(var r in t)la(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Yf.bind(t,r)})};var da=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var nr,Nu,oa,or,ho;var sa=da(()=>{nr={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},Nu={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},oa={Pending:0,Fulfilled:1,Rejected:2},or={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},ho={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function fo(...e){qu&&console.log("quickjs-emscripten:",...e)}function*wf(e){return yield e}function kv(e){return wf(Du(e))}function lf(e,t){return(...r)=>{let n=t.call(e,Lu,...r);return Du(n)}}function Ov(e,t){let r=t.call(e,Lu);return Du(r)}function Du(e){function t(r){return r.done?r.value:r.value instanceof Promise?r.value.then((n)=>t(e.next(n)),(n)=>t(e.throw(n))):t(e.next(r.value))}return t(e.next())}function xu(e,t){let r;try{e.dispose()}catch(n){r=n}if(t&&r)throw Object.assign(t,{message:`${t.message}
3
3
  Then, failed to dispose scope: ${r.message}`,disposeError:r}),t;if(t||r)throw t||r}function Cv(e){let t=e?Array.from(e):[];function r(){return t.forEach((o)=>o.alive?o.dispose():void 0)}function n(){return t.some((o)=>o.alive)}return Object.defineProperty(t,Mu,{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:n}),t}function aa(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Av(e){if(!e)return 0;let t=0;for(let[r,n]of Object.entries(e)){if(!(r in Nu))throw new vf(r);n&&(t|=Nu[r])}return t}function jv(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:r,strip:n,compileOnly:o,backtraceBarrier:i}=e,a=0;return t==="global"&&(a|=nr.JS_EVAL_TYPE_GLOBAL),t==="module"&&(a|=nr.JS_EVAL_TYPE_MODULE),r&&(a|=nr.JS_EVAL_FLAG_STRICT),n&&(a|=nr.JS_EVAL_FLAG_STRIP),o&&(a|=nr.JS_EVAL_FLAG_COMPILE_ONLY),i&&(a|=nr.JS_EVAL_FLAG_BACKTRACE_BARRIER),a}function Mv(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:r,quickjsPrivate:n,onlyEnumerable:o,numbers:i,numbersAsStrings:a}=e,s=0;return t&&(s|=or.JS_GPN_STRING_MASK),r&&(s|=or.JS_GPN_SYMBOL_MASK),n&&(s|=or.JS_GPN_PRIVATE_MASK),o&&(s|=or.JS_GPN_ENUM_ONLY),i&&(s|=or.QTS_GPN_NUMBER_MASK),a&&(s|=or.QTS_STANDARD_COMPLIANT_NUMBER),s}function qv(...e){let t=[];for(let r of e)r!==void 0&&(t=t.concat(r));return t}function Iu(e){return e>>8}function Zu(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function Vu(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var wv,$v=(e,t)=>{for(var r in t)wv(e,r,{get:t[r],enumerable:!0})},qu=!1,Ev,Au,gf,ju,_f,Sf,yf,Tv,Pv,vf,bf,Rf,zf,jt,Lu,ft,Mu,df,Be,sr,mf,lt,Uu,Nv,xv,Zr,Iv,$f=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((o)=>o.value)),r=t.length*t.BYTES_PER_ELEMENT,n=this.module._malloc(r);return new Uint8Array(this.module.HEAPU8.buffer,n,r).set(new Uint8Array(t.buffer)),new Be(n,void 0,(o)=>this.module._free(o))}newTypedArray(e,t){let r=new e(Array(t).fill(0)),n=r.length*r.BYTES_PER_ELEMENT,o=this.module._malloc(n),i=new e(this.module.HEAPU8.buffer,o,t);return i.set(r),new Be({typedArray:i,ptr:o},void 0,(a)=>this.module._free(a.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),r=t+1,n=this.module._malloc(r);return this.module.stringToUTF8(e,n,r),new Be({ptr:n,strlen:t},void 0,(o)=>this.module._free(o.ptr))}newHeapBufferPointer(e){let t=e.byteLength,r=this.module._malloc(t);return this.module.HEAPU8.set(e,r),new Be({pointer:r,numBytes:t},void 0,(n)=>this.module._free(n.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},iw,aw,Lv,pf=-2147483648,hf=2147483647,ia=0,Dv=class{constructor(){this.nextId=pf,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),r=Iu(t),n=this.groups.get(r);return n||(n=new Map,this.groups.set(r,n)),n.set(t,e),t}get(e){if(e===ia)throw new jt("no host reference id defined");let t=Iu(e),r=this.groups.get(t);if(!r)throw new jt(`host reference id ${e} is not defined`);let n=r.get(e);if(!n)throw new jt(`host reference id ${e} is not defined`);return n}delete(e){if(e===ia)throw new jt("no host reference id defined");let t=Iu(e),r=this.groups.get(t);if(!r)throw new jt(`host reference id ${e} is not defined`);r.delete(e),r.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===ia&&this.nextId++,this.nextId>hf)throw new zf(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${hf-pf}`);return this.nextId++}},ff,Uv,Fv,Zv,Vv=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},Fu=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new Vv({freeHostRef:(t,r,n)=>{let o=this.runtimeCallbacks.get(r);if(!o)throw Error(`QuickJSRuntime(rt = ${r}) not found when trying to free HostRef(id = ${n})`);o.freeHostRef(r,n)},callFunction:(t,r,n,o,i,a)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(r);if(!s)throw Error(`QuickJSContext(ctx = ${r}) not found for C function call "${a}"`);return s.callFunction(r,n,o,i,a)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,r)=>this.handleAsyncify(t,()=>{try{let n=this.runtimeCallbacks.get(r);if(!n)throw Error(`QuickJSRuntime(rt = ${r}) not found for C interrupt`);return n.shouldInterrupt(r)}catch(n){return console.error("[C to host interrupt: returning error]",n),1}}),loadModuleSource:(t,r,n,o)=>this.handleAsyncify(t,()=>{try{let i=this.runtimeCallbacks.get(r);if(!i)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let a=i.loadModuleSource;if(!a)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return a(r,n,o)}catch(i){return console.error("[C to host module loader error: returning null]",i),0}}),normalizeModule:(t,r,n,o,i)=>this.handleAsyncify(t,()=>{try{let a=this.runtimeCallbacks.get(r);if(!a)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let s=a.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return s(r,n,o,i)}catch(a){return console.error("[C to host module loader error: returning null]",a),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((n)=>{try{let o=t();if(!(o instanceof Promise)){fo("asyncify.handleSleep: not suspending:",o),n(o);return}if(this.suspended)throw new Sf(`Already suspended at: ${this.suspended.stack}
4
4
  Attempted to suspend at:`);this.suspended=new yf(`(${this.suspendedCount++})`),fo("asyncify.handleSleep: suspending:",this.suspended),o.then((i)=>{this.suspended=void 0,fo("asyncify.handleSleep: resolved:",i),n(i)},(i)=>{fo("asyncify.handleSleep: rejected:",i),console.error("QuickJS: cannot handle error in suspended function",i),this.suspended=void 0})}catch(o){throw fo("asyncify.handleSleep: error:",o),this.suspended=void 0,o}});let r=t();if(r instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return r}},Ef=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new Fu(e)}newRuntime(e={}){let t=new Be(this.ffi.QTS_NewRuntime(),void 0,(n)=>{this.ffi.QTS_FreeRuntime(n),this.callbacks.deleteRuntime(n)}),r=new Zv({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return Zu(r,e),e.moduleLoader&&r.setModuleLoader(e.moduleLoader),r}newContext(e={}){let t=this.newRuntime(),r=t.newContext({...e,ownedLifetimes:qv(t,e.ownedLifetimes)});return t.context=r,r}evalCode(e,t={}){return lt.withScope((r)=>{let n=r.manage(this.newContext());Vu(n.runtime,t);let o=n.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&n.runtime.setMemoryLimit(-1),o.error)throw n.dump(r.manage(o.error));return n.dump(r.manage(o.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var Tf=da(()=>{sa();sa();wv=Object.defineProperty;Ev={};$v(Ev,{QuickJSAsyncifyError:()=>Sf,QuickJSAsyncifySuspended:()=>yf,QuickJSEmptyGetOwnPropertyNames:()=>Rf,QuickJSEmscriptenModuleError:()=>Pv,QuickJSHostRefInvalid:()=>jt,QuickJSHostRefRangeExceeded:()=>zf,QuickJSMemoryLeakDetected:()=>Tv,QuickJSNotImplemented:()=>_f,QuickJSPromisePending:()=>bf,QuickJSUnknownIntrinsic:()=>vf,QuickJSUnwrapError:()=>Au,QuickJSUseAfterFree:()=>ju,QuickJSWrongOwner:()=>gf});Au=class extends Error{constructor(e,t){let r=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(r);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},gf=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},ju=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},_f=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},Sf=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},yf=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},Tv=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Pv=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},vf=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},bf=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},Rf=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},zf=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},jt=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};Lu=wf;Lu.of=kv;ft=class{[Symbol.dispose](){return this.dispose()}},Mu=Symbol.dispose??Symbol.for("Symbol.dispose"),df=ft.prototype;df[Mu]||(df[Mu]=function(){return this.dispose()});Be=class e extends ft{constructor(t,r,n,o){super();this._value=t,this.copier=r,this.disposer=n,this._owner=o,this._alive=!0,this._constructorStack=qu?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let r=t(this);return this.dispose(),r}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ju(`Lifetime not alive
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcpcloud/runtime",
3
- "version": "0.19.0",
3
+ "version": "0.19.1",
4
4
  "description": "MCPCloud generated-server runtime: transports, config, upstream auth/HTTP, validation, projection, and discovery for MCP servers built on MCPCloud.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",