@mcpcloud/runtime 0.15.1 → 0.17.2

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.15.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.17.2 — (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.15.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.17.2 — (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
package/dist/config.d.ts CHANGED
@@ -20,6 +20,7 @@ export interface RuntimeEnv {
20
20
  MCP_OAUTH_TOOL_OVERRIDES?: string;
21
21
  MCP_MEMBER_KEY_MODE?: string;
22
22
  MCP_MEMBER_KEY_RUNTIME_URL?: string;
23
+ MCP_MEMBER_KEY_CONNECT_URL?: string;
23
24
  MCP_MEMBER_KEY_RUNTIME_TOKEN?: string;
24
25
  MCP_RUNTIME_AUTH_ACCESS_MODE?: string;
25
26
  MCP_RUNTIME_AUTH_AUDIENCE?: string;
@@ -57,6 +58,16 @@ export interface RuntimeOAuthConfig {
57
58
  }
58
59
  export interface RuntimeMemberKeyConfig {
59
60
  runtimeUrl: string;
61
+ /**
62
+ * The server's connect page — where this caller pasted their upstream key,
63
+ * and where they go to replace it when the upstream stops accepting it.
64
+ *
65
+ * Stamped at deploy (the runtime cannot derive it: the platform endpoint is
66
+ * a different host from the app, and a lane only knows its name from a
67
+ * binding). Null on a deployment built before this binding existed, or in an
68
+ * environment with no `APP_URL`.
69
+ */
70
+ connectPageUrl: string | null;
60
71
  }
61
72
  /**
62
73
  * Per-request tally of what response projection trimmed.
@@ -1,12 +1,12 @@
1
- /*! @mcpcloud/runtime v0.15.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
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 kt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ct=(e)=>e;function It(e,t){this[e]=Ct.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,H;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},H={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function J(...e){ce&&console.log("quickjs-emscripten:",...e)}function*ot(e){return yield e}function Ft(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}
1
+ /*! @mcpcloud/runtime v0.17.2 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
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,H;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},H={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function J(...e){ce&&console.log("quickjs-emscripten:",...e)}function*ot(e){return yield e}function Ft(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,Ht,Jt,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)){J("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++})`),J("asyncify.handleSleep: suspending:",this.suspended),l.then((d)=>{this.suspended=void 0,J("asyncify.handleSleep: resolved:",d),o(d)},(d)=>{J("asyncify.handleSleep: rejected:",d),console.error("QuickJS: cannot handle error in suspended function",d),this.suspended=void 0})}catch(l){throw J("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:()=>Jt,QuickJSHostRefInvalid:()=>I,QuickJSHostRefRangeExceeded:()=>st,QuickJSMemoryLeakDetected:()=>Ht,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"}},Ht=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Jt=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=Ft;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
5
5
  ${this._constructorStack}
6
- Lifetime used`):new ue("Lifetime not alive")}},B=class extends A{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},Ge=class extends A{constructor(e,t,r,o){super(e,t,r,o)}dispose(){this._alive=!1}};M=class e extends N{constructor(){super(...arguments);this._disposables=new A(new Set),this.manage=(t)=>(this._disposables.value.add(t),t)}static withScope(t){let r=new e,o;try{return t(r)}catch(l){throw o=l,l}finally{se(r,o)}}static withScopeMaybeAsync(t,r){return Dt(void 0,function*(o){let l=new e,d;try{return yield*o.of(r.call(t,o,l))}catch(f){throw d=f,f}finally{se(l,d)}})}static async withScopeAsync(t){let r=new e,o;try{return await t(r)}catch(l){throw o=l,l}finally{se(r,o)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let r of t)r.alive&&r.dispose();this._disposables.dispose()}};fe=class e extends N{static success(t){return new jt(t)}static fail(t,r){return new $t(t,r)}static is(t){return t instanceof e}},jt=class extends fe{constructor(e){super();this.value=e}get alive(){return W(this.value)?this.value.alive:!0}dispose(){W(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},$t=class extends fe{constructor(e,t){super();this.error=e,this.onUnwrap=t}get alive(){return W(this.error)?this.error.alive:!0}dispose(){W(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},Y=fe,Vt=class extends N{constructor(e){super();this.resolve=(t)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(t)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise((t)=>{this.onSettled=t}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},Lr=Symbol("Unstable"),Ur=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});Xt=class extends N{constructor(e,t){super();this.handle=e,this.context=t,this._isDone=!1,this.owner=t.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let t=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(t,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let t=this.context.getProp(this.handle,"return");if(t===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let r=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),r}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof A?e:this.context.newError(e),r=this.context.getProp(this.handle,"throw"),o=this.callIteratorMethod(r,e);return t.alive&&t.dispose(),r.dispose(),this.dispose(),o}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let r=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(r.error)return this.dispose(),{value:r};let o=this.context.getProp(r.value,"done").consume((d)=>this.context.dump(d)),l=this.context.getProp(r.value,"value");return r.value.dispose(),o&&this.dispose(),{value:Y.success(l),done:o}}};ze=class extends N{constructor(e,t,r){if(r===G)throw new I("cannot create HostRef with undefined id");super();this.runtime=e,this.handle=t,this.id=r}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},er=class extends at{constructor(e){super(e.module);this.scope=new M,this.copyJSValue=(t)=>this.ffi.QTS_DupValuePointer(this.ctx.value,t),this.freeJSValue=(t)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,t)},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let t=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),t}heapValueHandle(e,t){let r=t?(o)=>{t(),this.freeJSValue(o)}:this.freeJSValue;return new A(e,this.copyJSValue,r,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new B(e,this.owner)}},tr=class extends N{constructor(e){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:(t,r,o,l,d)=>{if(t!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let f=this.getFunction(d);return M.withScopeMaybeAsync(this,function*(s,_){let b=_.manage(new Ge(r,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),x=Array(o);for(let S=0;S<o;S++){let k=this.ffi.QTS_ArgvGetJSValueConstPointer(l,S);x[S]=_.manage(new Ge(k,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let S=yield*s(f.apply(b,x));if(S){if("error"in S&&S.error)throw this.runtime.debugLog("throw error",S.error),S.error;let k=_.manage(S instanceof A?S:S.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,k.value)}return 0}catch(S){return this.errorToHandle(S).consume((k)=>this.ffi.QTS_Throw(this.ctx.value,k.value))}})}},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new er({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new B(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new B(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new B(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new B(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let t=this.memory.newHeapCharPointer(e).consume((r)=>this.ffi.QTS_NewString(this.ctx.value,r.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,0));return this.memory.heapValueHandle(r)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,1));return this.memory.heapValueHandle(r)}getWellKnownSymbol(e){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let o=this.getProp(this.global,"BigInt");this.memory.manage(o),this._BigInt=new B(o.value,this.runtime)}let t=this._BigInt,r=String(e);return this.newString(r).consume((o)=>this.unwrapResult(this.callFunction(t,this.undefined,o)))}newObject(e){e&&this.runtime.assertOwned(e);let t=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(t)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let t=new Uint8Array(e),r=this.memory.newHeapBufferPointer(t),o=this.ffi.QTS_NewArrayBuffer(this.ctx.value,r.value.pointer,t.length);return this.memory.heapValueHandle(o)}newPromise(e){let t=M.withScope((r)=>{let o=r.manage(this.memory.newMutablePointerArray(2)),l=this.ffi.QTS_NewPromiseCapability(this.ctx.value,o.value.ptr),d=this.memory.heapValueHandle(l),[f,s]=Array.from(o.value.typedArray).map((_)=>this.memory.heapValueHandle(_));return new Vt({context:this,promiseHandle:d,resolveHandle:f,rejectHandle:s})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,(r)=>r instanceof A?t.reject(r):this.newError(r).consume(t.reject)),t}newFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!1,fn:r})}newConstructorFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!0,fn:r})}newFunctionWithOptions(e){let{name:t,length:r,isConstructor:o,fn:l}=e,d=this.runtime.hostRefs.put(l);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",r,o,d))}catch(f){throw this.runtime.hostRefs.delete(d),f}}newError(e){let t=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e=="object"?(e.name!==void 0&&this.newString(e.name).consume((r)=>this.setProp(t,"name",r)),e.message!==void 0&&this.newString(e.message).consume((r)=>this.setProp(t,"message",r))):typeof e=="string"?this.newString(e).consume((r)=>this.setProp(t,"message",r)):e!==void 0&&this.newString(String(e)).consume((r)=>this.setProp(t,"message",r)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let r=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new ze(this.runtime,r,t)}catch(r){throw this.runtime.hostRefs.delete(t),r}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new ze(this.runtime,e.dup(),t)}unwrapHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t===0)throw new I("handle is not a HostRef");return this.runtime.hostRefs.get(t)}typeof(e){return this.runtime.assertOwned(e),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,e.value))}getNumber(e){return this.runtime.assertOwned(e),this.ffi.QTS_GetFloat64(this.ctx.value,e.value)}getString(e){return this.runtime.assertOwned(e),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,e.value))}getSymbol(e){this.runtime.assertOwned(e);let t=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,e.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,e.value)?Symbol.for(t):Symbol(t)}getBigInt(e){this.runtime.assertOwned(e);let t=this.getString(e);return BigInt(t)}getArrayBuffer(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,e.value),r=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!r)throw Error("Couldn't allocate memory to get ArrayBuffer");return new A(this.module.HEAPU8.subarray(r,r+t),void 0,()=>this.module._free(r))}getPromiseState(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(t<0)return{type:"fulfilled",value:e,notAPromise:!0};if(t===j.Pending)return{type:"pending",get error(){return new nt("Cannot unwrap a pending promise")}};let r=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),o=this.memory.heapValueHandle(r);if(t===j.Fulfilled)return{type:"fulfilled",value:o};if(t===j.Rejected)return{type:"rejected",error:o};throw o.dispose(),Error(`Unknown JSPromiseStateEnum: ${t}`)}resolvePromise(e){this.runtime.assertOwned(e);let t=M.withScope((r)=>{let o=r.manage(this.getProp(this.global,"Promise")),l=r.manage(this.getProp(o,"resolve"));return this.callFunction(l,o,e)});return t.error?Promise.resolve(t):new Promise((r)=>{M.withScope((o)=>{let l=o.manage(this.newFunction("resolve",(_)=>{r(this.success(_&&_.dup()))})),d=o.manage(this.newFunction("reject",(_)=>{r(this.fail(_&&_.dup()))})),f=o.manage(t.value),s=o.manage(this.getProp(f,"then"));this.callFunction(s,f,l,d).unwrap().dispose()})})}isEqual(e,t,r=H.IsStrictlyEqual){if(e===t)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(t);let o=this.ffi.QTS_IsEqual(this.ctx.value,e.value,t.value,r);if(o===-1)throw new Ze("WASM variant does not expose equality");return!!o}eq(e,t){return this.isEqual(e,t,H.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,H.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,H.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let r;return typeof t=="number"&&t>=0?r=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):r=this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_GetProp(this.ctx.value,e.value,o.value)),this.memory.heapValueHandle(r)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,t={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let r=qt(t);if(r===0)throw new it("No options set, will return an empty array");return M.withScope((o)=>{let l=o.manage(this.memory.newMutablePointerArray(1)),d=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,l.value.ptr,this.uint32Out.value.ptr,e.value,r);if(d)return this.fail(this.memory.heapValueHandle(d));let f=this.uint32Out.value.typedArray[0],s=l.value.typedArray[0],_=new Uint32Array(this.module.HEAP8.buffer,s,f),b=Array.from(_).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,s),this.success(Qt(b))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return M.withScope((r)=>{let o=r.manage(this.getProp(e,t)),l=this.callFunction(o,e);return l.error?l:this.success(new Xt(l.value,this))})}setProp(e,t,r){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_SetProp(this.ctx.value,e.value,o.value,r.value))}defineProp(e,t,r){this.runtime.assertOwned(e),M.withScope((o)=>{let l=o.manage(this.borrowPropertyKey(t)),d=r.value||this.undefined,f=!!r.configurable,s=!!r.enumerable,_=!!r.value,b=r.get?o.manage(this.newFunction(r.get.name,r.get)):this.undefined,x=r.set?o.manage(this.newFunction(r.set.name,r.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,l.value,d.value,b.value,x.value,f,s,_)})}callFunction(e,t,...r){this.runtime.assertOwned(e);let o,l=r[0];l===void 0||Array.isArray(l)?o=l??[]:o=r;let d=this.memory.toPointerArray(o).consume((s)=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,o.length,s.value)),f=this.ffi.QTS_ResolveException(this.ctx.value,d);return f?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(f))):this.success(this.memory.heapValueHandle(d))}callMethod(e,t,r=[]){return this.getProp(e,t).consume((o)=>this.callFunction(o,e,r))}evalCode(e,t="eval.js",r){let o=r===void 0?1:0,l=Wt(r),d=this.memory.newHeapCharPointer(e).consume((s)=>this.ffi.QTS_Eval(this.ctx.value,s.value.ptr,s.value.strlen,t,o,l)),f=this.ffi.QTS_ResolveException(this.ctx.value,d);return f?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(f))):this.success(this.memory.heapValueHandle(d))}throw(e){return this.errorToHandle(e).consume((t)=>this.ffi.QTS_Throw(this.ctx.value,t.value))}borrowPropertyKey(e){return typeof e=="number"?this.newNumber(e):typeof e=="string"?this.newString(e):new B(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(e){this.runtime.assertOwned(e);let t=this.typeof(e);if(t==="string")return this.getString(e);if(t==="number")return this.getNumber(e);if(t==="bigint")return this.getBigInt(e);if(t==="undefined")return;if(t==="symbol")return this.getSymbol(e);let r=this.getPromiseState(e);if(r.type==="fulfilled"&&!r.notAPromise)return e.dispose(),{type:r.type,value:r.value.consume(this.dump)};if(r.type==="pending")return e.dispose(),{type:r.type};if(r.type==="rejected")return e.dispose(),{type:r.type,error:r.error.consume(this.dump)};let o=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(o)}catch{return o}}unwrapResult(e){if(e.error){let t="context"in e.error?e.error.context:this,r=e.error.consume((o)=>this.dump(o));if(r&&typeof r=="object"&&typeof r.message=="string"){let{message:o,name:l,stack:d,...f}=r,s=new ae(r,t);typeof l=="string"&&(s.name=r.name),s.message=o;let _=s.stack;throw typeof d=="string"&&(s.stack=`${l}: ${o}
7
- ${r.stack}Host: ${_}`),Object.assign(s,f),s}throw new ae(r)}return e.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(e){let t=this.runtime.hostRefs.get(e);if(typeof t!="function")throw Error(`Host reference ${e} is not a function`);return t}errorToHandle(e){return e instanceof A?e:this.newError(e)}encodeBinaryJSON(e){let t=this.ffi.QTS_bjson_encode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}decodeBinaryJSON(e){let t=this.ffi.QTS_bjson_decode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}success(e){return Y.success(e)}fail(e){return Y.fail(e,(t)=>this.unwrapResult(t))}},rr=class extends N{constructor(e){super();this.scope=new M,this.contextMap=new Map,this.hostRefs=new Zt,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(t,r)=>{if(t!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(r)},shouldInterrupt:(t)=>{if(t!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let r=this.interruptHandler;if(!r)throw Error("QuickJSContext had no interrupt handler");return r(this)?1:0},loadModuleSource:$e(this,function*(t,r,o,l){let d=this.moduleLoader;if(!d)throw Error("Runtime has no module loader");if(r!==this.rt.value)throw Error("Runtime pointer mismatch");let f=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let s=yield*t(d(l,f));if(typeof s=="object"&&"error"in s&&s.error)throw this.debugLog("cToHostLoadModule: loader returned error",s.error),s.error;let _=typeof s=="string"?s:("value"in s)?s.value:s;return this.memory.newHeapCharPointer(_).value.ptr}catch(s){return this.debugLog("cToHostLoadModule: caught error",s),f.throw(s),0}}),normalizeModule:$e(this,function*(t,r,o,l,d){let f=this.moduleNormalizer;if(!f)throw Error("Runtime has no module normalizer");if(r!==this.rt.value)throw Error("Runtime pointer mismatch");let s=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let _=yield*t(f(l,d,s));if(typeof _=="object"&&"error"in _&&_.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",_.error),_.error;let b=typeof _=="string"?_:_.value;return s.getMemory(this.rt.value).newHeapCharPointer(b).value.ptr}catch(_){return this.debugLog("normalizeModule: caught error",_),s.throw(_),0}})},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.module=e.module,this.memory=new at(this.module),this.ffi=e.ffi,this.rt=e.rt,this.callbacks=e.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),ce&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(e={}){let t=Gt(e.intrinsics),r=new A(e.contextPointer||this.ffi.QTS_NewContext(this.rt.value,t),void 0,(l)=>{this.contextMap.delete(l),this.callbacks.deleteContext(l),this.ffi.QTS_FreeContext(l)}),o=new tr({module:this.module,ctx:r,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(r.value,o),o}setModuleLoader(e,t){this.moduleLoader=e,this.moduleNormalizer=t,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(e){let t=this.interruptHandler;this.interruptHandler=e,t||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(e=-1){let t=this.memory.newMutablePointerArray(1),r=this.ffi.QTS_ExecutePendingJob(this.rt.value,e??-1,t.value.ptr),o=t.value.typedArray[0];if(t.dispose(),o===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,r),Y.success(0);let l=this.contextMap.get(o)??this.newContext({contextPointer:o}),d=l.getMemory(this.rt.value).heapValueHandle(r);if(l.typeof(d)==="number"){let f=l.getNumber(d);return d.dispose(),Y.success(f)}else{let f=Object.assign(d,{context:l});return Y.fail(f,(s)=>l.unwrapResult(s))}}setMemoryLimit(e){if(e<0&&e!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,e)}computeMemoryUsage(){let e=this.getSystemContext().getMemory(this.rt.value);return e.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,e.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(e){if(e<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,e)}assertOwned(e){if(e.owner&&e.owner.rt!==this.rt)throw new Xe(`Handle is not owned by this runtime: ${e.owner.rt.value} != ${this.rt.value}`)}setDebugMode(e){this._debugMode=e,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,e?1:0)}isDebugMode(){return this._debugMode}debugLog(...e){this._debugMode&&console.log("quickjs-emscripten:",...e)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}}});var ct={};Lt(ct,{QuickJSModuleCallbacks:()=>me,QuickJSWASMModule:()=>ut,applyBaseRuntimeOptions:()=>pe,applyModuleEvalRuntimeOptions:()=>_e});var ht=ne(()=>{lt()});var gt=kt(function(q,_t){(function(e,t){typeof q==="object"&&typeof _t<"u"?t(q):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.jmespath={}))})(q,function(e){let t=(n)=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",r=(n,i)=>{if(n===i)return!0;if(typeof n!==typeof i)return!1;if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return!1;for(let a=0;a<n.length;a+=1)if(!r(n[a],i[a]))return!1;return!0}if(t(n)&&t(i)){let a=Object.entries(n),u=new Set(Object.keys(i));if(a.length!==u.size)return!1;for(let[h,m]of a){if(!r(m,i[h]))return!1;u.delete(h)}return u.size===0}return!1},o=(n)=>{if(n===""||n===!1||n===null||n===void 0)return!0;if(Array.isArray(n)&&n.length===0)return!0;if(t(n)){for(let i in n)if(n.hasOwnProperty(i))return!1;return!0}return!1},l=(n)=>n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="_",d=(n)=>n>="0"&&n<="9"||n==="-",f=(n)=>n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||n==="_";var s;(function(n){n.TOK_EOF="EOF",n.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",n.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",n.TOK_RBRACKET="Rbracket",n.TOK_RPAREN="Rparen",n.TOK_COMMA="Comma",n.TOK_COLON="Colon",n.TOK_RBRACE="Rbrace",n.TOK_NUMBER="Number",n.TOK_CURRENT="Current",n.TOK_ROOT="Root",n.TOK_EXPREF="Expref",n.TOK_PIPE="Pipe",n.TOK_OR="Or",n.TOK_AND="And",n.TOK_EQ="EQ",n.TOK_GT="GT",n.TOK_LT="LT",n.TOK_GTE="GTE",n.TOK_LTE="LTE",n.TOK_NE="NE",n.TOK_FLATTEN="Flatten",n.TOK_STAR="Star",n.TOK_FILTER="Filter",n.TOK_DOT="Dot",n.TOK_NOT="Not",n.TOK_LBRACE="Lbrace",n.TOK_LBRACKET="Lbracket",n.TOK_LPAREN="Lparen",n.TOK_LITERAL="Literal"})(s||(s={}));let _={"(":s.TOK_LPAREN,")":s.TOK_RPAREN,"*":s.TOK_STAR,",":s.TOK_COMMA,".":s.TOK_DOT,":":s.TOK_COLON,"@":s.TOK_CURRENT,["$"]:s.TOK_ROOT,"]":s.TOK_RBRACKET,"{":s.TOK_LBRACE,"}":s.TOK_RBRACE},b={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class S{constructor(){this._current=0}tokenize(n){let i=[];this._current=0;let a,u,h;while(this._current<n.length)if(l(n[this._current]))a=this._current,u=this.consumeUnquotedIdentifier(n),i.push({start:a,type:s.TOK_UNQUOTEDIDENTIFIER,value:u});else if(_[n[this._current]]!==void 0)i.push({start:this._current,type:_[n[this._current]],value:n[this._current]}),this._current+=1;else if(d(n[this._current]))h=this.consumeNumber(n),i.push(h);else if(n[this._current]==="[")h=this.consumeLBracket(n),i.push(h);else if(n[this._current]==='"')a=this._current,u=this.consumeQuotedIdentifier(n),i.push({start:a,type:s.TOK_QUOTEDIDENTIFIER,value:u});else if(n[this._current]==="'")a=this._current,u=this.consumeRawStringLiteral(n),i.push({start:a,type:s.TOK_LITERAL,value:u});else if(n[this._current]==="`"){a=this._current;let m=this.consumeLiteral(n);i.push({start:a,type:s.TOK_LITERAL,value:m})}else if(b[n[this._current]]!==void 0)h=this.consumeOperator(n),h&&i.push(h);else if(x[n[this._current]]!==void 0)this._current+=1;else if(n[this._current]==="&")if(a=this._current,this._current+=1,n[this._current]==="&")this._current+=1,i.push({start:a,type:s.TOK_AND,value:"&&"});else i.push({start:a,type:s.TOK_EXPREF,value:"&"});else if(n[this._current]==="|")if(a=this._current,this._current+=1,n[this._current]==="|")this._current+=1,i.push({start:a,type:s.TOK_OR,value:"||"});else i.push({start:a,type:s.TOK_PIPE,value:"|"});else{let m=Error(`Unknown character: ${n[this._current]}`);throw m.name="LexerError",m}return i}consumeUnquotedIdentifier(n){let i=this._current;this._current+=1;while(this._current<n.length&&f(n[this._current]))this._current+=1;return n.slice(i,this._current)}consumeQuotedIdentifier(n){let i=this._current;this._current+=1;let a=n.length;while(n[this._current]!=='"'&&this._current<a){let u=this._current;if(n[u]==="\\"&&(n[u+1]==="\\"||n[u+1]==='"'))u+=2;else u+=1;this._current=u}return this._current+=1,JSON.parse(n.slice(i,this._current))}consumeRawStringLiteral(n){let i=this._current;this._current+=1;let a=n.length;while(n[this._current]!=="'"&&this._current<a){let h=this._current;if(n[h]==="\\"&&(n[h+1]==="\\"||n[h+1]==="'"))h+=2;else h+=1;this._current=h}return this._current+=1,n.slice(i+1,this._current-1).replace("\\'","'")}consumeNumber(n){let i=this._current;this._current+=1;let a=n.length;while(d(n[this._current])&&this._current<a)this._current+=1;let u=parseInt(n.slice(i,this._current),10);return{start:i,value:u,type:s.TOK_NUMBER}}consumeLBracket(n){let i=this._current;if(this._current+=1,n[this._current]==="?")return this._current+=1,{start:i,type:s.TOK_FILTER,value:"[?"};if(n[this._current]==="]")return this._current+=1,{start:i,type:s.TOK_FLATTEN,value:"[]"};return{start:i,type:s.TOK_LBRACKET,value:"["}}consumeOperator(n){let i=this._current,a=n[i];if(this._current+=1,a==="!"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_NE,value:"!="};return{start:i,type:s.TOK_NOT,value:"!"}}if(a==="<"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_LTE,value:"<="};return{start:i,type:s.TOK_LT,value:"<"}}if(a===">"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_GTE,value:">="};return{start:i,type:s.TOK_GT,value:">"}}if(a==="="&&n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_EQ,value:"=="}}consumeLiteral(n){this._current+=1;let i=this._current,a=n.length;while(n[this._current]!=="`"&&this._current<a){let m=this._current;if(n[m]==="\\"&&(n[m+1]==="\\"||n[m+1]==="`"))m+=2;else m+=1;this._current=m}let u=n.slice(i,this._current).trimLeft();u=u.replace("\\`","`");let h=this.looksLikeJSON(u)?JSON.parse(u):JSON.parse(`"${u}"`);return this._current+=1,h}looksLikeJSON(n){let a=["true","false","null"],u="-0123456789";if(n==="")return!1;if('[{"'.includes(n[0]))return!0;if(a.includes(n))return!0;if("-0123456789".includes(n[0]))try{return JSON.parse(n),!0}catch(h){return!1}return!1}}let k=new S,w={[s.TOK_EOF]:0,[s.TOK_UNQUOTEDIDENTIFIER]:0,[s.TOK_QUOTEDIDENTIFIER]:0,[s.TOK_RBRACKET]:0,[s.TOK_RPAREN]:0,[s.TOK_COMMA]:0,[s.TOK_RBRACE]:0,[s.TOK_NUMBER]:0,[s.TOK_CURRENT]:0,[s.TOK_EXPREF]:0,[s.TOK_ROOT]:0,[s.TOK_PIPE]:1,[s.TOK_OR]:2,[s.TOK_AND]:3,[s.TOK_EQ]:5,[s.TOK_GT]:5,[s.TOK_LT]:5,[s.TOK_GTE]:5,[s.TOK_LTE]:5,[s.TOK_NE]:5,[s.TOK_FLATTEN]:9,[s.TOK_STAR]:20,[s.TOK_FILTER]:21,[s.TOK_DOT]:40,[s.TOK_NOT]:45,[s.TOK_LBRACE]:50,[s.TOK_LBRACKET]:55,[s.TOK_LPAREN]:60};class Te{constructor(){this.index=0,this.tokens=[]}parse(n){this.loadTokens(n),this.index=0;let i=this.expression(0);if(this.lookahead(0)!==s.TOK_EOF){let a=this.lookaheadToken(0);this.errorToken(a,`Unexpected token type: ${a.type}, value: ${a.value}`)}return i}loadTokens(n){this.tokens=[...k.tokenize(n),{type:s.TOK_EOF,value:"",start:n.length}]}expression(n){let i=this.lookaheadToken(0);this.advance();let a=this.nud(i),u=this.lookahead(0);while(n<w[u])this.advance(),a=this.led(u,a),u=this.lookahead(0);return a}lookahead(n){return this.tokens[this.index+n].type}lookaheadToken(n){return this.tokens[this.index+n]}advance(){this.index+=1}nud(n){let i,a,u;switch(n.type){case s.TOK_LITERAL:return{type:"Literal",value:n.value};case s.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:n.value};case s.TOK_QUOTEDIDENTIFIER:let h={type:"Field",name:n.value};if(this.lookahead(0)===s.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return h;case s.TOK_NOT:return a=this.expression(w.Not),{type:"NotExpression",children:[a]};case s.TOK_STAR:return i={type:"Identity"},a=this.lookahead(0)===s.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(w.Star),{type:"ValueProjection",children:[i,a]};case s.TOK_FILTER:return this.led(n.type,{type:"Identity"});case s.TOK_LBRACE:return this.parseMultiselectHash();case s.TOK_FLATTEN:return i={type:s.TOK_FLATTEN,children:[{type:"Identity"}]},a=this.parseProjectionRHS(w.Flatten),{type:"Projection",children:[i,a]};case s.TOK_LBRACKET:if(this.lookahead(0)===s.TOK_NUMBER||this.lookahead(0)===s.TOK_COLON)return a=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},a);if(this.lookahead(0)===s.TOK_STAR&&this.lookahead(1)===s.TOK_RBRACKET)return this.advance(),this.advance(),a=this.parseProjectionRHS(w.Star),{children:[{type:"Identity"},a],type:"Projection"};return this.parseMultiselectList();case s.TOK_CURRENT:return{type:s.TOK_CURRENT};case s.TOK_ROOT:return{type:s.TOK_ROOT};case s.TOK_EXPREF:return u=this.expression(w.Expref),{type:"ExpressionReference",children:[u]};case s.TOK_LPAREN:let m=[];while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)u={type:s.TOK_CURRENT},this.advance();else u=this.expression(0);m.push(u)}return this.match(s.TOK_RPAREN),m[0];default:this.errorToken(n)}}led(n,i){let a;switch(n){case s.TOK_DOT:let u=w.Dot;if(this.lookahead(0)!==s.TOK_STAR)return a=this.parseDotRHS(u),{type:"Subexpression",children:[i,a]};return this.advance(),a=this.parseProjectionRHS(u),{type:"ValueProjection",children:[i,a]};case s.TOK_PIPE:return a=this.expression(w.Pipe),{type:s.TOK_PIPE,children:[i,a]};case s.TOK_OR:return a=this.expression(w.Or),{type:"OrExpression",children:[i,a]};case s.TOK_AND:return a=this.expression(w.And),{type:"AndExpression",children:[i,a]};case s.TOK_LPAREN:let h=i.name,m=[],g;while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)g={type:s.TOK_CURRENT},this.advance();else g=this.expression(0);if(this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);m.push(g)}return this.match(s.TOK_RPAREN),{name:h,type:"Function",children:m};case s.TOK_FILTER:let E=this.expression(0);return this.match(s.TOK_RBRACKET),a=this.lookahead(0)===s.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(w.Filter),{type:"FilterProjection",children:[i,a,E]};case s.TOK_FLATTEN:let P={type:s.TOK_FLATTEN,children:[i]},T=this.parseProjectionRHS(w.Flatten);return{type:"Projection",children:[P,T]};case s.TOK_EQ:case s.TOK_NE:case s.TOK_GT:case s.TOK_GTE:case s.TOK_LT:case s.TOK_LTE:return this.parseComparator(i,n);case s.TOK_LBRACKET:let p=this.lookaheadToken(0);if(p.type===s.TOK_NUMBER||p.type===s.TOK_COLON)return a=this.parseIndexExpression(),this.projectIfSlice(i,a);return this.match(s.TOK_STAR),this.match(s.TOK_RBRACKET),a=this.parseProjectionRHS(w.Star),{type:"Projection",children:[i,a]};default:return this.errorToken(this.lookaheadToken(0))}}match(n){if(this.lookahead(0)===n){this.advance();return}else{let i=this.lookaheadToken(0);this.errorToken(i,`Expected ${n}, got: ${i.type}`)}}errorToken(n,i=""){let a=Error(i||`Invalid token (${n.type}): "${n.value}"`);throw a.name="ParserError",a}parseIndexExpression(){if(this.lookahead(0)===s.TOK_COLON||this.lookahead(1)===s.TOK_COLON)return this.parseSliceExpression();let n={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(s.TOK_RBRACKET),n}projectIfSlice(n,i){let a={type:"IndexExpression",children:[n,i]};if(i.type==="Slice")return{children:[a,this.parseProjectionRHS(w.Star)],type:"Projection"};return a}parseSliceExpression(){let n=[null,null,null],i=0,a=this.lookahead(0);while(a!==s.TOK_RBRACKET&&i<3){if(a===s.TOK_COLON)i+=1,this.advance();else if(a===s.TOK_NUMBER)n[i]=this.lookaheadToken(0).value,this.advance();else{let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}a=this.lookahead(0)}return this.match(s.TOK_RBRACKET),{children:n,type:"Slice"}}parseComparator(n,i){let a=this.expression(w[i]);return{type:"Comparator",name:i,children:[n,a]}}parseDotRHS(n){let i=this.lookahead(0);if([s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER,s.TOK_STAR].includes(i))return this.expression(n);if(i===s.TOK_LBRACKET)return this.match(s.TOK_LBRACKET),this.parseMultiselectList();if(i===s.TOK_LBRACE)return this.match(s.TOK_LBRACE),this.parseMultiselectHash();let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}parseProjectionRHS(n){if(w[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===s.TOK_LBRACKET)return this.expression(n);if(this.lookahead(0)===s.TOK_FILTER)return this.expression(n);if(this.lookahead(0)===s.TOK_DOT)return this.match(s.TOK_DOT),this.parseDotRHS(n);let i=this.lookaheadToken(0);this.errorToken(i,`Syntax error, unexpected token: ${i.value}(${i.type})`)}parseMultiselectList(){let n=[];while(this.lookahead(0)!==s.TOK_RBRACKET){let i=this.expression(0);if(n.push(i),this.lookahead(0)===s.TOK_COMMA){if(this.match(s.TOK_COMMA),this.lookahead(0)===s.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(s.TOK_RBRACKET),{type:"MultiSelectList",children:n}}parseMultiselectHash(){let n=[],i=[s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER],a,u,h;for(;;){if(a=this.lookaheadToken(0),!i.includes(a.type))throw Error(`Expecting an identifier token, got: ${a.type}`);if(u=a.value,this.advance(),this.match(s.TOK_COLON),h=this.expression(0),n.push({value:h,type:"KeyValuePair",name:u}),this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);else if(this.lookahead(0)===s.TOK_RBRACE){this.match(s.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:n}}}let Se=new Te;var c;(function(n){n[n.TYPE_NUMBER=0]="TYPE_NUMBER",n[n.TYPE_ANY=1]="TYPE_ANY",n[n.TYPE_STRING=2]="TYPE_STRING",n[n.TYPE_ARRAY=3]="TYPE_ARRAY",n[n.TYPE_OBJECT=4]="TYPE_OBJECT",n[n.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",n[n.TYPE_EXPREF=6]="TYPE_EXPREF",n[n.TYPE_NULL=7]="TYPE_NULL",n[n.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",n[n.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(c||(c={}));class Re{constructor(n){this.TYPE_NAME_TABLE={[c.TYPE_NUMBER]:"number",[c.TYPE_ANY]:"any",[c.TYPE_STRING]:"string",[c.TYPE_ARRAY]:"array",[c.TYPE_OBJECT]:"object",[c.TYPE_BOOLEAN]:"boolean",[c.TYPE_EXPREF]:"expression",[c.TYPE_NULL]:"null",[c.TYPE_ARRAY_NUMBER]:"Array<number>",[c.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([i])=>Math.abs(i),this.functionAvg=([i])=>{let a=0;for(let u=0;u<i.length;u+=1)a+=i[u];return a/i.length},this.functionCeil=([i])=>Math.ceil(i),this.functionContains=(i)=>{let[a,u]=i;return a.includes(u)},this.functionEndsWith=(i)=>{let[a,u]=i;return a.includes(u,a.length-u.length)},this.functionFloor=([i])=>Math.floor(i),this.functionJoin=(i)=>{let[a,u]=i;return u.join(a)},this.functionKeys=([i])=>Object.keys(i),this.functionLength=([i])=>{if(!t(i))return i.length;return Object.keys(i).length},this.functionMap=(i)=>{if(!this._interpreter)return[];let a=[],u=this._interpreter,h=i[0],m=i[1];for(let g=0;g<m.length;g+=1)a.push(u.visit(h,m[g]));return a},this.functionMax=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.max(...i);let u=i,h=u[0];for(let m=1;m<u.length;m+=1)if(h.localeCompare(u[m])<0)h=u[m];return h},this.functionMaxBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),m=-1/0,g,y;for(let E=0;E<u.length;E+=1)if(y=h&&h(u[E]),y!==void 0&&y>m)m=y,g=u[E];return g},this.functionMerge=(i)=>{let a={};for(let u=0;u<i.length;u+=1){let h=i[u];a=Object.assign(a,h)}return a},this.functionMin=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.min(...i);let u=i,h=u[0];for(let m=1;m<u.length;m+=1)if(u[m].localeCompare(h)<0)h=u[m];return h},this.functionMinBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),m=1/0,g,y;for(let E=0;E<u.length;E+=1)if(y=h&&h(u[E]),y!==void 0&&y<m)m=y,g=u[E];return g},this.functionNotNull=(i)=>{for(let a=0;a<i.length;a+=1)if(this.getTypeName(i[a])!==c.TYPE_NULL)return i[a];return null},this.functionReverse=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING){let h=i,m="";for(let g=h.length-1;g>=0;g-=1)m+=h[g];return m}let u=i.slice(0);return u.reverse(),u},this.functionSort=([i])=>[...i].sort(),this.functionSortBy=(i)=>{if(!this._interpreter)return[];let a=i[0].slice(0);if(a.length===0)return a;let u=this._interpreter,h=i[1],m=this.getTypeName(u.visit(h,a[0]));if(m!==void 0&&![c.TYPE_NUMBER,c.TYPE_STRING].includes(m))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[m]})`);let g=[];for(let y=0;y<a.length;y+=1)g.push([y,a[y]]);g.sort((y,E)=>{let P=u.visit(h,y[1]),T=u.visit(h,E[1]);if(this.getTypeName(P)!==m)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[m]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(P)]}`);else if(this.getTypeName(T)!==m)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[m]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(T)]}`);if(P>T)return 1;return P<T?-1:y[0]-E[0]});for(let y=0;y<g.length;y+=1)a[y]=g[y][1];return a},this.functionStartsWith=([i,a])=>i.startsWith(a),this.functionSum=([i])=>i.reduce((a,u)=>a+u,0),this.functionToArray=([i])=>{if(this.getTypeName(i)===c.TYPE_ARRAY)return i;return[i]},this.functionToNumber=([i])=>{let a=this.getTypeName(i),u;if(a===c.TYPE_NUMBER)return i;if(a===c.TYPE_STRING){if(u=+i,!isNaN(u))return u}return null},this.functionToString=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING)return i;return JSON.stringify(i)},this.functionType=([i])=>{switch(this.getTypeName(i)){case c.TYPE_NUMBER:return"number";case c.TYPE_STRING:return"string";case c.TYPE_ARRAY:return"array";case c.TYPE_OBJECT:return"object";case c.TYPE_BOOLEAN:return"boolean";case c.TYPE_EXPREF:return"expref";case c.TYPE_NULL:return"null";default:return}},this.functionValues=([i])=>Object.values(i),this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[c.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[c.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]},{types:[c.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[c.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[c.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY,c.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[c.TYPE_EXPREF]},{types:[c.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[c.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[c.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[c.TYPE_ARRAY_STRING,c.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[c.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[c.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[c.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[c.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[c.TYPE_OBJECT]}]}},this._interpreter=n}registerFunction(n,i,a){if(n in this.functionTable)throw Error(`Function already defined: ${n}()`);this.functionTable[n]={_func:i.bind(this),_signature:a}}callFunction(n,i){let a=this.functionTable[n];if(a===void 0)throw Error(`Unknown function: ${n}()`);return this.validateArgs(n,i,a._signature),a._func.call(this,i)}validateInputSignatures(n,i){for(let a=0;a<i.length;a+=1)if("variadic"in i[a]&&a!==i.length-1)throw Error(`ArgumentError: ${n}() 'variadic' argument ${a+1} must occur last`)}validateArgs(n,i,a){var u,h;let m;this.validateInputSignatures(n,a);let g=a.filter((O)=>{var v;return(v=!O.optional)!==null&&v!==void 0?v:!1}).length,y=(h=(u=a[a.length-1])===null||u===void 0?void 0:u.variadic)!==null&&h!==void 0?h:!1,E=i.length<g,P=i.length>a.length,T=E&&(!y&&g>1||y)?"at least ":"";if(y&&E||!y&&(E||P))throw m=a.length>1,Error(`ArgumentError: ${n}() takes ${T}${g} argument${m&&"s"||""} but received ${i.length}`);let p,R,C;for(let O=0;O<a.length;O+=1){C=!1,p=a[O].types,R=this.getTypeName(i[O]);let v;for(v=0;v<p.length;v+=1)if(R!==void 0&&this.typeMatches(R,p[v],i[O])){C=!0;break}if(!C&&R!==void 0){let F=p.map((D)=>this.TYPE_NAME_TABLE[D]).join(" | ");throw Error(`TypeError: ${n}() expected argument ${O+1} to be type (${F}) but received type ${this.TYPE_NAME_TABLE[R]} instead.`)}}}typeMatches(n,i,a){if(i===c.TYPE_ANY)return!0;if(i===c.TYPE_ARRAY_STRING||i===c.TYPE_ARRAY_NUMBER||i===c.TYPE_ARRAY){if(i===c.TYPE_ARRAY)return n===c.TYPE_ARRAY;if(n===c.TYPE_ARRAY){let u;if(i===c.TYPE_ARRAY_NUMBER)u=c.TYPE_NUMBER;else if(i===c.TYPE_ARRAY_STRING)u=c.TYPE_STRING;for(let h=0;h<a.length;h+=1){let m=this.getTypeName(a[h]);if(m!==void 0&&u!==void 0&&!this.typeMatches(m,u,a[h]))return!1}return!0}}else return n===i;return!1}getTypeName(n){switch(Object.prototype.toString.call(n)){case"[object String]":return c.TYPE_STRING;case"[object Number]":return c.TYPE_NUMBER;case"[object Array]":return c.TYPE_ARRAY;case"[object Boolean]":return c.TYPE_BOOLEAN;case"[object Null]":return c.TYPE_NULL;case"[object Object]":if(n.jmespathType===s.TOK_EXPREF)return c.TYPE_EXPREF;return c.TYPE_OBJECT;default:return}}createKeyFunction(n,i){if(!this._interpreter)return;let a=this._interpreter;return(h)=>{let m=a.visit(n,h);if(!i.includes(this.getTypeName(m))){let g=`TypeError: expected one of (${i.map((y)=>this.TYPE_NAME_TABLE[y]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(m)]}`;throw Error(g)}return m}}}class we{constructor(){this._rootValue=null,this.runtime=new Re(this)}search(n,i){return this._rootValue=i,this.visit(n,i)}visit(n,i){let a,u,h,m,g,y,E,P,T,p,R;switch(n.type){case"Field":if(i===null)return null;if(t(i)){if(y=i[n.name],y===void 0)return null;return y}return null;case"Subexpression":h=this.visit(n.children[0],i);for(p=1;p<n.children.length;p+=1)if(h=this.visit(n.children[1],h),h===null)return null;return h;case"IndexExpression":return E=this.visit(n.children[0],i),P=this.visit(n.children[1],E),P;case"Index":if(!Array.isArray(i))return null;let C=n.value;if(C<0)C=i.length+C;if(h=i[C],h===void 0)h=null;return h;case"Slice":if(!Array.isArray(i))return null;let O=[...n.children],v=this.computeSliceParams(i.length,O),[F,D,X]=v;if(h=[],X>0)for(p=F;p<D;p+=X)h.push(i[p]);else for(p=F;p>D;p+=X)h.push(i[p]);return h;case"Projection":if(R=this.visit(n.children[0],i),!Array.isArray(R))return null;T=[];for(p=0;p<R.length;p+=1)if(u=this.visit(n.children[1],R[p]),u!==null)T.push(u);return T;case"ValueProjection":if(R=this.visit(n.children[0],i),!t(R))return null;T=[];let He=Object.values(R);for(p=0;p<He.length;p+=1)if(u=this.visit(n.children[1],He[p]),u!==null)T.push(u);return T;case"FilterProjection":if(R=this.visit(n.children[0],i),!Array.isArray(R))return null;let Z=[],Je=[];for(p=0;p<R.length;p+=1)if(a=this.visit(n.children[2],R[p]),!o(a))Z.push(R[p]);for(let L=0;L<Z.length;L+=1)if(u=this.visit(n.children[1],Z[L]),u!==null)Je.push(u);return Je;case"Comparator":switch(m=this.visit(n.children[0],i),g=this.visit(n.children[1],i),n.name){case s.TOK_EQ:h=r(m,g);break;case s.TOK_NE:h=!r(m,g);break;case s.TOK_GT:h=m>g;break;case s.TOK_GTE:h=m>=g;break;case s.TOK_LT:h=m<g;break;case s.TOK_LTE:h=m<=g;break;default:throw Error(`Unknown comparator: ${n.name}`)}return h;case s.TOK_FLATTEN:let ee=this.visit(n.children[0],i);if(!Array.isArray(ee))return null;let Q=[];for(p=0;p<ee.length;p+=1)if(u=ee[p],Array.isArray(u))Q=[...Q,...u];else Q.push(u);return Q;case"Identity":return i;case"MultiSelectList":if(i===null)return null;T=[];for(p=0;p<n.children.length;p+=1)T.push(this.visit(n.children[p],i));return T;case"MultiSelectHash":if(i===null)return null;T={};let te;for(p=0;p<n.children.length;p+=1)te=n.children[p],T[te.name]=this.visit(te.value,i);return T;case"OrExpression":if(a=this.visit(n.children[0],i),o(a))a=this.visit(n.children[1],i);return a;case"AndExpression":if(m=this.visit(n.children[0],i),o(m))return m;return this.visit(n.children[1],i);case"NotExpression":return m=this.visit(n.children[0],i),o(m);case"Literal":return n.value;case s.TOK_PIPE:return E=this.visit(n.children[0],i),this.visit(n.children[1],E);case s.TOK_CURRENT:return i;case s.TOK_ROOT:return this._rootValue;case"Function":let Fe=[];for(let L=0;L<n.children.length;L+=1)Fe.push(this.visit(n.children[L],i));return this.runtime.callFunction(n.name,Fe);case"ExpressionReference":let De=n.children[0];return De.jmespathType=s.TOK_EXPREF,De;default:throw Error(`Unknown node type: ${n.type}`)}}computeSliceParams(n,i){let[a,u,h]=i;if(h===null)h=1;else if(h===0){let g=Error("Invalid slice, step cannot be 0");throw g.name="RuntimeError",g}let m=h<0?!0:!1;return a=a===null?m?n-1:0:this.capSliceRange(n,a,h),u=u===null?m?-1:n:this.capSliceRange(n,u,h),[a,u,h]}capSliceRange(n,i,a){let u=i;if(u<0){if(u+=n,u<0)u=a<0?-1:0}else if(u>=n)u=a<0?n-1:n;return u}}let z=new we,Ae=c.TYPE_ANY,be=c.TYPE_ARRAY,Pe=c.TYPE_ARRAY_NUMBER,Oe=c.TYPE_ARRAY_STRING,ve=c.TYPE_BOOLEAN,Me=c.TYPE_EXPREF,xe=c.TYPE_NULL,Ne=c.TYPE_NUMBER,ke=c.TYPE_OBJECT,Ce=c.TYPE_STRING;function Ie(n){return Se.parse(n)}function Le(n){return k.tokenize(n)}let Ue=(n,i,a)=>{z.runtime.registerFunction(n,i,a)};function Ke(n,i){let a=Se.parse(i);return z.search(a,n)}let Be=z,Ye={compile:Ie,registerFunction:Ue,search:Ke,tokenize:Le,TreeInterpreter:Be,TYPE_ANY:Ae,TYPE_ARRAY_NUMBER:Pe,TYPE_ARRAY_STRING:Oe,TYPE_ARRAY:be,TYPE_BOOLEAN:ve,TYPE_EXPREF:Me,TYPE_NULL:xe,TYPE_NUMBER:Ne,TYPE_OBJECT:ke,TYPE_STRING:Ce};e.TYPE_ANY=Ae,e.TYPE_ARRAY=be,e.TYPE_ARRAY_NUMBER=Pe,e.TYPE_ARRAY_STRING=Oe,e.TYPE_BOOLEAN=ve,e.TYPE_EXPREF=Me,e.TYPE_NULL=xe,e.TYPE_NUMBER=Ne,e.TYPE_OBJECT=ke,e.TYPE_STRING=Ce,e.TreeInterpreter=Be,e.compile=Ie,e.default=Ye,e.jmespath=Ye,e.registerFunction=Ue,e.search=Ke,e.tokenize=Le,Object.defineProperty(e,"__esModule",{value:!0})})});import{mkdirSync as Sr,mkdtempSync as Rr,writeFileSync as wr}from"node:fs";import{tmpdir as Ar}from"node:os";import{dirname as br,join as ye}from"node:path";import{pathToFileURL as Pr}from"node:url";import{timingSafeEqual as mr}from"node:crypto";import{createServer as pr}from"node:http";import{Readable as _r}from"node:stream";function Ut(){return typeof process>"u"?{}:process.env}function je(e=Ut()){return e.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as dr}from"node:fs";V();async function dt(e){let t=ge(await e),[r,o,{QuickJSWASMModule:l}]=await Promise.all([t.importModuleLoader().then(ge),t.importFFI(),Promise.resolve().then(() => (ht(),ct)).then(ge)]),d=await r();d.type="sync";let f=new o(d);return new l(d,f)}function ge(e){return e&&"default"in e&&e.default?e.default&&"default"in e.default&&e.default.default?e.default.default:e.default:e}var mt="engine";function ir(e){let t=(r)=>new URL(r,e).href;return{type:"sync",importFFI:()=>import(t("ffi.mjs")).then((r)=>r.QuickJSFFI),importModuleLoader:()=>import(t("emscripten-module.mjs")).then((r)=>r.default)}}var ft=null;function pt(e){return()=>(ft??=dt(ir(e)),ft)}var sr=Nt(gt(),1);var ar="__mcpcloud_call_tool",bn=`globalThis.tool = (name, args) =>
6
+ Lifetime used`):new ue("Lifetime not alive")}},B=class extends A{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},Ge=class extends A{constructor(e,t,r,o){super(e,t,r,o)}dispose(){this._alive=!1}};M=class e extends N{constructor(){super(...arguments);this._disposables=new A(new Set),this.manage=(t)=>(this._disposables.value.add(t),t)}static withScope(t){let r=new e,o;try{return t(r)}catch(l){throw o=l,l}finally{se(r,o)}}static withScopeMaybeAsync(t,r){return Dt(void 0,function*(o){let l=new e,d;try{return yield*o.of(r.call(t,o,l))}catch(f){throw d=f,f}finally{se(l,d)}})}static async withScopeAsync(t){let r=new e,o;try{return await t(r)}catch(l){throw o=l,l}finally{se(r,o)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let r of t)r.alive&&r.dispose();this._disposables.dispose()}};fe=class e extends N{static success(t){return new jt(t)}static fail(t,r){return new $t(t,r)}static is(t){return t instanceof e}},jt=class extends fe{constructor(e){super();this.value=e}get alive(){return W(this.value)?this.value.alive:!0}dispose(){W(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},$t=class extends fe{constructor(e,t){super();this.error=e,this.onUnwrap=t}get alive(){return W(this.error)?this.error.alive:!0}dispose(){W(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},Y=fe,Vt=class extends N{constructor(e){super();this.resolve=(t)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(t)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise((t)=>{this.onSettled=t}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},Lr=Symbol("Unstable"),Ur=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});Xt=class extends N{constructor(e,t){super();this.handle=e,this.context=t,this._isDone=!1,this.owner=t.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let t=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(t,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let t=this.context.getProp(this.handle,"return");if(t===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let r=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),r}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof A?e:this.context.newError(e),r=this.context.getProp(this.handle,"throw"),o=this.callIteratorMethod(r,e);return t.alive&&t.dispose(),r.dispose(),this.dispose(),o}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let r=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(r.error)return this.dispose(),{value:r};let o=this.context.getProp(r.value,"done").consume((d)=>this.context.dump(d)),l=this.context.getProp(r.value,"value");return r.value.dispose(),o&&this.dispose(),{value:Y.success(l),done:o}}};ze=class extends N{constructor(e,t,r){if(r===G)throw new I("cannot create HostRef with undefined id");super();this.runtime=e,this.handle=t,this.id=r}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},er=class extends at{constructor(e){super(e.module);this.scope=new M,this.copyJSValue=(t)=>this.ffi.QTS_DupValuePointer(this.ctx.value,t),this.freeJSValue=(t)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,t)},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let t=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),t}heapValueHandle(e,t){let r=t?(o)=>{t(),this.freeJSValue(o)}:this.freeJSValue;return new A(e,this.copyJSValue,r,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new B(e,this.owner)}},tr=class extends N{constructor(e){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:(t,r,o,l,d)=>{if(t!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let f=this.getFunction(d);return M.withScopeMaybeAsync(this,function*(s,_){let b=_.manage(new Ge(r,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),x=Array(o);for(let S=0;S<o;S++){let C=this.ffi.QTS_ArgvGetJSValueConstPointer(l,S);x[S]=_.manage(new Ge(C,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let S=yield*s(f.apply(b,x));if(S){if("error"in S&&S.error)throw this.runtime.debugLog("throw error",S.error),S.error;let C=_.manage(S instanceof A?S:S.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,C.value)}return 0}catch(S){return this.errorToHandle(S).consume((C)=>this.ffi.QTS_Throw(this.ctx.value,C.value))}})}},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new er({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new B(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new B(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new B(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new B(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let t=this.memory.newHeapCharPointer(e).consume((r)=>this.ffi.QTS_NewString(this.ctx.value,r.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,0));return this.memory.heapValueHandle(r)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,1));return this.memory.heapValueHandle(r)}getWellKnownSymbol(e){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let o=this.getProp(this.global,"BigInt");this.memory.manage(o),this._BigInt=new B(o.value,this.runtime)}let t=this._BigInt,r=String(e);return this.newString(r).consume((o)=>this.unwrapResult(this.callFunction(t,this.undefined,o)))}newObject(e){e&&this.runtime.assertOwned(e);let t=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(t)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let t=new Uint8Array(e),r=this.memory.newHeapBufferPointer(t),o=this.ffi.QTS_NewArrayBuffer(this.ctx.value,r.value.pointer,t.length);return this.memory.heapValueHandle(o)}newPromise(e){let t=M.withScope((r)=>{let o=r.manage(this.memory.newMutablePointerArray(2)),l=this.ffi.QTS_NewPromiseCapability(this.ctx.value,o.value.ptr),d=this.memory.heapValueHandle(l),[f,s]=Array.from(o.value.typedArray).map((_)=>this.memory.heapValueHandle(_));return new Vt({context:this,promiseHandle:d,resolveHandle:f,rejectHandle:s})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,(r)=>r instanceof A?t.reject(r):this.newError(r).consume(t.reject)),t}newFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!1,fn:r})}newConstructorFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!0,fn:r})}newFunctionWithOptions(e){let{name:t,length:r,isConstructor:o,fn:l}=e,d=this.runtime.hostRefs.put(l);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",r,o,d))}catch(f){throw this.runtime.hostRefs.delete(d),f}}newError(e){let t=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e=="object"?(e.name!==void 0&&this.newString(e.name).consume((r)=>this.setProp(t,"name",r)),e.message!==void 0&&this.newString(e.message).consume((r)=>this.setProp(t,"message",r))):typeof e=="string"?this.newString(e).consume((r)=>this.setProp(t,"message",r)):e!==void 0&&this.newString(String(e)).consume((r)=>this.setProp(t,"message",r)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let r=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new ze(this.runtime,r,t)}catch(r){throw this.runtime.hostRefs.delete(t),r}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new ze(this.runtime,e.dup(),t)}unwrapHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t===0)throw new I("handle is not a HostRef");return this.runtime.hostRefs.get(t)}typeof(e){return this.runtime.assertOwned(e),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,e.value))}getNumber(e){return this.runtime.assertOwned(e),this.ffi.QTS_GetFloat64(this.ctx.value,e.value)}getString(e){return this.runtime.assertOwned(e),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,e.value))}getSymbol(e){this.runtime.assertOwned(e);let t=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,e.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,e.value)?Symbol.for(t):Symbol(t)}getBigInt(e){this.runtime.assertOwned(e);let t=this.getString(e);return BigInt(t)}getArrayBuffer(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,e.value),r=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!r)throw Error("Couldn't allocate memory to get ArrayBuffer");return new A(this.module.HEAPU8.subarray(r,r+t),void 0,()=>this.module._free(r))}getPromiseState(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(t<0)return{type:"fulfilled",value:e,notAPromise:!0};if(t===j.Pending)return{type:"pending",get error(){return new nt("Cannot unwrap a pending promise")}};let r=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),o=this.memory.heapValueHandle(r);if(t===j.Fulfilled)return{type:"fulfilled",value:o};if(t===j.Rejected)return{type:"rejected",error:o};throw o.dispose(),Error(`Unknown JSPromiseStateEnum: ${t}`)}resolvePromise(e){this.runtime.assertOwned(e);let t=M.withScope((r)=>{let o=r.manage(this.getProp(this.global,"Promise")),l=r.manage(this.getProp(o,"resolve"));return this.callFunction(l,o,e)});return t.error?Promise.resolve(t):new Promise((r)=>{M.withScope((o)=>{let l=o.manage(this.newFunction("resolve",(_)=>{r(this.success(_&&_.dup()))})),d=o.manage(this.newFunction("reject",(_)=>{r(this.fail(_&&_.dup()))})),f=o.manage(t.value),s=o.manage(this.getProp(f,"then"));this.callFunction(s,f,l,d).unwrap().dispose()})})}isEqual(e,t,r=H.IsStrictlyEqual){if(e===t)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(t);let o=this.ffi.QTS_IsEqual(this.ctx.value,e.value,t.value,r);if(o===-1)throw new Ze("WASM variant does not expose equality");return!!o}eq(e,t){return this.isEqual(e,t,H.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,H.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,H.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let r;return typeof t=="number"&&t>=0?r=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):r=this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_GetProp(this.ctx.value,e.value,o.value)),this.memory.heapValueHandle(r)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,t={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let r=qt(t);if(r===0)throw new it("No options set, will return an empty array");return M.withScope((o)=>{let l=o.manage(this.memory.newMutablePointerArray(1)),d=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,l.value.ptr,this.uint32Out.value.ptr,e.value,r);if(d)return this.fail(this.memory.heapValueHandle(d));let f=this.uint32Out.value.typedArray[0],s=l.value.typedArray[0],_=new Uint32Array(this.module.HEAP8.buffer,s,f),b=Array.from(_).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,s),this.success(Qt(b))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return M.withScope((r)=>{let o=r.manage(this.getProp(e,t)),l=this.callFunction(o,e);return l.error?l:this.success(new Xt(l.value,this))})}setProp(e,t,r){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_SetProp(this.ctx.value,e.value,o.value,r.value))}defineProp(e,t,r){this.runtime.assertOwned(e),M.withScope((o)=>{let l=o.manage(this.borrowPropertyKey(t)),d=r.value||this.undefined,f=!!r.configurable,s=!!r.enumerable,_=!!r.value,b=r.get?o.manage(this.newFunction(r.get.name,r.get)):this.undefined,x=r.set?o.manage(this.newFunction(r.set.name,r.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,l.value,d.value,b.value,x.value,f,s,_)})}callFunction(e,t,...r){this.runtime.assertOwned(e);let o,l=r[0];l===void 0||Array.isArray(l)?o=l??[]:o=r;let d=this.memory.toPointerArray(o).consume((s)=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,o.length,s.value)),f=this.ffi.QTS_ResolveException(this.ctx.value,d);return f?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(f))):this.success(this.memory.heapValueHandle(d))}callMethod(e,t,r=[]){return this.getProp(e,t).consume((o)=>this.callFunction(o,e,r))}evalCode(e,t="eval.js",r){let o=r===void 0?1:0,l=Wt(r),d=this.memory.newHeapCharPointer(e).consume((s)=>this.ffi.QTS_Eval(this.ctx.value,s.value.ptr,s.value.strlen,t,o,l)),f=this.ffi.QTS_ResolveException(this.ctx.value,d);return f?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(f))):this.success(this.memory.heapValueHandle(d))}throw(e){return this.errorToHandle(e).consume((t)=>this.ffi.QTS_Throw(this.ctx.value,t.value))}borrowPropertyKey(e){return typeof e=="number"?this.newNumber(e):typeof e=="string"?this.newString(e):new B(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(e){this.runtime.assertOwned(e);let t=this.typeof(e);if(t==="string")return this.getString(e);if(t==="number")return this.getNumber(e);if(t==="bigint")return this.getBigInt(e);if(t==="undefined")return;if(t==="symbol")return this.getSymbol(e);let r=this.getPromiseState(e);if(r.type==="fulfilled"&&!r.notAPromise)return e.dispose(),{type:r.type,value:r.value.consume(this.dump)};if(r.type==="pending")return e.dispose(),{type:r.type};if(r.type==="rejected")return e.dispose(),{type:r.type,error:r.error.consume(this.dump)};let o=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(o)}catch{return o}}unwrapResult(e){if(e.error){let t="context"in e.error?e.error.context:this,r=e.error.consume((o)=>this.dump(o));if(r&&typeof r=="object"&&typeof r.message=="string"){let{message:o,name:l,stack:d,...f}=r,s=new ae(r,t);typeof l=="string"&&(s.name=r.name),s.message=o;let _=s.stack;throw typeof d=="string"&&(s.stack=`${l}: ${o}
7
+ ${r.stack}Host: ${_}`),Object.assign(s,f),s}throw new ae(r)}return e.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(e){let t=this.runtime.hostRefs.get(e);if(typeof t!="function")throw Error(`Host reference ${e} is not a function`);return t}errorToHandle(e){return e instanceof A?e:this.newError(e)}encodeBinaryJSON(e){let t=this.ffi.QTS_bjson_encode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}decodeBinaryJSON(e){let t=this.ffi.QTS_bjson_decode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}success(e){return Y.success(e)}fail(e){return Y.fail(e,(t)=>this.unwrapResult(t))}},rr=class extends N{constructor(e){super();this.scope=new M,this.contextMap=new Map,this.hostRefs=new Zt,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(t,r)=>{if(t!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(r)},shouldInterrupt:(t)=>{if(t!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let r=this.interruptHandler;if(!r)throw Error("QuickJSContext had no interrupt handler");return r(this)?1:0},loadModuleSource:$e(this,function*(t,r,o,l){let d=this.moduleLoader;if(!d)throw Error("Runtime has no module loader");if(r!==this.rt.value)throw Error("Runtime pointer mismatch");let f=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let s=yield*t(d(l,f));if(typeof s=="object"&&"error"in s&&s.error)throw this.debugLog("cToHostLoadModule: loader returned error",s.error),s.error;let _=typeof s=="string"?s:("value"in s)?s.value:s;return this.memory.newHeapCharPointer(_).value.ptr}catch(s){return this.debugLog("cToHostLoadModule: caught error",s),f.throw(s),0}}),normalizeModule:$e(this,function*(t,r,o,l,d){let f=this.moduleNormalizer;if(!f)throw Error("Runtime has no module normalizer");if(r!==this.rt.value)throw Error("Runtime pointer mismatch");let s=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let _=yield*t(f(l,d,s));if(typeof _=="object"&&"error"in _&&_.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",_.error),_.error;let b=typeof _=="string"?_:_.value;return s.getMemory(this.rt.value).newHeapCharPointer(b).value.ptr}catch(_){return this.debugLog("normalizeModule: caught error",_),s.throw(_),0}})},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.module=e.module,this.memory=new at(this.module),this.ffi=e.ffi,this.rt=e.rt,this.callbacks=e.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),ce&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(e={}){let t=Gt(e.intrinsics),r=new A(e.contextPointer||this.ffi.QTS_NewContext(this.rt.value,t),void 0,(l)=>{this.contextMap.delete(l),this.callbacks.deleteContext(l),this.ffi.QTS_FreeContext(l)}),o=new tr({module:this.module,ctx:r,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(r.value,o),o}setModuleLoader(e,t){this.moduleLoader=e,this.moduleNormalizer=t,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(e){let t=this.interruptHandler;this.interruptHandler=e,t||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(e=-1){let t=this.memory.newMutablePointerArray(1),r=this.ffi.QTS_ExecutePendingJob(this.rt.value,e??-1,t.value.ptr),o=t.value.typedArray[0];if(t.dispose(),o===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,r),Y.success(0);let l=this.contextMap.get(o)??this.newContext({contextPointer:o}),d=l.getMemory(this.rt.value).heapValueHandle(r);if(l.typeof(d)==="number"){let f=l.getNumber(d);return d.dispose(),Y.success(f)}else{let f=Object.assign(d,{context:l});return Y.fail(f,(s)=>l.unwrapResult(s))}}setMemoryLimit(e){if(e<0&&e!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,e)}computeMemoryUsage(){let e=this.getSystemContext().getMemory(this.rt.value);return e.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,e.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(e){if(e<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,e)}assertOwned(e){if(e.owner&&e.owner.rt!==this.rt)throw new Xe(`Handle is not owned by this runtime: ${e.owner.rt.value} != ${this.rt.value}`)}setDebugMode(e){this._debugMode=e,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,e?1:0)}isDebugMode(){return this._debugMode}debugLog(...e){this._debugMode&&console.log("quickjs-emscripten:",...e)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}}});var ct={};Lt(ct,{QuickJSModuleCallbacks:()=>me,QuickJSWASMModule:()=>ut,applyBaseRuntimeOptions:()=>pe,applyModuleEvalRuntimeOptions:()=>_e});var ht=ne(()=>{lt()});var gt=Ct(function(q,_t){(function(e,t){typeof q==="object"&&typeof _t<"u"?t(q):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.jmespath={}))})(q,function(e){let t=(n)=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",r=(n,i)=>{if(n===i)return!0;if(typeof n!==typeof i)return!1;if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return!1;for(let a=0;a<n.length;a+=1)if(!r(n[a],i[a]))return!1;return!0}if(t(n)&&t(i)){let a=Object.entries(n),u=new Set(Object.keys(i));if(a.length!==u.size)return!1;for(let[h,m]of a){if(!r(m,i[h]))return!1;u.delete(h)}return u.size===0}return!1},o=(n)=>{if(n===""||n===!1||n===null||n===void 0)return!0;if(Array.isArray(n)&&n.length===0)return!0;if(t(n)){for(let i in n)if(n.hasOwnProperty(i))return!1;return!0}return!1},l=(n)=>n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="_",d=(n)=>n>="0"&&n<="9"||n==="-",f=(n)=>n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||n==="_";var s;(function(n){n.TOK_EOF="EOF",n.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",n.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",n.TOK_RBRACKET="Rbracket",n.TOK_RPAREN="Rparen",n.TOK_COMMA="Comma",n.TOK_COLON="Colon",n.TOK_RBRACE="Rbrace",n.TOK_NUMBER="Number",n.TOK_CURRENT="Current",n.TOK_ROOT="Root",n.TOK_EXPREF="Expref",n.TOK_PIPE="Pipe",n.TOK_OR="Or",n.TOK_AND="And",n.TOK_EQ="EQ",n.TOK_GT="GT",n.TOK_LT="LT",n.TOK_GTE="GTE",n.TOK_LTE="LTE",n.TOK_NE="NE",n.TOK_FLATTEN="Flatten",n.TOK_STAR="Star",n.TOK_FILTER="Filter",n.TOK_DOT="Dot",n.TOK_NOT="Not",n.TOK_LBRACE="Lbrace",n.TOK_LBRACKET="Lbracket",n.TOK_LPAREN="Lparen",n.TOK_LITERAL="Literal"})(s||(s={}));let _={"(":s.TOK_LPAREN,")":s.TOK_RPAREN,"*":s.TOK_STAR,",":s.TOK_COMMA,".":s.TOK_DOT,":":s.TOK_COLON,"@":s.TOK_CURRENT,["$"]:s.TOK_ROOT,"]":s.TOK_RBRACKET,"{":s.TOK_LBRACE,"}":s.TOK_RBRACE},b={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class S{constructor(){this._current=0}tokenize(n){let i=[];this._current=0;let a,u,h;while(this._current<n.length)if(l(n[this._current]))a=this._current,u=this.consumeUnquotedIdentifier(n),i.push({start:a,type:s.TOK_UNQUOTEDIDENTIFIER,value:u});else if(_[n[this._current]]!==void 0)i.push({start:this._current,type:_[n[this._current]],value:n[this._current]}),this._current+=1;else if(d(n[this._current]))h=this.consumeNumber(n),i.push(h);else if(n[this._current]==="[")h=this.consumeLBracket(n),i.push(h);else if(n[this._current]==='"')a=this._current,u=this.consumeQuotedIdentifier(n),i.push({start:a,type:s.TOK_QUOTEDIDENTIFIER,value:u});else if(n[this._current]==="'")a=this._current,u=this.consumeRawStringLiteral(n),i.push({start:a,type:s.TOK_LITERAL,value:u});else if(n[this._current]==="`"){a=this._current;let m=this.consumeLiteral(n);i.push({start:a,type:s.TOK_LITERAL,value:m})}else if(b[n[this._current]]!==void 0)h=this.consumeOperator(n),h&&i.push(h);else if(x[n[this._current]]!==void 0)this._current+=1;else if(n[this._current]==="&")if(a=this._current,this._current+=1,n[this._current]==="&")this._current+=1,i.push({start:a,type:s.TOK_AND,value:"&&"});else i.push({start:a,type:s.TOK_EXPREF,value:"&"});else if(n[this._current]==="|")if(a=this._current,this._current+=1,n[this._current]==="|")this._current+=1,i.push({start:a,type:s.TOK_OR,value:"||"});else i.push({start:a,type:s.TOK_PIPE,value:"|"});else{let m=Error(`Unknown character: ${n[this._current]}`);throw m.name="LexerError",m}return i}consumeUnquotedIdentifier(n){let i=this._current;this._current+=1;while(this._current<n.length&&f(n[this._current]))this._current+=1;return n.slice(i,this._current)}consumeQuotedIdentifier(n){let i=this._current;this._current+=1;let a=n.length;while(n[this._current]!=='"'&&this._current<a){let u=this._current;if(n[u]==="\\"&&(n[u+1]==="\\"||n[u+1]==='"'))u+=2;else u+=1;this._current=u}return this._current+=1,JSON.parse(n.slice(i,this._current))}consumeRawStringLiteral(n){let i=this._current;this._current+=1;let a=n.length;while(n[this._current]!=="'"&&this._current<a){let h=this._current;if(n[h]==="\\"&&(n[h+1]==="\\"||n[h+1]==="'"))h+=2;else h+=1;this._current=h}return this._current+=1,n.slice(i+1,this._current-1).replace("\\'","'")}consumeNumber(n){let i=this._current;this._current+=1;let a=n.length;while(d(n[this._current])&&this._current<a)this._current+=1;let u=parseInt(n.slice(i,this._current),10);return{start:i,value:u,type:s.TOK_NUMBER}}consumeLBracket(n){let i=this._current;if(this._current+=1,n[this._current]==="?")return this._current+=1,{start:i,type:s.TOK_FILTER,value:"[?"};if(n[this._current]==="]")return this._current+=1,{start:i,type:s.TOK_FLATTEN,value:"[]"};return{start:i,type:s.TOK_LBRACKET,value:"["}}consumeOperator(n){let i=this._current,a=n[i];if(this._current+=1,a==="!"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_NE,value:"!="};return{start:i,type:s.TOK_NOT,value:"!"}}if(a==="<"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_LTE,value:"<="};return{start:i,type:s.TOK_LT,value:"<"}}if(a===">"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_GTE,value:">="};return{start:i,type:s.TOK_GT,value:">"}}if(a==="="&&n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_EQ,value:"=="}}consumeLiteral(n){this._current+=1;let i=this._current,a=n.length;while(n[this._current]!=="`"&&this._current<a){let m=this._current;if(n[m]==="\\"&&(n[m+1]==="\\"||n[m+1]==="`"))m+=2;else m+=1;this._current=m}let u=n.slice(i,this._current).trimLeft();u=u.replace("\\`","`");let h=this.looksLikeJSON(u)?JSON.parse(u):JSON.parse(`"${u}"`);return this._current+=1,h}looksLikeJSON(n){let a=["true","false","null"],u="-0123456789";if(n==="")return!1;if('[{"'.includes(n[0]))return!0;if(a.includes(n))return!0;if("-0123456789".includes(n[0]))try{return JSON.parse(n),!0}catch(h){return!1}return!1}}let C=new S,w={[s.TOK_EOF]:0,[s.TOK_UNQUOTEDIDENTIFIER]:0,[s.TOK_QUOTEDIDENTIFIER]:0,[s.TOK_RBRACKET]:0,[s.TOK_RPAREN]:0,[s.TOK_COMMA]:0,[s.TOK_RBRACE]:0,[s.TOK_NUMBER]:0,[s.TOK_CURRENT]:0,[s.TOK_EXPREF]:0,[s.TOK_ROOT]:0,[s.TOK_PIPE]:1,[s.TOK_OR]:2,[s.TOK_AND]:3,[s.TOK_EQ]:5,[s.TOK_GT]:5,[s.TOK_LT]:5,[s.TOK_GTE]:5,[s.TOK_LTE]:5,[s.TOK_NE]:5,[s.TOK_FLATTEN]:9,[s.TOK_STAR]:20,[s.TOK_FILTER]:21,[s.TOK_DOT]:40,[s.TOK_NOT]:45,[s.TOK_LBRACE]:50,[s.TOK_LBRACKET]:55,[s.TOK_LPAREN]:60};class Te{constructor(){this.index=0,this.tokens=[]}parse(n){this.loadTokens(n),this.index=0;let i=this.expression(0);if(this.lookahead(0)!==s.TOK_EOF){let a=this.lookaheadToken(0);this.errorToken(a,`Unexpected token type: ${a.type}, value: ${a.value}`)}return i}loadTokens(n){this.tokens=[...C.tokenize(n),{type:s.TOK_EOF,value:"",start:n.length}]}expression(n){let i=this.lookaheadToken(0);this.advance();let a=this.nud(i),u=this.lookahead(0);while(n<w[u])this.advance(),a=this.led(u,a),u=this.lookahead(0);return a}lookahead(n){return this.tokens[this.index+n].type}lookaheadToken(n){return this.tokens[this.index+n]}advance(){this.index+=1}nud(n){let i,a,u;switch(n.type){case s.TOK_LITERAL:return{type:"Literal",value:n.value};case s.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:n.value};case s.TOK_QUOTEDIDENTIFIER:let h={type:"Field",name:n.value};if(this.lookahead(0)===s.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return h;case s.TOK_NOT:return a=this.expression(w.Not),{type:"NotExpression",children:[a]};case s.TOK_STAR:return i={type:"Identity"},a=this.lookahead(0)===s.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(w.Star),{type:"ValueProjection",children:[i,a]};case s.TOK_FILTER:return this.led(n.type,{type:"Identity"});case s.TOK_LBRACE:return this.parseMultiselectHash();case s.TOK_FLATTEN:return i={type:s.TOK_FLATTEN,children:[{type:"Identity"}]},a=this.parseProjectionRHS(w.Flatten),{type:"Projection",children:[i,a]};case s.TOK_LBRACKET:if(this.lookahead(0)===s.TOK_NUMBER||this.lookahead(0)===s.TOK_COLON)return a=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},a);if(this.lookahead(0)===s.TOK_STAR&&this.lookahead(1)===s.TOK_RBRACKET)return this.advance(),this.advance(),a=this.parseProjectionRHS(w.Star),{children:[{type:"Identity"},a],type:"Projection"};return this.parseMultiselectList();case s.TOK_CURRENT:return{type:s.TOK_CURRENT};case s.TOK_ROOT:return{type:s.TOK_ROOT};case s.TOK_EXPREF:return u=this.expression(w.Expref),{type:"ExpressionReference",children:[u]};case s.TOK_LPAREN:let m=[];while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)u={type:s.TOK_CURRENT},this.advance();else u=this.expression(0);m.push(u)}return this.match(s.TOK_RPAREN),m[0];default:this.errorToken(n)}}led(n,i){let a;switch(n){case s.TOK_DOT:let u=w.Dot;if(this.lookahead(0)!==s.TOK_STAR)return a=this.parseDotRHS(u),{type:"Subexpression",children:[i,a]};return this.advance(),a=this.parseProjectionRHS(u),{type:"ValueProjection",children:[i,a]};case s.TOK_PIPE:return a=this.expression(w.Pipe),{type:s.TOK_PIPE,children:[i,a]};case s.TOK_OR:return a=this.expression(w.Or),{type:"OrExpression",children:[i,a]};case s.TOK_AND:return a=this.expression(w.And),{type:"AndExpression",children:[i,a]};case s.TOK_LPAREN:let h=i.name,m=[],g;while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)g={type:s.TOK_CURRENT},this.advance();else g=this.expression(0);if(this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);m.push(g)}return this.match(s.TOK_RPAREN),{name:h,type:"Function",children:m};case s.TOK_FILTER:let y=this.expression(0);return this.match(s.TOK_RBRACKET),a=this.lookahead(0)===s.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(w.Filter),{type:"FilterProjection",children:[i,a,y]};case s.TOK_FLATTEN:let P={type:s.TOK_FLATTEN,children:[i]},T=this.parseProjectionRHS(w.Flatten);return{type:"Projection",children:[P,T]};case s.TOK_EQ:case s.TOK_NE:case s.TOK_GT:case s.TOK_GTE:case s.TOK_LT:case s.TOK_LTE:return this.parseComparator(i,n);case s.TOK_LBRACKET:let p=this.lookaheadToken(0);if(p.type===s.TOK_NUMBER||p.type===s.TOK_COLON)return a=this.parseIndexExpression(),this.projectIfSlice(i,a);return this.match(s.TOK_STAR),this.match(s.TOK_RBRACKET),a=this.parseProjectionRHS(w.Star),{type:"Projection",children:[i,a]};default:return this.errorToken(this.lookaheadToken(0))}}match(n){if(this.lookahead(0)===n){this.advance();return}else{let i=this.lookaheadToken(0);this.errorToken(i,`Expected ${n}, got: ${i.type}`)}}errorToken(n,i=""){let a=Error(i||`Invalid token (${n.type}): "${n.value}"`);throw a.name="ParserError",a}parseIndexExpression(){if(this.lookahead(0)===s.TOK_COLON||this.lookahead(1)===s.TOK_COLON)return this.parseSliceExpression();let n={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(s.TOK_RBRACKET),n}projectIfSlice(n,i){let a={type:"IndexExpression",children:[n,i]};if(i.type==="Slice")return{children:[a,this.parseProjectionRHS(w.Star)],type:"Projection"};return a}parseSliceExpression(){let n=[null,null,null],i=0,a=this.lookahead(0);while(a!==s.TOK_RBRACKET&&i<3){if(a===s.TOK_COLON)i+=1,this.advance();else if(a===s.TOK_NUMBER)n[i]=this.lookaheadToken(0).value,this.advance();else{let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}a=this.lookahead(0)}return this.match(s.TOK_RBRACKET),{children:n,type:"Slice"}}parseComparator(n,i){let a=this.expression(w[i]);return{type:"Comparator",name:i,children:[n,a]}}parseDotRHS(n){let i=this.lookahead(0);if([s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER,s.TOK_STAR].includes(i))return this.expression(n);if(i===s.TOK_LBRACKET)return this.match(s.TOK_LBRACKET),this.parseMultiselectList();if(i===s.TOK_LBRACE)return this.match(s.TOK_LBRACE),this.parseMultiselectHash();let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}parseProjectionRHS(n){if(w[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===s.TOK_LBRACKET)return this.expression(n);if(this.lookahead(0)===s.TOK_FILTER)return this.expression(n);if(this.lookahead(0)===s.TOK_DOT)return this.match(s.TOK_DOT),this.parseDotRHS(n);let i=this.lookaheadToken(0);this.errorToken(i,`Syntax error, unexpected token: ${i.value}(${i.type})`)}parseMultiselectList(){let n=[];while(this.lookahead(0)!==s.TOK_RBRACKET){let i=this.expression(0);if(n.push(i),this.lookahead(0)===s.TOK_COMMA){if(this.match(s.TOK_COMMA),this.lookahead(0)===s.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(s.TOK_RBRACKET),{type:"MultiSelectList",children:n}}parseMultiselectHash(){let n=[],i=[s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER],a,u,h;for(;;){if(a=this.lookaheadToken(0),!i.includes(a.type))throw Error(`Expecting an identifier token, got: ${a.type}`);if(u=a.value,this.advance(),this.match(s.TOK_COLON),h=this.expression(0),n.push({value:h,type:"KeyValuePair",name:u}),this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);else if(this.lookahead(0)===s.TOK_RBRACE){this.match(s.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:n}}}let Se=new Te;var c;(function(n){n[n.TYPE_NUMBER=0]="TYPE_NUMBER",n[n.TYPE_ANY=1]="TYPE_ANY",n[n.TYPE_STRING=2]="TYPE_STRING",n[n.TYPE_ARRAY=3]="TYPE_ARRAY",n[n.TYPE_OBJECT=4]="TYPE_OBJECT",n[n.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",n[n.TYPE_EXPREF=6]="TYPE_EXPREF",n[n.TYPE_NULL=7]="TYPE_NULL",n[n.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",n[n.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(c||(c={}));class Re{constructor(n){this.TYPE_NAME_TABLE={[c.TYPE_NUMBER]:"number",[c.TYPE_ANY]:"any",[c.TYPE_STRING]:"string",[c.TYPE_ARRAY]:"array",[c.TYPE_OBJECT]:"object",[c.TYPE_BOOLEAN]:"boolean",[c.TYPE_EXPREF]:"expression",[c.TYPE_NULL]:"null",[c.TYPE_ARRAY_NUMBER]:"Array<number>",[c.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([i])=>Math.abs(i),this.functionAvg=([i])=>{let a=0;for(let u=0;u<i.length;u+=1)a+=i[u];return a/i.length},this.functionCeil=([i])=>Math.ceil(i),this.functionContains=(i)=>{let[a,u]=i;return a.includes(u)},this.functionEndsWith=(i)=>{let[a,u]=i;return a.includes(u,a.length-u.length)},this.functionFloor=([i])=>Math.floor(i),this.functionJoin=(i)=>{let[a,u]=i;return u.join(a)},this.functionKeys=([i])=>Object.keys(i),this.functionLength=([i])=>{if(!t(i))return i.length;return Object.keys(i).length},this.functionMap=(i)=>{if(!this._interpreter)return[];let a=[],u=this._interpreter,h=i[0],m=i[1];for(let g=0;g<m.length;g+=1)a.push(u.visit(h,m[g]));return a},this.functionMax=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.max(...i);let u=i,h=u[0];for(let m=1;m<u.length;m+=1)if(h.localeCompare(u[m])<0)h=u[m];return h},this.functionMaxBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),m=-1/0,g,E;for(let y=0;y<u.length;y+=1)if(E=h&&h(u[y]),E!==void 0&&E>m)m=E,g=u[y];return g},this.functionMerge=(i)=>{let a={};for(let u=0;u<i.length;u+=1){let h=i[u];a=Object.assign(a,h)}return a},this.functionMin=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.min(...i);let u=i,h=u[0];for(let m=1;m<u.length;m+=1)if(u[m].localeCompare(h)<0)h=u[m];return h},this.functionMinBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),m=1/0,g,E;for(let y=0;y<u.length;y+=1)if(E=h&&h(u[y]),E!==void 0&&E<m)m=E,g=u[y];return g},this.functionNotNull=(i)=>{for(let a=0;a<i.length;a+=1)if(this.getTypeName(i[a])!==c.TYPE_NULL)return i[a];return null},this.functionReverse=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING){let h=i,m="";for(let g=h.length-1;g>=0;g-=1)m+=h[g];return m}let u=i.slice(0);return u.reverse(),u},this.functionSort=([i])=>[...i].sort(),this.functionSortBy=(i)=>{if(!this._interpreter)return[];let a=i[0].slice(0);if(a.length===0)return a;let u=this._interpreter,h=i[1],m=this.getTypeName(u.visit(h,a[0]));if(m!==void 0&&![c.TYPE_NUMBER,c.TYPE_STRING].includes(m))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[m]})`);let g=[];for(let E=0;E<a.length;E+=1)g.push([E,a[E]]);g.sort((E,y)=>{let P=u.visit(h,E[1]),T=u.visit(h,y[1]);if(this.getTypeName(P)!==m)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[m]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(P)]}`);else if(this.getTypeName(T)!==m)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[m]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(T)]}`);if(P>T)return 1;return P<T?-1:E[0]-y[0]});for(let E=0;E<g.length;E+=1)a[E]=g[E][1];return a},this.functionStartsWith=([i,a])=>i.startsWith(a),this.functionSum=([i])=>i.reduce((a,u)=>a+u,0),this.functionToArray=([i])=>{if(this.getTypeName(i)===c.TYPE_ARRAY)return i;return[i]},this.functionToNumber=([i])=>{let a=this.getTypeName(i),u;if(a===c.TYPE_NUMBER)return i;if(a===c.TYPE_STRING){if(u=+i,!isNaN(u))return u}return null},this.functionToString=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING)return i;return JSON.stringify(i)},this.functionType=([i])=>{switch(this.getTypeName(i)){case c.TYPE_NUMBER:return"number";case c.TYPE_STRING:return"string";case c.TYPE_ARRAY:return"array";case c.TYPE_OBJECT:return"object";case c.TYPE_BOOLEAN:return"boolean";case c.TYPE_EXPREF:return"expref";case c.TYPE_NULL:return"null";default:return}},this.functionValues=([i])=>Object.values(i),this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[c.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[c.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]},{types:[c.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[c.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[c.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY,c.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[c.TYPE_EXPREF]},{types:[c.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[c.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[c.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[c.TYPE_ARRAY_STRING,c.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[c.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[c.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[c.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[c.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[c.TYPE_OBJECT]}]}},this._interpreter=n}registerFunction(n,i,a){if(n in this.functionTable)throw Error(`Function already defined: ${n}()`);this.functionTable[n]={_func:i.bind(this),_signature:a}}callFunction(n,i){let a=this.functionTable[n];if(a===void 0)throw Error(`Unknown function: ${n}()`);return this.validateArgs(n,i,a._signature),a._func.call(this,i)}validateInputSignatures(n,i){for(let a=0;a<i.length;a+=1)if("variadic"in i[a]&&a!==i.length-1)throw Error(`ArgumentError: ${n}() 'variadic' argument ${a+1} must occur last`)}validateArgs(n,i,a){var u,h;let m;this.validateInputSignatures(n,a);let g=a.filter((O)=>{var v;return(v=!O.optional)!==null&&v!==void 0?v:!1}).length,E=(h=(u=a[a.length-1])===null||u===void 0?void 0:u.variadic)!==null&&h!==void 0?h:!1,y=i.length<g,P=i.length>a.length,T=y&&(!E&&g>1||E)?"at least ":"";if(E&&y||!E&&(y||P))throw m=a.length>1,Error(`ArgumentError: ${n}() takes ${T}${g} argument${m&&"s"||""} but received ${i.length}`);let p,R,k;for(let O=0;O<a.length;O+=1){k=!1,p=a[O].types,R=this.getTypeName(i[O]);let v;for(v=0;v<p.length;v+=1)if(R!==void 0&&this.typeMatches(R,p[v],i[O])){k=!0;break}if(!k&&R!==void 0){let F=p.map((D)=>this.TYPE_NAME_TABLE[D]).join(" | ");throw Error(`TypeError: ${n}() expected argument ${O+1} to be type (${F}) but received type ${this.TYPE_NAME_TABLE[R]} instead.`)}}}typeMatches(n,i,a){if(i===c.TYPE_ANY)return!0;if(i===c.TYPE_ARRAY_STRING||i===c.TYPE_ARRAY_NUMBER||i===c.TYPE_ARRAY){if(i===c.TYPE_ARRAY)return n===c.TYPE_ARRAY;if(n===c.TYPE_ARRAY){let u;if(i===c.TYPE_ARRAY_NUMBER)u=c.TYPE_NUMBER;else if(i===c.TYPE_ARRAY_STRING)u=c.TYPE_STRING;for(let h=0;h<a.length;h+=1){let m=this.getTypeName(a[h]);if(m!==void 0&&u!==void 0&&!this.typeMatches(m,u,a[h]))return!1}return!0}}else return n===i;return!1}getTypeName(n){switch(Object.prototype.toString.call(n)){case"[object String]":return c.TYPE_STRING;case"[object Number]":return c.TYPE_NUMBER;case"[object Array]":return c.TYPE_ARRAY;case"[object Boolean]":return c.TYPE_BOOLEAN;case"[object Null]":return c.TYPE_NULL;case"[object Object]":if(n.jmespathType===s.TOK_EXPREF)return c.TYPE_EXPREF;return c.TYPE_OBJECT;default:return}}createKeyFunction(n,i){if(!this._interpreter)return;let a=this._interpreter;return(h)=>{let m=a.visit(n,h);if(!i.includes(this.getTypeName(m))){let g=`TypeError: expected one of (${i.map((E)=>this.TYPE_NAME_TABLE[E]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(m)]}`;throw Error(g)}return m}}}class we{constructor(){this._rootValue=null,this.runtime=new Re(this)}search(n,i){return this._rootValue=i,this.visit(n,i)}visit(n,i){let a,u,h,m,g,E,y,P,T,p,R;switch(n.type){case"Field":if(i===null)return null;if(t(i)){if(E=i[n.name],E===void 0)return null;return E}return null;case"Subexpression":h=this.visit(n.children[0],i);for(p=1;p<n.children.length;p+=1)if(h=this.visit(n.children[1],h),h===null)return null;return h;case"IndexExpression":return y=this.visit(n.children[0],i),P=this.visit(n.children[1],y),P;case"Index":if(!Array.isArray(i))return null;let k=n.value;if(k<0)k=i.length+k;if(h=i[k],h===void 0)h=null;return h;case"Slice":if(!Array.isArray(i))return null;let O=[...n.children],v=this.computeSliceParams(i.length,O),[F,D,X]=v;if(h=[],X>0)for(p=F;p<D;p+=X)h.push(i[p]);else for(p=F;p>D;p+=X)h.push(i[p]);return h;case"Projection":if(R=this.visit(n.children[0],i),!Array.isArray(R))return null;T=[];for(p=0;p<R.length;p+=1)if(u=this.visit(n.children[1],R[p]),u!==null)T.push(u);return T;case"ValueProjection":if(R=this.visit(n.children[0],i),!t(R))return null;T=[];let He=Object.values(R);for(p=0;p<He.length;p+=1)if(u=this.visit(n.children[1],He[p]),u!==null)T.push(u);return T;case"FilterProjection":if(R=this.visit(n.children[0],i),!Array.isArray(R))return null;let Z=[],Je=[];for(p=0;p<R.length;p+=1)if(a=this.visit(n.children[2],R[p]),!o(a))Z.push(R[p]);for(let L=0;L<Z.length;L+=1)if(u=this.visit(n.children[1],Z[L]),u!==null)Je.push(u);return Je;case"Comparator":switch(m=this.visit(n.children[0],i),g=this.visit(n.children[1],i),n.name){case s.TOK_EQ:h=r(m,g);break;case s.TOK_NE:h=!r(m,g);break;case s.TOK_GT:h=m>g;break;case s.TOK_GTE:h=m>=g;break;case s.TOK_LT:h=m<g;break;case s.TOK_LTE:h=m<=g;break;default:throw Error(`Unknown comparator: ${n.name}`)}return h;case s.TOK_FLATTEN:let ee=this.visit(n.children[0],i);if(!Array.isArray(ee))return null;let Q=[];for(p=0;p<ee.length;p+=1)if(u=ee[p],Array.isArray(u))Q=[...Q,...u];else Q.push(u);return Q;case"Identity":return i;case"MultiSelectList":if(i===null)return null;T=[];for(p=0;p<n.children.length;p+=1)T.push(this.visit(n.children[p],i));return T;case"MultiSelectHash":if(i===null)return null;T={};let te;for(p=0;p<n.children.length;p+=1)te=n.children[p],T[te.name]=this.visit(te.value,i);return T;case"OrExpression":if(a=this.visit(n.children[0],i),o(a))a=this.visit(n.children[1],i);return a;case"AndExpression":if(m=this.visit(n.children[0],i),o(m))return m;return this.visit(n.children[1],i);case"NotExpression":return m=this.visit(n.children[0],i),o(m);case"Literal":return n.value;case s.TOK_PIPE:return y=this.visit(n.children[0],i),this.visit(n.children[1],y);case s.TOK_CURRENT:return i;case s.TOK_ROOT:return this._rootValue;case"Function":let Fe=[];for(let L=0;L<n.children.length;L+=1)Fe.push(this.visit(n.children[L],i));return this.runtime.callFunction(n.name,Fe);case"ExpressionReference":let De=n.children[0];return De.jmespathType=s.TOK_EXPREF,De;default:throw Error(`Unknown node type: ${n.type}`)}}computeSliceParams(n,i){let[a,u,h]=i;if(h===null)h=1;else if(h===0){let g=Error("Invalid slice, step cannot be 0");throw g.name="RuntimeError",g}let m=h<0?!0:!1;return a=a===null?m?n-1:0:this.capSliceRange(n,a,h),u=u===null?m?-1:n:this.capSliceRange(n,u,h),[a,u,h]}capSliceRange(n,i,a){let u=i;if(u<0){if(u+=n,u<0)u=a<0?-1:0}else if(u>=n)u=a<0?n-1:n;return u}}let z=new we,Ae=c.TYPE_ANY,be=c.TYPE_ARRAY,Pe=c.TYPE_ARRAY_NUMBER,Oe=c.TYPE_ARRAY_STRING,ve=c.TYPE_BOOLEAN,Me=c.TYPE_EXPREF,xe=c.TYPE_NULL,Ne=c.TYPE_NUMBER,Ce=c.TYPE_OBJECT,ke=c.TYPE_STRING;function Ie(n){return Se.parse(n)}function Le(n){return C.tokenize(n)}let Ue=(n,i,a)=>{z.runtime.registerFunction(n,i,a)};function Ke(n,i){let a=Se.parse(i);return z.search(a,n)}let Be=z,Ye={compile:Ie,registerFunction:Ue,search:Ke,tokenize:Le,TreeInterpreter:Be,TYPE_ANY:Ae,TYPE_ARRAY_NUMBER:Pe,TYPE_ARRAY_STRING:Oe,TYPE_ARRAY:be,TYPE_BOOLEAN:ve,TYPE_EXPREF:Me,TYPE_NULL:xe,TYPE_NUMBER:Ne,TYPE_OBJECT:Ce,TYPE_STRING:ke};e.TYPE_ANY=Ae,e.TYPE_ARRAY=be,e.TYPE_ARRAY_NUMBER=Pe,e.TYPE_ARRAY_STRING=Oe,e.TYPE_BOOLEAN=ve,e.TYPE_EXPREF=Me,e.TYPE_NULL=xe,e.TYPE_NUMBER=Ne,e.TYPE_OBJECT=Ce,e.TYPE_STRING=ke,e.TreeInterpreter=Be,e.compile=Ie,e.default=Ye,e.jmespath=Ye,e.registerFunction=Ue,e.search=Ke,e.tokenize=Le,Object.defineProperty(e,"__esModule",{value:!0})})});import{mkdirSync as Sr,mkdtempSync as Rr,writeFileSync as wr}from"node:fs";import{tmpdir as Ar}from"node:os";import{dirname as br,join as Ee}from"node:path";import{pathToFileURL as Pr}from"node:url";import{timingSafeEqual as mr}from"node:crypto";import{createServer as pr}from"node:http";import{Readable as _r}from"node:stream";function Ut(){return typeof process>"u"?{}:process.env}function je(e=Ut()){return e.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as dr}from"node:fs";V();async function dt(e){let t=ge(await e),[r,o,{QuickJSWASMModule:l}]=await Promise.all([t.importModuleLoader().then(ge),t.importFFI(),Promise.resolve().then(() => (ht(),ct)).then(ge)]),d=await r();d.type="sync";let f=new o(d);return new l(d,f)}function ge(e){return e&&"default"in e&&e.default?e.default&&"default"in e.default&&e.default.default?e.default.default:e.default:e}var mt="engine";function ir(e){let t=(r)=>new URL(r,e).href;return{type:"sync",importFFI:()=>import(t("ffi.mjs")).then((r)=>r.QuickJSFFI),importModuleLoader:()=>import(t("emscripten-module.mjs")).then((r)=>r.default)}}var ft=null;function pt(e){return()=>(ft??=dt(ir(e)),ft)}var sr=Nt(gt(),1);var ar="__mcpcloud_call_tool",bn=`globalThis.tool = (name, args) =>
8
8
  globalThis.${ar}(String(name), JSON.stringify(args ?? {}))
9
9
  .then((json) => JSON.parse(json));`;var ur=6,lr=["log","warn","error","info","debug"],cr="__mcpcloud_console",vn=`globalThis.console = {
10
10
  ${lr.map((e)=>` ${e}: (...args) => globalThis.${cr}(${JSON.stringify(e)}, JSON.stringify(args.slice(0, ${ur}).map((value) => (value instanceof Error ? { __mcpcloudError: value.name + ': ' + value.message } : value)))),`).join(`
11
11
  `)}
12
- };`;var hr=Symbol.for("@mcpcloud/runtime.codeModeEngineProvider");function yt(e){globalThis[hr]=e}var Et=[`./${mt}/`,"../engine/vendor/","../../engine/vendor/"];function fr(e=new URL(import.meta.url)){for(let t of Et){let r=new URL(t,e);if(dr(new URL("emscripten-module.wasm",r)))return r}throw Error(`Code Mode engine not found. Looked for emscripten-module.wasm in: ${Et.join(", ")} (relative to ${e.href}).`)}function Tt(){yt(()=>pt(fr())())}function gr(e,t){let r=Buffer.from(e),o=Buffer.from(t);return r.length===o.length&&mr(r,o)}function yr(e,t){let r=je(t);if(!r)return null;if(new URL(e.url).pathname==="/health")return null;let o=e.headers.get("authorization")??"",l=/^Bearer\s+(.+)$/i.exec(o.trim());if(l&&gr(l[1].trim(),r))return null;return Response.json({error:"unauthorized",message:"This MCP endpoint requires a bearer token (set in Authorization: Bearer <token>)."},{status:401,headers:{"www-authenticate":"Bearer"}})}function Er(e,t){let r=new URL(e.url??"/",t),o=new Headers;for(let[f,s]of Object.entries(e.headers))if(Array.isArray(s))for(let _ of s)o.append(f,_);else if(typeof s==="string")o.set(f,s);let l=e.method??"GET",d=l==="GET"||l==="HEAD"?void 0:_r.toWeb(e);return new Request(r,{method:l,headers:o,body:d,...d?{duplex:"half"}:{}})}async function Tr(e,t){if(t.statusCode=e.status,e.headers.forEach((o,l)=>{t.setHeader(l,o)}),!e.body){t.end();return}let r=e.body.getReader();for(;;){let{done:o,value:l}=await r.read();if(o)break;t.write(l)}t.end()}function St(e,t={}){Tt();let r=t.port??Number(process.env.PORT??8080),o=t.hostname??"0.0.0.0",l=pr((d,f)=>{let s=`http://${d.headers.host??`${o}:${r}`}`,_=Er(d,s),b=yr(_,t.env);(b?Promise.resolve(b):e.handleRequest(_,t.env)).then((S)=>Tr(S,f)).catch(()=>{f.statusCode=500,f.end(JSON.stringify({error:"internal_error"}))})});return l.listen(r,o),l}var Ee=1;function Rt(e=process.env){let t=e.BUNDLE_URL?.trim(),r=e.BUNDLE_SHA256?.trim();if(!t)throw Error("BUNDLE_URL is not set; the runtime host has no code to run.");if(!r)throw Error("BUNDLE_SHA256 is not set; refusing to boot unverified code.");let o=Number(e.PORT??8080);if(!Number.isInteger(o)||o<=0)throw Error(`Invalid PORT: ${String(e.PORT)}`);return{bundleUrl:t,bundleSha256:r,port:o}}async function Or(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((o)=>o.toString(16).padStart(2,"0")).join("")}function vr(e){let t=JSON.parse(new TextDecoder().decode(e));if(!t||typeof t!=="object")throw Error("Boot artifact must be a JSON object.");let r=t;if(r.schemaVersion!==Ee)throw Error(`Unsupported boot artifact schemaVersion: ${String(r.schemaVersion)}.`);if(typeof r.runtimeVersion!=="string"||typeof r.mainEntry!=="string"||!Array.isArray(r.files))throw Error("Boot artifact is malformed.");let o=r.files.map((l)=>{if(!l||typeof l!=="object"||typeof l.path!=="string"||typeof l.content!=="string")throw Error("Boot artifact files must be { path, content }.");let d=l;return{path:d.path,content:d.content}});return{schemaVersion:Ee,runtimeVersion:r.runtimeVersion,mainEntry:r.mainEntry,files:o}}async function wt(e,t=fetch){let r=await t(e.bundleUrl);if(!r.ok)throw Error(`Bundle fetch failed (HTTP ${r.status}).`);let o=new Uint8Array(await r.arrayBuffer()),l=await Or(o);if(l!==e.bundleSha256.toLowerCase())throw Error(`Bundle sha256 mismatch (expected ${e.bundleSha256}, got ${l}).`);return vr(o)}function At(e,t){for(let r of e.files){let o=ye(t,r.path);Sr(br(o),{recursive:!0}),wr(o,r.content)}return{entryPath:ye(t,e.mainEntry)}}async function Mr(e={}){let t=e.bootConfig??Rt(),r=await wt(t,e.fetchImpl),o=e.workDir??Rr(ye(Ar(),"mcpcloud-server-")),{entryPath:l}=At(r,o),d=await import(Pr(l).href),f=d.server??d.default;if(!f)throw Error(`Boot module ${r.mainEntry} does not export a \`server\`.`);let s={port:t.port,...e.hostname?{hostname:e.hostname}:{},...e.env?{env:e.env}:{}};return St(f,s)}export{Ee as BOOT_ARTIFACT_SCHEMA_VERSION,wt as fetchAndVerifyBundle,At as materializeBundle,Rt as resolveBootConfig,Mr as serveFromBundle};
12
+ };`;var hr=Symbol.for("@mcpcloud/runtime.codeModeEngineProvider");function Et(e){globalThis[hr]=e}var yt=[`./${mt}/`,"../engine/vendor/","../../engine/vendor/"];function fr(e=new URL(import.meta.url)){for(let t of yt){let r=new URL(t,e);if(dr(new URL("emscripten-module.wasm",r)))return r}throw Error(`Code Mode engine not found. Looked for emscripten-module.wasm in: ${yt.join(", ")} (relative to ${e.href}).`)}function Tt(){Et(()=>pt(fr())())}function gr(e,t){let r=Buffer.from(e),o=Buffer.from(t);return r.length===o.length&&mr(r,o)}function Er(e,t){let r=je(t);if(!r)return null;if(new URL(e.url).pathname==="/health")return null;let o=e.headers.get("authorization")??"",l=/^Bearer\s+(.+)$/i.exec(o.trim());if(l&&gr(l[1].trim(),r))return null;return Response.json({error:"unauthorized",message:"This MCP endpoint requires a bearer token (set in Authorization: Bearer <token>)."},{status:401,headers:{"www-authenticate":"Bearer"}})}function yr(e,t){let r=new URL(e.url??"/",t),o=new Headers;for(let[f,s]of Object.entries(e.headers))if(Array.isArray(s))for(let _ of s)o.append(f,_);else if(typeof s==="string")o.set(f,s);let l=e.method??"GET",d=l==="GET"||l==="HEAD"?void 0:_r.toWeb(e);return new Request(r,{method:l,headers:o,body:d,...d?{duplex:"half"}:{}})}async function Tr(e,t){if(t.statusCode=e.status,e.headers.forEach((o,l)=>{t.setHeader(l,o)}),!e.body){t.end();return}let r=e.body.getReader();for(;;){let{done:o,value:l}=await r.read();if(o)break;t.write(l)}t.end()}function St(e,t={}){Tt();let r=t.port??Number(process.env.PORT??8080),o=t.hostname??"0.0.0.0",l=pr((d,f)=>{let s=`http://${d.headers.host??`${o}:${r}`}`,_=yr(d,s),b=Er(_,t.env);(b?Promise.resolve(b):e.handleRequest(_,t.env)).then((S)=>Tr(S,f)).catch(()=>{f.statusCode=500,f.end(JSON.stringify({error:"internal_error"}))})});return l.listen(r,o),l}var ye=1;function Rt(e=process.env){let t=e.BUNDLE_URL?.trim(),r=e.BUNDLE_SHA256?.trim();if(!t)throw Error("BUNDLE_URL is not set; the runtime host has no code to run.");if(!r)throw Error("BUNDLE_SHA256 is not set; refusing to boot unverified code.");let o=Number(e.PORT??8080);if(!Number.isInteger(o)||o<=0)throw Error(`Invalid PORT: ${String(e.PORT)}`);return{bundleUrl:t,bundleSha256:r,port:o}}async function Or(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((o)=>o.toString(16).padStart(2,"0")).join("")}function vr(e){let t=JSON.parse(new TextDecoder().decode(e));if(!t||typeof t!=="object")throw Error("Boot artifact must be a JSON object.");let r=t;if(r.schemaVersion!==ye)throw Error(`Unsupported boot artifact schemaVersion: ${String(r.schemaVersion)}.`);if(typeof r.runtimeVersion!=="string"||typeof r.mainEntry!=="string"||!Array.isArray(r.files))throw Error("Boot artifact is malformed.");let o=r.files.map((l)=>{if(!l||typeof l!=="object"||typeof l.path!=="string"||typeof l.content!=="string")throw Error("Boot artifact files must be { path, content }.");let d=l;return{path:d.path,content:d.content}});return{schemaVersion:ye,runtimeVersion:r.runtimeVersion,mainEntry:r.mainEntry,files:o}}async function wt(e,t=fetch){let r=await t(e.bundleUrl);if(!r.ok)throw Error(`Bundle fetch failed (HTTP ${r.status}).`);let o=new Uint8Array(await r.arrayBuffer()),l=await Or(o);if(l!==e.bundleSha256.toLowerCase())throw Error(`Bundle sha256 mismatch (expected ${e.bundleSha256}, got ${l}).`);return vr(o)}function At(e,t){for(let r of e.files){let o=Ee(t,r.path);Sr(br(o),{recursive:!0}),wr(o,r.content)}return{entryPath:Ee(t,e.mainEntry)}}async function Mr(e={}){let t=e.bootConfig??Rt(),r=await wt(t,e.fetchImpl),o=e.workDir??Rr(Ee(Ar(),"mcpcloud-server-")),{entryPath:l}=At(r,o),d=await import(Pr(l).href),f=d.server??d.default;if(!f)throw Error(`Boot module ${r.mainEntry} does not export a \`server\`.`);let s={port:t.port,...e.hostname?{hostname:e.hostname}:{},...e.env?{env:e.env}:{}};return St(f,s)}export{ye as BOOT_ARTIFACT_SCHEMA_VERSION,wt as fetchAndVerifyBundle,At as materializeBundle,Rt as resolveBootConfig,Mr as serveFromBundle};
package/dist/http.d.ts CHANGED
@@ -14,6 +14,22 @@ export declare function parseUpstreamResponse(response: Response): Promise<unkno
14
14
  * unparseable is dropped rather than guessed at.
15
15
  */
16
16
  export declare function parseRetryAfterSeconds(headerValue: string | null): number | null;
17
- export declare function mapUpstreamError(tool: ToolDefinition, status: number, payload: unknown, retryAfterSeconds?: number | null): UpstreamHttpError;
18
- export declare function normalizeUpstreamPayload(tool: ToolDefinition, response: Response, payload: unknown): unknown;
17
+ /**
18
+ * What to tell a caller whose UPSTREAM refused their credential.
19
+ *
20
+ * This is the dead end both integrator reports describe. Under per-member
21
+ * custody a revoked or rotated key makes every call fail with the upstream's
22
+ * own `invalid_token`, and nothing in that answer says where the key lives.
23
+ * Worse, an MCP client's reconnect reports "Authentication successful" —
24
+ * truthfully, because it re-authenticated to MCPCloud, which was never the
25
+ * thing that was broken. The agent retries and fails identically, forever.
26
+ *
27
+ * So the runtime says the part only it knows: whose key it was, and the page
28
+ * that replaces it. Only for 401/403, only under per-member custody, and only
29
+ * after the handler's one forced refresh has already failed — a shared-key
30
+ * server's 401 is the operator's problem and no end user can act on it.
31
+ */
32
+ export declare function describeRefusedMemberCredential(status: number, config: Pick<RuntimeConfig, 'memberKey' | 'serverName'> | null | undefined): string | null;
33
+ export declare function mapUpstreamError(tool: ToolDefinition, status: number, payload: unknown, retryAfterSeconds?: number | null, config?: Pick<RuntimeConfig, 'memberKey' | 'serverName'> | null): UpstreamHttpError;
34
+ export declare function normalizeUpstreamPayload(tool: ToolDefinition, response: Response, payload: unknown, config?: Pick<RuntimeConfig, 'memberKey' | 'serverName'> | null): unknown;
19
35
  export declare function formatToolResultText(tool: ToolDefinition, payload: unknown): string;
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ export type { EndpointDefinition, ErrorMappingDefinition, SecuritySchemeDefiniti
9
9
  export { getProcessEnv, postOAuthRuntimeRequest, resolveRuntimeAccessMode, resolveRuntimeConfig, } from './config';
10
10
  export type { CallerContext, RuntimeAccessConfig, RuntimeAccessMode, RuntimeConfig, RuntimeEnv, RuntimeOAuthConfig, ServerIdentity, } from './config';
11
11
  export { buildUpstreamHeaders, hasOauthSecurity, resolveUseOAuth, } from './auth-headers';
12
- export { buildUpstreamRequest, encodeFormUrlencodedBody, formatToolResultText, mapUpstreamError, normalizeUpstreamPayload, parseUpstreamResponse, } from './http';
12
+ export { buildUpstreamRequest, encodeFormUrlencodedBody, formatToolResultText, describeRefusedMemberCredential, mapUpstreamError, normalizeUpstreamPayload, parseUpstreamResponse, } from './http';
13
13
  export { authorizeRuntimeRequest, describeRuntimeAccess, isProtectedRuntimeAccessMode, } from './access';
14
14
  export type { RuntimeAuthorization } from './access';
15
15
  export { assertValidInput } from './validation';