@mcpcloud/runtime 0.17.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.js CHANGED
@@ -1,10 +1,10 @@
1
- /*! @mcpcloud/runtime v0.17.2 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
- var Tt=Object.create;var{getPrototypeOf:yt,defineProperty:re,getOwnPropertyNames:St}=Object;var De=Object.prototype.hasOwnProperty;function Rt(e){return this[e]}var wt,Pt,At=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var l=t?wt??=new WeakMap:Pt??=new WeakMap,d=l.get(e);if(d)return d}n=e!=null?Tt(yt(e)):{};let m=t||!e||!e.__esModule||!De.call(e,"default")?re(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of St(e))if(!De.call(m,s))re(m,s,{get:Rt.bind(e,s),enumerable:!0})}if(o)l.set(e,m);return m};var bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ot=(e)=>e;function Mt(e,t){this[e]=Ot.bind(null,t)}var vt=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Mt.bind(t,n)})};var ne=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(o){n=[o]}if(n)throw n[0];return t};var U,ie,j,K,J;var 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},J={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function H(...e){ce&&console.log("quickjs-emscripten:",...e)}function*st(e){return yield e}function Ut(e){return st(de(e))}function je(e,t){return(...n)=>{let o=t.call(e,he,...n);return de(o)}}function Kt(e,t){let n=t.call(e,he);return de(n)}function de(e){function t(n){return n.done?n.value:n.value instanceof Promise?n.value.then((o)=>t(e.next(o)),(o)=>t(e.throw(o))):t(e.next(n.value))}return t(e.next())}function se(e,t){let n;try{e.dispose()}catch(o){n=o}if(t&&n)throw Object.assign(t,{message:`${t.message}
3
- Then, failed to dispose scope: ${n.message}`,disposeError:n}),t;if(t||n)throw t||n}function Yt(e){let t=e?Array.from(e):[];function n(){return t.forEach((l)=>l.alive?l.dispose():void 0)}function o(){return t.some((l)=>l.alive)}return Object.defineProperty(t,le,{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:o}),t}function W(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Ft(e){if(!e)return 0;let t=0;for(let[n,o]of Object.entries(e)){if(!(n in ie))throw new tt(n);o&&(t|=ie[n])}return t}function Dt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:n,strip:o,compileOnly:l,backtraceBarrier:d}=e,m=0;return t==="global"&&(m|=U.JS_EVAL_TYPE_GLOBAL),t==="module"&&(m|=U.JS_EVAL_TYPE_MODULE),n&&(m|=U.JS_EVAL_FLAG_STRICT),o&&(m|=U.JS_EVAL_FLAG_STRIP),l&&(m|=U.JS_EVAL_FLAG_COMPILE_ONLY),d&&(m|=U.JS_EVAL_FLAG_BACKTRACE_BARRIER),m}function Qt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:n,quickjsPrivate:o,onlyEnumerable:l,numbers:d,numbersAsStrings:m}=e,s=0;return t&&(s|=K.JS_GPN_STRING_MASK),n&&(s|=K.JS_GPN_SYMBOL_MASK),o&&(s|=K.JS_GPN_PRIVATE_MASK),l&&(s|=K.JS_GPN_ENUM_ONLY),d&&(s|=K.QTS_GPN_NUMBER_MASK),m&&(s|=K.QTS_STANDARD_COMPLIANT_NUMBER),s}function jt(...e){let t=[];for(let n of e)n!==void 0&&(t=t.concat(n));return t}function oe(e){return e>>8}function pe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function _e(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var Nt,kt=(e,t)=>{for(var n in t)Nt(e,n,{get:t[n],enumerable:!0})},ce=!1,Ct,ae,ze,ue,Xe,Ze,et,It,Lt,tt,rt,nt,it,I,he,N,le,$e,P,Y,Ve,v,fe,Bt,Jt,B,Ht,ot=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((l)=>l.value)),n=t.length*t.BYTES_PER_ELEMENT,o=this.module._malloc(n);return new Uint8Array(this.module.HEAPU8.buffer,o,n).set(new Uint8Array(t.buffer)),new P(o,void 0,(l)=>this.module._free(l))}newTypedArray(e,t){let n=new e(Array(t).fill(0)),o=n.length*n.BYTES_PER_ELEMENT,l=this.module._malloc(o),d=new e(this.module.HEAPU8.buffer,l,t);return d.set(n),new P({typedArray:d,ptr:l},void 0,(m)=>this.module._free(m.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),n=t+1,o=this.module._malloc(n);return this.module.stringToUTF8(e,o,n),new P({ptr:o,strlen:t},void 0,(l)=>this.module._free(l.ptr))}newHeapBufferPointer(e){let t=e.byteLength,n=this.module._malloc(t);return this.module.HEAPU8.set(e,n),new P({pointer:n,numBytes:t},void 0,(o)=>this.module._free(o.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Sr,Rr,$t,Ge=-2147483648,We=2147483647,G=0,Vt=class{constructor(){this.nextId=Ge,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),n=oe(t),o=this.groups.get(n);return o||(o=new Map,this.groups.set(n,o)),o.set(t,e),t}get(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new I(`host reference id ${e} is not defined`);let o=n.get(e);if(!o)throw new I(`host reference id ${e} is not defined`);return o}delete(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new I(`host reference id ${e} is not defined`);n.delete(e),n.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===G&&this.nextId++,this.nextId>We)throw new it(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${We-Ge}`);return this.nextId++}},qe,Gt,Wt,qt,zt=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},me=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new zt({freeHostRef:(t,n,o)=>{let l=this.runtimeCallbacks.get(n);if(!l)throw Error(`QuickJSRuntime(rt = ${n}) not found when trying to free HostRef(id = ${o})`);l.freeHostRef(n,o)},callFunction:(t,n,o,l,d,m)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(n);if(!s)throw Error(`QuickJSContext(ctx = ${n}) not found for C function call "${m}"`);return s.callFunction(n,o,l,d,m)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,n)=>this.handleAsyncify(t,()=>{try{let o=this.runtimeCallbacks.get(n);if(!o)throw Error(`QuickJSRuntime(rt = ${n}) not found for C interrupt`);return o.shouldInterrupt(n)}catch(o){return console.error("[C to host interrupt: returning error]",o),1}}),loadModuleSource:(t,n,o,l)=>this.handleAsyncify(t,()=>{try{let d=this.runtimeCallbacks.get(n);if(!d)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let m=d.loadModuleSource;if(!m)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return m(n,o,l)}catch(d){return console.error("[C to host module loader error: returning null]",d),0}}),normalizeModule:(t,n,o,l,d)=>this.handleAsyncify(t,()=>{try{let m=this.runtimeCallbacks.get(n);if(!m)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let s=m.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return s(n,o,l,d)}catch(m){return console.error("[C to host module loader error: returning null]",m),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((o)=>{try{let l=t();if(!(l instanceof Promise)){H("asyncify.handleSleep: not suspending:",l),o(l);return}if(this.suspended)throw new Ze(`Already suspended at: ${this.suspended.stack}
4
- Attempted to suspend at:`);this.suspended=new et(`(${this.suspendedCount++})`),H("asyncify.handleSleep: suspending:",this.suspended),l.then((d)=>{this.suspended=void 0,H("asyncify.handleSleep: resolved:",d),o(d)},(d)=>{H("asyncify.handleSleep: rejected:",d),console.error("QuickJS: cannot handle error in suspended function",d),this.suspended=void 0})}catch(l){throw H("asyncify.handleSleep: error:",l),this.suspended=void 0,l}});let n=t();if(n instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return n}},at=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new me(e)}newRuntime(e={}){let t=new P(this.ffi.QTS_NewRuntime(),void 0,(o)=>{this.ffi.QTS_FreeRuntime(o),this.callbacks.deleteRuntime(o)}),n=new qt({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return pe(n,e),e.moduleLoader&&n.setModuleLoader(e.moduleLoader),n}newContext(e={}){let t=this.newRuntime(),n=t.newContext({...e,ownedLifetimes:jt(t,e.ownedLifetimes)});return t.context=n,n}evalCode(e,t={}){return v.withScope((n)=>{let o=n.manage(this.newContext());_e(o.runtime,t);let l=o.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&o.runtime.setMemoryLimit(-1),l.error)throw o.dump(n.manage(l.error));return o.dump(n.manage(l.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var ut=ne(()=>{V();V();Nt=Object.defineProperty;Ct={};kt(Ct,{QuickJSAsyncifyError:()=>Ze,QuickJSAsyncifySuspended:()=>et,QuickJSEmptyGetOwnPropertyNames:()=>nt,QuickJSEmscriptenModuleError:()=>Lt,QuickJSHostRefInvalid:()=>I,QuickJSHostRefRangeExceeded:()=>it,QuickJSMemoryLeakDetected:()=>It,QuickJSNotImplemented:()=>Xe,QuickJSPromisePending:()=>rt,QuickJSUnknownIntrinsic:()=>tt,QuickJSUnwrapError:()=>ae,QuickJSUseAfterFree:()=>ue,QuickJSWrongOwner:()=>ze});ae=class extends Error{constructor(e,t){let n=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(n);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},ue=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},Xe=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},Ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},et=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},It=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Lt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},tt=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},rt=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},nt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},it=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},I=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};he=st;he.of=Ut;N=class{[Symbol.dispose](){return this.dispose()}},le=Symbol.dispose??Symbol.for("Symbol.dispose"),$e=N.prototype;$e[le]||($e[le]=function(){return this.dispose()});P=class e extends N{constructor(t,n,o,l){super();this._value=t,this.copier=n,this.disposer=o,this._owner=l,this._alive=!0,this._constructorStack=ce?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let n=t(this);return this.dispose(),n}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ue(`Lifetime not alive
1
+ /*! @mcpcloud/runtime v0.18.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
+ var Tt=Object.create;var{getPrototypeOf:yt,defineProperty:re,getOwnPropertyNames:St}=Object;var De=Object.prototype.hasOwnProperty;function Rt(e){return this[e]}var wt,Pt,At=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var l=t?wt??=new WeakMap:Pt??=new WeakMap,d=l.get(e);if(d)return d}n=e!=null?Tt(yt(e)):{};let m=t||!e||!e.__esModule||!De.call(e,"default")?re(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of St(e))if(!De.call(m,s))re(m,s,{get:Rt.bind(e,s),enumerable:!0})}if(o)l.set(e,m);return m};var bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ot=(e)=>e;function Mt(e,t){this[e]=Ot.bind(null,t)}var vt=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Mt.bind(t,n)})};var ne=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(o){n=[o]}if(n)throw n[0];return t};var U,ie,j,K,J;var 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},J={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function F(...e){ce&&console.log("quickjs-emscripten:",...e)}function*st(e){return yield e}function Ut(e){return st(de(e))}function je(e,t){return(...n)=>{let o=t.call(e,he,...n);return de(o)}}function Kt(e,t){let n=t.call(e,he);return de(n)}function de(e){function t(n){return n.done?n.value:n.value instanceof Promise?n.value.then((o)=>t(e.next(o)),(o)=>t(e.throw(o))):t(e.next(n.value))}return t(e.next())}function se(e,t){let n;try{e.dispose()}catch(o){n=o}if(t&&n)throw Object.assign(t,{message:`${t.message}
3
+ Then, failed to dispose scope: ${n.message}`,disposeError:n}),t;if(t||n)throw t||n}function Yt(e){let t=e?Array.from(e):[];function n(){return t.forEach((l)=>l.alive?l.dispose():void 0)}function o(){return t.some((l)=>l.alive)}return Object.defineProperty(t,le,{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:o}),t}function W(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Ht(e){if(!e)return 0;let t=0;for(let[n,o]of Object.entries(e)){if(!(n in ie))throw new tt(n);o&&(t|=ie[n])}return t}function Dt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:n,strip:o,compileOnly:l,backtraceBarrier:d}=e,m=0;return t==="global"&&(m|=U.JS_EVAL_TYPE_GLOBAL),t==="module"&&(m|=U.JS_EVAL_TYPE_MODULE),n&&(m|=U.JS_EVAL_FLAG_STRICT),o&&(m|=U.JS_EVAL_FLAG_STRIP),l&&(m|=U.JS_EVAL_FLAG_COMPILE_ONLY),d&&(m|=U.JS_EVAL_FLAG_BACKTRACE_BARRIER),m}function Qt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:n,quickjsPrivate:o,onlyEnumerable:l,numbers:d,numbersAsStrings:m}=e,s=0;return t&&(s|=K.JS_GPN_STRING_MASK),n&&(s|=K.JS_GPN_SYMBOL_MASK),o&&(s|=K.JS_GPN_PRIVATE_MASK),l&&(s|=K.JS_GPN_ENUM_ONLY),d&&(s|=K.QTS_GPN_NUMBER_MASK),m&&(s|=K.QTS_STANDARD_COMPLIANT_NUMBER),s}function jt(...e){let t=[];for(let n of e)n!==void 0&&(t=t.concat(n));return t}function oe(e){return e>>8}function pe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function _e(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var Nt,Ct=(e,t)=>{for(var n in t)Nt(e,n,{get:t[n],enumerable:!0})},ce=!1,kt,ae,ze,ue,Xe,Ze,et,It,Lt,tt,rt,nt,it,I,he,N,le,$e,P,Y,Ve,v,fe,Bt,Jt,B,Ft,ot=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((l)=>l.value)),n=t.length*t.BYTES_PER_ELEMENT,o=this.module._malloc(n);return new Uint8Array(this.module.HEAPU8.buffer,o,n).set(new Uint8Array(t.buffer)),new P(o,void 0,(l)=>this.module._free(l))}newTypedArray(e,t){let n=new e(Array(t).fill(0)),o=n.length*n.BYTES_PER_ELEMENT,l=this.module._malloc(o),d=new e(this.module.HEAPU8.buffer,l,t);return d.set(n),new P({typedArray:d,ptr:l},void 0,(m)=>this.module._free(m.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),n=t+1,o=this.module._malloc(n);return this.module.stringToUTF8(e,o,n),new P({ptr:o,strlen:t},void 0,(l)=>this.module._free(l.ptr))}newHeapBufferPointer(e){let t=e.byteLength,n=this.module._malloc(t);return this.module.HEAPU8.set(e,n),new P({pointer:n,numBytes:t},void 0,(o)=>this.module._free(o.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Sr,Rr,$t,Ge=-2147483648,We=2147483647,G=0,Vt=class{constructor(){this.nextId=Ge,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),n=oe(t),o=this.groups.get(n);return o||(o=new Map,this.groups.set(n,o)),o.set(t,e),t}get(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new I(`host reference id ${e} is not defined`);let o=n.get(e);if(!o)throw new I(`host reference id ${e} is not defined`);return o}delete(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new I(`host reference id ${e} is not defined`);n.delete(e),n.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===G&&this.nextId++,this.nextId>We)throw new it(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${We-Ge}`);return this.nextId++}},qe,Gt,Wt,qt,zt=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},me=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new zt({freeHostRef:(t,n,o)=>{let l=this.runtimeCallbacks.get(n);if(!l)throw Error(`QuickJSRuntime(rt = ${n}) not found when trying to free HostRef(id = ${o})`);l.freeHostRef(n,o)},callFunction:(t,n,o,l,d,m)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(n);if(!s)throw Error(`QuickJSContext(ctx = ${n}) not found for C function call "${m}"`);return s.callFunction(n,o,l,d,m)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,n)=>this.handleAsyncify(t,()=>{try{let o=this.runtimeCallbacks.get(n);if(!o)throw Error(`QuickJSRuntime(rt = ${n}) not found for C interrupt`);return o.shouldInterrupt(n)}catch(o){return console.error("[C to host interrupt: returning error]",o),1}}),loadModuleSource:(t,n,o,l)=>this.handleAsyncify(t,()=>{try{let d=this.runtimeCallbacks.get(n);if(!d)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let m=d.loadModuleSource;if(!m)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return m(n,o,l)}catch(d){return console.error("[C to host module loader error: returning null]",d),0}}),normalizeModule:(t,n,o,l,d)=>this.handleAsyncify(t,()=>{try{let m=this.runtimeCallbacks.get(n);if(!m)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let s=m.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return s(n,o,l,d)}catch(m){return console.error("[C to host module loader error: returning null]",m),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((o)=>{try{let l=t();if(!(l instanceof Promise)){F("asyncify.handleSleep: not suspending:",l),o(l);return}if(this.suspended)throw new Ze(`Already suspended at: ${this.suspended.stack}
4
+ Attempted to suspend at:`);this.suspended=new et(`(${this.suspendedCount++})`),F("asyncify.handleSleep: suspending:",this.suspended),l.then((d)=>{this.suspended=void 0,F("asyncify.handleSleep: resolved:",d),o(d)},(d)=>{F("asyncify.handleSleep: rejected:",d),console.error("QuickJS: cannot handle error in suspended function",d),this.suspended=void 0})}catch(l){throw F("asyncify.handleSleep: error:",l),this.suspended=void 0,l}});let n=t();if(n instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return n}},at=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new me(e)}newRuntime(e={}){let t=new P(this.ffi.QTS_NewRuntime(),void 0,(o)=>{this.ffi.QTS_FreeRuntime(o),this.callbacks.deleteRuntime(o)}),n=new qt({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return pe(n,e),e.moduleLoader&&n.setModuleLoader(e.moduleLoader),n}newContext(e={}){let t=this.newRuntime(),n=t.newContext({...e,ownedLifetimes:jt(t,e.ownedLifetimes)});return t.context=n,n}evalCode(e,t={}){return v.withScope((n)=>{let o=n.manage(this.newContext());_e(o.runtime,t);let l=o.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&o.runtime.setMemoryLimit(-1),l.error)throw o.dump(n.manage(l.error));return o.dump(n.manage(l.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var ut=ne(()=>{V();V();Nt=Object.defineProperty;kt={};Ct(kt,{QuickJSAsyncifyError:()=>Ze,QuickJSAsyncifySuspended:()=>et,QuickJSEmptyGetOwnPropertyNames:()=>nt,QuickJSEmscriptenModuleError:()=>Lt,QuickJSHostRefInvalid:()=>I,QuickJSHostRefRangeExceeded:()=>it,QuickJSMemoryLeakDetected:()=>It,QuickJSNotImplemented:()=>Xe,QuickJSPromisePending:()=>rt,QuickJSUnknownIntrinsic:()=>tt,QuickJSUnwrapError:()=>ae,QuickJSUseAfterFree:()=>ue,QuickJSWrongOwner:()=>ze});ae=class extends Error{constructor(e,t){let n=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(n);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},ue=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},Xe=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},Ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},et=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},It=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Lt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},tt=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},rt=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},nt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},it=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},I=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};he=st;he.of=Ut;N=class{[Symbol.dispose](){return this.dispose()}},le=Symbol.dispose??Symbol.for("Symbol.dispose"),$e=N.prototype;$e[le]||($e[le]=function(){return this.dispose()});P=class e extends N{constructor(t,n,o,l){super();this._value=t,this.copier=n,this.disposer=o,this._owner=l,this._alive=!0,this._constructorStack=ce?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let n=t(this);return this.dispose(),n}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ue(`Lifetime not alive
5
5
  ${this._constructorStack}
6
- Lifetime used`):new ue("Lifetime not alive")}},Y=class extends P{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},Ve=class extends P{constructor(e,t,n,o){super(e,t,n,o)}dispose(){this._alive=!1}};v=class e extends N{constructor(){super(...arguments);this._disposables=new P(new Set),this.manage=(t)=>(this._disposables.value.add(t),t)}static withScope(t){let n=new e,o;try{return t(n)}catch(l){throw o=l,l}finally{se(n,o)}}static withScopeMaybeAsync(t,n){return Kt(void 0,function*(o){let l=new e,d;try{return yield*o.of(n.call(t,o,l))}catch(m){throw d=m,m}finally{se(l,d)}})}static async withScopeAsync(t){let n=new e,o;try{return await t(n)}catch(l){throw o=l,l}finally{se(n,o)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let n of t)n.alive&&n.dispose();this._disposables.dispose()}};fe=class e extends N{static success(t){return new Bt(t)}static fail(t,n){return new Jt(t,n)}static is(t){return t instanceof e}},Bt=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}},Jt=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}},B=fe,Ht=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()}},Sr=Symbol("Unstable"),Rr=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});$t=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 n=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),n}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof P?e:this.context.newError(e),n=this.context.getProp(this.handle,"throw"),o=this.callIteratorMethod(n,e);return t.alive&&t.dispose(),n.dispose(),this.dispose(),o}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let n=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(n.error)return this.dispose(),{value:n};let o=this.context.getProp(n.value,"done").consume((d)=>this.context.dump(d)),l=this.context.getProp(n.value,"value");return n.value.dispose(),o&&this.dispose(),{value:B.success(l),done:o}}};qe=class extends N{constructor(e,t,n){if(n===G)throw new I("cannot create HostRef with undefined id");super();this.runtime=e,this.handle=t,this.id=n}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},Gt=class extends ot{constructor(e){super(e.module);this.scope=new v,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 n=t?(o)=>{t(),this.freeJSValue(o)}:this.freeJSValue;return new P(e,this.copyJSValue,n,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new Y(e,this.owner)}},Wt=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,n,o,l,d)=>{if(t!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let m=this.getFunction(d);return v.withScopeMaybeAsync(this,function*(s,_){let A=_.manage(new Ve(n,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 Ve(k,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let S=yield*s(m.apply(A,x));if(S){if("error"in S&&S.error)throw this.runtime.debugLog("throw error",S.error),S.error;let k=_.manage(S instanceof P?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 Gt({...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 Y(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new Y(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new Y(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new Y(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((n)=>this.ffi.QTS_NewString(this.ctx.value,n.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",n=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,0));return this.memory.heapValueHandle(n)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",n=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,1));return this.memory.heapValueHandle(n)}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 Y(o.value,this.runtime)}let t=this._BigInt,n=String(e);return this.newString(n).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),n=this.memory.newHeapBufferPointer(t),o=this.ffi.QTS_NewArrayBuffer(this.ctx.value,n.value.pointer,t.length);return this.memory.heapValueHandle(o)}newPromise(e){let t=v.withScope((n)=>{let o=n.manage(this.memory.newMutablePointerArray(2)),l=this.ffi.QTS_NewPromiseCapability(this.ctx.value,o.value.ptr),d=this.memory.heapValueHandle(l),[m,s]=Array.from(o.value.typedArray).map((_)=>this.memory.heapValueHandle(_));return new Ht({context:this,promiseHandle:d,resolveHandle:m,rejectHandle:s})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,(n)=>n instanceof P?t.reject(n):this.newError(n).consume(t.reject)),t}newFunction(e,t){let n=typeof e=="function"?e:t;if(!n)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:n.length,isConstructor:!1,fn:n})}newConstructorFunction(e,t){let n=typeof e=="function"?e:t;if(!n)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:n.length,isConstructor:!0,fn:n})}newFunctionWithOptions(e){let{name:t,length:n,isConstructor:o,fn:l}=e,d=this.runtime.hostRefs.put(l);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",n,o,d))}catch(m){throw this.runtime.hostRefs.delete(d),m}}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((n)=>this.setProp(t,"name",n)),e.message!==void 0&&this.newString(e.message).consume((n)=>this.setProp(t,"message",n))):typeof e=="string"?this.newString(e).consume((n)=>this.setProp(t,"message",n)):e!==void 0&&this.newString(String(e)).consume((n)=>this.setProp(t,"message",n)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let n=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new qe(this.runtime,n,t)}catch(n){throw this.runtime.hostRefs.delete(t),n}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new qe(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),n=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!n)throw Error("Couldn't allocate memory to get ArrayBuffer");return new P(this.module.HEAPU8.subarray(n,n+t),void 0,()=>this.module._free(n))}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 rt("Cannot unwrap a pending promise")}};let n=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),o=this.memory.heapValueHandle(n);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=v.withScope((n)=>{let o=n.manage(this.getProp(this.global,"Promise")),l=n.manage(this.getProp(o,"resolve"));return this.callFunction(l,o,e)});return t.error?Promise.resolve(t):new Promise((n)=>{v.withScope((o)=>{let l=o.manage(this.newFunction("resolve",(_)=>{n(this.success(_&&_.dup()))})),d=o.manage(this.newFunction("reject",(_)=>{n(this.fail(_&&_.dup()))})),m=o.manage(t.value),s=o.manage(this.getProp(m,"then"));this.callFunction(s,m,l,d).unwrap().dispose()})})}isEqual(e,t,n=J.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,n);if(o===-1)throw new Xe("WASM variant does not expose equality");return!!o}eq(e,t){return this.isEqual(e,t,J.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,J.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,J.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let n;return typeof t=="number"&&t>=0?n=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):n=this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_GetProp(this.ctx.value,e.value,o.value)),this.memory.heapValueHandle(n)}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 n=Qt(t);if(n===0)throw new nt("No options set, will return an empty array");return v.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,n);if(d)return this.fail(this.memory.heapValueHandle(d));let m=this.uint32Out.value.typedArray[0],s=l.value.typedArray[0],_=new Uint32Array(this.module.HEAP8.buffer,s,m),A=Array.from(_).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,s),this.success(Yt(A))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return v.withScope((n)=>{let o=n.manage(this.getProp(e,t)),l=this.callFunction(o,e);return l.error?l:this.success(new $t(l.value,this))})}setProp(e,t,n){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_SetProp(this.ctx.value,e.value,o.value,n.value))}defineProp(e,t,n){this.runtime.assertOwned(e),v.withScope((o)=>{let l=o.manage(this.borrowPropertyKey(t)),d=n.value||this.undefined,m=!!n.configurable,s=!!n.enumerable,_=!!n.value,A=n.get?o.manage(this.newFunction(n.get.name,n.get)):this.undefined,x=n.set?o.manage(this.newFunction(n.set.name,n.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,l.value,d.value,A.value,x.value,m,s,_)})}callFunction(e,t,...n){this.runtime.assertOwned(e);let o,l=n[0];l===void 0||Array.isArray(l)?o=l??[]:o=n;let d=this.memory.toPointerArray(o).consume((s)=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,o.length,s.value)),m=this.ffi.QTS_ResolveException(this.ctx.value,d);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(m))):this.success(this.memory.heapValueHandle(d))}callMethod(e,t,n=[]){return this.getProp(e,t).consume((o)=>this.callFunction(o,e,n))}evalCode(e,t="eval.js",n){let o=n===void 0?1:0,l=Dt(n),d=this.memory.newHeapCharPointer(e).consume((s)=>this.ffi.QTS_Eval(this.ctx.value,s.value.ptr,s.value.strlen,t,o,l)),m=this.ffi.QTS_ResolveException(this.ctx.value,d);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(m))):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 Y(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 n=this.getPromiseState(e);if(n.type==="fulfilled"&&!n.notAPromise)return e.dispose(),{type:n.type,value:n.value.consume(this.dump)};if(n.type==="pending")return e.dispose(),{type:n.type};if(n.type==="rejected")return e.dispose(),{type:n.type,error:n.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,n=e.error.consume((o)=>this.dump(o));if(n&&typeof n=="object"&&typeof n.message=="string"){let{message:o,name:l,stack:d,...m}=n,s=new ae(n,t);typeof l=="string"&&(s.name=n.name),s.message=o;let _=s.stack;throw typeof d=="string"&&(s.stack=`${l}: ${o}
7
- ${n.stack}Host: ${_}`),Object.assign(s,m),s}throw new ae(n)}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 P?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 B.success(e)}fail(e){return B.fail(e,(t)=>this.unwrapResult(t))}},qt=class extends N{constructor(e){super();this.scope=new v,this.contextMap=new Map,this.hostRefs=new Vt,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(t,n)=>{if(t!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(n)},shouldInterrupt:(t)=>{if(t!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let n=this.interruptHandler;if(!n)throw Error("QuickJSContext had no interrupt handler");return n(this)?1:0},loadModuleSource:je(this,function*(t,n,o,l){let d=this.moduleLoader;if(!d)throw Error("Runtime has no module loader");if(n!==this.rt.value)throw Error("Runtime pointer mismatch");let m=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let s=yield*t(d(l,m));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),m.throw(s),0}}),normalizeModule:je(this,function*(t,n,o,l,d){let m=this.moduleNormalizer;if(!m)throw Error("Runtime has no module normalizer");if(n!==this.rt.value)throw Error("Runtime pointer mismatch");let s=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let _=yield*t(m(l,d,s));if(typeof _=="object"&&"error"in _&&_.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",_.error),_.error;let A=typeof _=="string"?_:_.value;return s.getMemory(this.rt.value).newHeapCharPointer(A).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 ot(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=Ft(e.intrinsics),n=new P(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 Wt({module:this.module,ctx:n,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(n.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),n=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,n),B.success(0);let l=this.contextMap.get(o)??this.newContext({contextPointer:o}),d=l.getMemory(this.rt.value).heapValueHandle(n);if(l.typeof(d)==="number"){let m=l.getNumber(d);return d.dispose(),B.success(m)}else{let m=Object.assign(d,{context:l});return B.fail(m,(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 ze(`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 lt={};vt(lt,{QuickJSModuleCallbacks:()=>me,QuickJSWASMModule:()=>at,applyBaseRuntimeOptions:()=>pe,applyModuleEvalRuntimeOptions:()=>_e});var ct=ne(()=>{ut()});var _t=bt(function(q,pt){(function(e,t){typeof q==="object"&&typeof pt<"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=(r)=>r!==null&&Object.prototype.toString.call(r)==="[object Object]",n=(r,i)=>{if(r===i)return!0;if(typeof r!==typeof i)return!1;if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let a=0;a<r.length;a+=1)if(!n(r[a],i[a]))return!1;return!0}if(t(r)&&t(i)){let a=Object.entries(r),u=new Set(Object.keys(i));if(a.length!==u.size)return!1;for(let[h,f]of a){if(!n(f,i[h]))return!1;u.delete(h)}return u.size===0}return!1},o=(r)=>{if(r===""||r===!1||r===null||r===void 0)return!0;if(Array.isArray(r)&&r.length===0)return!0;if(t(r)){for(let i in r)if(r.hasOwnProperty(i))return!1;return!0}return!1},l=(r)=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_",d=(r)=>r>="0"&&r<="9"||r==="-",m=(r)=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_";var s;(function(r){r.TOK_EOF="EOF",r.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",r.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",r.TOK_RBRACKET="Rbracket",r.TOK_RPAREN="Rparen",r.TOK_COMMA="Comma",r.TOK_COLON="Colon",r.TOK_RBRACE="Rbrace",r.TOK_NUMBER="Number",r.TOK_CURRENT="Current",r.TOK_ROOT="Root",r.TOK_EXPREF="Expref",r.TOK_PIPE="Pipe",r.TOK_OR="Or",r.TOK_AND="And",r.TOK_EQ="EQ",r.TOK_GT="GT",r.TOK_LT="LT",r.TOK_GTE="GTE",r.TOK_LTE="LTE",r.TOK_NE="NE",r.TOK_FLATTEN="Flatten",r.TOK_STAR="Star",r.TOK_FILTER="Filter",r.TOK_DOT="Dot",r.TOK_NOT="Not",r.TOK_LBRACE="Lbrace",r.TOK_LBRACKET="Lbracket",r.TOK_LPAREN="Lparen",r.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},A={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class S{constructor(){this._current=0}tokenize(r){let i=[];this._current=0;let a,u,h;while(this._current<r.length)if(l(r[this._current]))a=this._current,u=this.consumeUnquotedIdentifier(r),i.push({start:a,type:s.TOK_UNQUOTEDIDENTIFIER,value:u});else if(_[r[this._current]]!==void 0)i.push({start:this._current,type:_[r[this._current]],value:r[this._current]}),this._current+=1;else if(d(r[this._current]))h=this.consumeNumber(r),i.push(h);else if(r[this._current]==="[")h=this.consumeLBracket(r),i.push(h);else if(r[this._current]==='"')a=this._current,u=this.consumeQuotedIdentifier(r),i.push({start:a,type:s.TOK_QUOTEDIDENTIFIER,value:u});else if(r[this._current]==="'")a=this._current,u=this.consumeRawStringLiteral(r),i.push({start:a,type:s.TOK_LITERAL,value:u});else if(r[this._current]==="`"){a=this._current;let f=this.consumeLiteral(r);i.push({start:a,type:s.TOK_LITERAL,value:f})}else if(A[r[this._current]]!==void 0)h=this.consumeOperator(r),h&&i.push(h);else if(x[r[this._current]]!==void 0)this._current+=1;else if(r[this._current]==="&")if(a=this._current,this._current+=1,r[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(r[this._current]==="|")if(a=this._current,this._current+=1,r[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 f=Error(`Unknown character: ${r[this._current]}`);throw f.name="LexerError",f}return i}consumeUnquotedIdentifier(r){let i=this._current;this._current+=1;while(this._current<r.length&&m(r[this._current]))this._current+=1;return r.slice(i,this._current)}consumeQuotedIdentifier(r){let i=this._current;this._current+=1;let a=r.length;while(r[this._current]!=='"'&&this._current<a){let u=this._current;if(r[u]==="\\"&&(r[u+1]==="\\"||r[u+1]==='"'))u+=2;else u+=1;this._current=u}return this._current+=1,JSON.parse(r.slice(i,this._current))}consumeRawStringLiteral(r){let i=this._current;this._current+=1;let a=r.length;while(r[this._current]!=="'"&&this._current<a){let h=this._current;if(r[h]==="\\"&&(r[h+1]==="\\"||r[h+1]==="'"))h+=2;else h+=1;this._current=h}return this._current+=1,r.slice(i+1,this._current-1).replace("\\'","'")}consumeNumber(r){let i=this._current;this._current+=1;let a=r.length;while(d(r[this._current])&&this._current<a)this._current+=1;let u=parseInt(r.slice(i,this._current),10);return{start:i,value:u,type:s.TOK_NUMBER}}consumeLBracket(r){let i=this._current;if(this._current+=1,r[this._current]==="?")return this._current+=1,{start:i,type:s.TOK_FILTER,value:"[?"};if(r[this._current]==="]")return this._current+=1,{start:i,type:s.TOK_FLATTEN,value:"[]"};return{start:i,type:s.TOK_LBRACKET,value:"["}}consumeOperator(r){let i=this._current,a=r[i];if(this._current+=1,a==="!"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_NE,value:"!="};return{start:i,type:s.TOK_NOT,value:"!"}}if(a==="<"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_LTE,value:"<="};return{start:i,type:s.TOK_LT,value:"<"}}if(a===">"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_GTE,value:">="};return{start:i,type:s.TOK_GT,value:">"}}if(a==="="&&r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_EQ,value:"=="}}consumeLiteral(r){this._current+=1;let i=this._current,a=r.length;while(r[this._current]!=="`"&&this._current<a){let f=this._current;if(r[f]==="\\"&&(r[f+1]==="\\"||r[f+1]==="`"))f+=2;else f+=1;this._current=f}let u=r.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(r){let a=["true","false","null"],u="-0123456789";if(r==="")return!1;if('[{"'.includes(r[0]))return!0;if(a.includes(r))return!0;if("-0123456789".includes(r[0]))try{return JSON.parse(r),!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(r){this.loadTokens(r),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(r){this.tokens=[...k.tokenize(r),{type:s.TOK_EOF,value:"",start:r.length}]}expression(r){let i=this.lookaheadToken(0);this.advance();let a=this.nud(i),u=this.lookahead(0);while(r<w[u])this.advance(),a=this.led(u,a),u=this.lookahead(0);return a}lookahead(r){return this.tokens[this.index+r].type}lookaheadToken(r){return this.tokens[this.index+r]}advance(){this.index+=1}nud(r){let i,a,u;switch(r.type){case s.TOK_LITERAL:return{type:"Literal",value:r.value};case s.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:r.value};case s.TOK_QUOTEDIDENTIFIER:let h={type:"Field",name:r.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(r.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 f=[];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);f.push(u)}return this.match(s.TOK_RPAREN),f[0];default:this.errorToken(r)}}led(r,i){let a;switch(r){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,f=[],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);f.push(g)}return this.match(s.TOK_RPAREN),{name:h,type:"Function",children:f};case s.TOK_FILTER:let T=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,T]};case s.TOK_FLATTEN:let b={type:s.TOK_FLATTEN,children:[i]},y=this.parseProjectionRHS(w.Flatten);return{type:"Projection",children:[b,y]};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,r);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(r){if(this.lookahead(0)===r){this.advance();return}else{let i=this.lookaheadToken(0);this.errorToken(i,`Expected ${r}, got: ${i.type}`)}}errorToken(r,i=""){let a=Error(i||`Invalid token (${r.type}): "${r.value}"`);throw a.name="ParserError",a}parseIndexExpression(){if(this.lookahead(0)===s.TOK_COLON||this.lookahead(1)===s.TOK_COLON)return this.parseSliceExpression();let r={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(s.TOK_RBRACKET),r}projectIfSlice(r,i){let a={type:"IndexExpression",children:[r,i]};if(i.type==="Slice")return{children:[a,this.parseProjectionRHS(w.Star)],type:"Projection"};return a}parseSliceExpression(){let r=[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)r[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:r,type:"Slice"}}parseComparator(r,i){let a=this.expression(w[i]);return{type:"Comparator",name:i,children:[r,a]}}parseDotRHS(r){let i=this.lookahead(0);if([s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER,s.TOK_STAR].includes(i))return this.expression(r);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(r){if(w[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===s.TOK_LBRACKET)return this.expression(r);if(this.lookahead(0)===s.TOK_FILTER)return this.expression(r);if(this.lookahead(0)===s.TOK_DOT)return this.match(s.TOK_DOT),this.parseDotRHS(r);let i=this.lookaheadToken(0);this.errorToken(i,`Syntax error, unexpected token: ${i.value}(${i.type})`)}parseMultiselectList(){let r=[];while(this.lookahead(0)!==s.TOK_RBRACKET){let i=this.expression(0);if(r.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:r}}parseMultiselectHash(){let r=[],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),r.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:r}}}let ye=new Te;var c;(function(r){r[r.TYPE_NUMBER=0]="TYPE_NUMBER",r[r.TYPE_ANY=1]="TYPE_ANY",r[r.TYPE_STRING=2]="TYPE_STRING",r[r.TYPE_ARRAY=3]="TYPE_ARRAY",r[r.TYPE_OBJECT=4]="TYPE_OBJECT",r[r.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",r[r.TYPE_EXPREF=6]="TYPE_EXPREF",r[r.TYPE_NULL=7]="TYPE_NULL",r[r.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",r[r.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(c||(c={}));class Se{constructor(r){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],f=i[1];for(let g=0;g<f.length;g+=1)a.push(u.visit(h,f[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 f=1;f<u.length;f+=1)if(h.localeCompare(u[f])<0)h=u[f];return h},this.functionMaxBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),f=-1/0,g,E;for(let T=0;T<u.length;T+=1)if(E=h&&h(u[T]),E!==void 0&&E>f)f=E,g=u[T];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 f=1;f<u.length;f+=1)if(u[f].localeCompare(h)<0)h=u[f];return h},this.functionMinBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),f=1/0,g,E;for(let T=0;T<u.length;T+=1)if(E=h&&h(u[T]),E!==void 0&&E<f)f=E,g=u[T];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,f="";for(let g=h.length-1;g>=0;g-=1)f+=h[g];return f}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],f=this.getTypeName(u.visit(h,a[0]));if(f!==void 0&&![c.TYPE_NUMBER,c.TYPE_STRING].includes(f))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[f]})`);let g=[];for(let E=0;E<a.length;E+=1)g.push([E,a[E]]);g.sort((E,T)=>{let b=u.visit(h,E[1]),y=u.visit(h,T[1]);if(this.getTypeName(b)!==f)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[f]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(b)]}`);else if(this.getTypeName(y)!==f)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[f]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(y)]}`);if(b>y)return 1;return b<y?-1:E[0]-T[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=r}registerFunction(r,i,a){if(r in this.functionTable)throw Error(`Function already defined: ${r}()`);this.functionTable[r]={_func:i.bind(this),_signature:a}}callFunction(r,i){let a=this.functionTable[r];if(a===void 0)throw Error(`Unknown function: ${r}()`);return this.validateArgs(r,i,a._signature),a._func.call(this,i)}validateInputSignatures(r,i){for(let a=0;a<i.length;a+=1)if("variadic"in i[a]&&a!==i.length-1)throw Error(`ArgumentError: ${r}() 'variadic' argument ${a+1} must occur last`)}validateArgs(r,i,a){var u,h;let f;this.validateInputSignatures(r,a);let g=a.filter((O)=>{var M;return(M=!O.optional)!==null&&M!==void 0?M:!1}).length,E=(h=(u=a[a.length-1])===null||u===void 0?void 0:u.variadic)!==null&&h!==void 0?h:!1,T=i.length<g,b=i.length>a.length,y=T&&(!E&&g>1||E)?"at least ":"";if(E&&T||!E&&(T||b))throw f=a.length>1,Error(`ArgumentError: ${r}() takes ${y}${g} argument${f&&"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 M;for(M=0;M<p.length;M+=1)if(R!==void 0&&this.typeMatches(R,p[M],i[O])){C=!0;break}if(!C&&R!==void 0){let F=p.map((D)=>this.TYPE_NAME_TABLE[D]).join(" | ");throw Error(`TypeError: ${r}() expected argument ${O+1} to be type (${F}) but received type ${this.TYPE_NAME_TABLE[R]} instead.`)}}}typeMatches(r,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 r===c.TYPE_ARRAY;if(r===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 f=this.getTypeName(a[h]);if(f!==void 0&&u!==void 0&&!this.typeMatches(f,u,a[h]))return!1}return!0}}else return r===i;return!1}getTypeName(r){switch(Object.prototype.toString.call(r)){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(r.jmespathType===s.TOK_EXPREF)return c.TYPE_EXPREF;return c.TYPE_OBJECT;default:return}}createKeyFunction(r,i){if(!this._interpreter)return;let a=this._interpreter;return(h)=>{let f=a.visit(r,h);if(!i.includes(this.getTypeName(f))){let g=`TypeError: expected one of (${i.map((E)=>this.TYPE_NAME_TABLE[E]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(f)]}`;throw Error(g)}return f}}}class Re{constructor(){this._rootValue=null,this.runtime=new Se(this)}search(r,i){return this._rootValue=i,this.visit(r,i)}visit(r,i){let a,u,h,f,g,E,T,b,y,p,R;switch(r.type){case"Field":if(i===null)return null;if(t(i)){if(E=i[r.name],E===void 0)return null;return E}return null;case"Subexpression":h=this.visit(r.children[0],i);for(p=1;p<r.children.length;p+=1)if(h=this.visit(r.children[1],h),h===null)return null;return h;case"IndexExpression":return T=this.visit(r.children[0],i),b=this.visit(r.children[1],T),b;case"Index":if(!Array.isArray(i))return null;let C=r.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=[...r.children],M=this.computeSliceParams(i.length,O),[F,D,X]=M;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(r.children[0],i),!Array.isArray(R))return null;y=[];for(p=0;p<R.length;p+=1)if(u=this.visit(r.children[1],R[p]),u!==null)y.push(u);return y;case"ValueProjection":if(R=this.visit(r.children[0],i),!t(R))return null;y=[];let Be=Object.values(R);for(p=0;p<Be.length;p+=1)if(u=this.visit(r.children[1],Be[p]),u!==null)y.push(u);return y;case"FilterProjection":if(R=this.visit(r.children[0],i),!Array.isArray(R))return null;let Z=[],Je=[];for(p=0;p<R.length;p+=1)if(a=this.visit(r.children[2],R[p]),!o(a))Z.push(R[p]);for(let L=0;L<Z.length;L+=1)if(u=this.visit(r.children[1],Z[L]),u!==null)Je.push(u);return Je;case"Comparator":switch(f=this.visit(r.children[0],i),g=this.visit(r.children[1],i),r.name){case s.TOK_EQ:h=n(f,g);break;case s.TOK_NE:h=!n(f,g);break;case s.TOK_GT:h=f>g;break;case s.TOK_GTE:h=f>=g;break;case s.TOK_LT:h=f<g;break;case s.TOK_LTE:h=f<=g;break;default:throw Error(`Unknown comparator: ${r.name}`)}return h;case s.TOK_FLATTEN:let ee=this.visit(r.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;y=[];for(p=0;p<r.children.length;p+=1)y.push(this.visit(r.children[p],i));return y;case"MultiSelectHash":if(i===null)return null;y={};let te;for(p=0;p<r.children.length;p+=1)te=r.children[p],y[te.name]=this.visit(te.value,i);return y;case"OrExpression":if(a=this.visit(r.children[0],i),o(a))a=this.visit(r.children[1],i);return a;case"AndExpression":if(f=this.visit(r.children[0],i),o(f))return f;return this.visit(r.children[1],i);case"NotExpression":return f=this.visit(r.children[0],i),o(f);case"Literal":return r.value;case s.TOK_PIPE:return T=this.visit(r.children[0],i),this.visit(r.children[1],T);case s.TOK_CURRENT:return i;case s.TOK_ROOT:return this._rootValue;case"Function":let He=[];for(let L=0;L<r.children.length;L+=1)He.push(this.visit(r.children[L],i));return this.runtime.callFunction(r.name,He);case"ExpressionReference":let Fe=r.children[0];return Fe.jmespathType=s.TOK_EXPREF,Fe;default:throw Error(`Unknown node type: ${r.type}`)}}computeSliceParams(r,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 f=h<0?!0:!1;return a=a===null?f?r-1:0:this.capSliceRange(r,a,h),u=u===null?f?-1:r:this.capSliceRange(r,u,h),[a,u,h]}capSliceRange(r,i,a){let u=i;if(u<0){if(u+=r,u<0)u=a<0?-1:0}else if(u>=r)u=a<0?r-1:r;return u}}let z=new Re,we=c.TYPE_ANY,Pe=c.TYPE_ARRAY,Ae=c.TYPE_ARRAY_NUMBER,be=c.TYPE_ARRAY_STRING,Oe=c.TYPE_BOOLEAN,Me=c.TYPE_EXPREF,ve=c.TYPE_NULL,xe=c.TYPE_NUMBER,Ne=c.TYPE_OBJECT,ke=c.TYPE_STRING;function Ce(r){return ye.parse(r)}function Ie(r){return k.tokenize(r)}let Le=(r,i,a)=>{z.runtime.registerFunction(r,i,a)};function Ue(r,i){let a=ye.parse(i);return z.search(a,r)}let Ke=z,Ye={compile:Ce,registerFunction:Le,search:Ue,tokenize:Ie,TreeInterpreter:Ke,TYPE_ANY:we,TYPE_ARRAY_NUMBER:Ae,TYPE_ARRAY_STRING:be,TYPE_ARRAY:Pe,TYPE_BOOLEAN:Oe,TYPE_EXPREF:Me,TYPE_NULL:ve,TYPE_NUMBER:xe,TYPE_OBJECT:Ne,TYPE_STRING:ke};e.TYPE_ANY=we,e.TYPE_ARRAY=Pe,e.TYPE_ARRAY_NUMBER=Ae,e.TYPE_ARRAY_STRING=be,e.TYPE_BOOLEAN=Oe,e.TYPE_EXPREF=Me,e.TYPE_NULL=ve,e.TYPE_NUMBER=xe,e.TYPE_OBJECT=Ne,e.TYPE_STRING=ke,e.TreeInterpreter=Ke,e.compile=Ce,e.default=Ye,e.jmespath=Ye,e.registerFunction=Le,e.search=Ue,e.tokenize=Ie,Object.defineProperty(e,"__esModule",{value:!0})})});import{timingSafeEqual as ur}from"node:crypto";import{createServer as lr}from"node:http";import{Readable as cr}from"node:stream";function xt(){return typeof process>"u"?{}:process.env}function Qe(e=xt()){return e.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as or}from"node:fs";V();async function ht(e){let t=ge(await e),[n,o,{QuickJSWASMModule:l}]=await Promise.all([t.importModuleLoader().then(ge),t.importFFI(),Promise.resolve().then(() => (ct(),lt)).then(ge)]),d=await n();d.type="sync";let m=new o(d);return new l(d,m)}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 ft="engine";function Xt(e){let t=(n)=>new URL(n,e).href;return{type:"sync",importFFI:()=>import(t("ffi.mjs")).then((n)=>n.QuickJSFFI),importModuleLoader:()=>import(t("emscripten-module.mjs")).then((n)=>n.default)}}var dt=null;function mt(e){return()=>(dt??=ht(Xt(e)),dt)}var Zt=At(_t(),1);var tr="__mcpcloud_call_tool",hn=`globalThis.tool = (name, args) =>
6
+ Lifetime used`):new ue("Lifetime not alive")}},Y=class extends P{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},Ve=class extends P{constructor(e,t,n,o){super(e,t,n,o)}dispose(){this._alive=!1}};v=class e extends N{constructor(){super(...arguments);this._disposables=new P(new Set),this.manage=(t)=>(this._disposables.value.add(t),t)}static withScope(t){let n=new e,o;try{return t(n)}catch(l){throw o=l,l}finally{se(n,o)}}static withScopeMaybeAsync(t,n){return Kt(void 0,function*(o){let l=new e,d;try{return yield*o.of(n.call(t,o,l))}catch(m){throw d=m,m}finally{se(l,d)}})}static async withScopeAsync(t){let n=new e,o;try{return await t(n)}catch(l){throw o=l,l}finally{se(n,o)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let n of t)n.alive&&n.dispose();this._disposables.dispose()}};fe=class e extends N{static success(t){return new Bt(t)}static fail(t,n){return new Jt(t,n)}static is(t){return t instanceof e}},Bt=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}},Jt=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}},B=fe,Ft=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()}},Sr=Symbol("Unstable"),Rr=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});$t=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 n=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),n}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof P?e:this.context.newError(e),n=this.context.getProp(this.handle,"throw"),o=this.callIteratorMethod(n,e);return t.alive&&t.dispose(),n.dispose(),this.dispose(),o}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let n=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(n.error)return this.dispose(),{value:n};let o=this.context.getProp(n.value,"done").consume((d)=>this.context.dump(d)),l=this.context.getProp(n.value,"value");return n.value.dispose(),o&&this.dispose(),{value:B.success(l),done:o}}};qe=class extends N{constructor(e,t,n){if(n===G)throw new I("cannot create HostRef with undefined id");super();this.runtime=e,this.handle=t,this.id=n}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},Gt=class extends ot{constructor(e){super(e.module);this.scope=new v,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 n=t?(o)=>{t(),this.freeJSValue(o)}:this.freeJSValue;return new P(e,this.copyJSValue,n,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new Y(e,this.owner)}},Wt=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,n,o,l,d)=>{if(t!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let m=this.getFunction(d);return v.withScopeMaybeAsync(this,function*(s,_){let A=_.manage(new Ve(n,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 Ve(C,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let S=yield*s(m.apply(A,x));if(S){if("error"in S&&S.error)throw this.runtime.debugLog("throw error",S.error),S.error;let C=_.manage(S instanceof P?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 Gt({...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 Y(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new Y(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new Y(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new Y(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((n)=>this.ffi.QTS_NewString(this.ctx.value,n.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",n=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,0));return this.memory.heapValueHandle(n)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",n=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,1));return this.memory.heapValueHandle(n)}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 Y(o.value,this.runtime)}let t=this._BigInt,n=String(e);return this.newString(n).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),n=this.memory.newHeapBufferPointer(t),o=this.ffi.QTS_NewArrayBuffer(this.ctx.value,n.value.pointer,t.length);return this.memory.heapValueHandle(o)}newPromise(e){let t=v.withScope((n)=>{let o=n.manage(this.memory.newMutablePointerArray(2)),l=this.ffi.QTS_NewPromiseCapability(this.ctx.value,o.value.ptr),d=this.memory.heapValueHandle(l),[m,s]=Array.from(o.value.typedArray).map((_)=>this.memory.heapValueHandle(_));return new Ft({context:this,promiseHandle:d,resolveHandle:m,rejectHandle:s})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,(n)=>n instanceof P?t.reject(n):this.newError(n).consume(t.reject)),t}newFunction(e,t){let n=typeof e=="function"?e:t;if(!n)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:n.length,isConstructor:!1,fn:n})}newConstructorFunction(e,t){let n=typeof e=="function"?e:t;if(!n)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:n.length,isConstructor:!0,fn:n})}newFunctionWithOptions(e){let{name:t,length:n,isConstructor:o,fn:l}=e,d=this.runtime.hostRefs.put(l);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",n,o,d))}catch(m){throw this.runtime.hostRefs.delete(d),m}}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((n)=>this.setProp(t,"name",n)),e.message!==void 0&&this.newString(e.message).consume((n)=>this.setProp(t,"message",n))):typeof e=="string"?this.newString(e).consume((n)=>this.setProp(t,"message",n)):e!==void 0&&this.newString(String(e)).consume((n)=>this.setProp(t,"message",n)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let n=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new qe(this.runtime,n,t)}catch(n){throw this.runtime.hostRefs.delete(t),n}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new qe(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),n=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!n)throw Error("Couldn't allocate memory to get ArrayBuffer");return new P(this.module.HEAPU8.subarray(n,n+t),void 0,()=>this.module._free(n))}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 rt("Cannot unwrap a pending promise")}};let n=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),o=this.memory.heapValueHandle(n);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=v.withScope((n)=>{let o=n.manage(this.getProp(this.global,"Promise")),l=n.manage(this.getProp(o,"resolve"));return this.callFunction(l,o,e)});return t.error?Promise.resolve(t):new Promise((n)=>{v.withScope((o)=>{let l=o.manage(this.newFunction("resolve",(_)=>{n(this.success(_&&_.dup()))})),d=o.manage(this.newFunction("reject",(_)=>{n(this.fail(_&&_.dup()))})),m=o.manage(t.value),s=o.manage(this.getProp(m,"then"));this.callFunction(s,m,l,d).unwrap().dispose()})})}isEqual(e,t,n=J.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,n);if(o===-1)throw new Xe("WASM variant does not expose equality");return!!o}eq(e,t){return this.isEqual(e,t,J.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,J.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,J.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let n;return typeof t=="number"&&t>=0?n=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):n=this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_GetProp(this.ctx.value,e.value,o.value)),this.memory.heapValueHandle(n)}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 n=Qt(t);if(n===0)throw new nt("No options set, will return an empty array");return v.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,n);if(d)return this.fail(this.memory.heapValueHandle(d));let m=this.uint32Out.value.typedArray[0],s=l.value.typedArray[0],_=new Uint32Array(this.module.HEAP8.buffer,s,m),A=Array.from(_).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,s),this.success(Yt(A))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return v.withScope((n)=>{let o=n.manage(this.getProp(e,t)),l=this.callFunction(o,e);return l.error?l:this.success(new $t(l.value,this))})}setProp(e,t,n){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_SetProp(this.ctx.value,e.value,o.value,n.value))}defineProp(e,t,n){this.runtime.assertOwned(e),v.withScope((o)=>{let l=o.manage(this.borrowPropertyKey(t)),d=n.value||this.undefined,m=!!n.configurable,s=!!n.enumerable,_=!!n.value,A=n.get?o.manage(this.newFunction(n.get.name,n.get)):this.undefined,x=n.set?o.manage(this.newFunction(n.set.name,n.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,l.value,d.value,A.value,x.value,m,s,_)})}callFunction(e,t,...n){this.runtime.assertOwned(e);let o,l=n[0];l===void 0||Array.isArray(l)?o=l??[]:o=n;let d=this.memory.toPointerArray(o).consume((s)=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,o.length,s.value)),m=this.ffi.QTS_ResolveException(this.ctx.value,d);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(m))):this.success(this.memory.heapValueHandle(d))}callMethod(e,t,n=[]){return this.getProp(e,t).consume((o)=>this.callFunction(o,e,n))}evalCode(e,t="eval.js",n){let o=n===void 0?1:0,l=Dt(n),d=this.memory.newHeapCharPointer(e).consume((s)=>this.ffi.QTS_Eval(this.ctx.value,s.value.ptr,s.value.strlen,t,o,l)),m=this.ffi.QTS_ResolveException(this.ctx.value,d);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(m))):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 Y(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 n=this.getPromiseState(e);if(n.type==="fulfilled"&&!n.notAPromise)return e.dispose(),{type:n.type,value:n.value.consume(this.dump)};if(n.type==="pending")return e.dispose(),{type:n.type};if(n.type==="rejected")return e.dispose(),{type:n.type,error:n.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,n=e.error.consume((o)=>this.dump(o));if(n&&typeof n=="object"&&typeof n.message=="string"){let{message:o,name:l,stack:d,...m}=n,s=new ae(n,t);typeof l=="string"&&(s.name=n.name),s.message=o;let _=s.stack;throw typeof d=="string"&&(s.stack=`${l}: ${o}
7
+ ${n.stack}Host: ${_}`),Object.assign(s,m),s}throw new ae(n)}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 P?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 B.success(e)}fail(e){return B.fail(e,(t)=>this.unwrapResult(t))}},qt=class extends N{constructor(e){super();this.scope=new v,this.contextMap=new Map,this.hostRefs=new Vt,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(t,n)=>{if(t!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(n)},shouldInterrupt:(t)=>{if(t!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let n=this.interruptHandler;if(!n)throw Error("QuickJSContext had no interrupt handler");return n(this)?1:0},loadModuleSource:je(this,function*(t,n,o,l){let d=this.moduleLoader;if(!d)throw Error("Runtime has no module loader");if(n!==this.rt.value)throw Error("Runtime pointer mismatch");let m=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let s=yield*t(d(l,m));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),m.throw(s),0}}),normalizeModule:je(this,function*(t,n,o,l,d){let m=this.moduleNormalizer;if(!m)throw Error("Runtime has no module normalizer");if(n!==this.rt.value)throw Error("Runtime pointer mismatch");let s=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let _=yield*t(m(l,d,s));if(typeof _=="object"&&"error"in _&&_.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",_.error),_.error;let A=typeof _=="string"?_:_.value;return s.getMemory(this.rt.value).newHeapCharPointer(A).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 ot(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=Ht(e.intrinsics),n=new P(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 Wt({module:this.module,ctx:n,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(n.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),n=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,n),B.success(0);let l=this.contextMap.get(o)??this.newContext({contextPointer:o}),d=l.getMemory(this.rt.value).heapValueHandle(n);if(l.typeof(d)==="number"){let m=l.getNumber(d);return d.dispose(),B.success(m)}else{let m=Object.assign(d,{context:l});return B.fail(m,(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 ze(`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 lt={};vt(lt,{QuickJSModuleCallbacks:()=>me,QuickJSWASMModule:()=>at,applyBaseRuntimeOptions:()=>pe,applyModuleEvalRuntimeOptions:()=>_e});var ct=ne(()=>{ut()});var _t=bt(function(q,pt){(function(e,t){typeof q==="object"&&typeof pt<"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=(r)=>r!==null&&Object.prototype.toString.call(r)==="[object Object]",n=(r,i)=>{if(r===i)return!0;if(typeof r!==typeof i)return!1;if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let a=0;a<r.length;a+=1)if(!n(r[a],i[a]))return!1;return!0}if(t(r)&&t(i)){let a=Object.entries(r),u=new Set(Object.keys(i));if(a.length!==u.size)return!1;for(let[h,f]of a){if(!n(f,i[h]))return!1;u.delete(h)}return u.size===0}return!1},o=(r)=>{if(r===""||r===!1||r===null||r===void 0)return!0;if(Array.isArray(r)&&r.length===0)return!0;if(t(r)){for(let i in r)if(r.hasOwnProperty(i))return!1;return!0}return!1},l=(r)=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_",d=(r)=>r>="0"&&r<="9"||r==="-",m=(r)=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_";var s;(function(r){r.TOK_EOF="EOF",r.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",r.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",r.TOK_RBRACKET="Rbracket",r.TOK_RPAREN="Rparen",r.TOK_COMMA="Comma",r.TOK_COLON="Colon",r.TOK_RBRACE="Rbrace",r.TOK_NUMBER="Number",r.TOK_CURRENT="Current",r.TOK_ROOT="Root",r.TOK_EXPREF="Expref",r.TOK_PIPE="Pipe",r.TOK_OR="Or",r.TOK_AND="And",r.TOK_EQ="EQ",r.TOK_GT="GT",r.TOK_LT="LT",r.TOK_GTE="GTE",r.TOK_LTE="LTE",r.TOK_NE="NE",r.TOK_FLATTEN="Flatten",r.TOK_STAR="Star",r.TOK_FILTER="Filter",r.TOK_DOT="Dot",r.TOK_NOT="Not",r.TOK_LBRACE="Lbrace",r.TOK_LBRACKET="Lbracket",r.TOK_LPAREN="Lparen",r.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},A={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class S{constructor(){this._current=0}tokenize(r){let i=[];this._current=0;let a,u,h;while(this._current<r.length)if(l(r[this._current]))a=this._current,u=this.consumeUnquotedIdentifier(r),i.push({start:a,type:s.TOK_UNQUOTEDIDENTIFIER,value:u});else if(_[r[this._current]]!==void 0)i.push({start:this._current,type:_[r[this._current]],value:r[this._current]}),this._current+=1;else if(d(r[this._current]))h=this.consumeNumber(r),i.push(h);else if(r[this._current]==="[")h=this.consumeLBracket(r),i.push(h);else if(r[this._current]==='"')a=this._current,u=this.consumeQuotedIdentifier(r),i.push({start:a,type:s.TOK_QUOTEDIDENTIFIER,value:u});else if(r[this._current]==="'")a=this._current,u=this.consumeRawStringLiteral(r),i.push({start:a,type:s.TOK_LITERAL,value:u});else if(r[this._current]==="`"){a=this._current;let f=this.consumeLiteral(r);i.push({start:a,type:s.TOK_LITERAL,value:f})}else if(A[r[this._current]]!==void 0)h=this.consumeOperator(r),h&&i.push(h);else if(x[r[this._current]]!==void 0)this._current+=1;else if(r[this._current]==="&")if(a=this._current,this._current+=1,r[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(r[this._current]==="|")if(a=this._current,this._current+=1,r[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 f=Error(`Unknown character: ${r[this._current]}`);throw f.name="LexerError",f}return i}consumeUnquotedIdentifier(r){let i=this._current;this._current+=1;while(this._current<r.length&&m(r[this._current]))this._current+=1;return r.slice(i,this._current)}consumeQuotedIdentifier(r){let i=this._current;this._current+=1;let a=r.length;while(r[this._current]!=='"'&&this._current<a){let u=this._current;if(r[u]==="\\"&&(r[u+1]==="\\"||r[u+1]==='"'))u+=2;else u+=1;this._current=u}return this._current+=1,JSON.parse(r.slice(i,this._current))}consumeRawStringLiteral(r){let i=this._current;this._current+=1;let a=r.length;while(r[this._current]!=="'"&&this._current<a){let h=this._current;if(r[h]==="\\"&&(r[h+1]==="\\"||r[h+1]==="'"))h+=2;else h+=1;this._current=h}return this._current+=1,r.slice(i+1,this._current-1).replace("\\'","'")}consumeNumber(r){let i=this._current;this._current+=1;let a=r.length;while(d(r[this._current])&&this._current<a)this._current+=1;let u=parseInt(r.slice(i,this._current),10);return{start:i,value:u,type:s.TOK_NUMBER}}consumeLBracket(r){let i=this._current;if(this._current+=1,r[this._current]==="?")return this._current+=1,{start:i,type:s.TOK_FILTER,value:"[?"};if(r[this._current]==="]")return this._current+=1,{start:i,type:s.TOK_FLATTEN,value:"[]"};return{start:i,type:s.TOK_LBRACKET,value:"["}}consumeOperator(r){let i=this._current,a=r[i];if(this._current+=1,a==="!"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_NE,value:"!="};return{start:i,type:s.TOK_NOT,value:"!"}}if(a==="<"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_LTE,value:"<="};return{start:i,type:s.TOK_LT,value:"<"}}if(a===">"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_GTE,value:">="};return{start:i,type:s.TOK_GT,value:">"}}if(a==="="&&r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_EQ,value:"=="}}consumeLiteral(r){this._current+=1;let i=this._current,a=r.length;while(r[this._current]!=="`"&&this._current<a){let f=this._current;if(r[f]==="\\"&&(r[f+1]==="\\"||r[f+1]==="`"))f+=2;else f+=1;this._current=f}let u=r.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(r){let a=["true","false","null"],u="-0123456789";if(r==="")return!1;if('[{"'.includes(r[0]))return!0;if(a.includes(r))return!0;if("-0123456789".includes(r[0]))try{return JSON.parse(r),!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(r){this.loadTokens(r),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(r){this.tokens=[...C.tokenize(r),{type:s.TOK_EOF,value:"",start:r.length}]}expression(r){let i=this.lookaheadToken(0);this.advance();let a=this.nud(i),u=this.lookahead(0);while(r<w[u])this.advance(),a=this.led(u,a),u=this.lookahead(0);return a}lookahead(r){return this.tokens[this.index+r].type}lookaheadToken(r){return this.tokens[this.index+r]}advance(){this.index+=1}nud(r){let i,a,u;switch(r.type){case s.TOK_LITERAL:return{type:"Literal",value:r.value};case s.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:r.value};case s.TOK_QUOTEDIDENTIFIER:let h={type:"Field",name:r.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(r.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 f=[];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);f.push(u)}return this.match(s.TOK_RPAREN),f[0];default:this.errorToken(r)}}led(r,i){let a;switch(r){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,f=[],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);f.push(g)}return this.match(s.TOK_RPAREN),{name:h,type:"Function",children:f};case s.TOK_FILTER:let T=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,T]};case s.TOK_FLATTEN:let b={type:s.TOK_FLATTEN,children:[i]},y=this.parseProjectionRHS(w.Flatten);return{type:"Projection",children:[b,y]};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,r);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(r){if(this.lookahead(0)===r){this.advance();return}else{let i=this.lookaheadToken(0);this.errorToken(i,`Expected ${r}, got: ${i.type}`)}}errorToken(r,i=""){let a=Error(i||`Invalid token (${r.type}): "${r.value}"`);throw a.name="ParserError",a}parseIndexExpression(){if(this.lookahead(0)===s.TOK_COLON||this.lookahead(1)===s.TOK_COLON)return this.parseSliceExpression();let r={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(s.TOK_RBRACKET),r}projectIfSlice(r,i){let a={type:"IndexExpression",children:[r,i]};if(i.type==="Slice")return{children:[a,this.parseProjectionRHS(w.Star)],type:"Projection"};return a}parseSliceExpression(){let r=[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)r[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:r,type:"Slice"}}parseComparator(r,i){let a=this.expression(w[i]);return{type:"Comparator",name:i,children:[r,a]}}parseDotRHS(r){let i=this.lookahead(0);if([s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER,s.TOK_STAR].includes(i))return this.expression(r);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(r){if(w[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===s.TOK_LBRACKET)return this.expression(r);if(this.lookahead(0)===s.TOK_FILTER)return this.expression(r);if(this.lookahead(0)===s.TOK_DOT)return this.match(s.TOK_DOT),this.parseDotRHS(r);let i=this.lookaheadToken(0);this.errorToken(i,`Syntax error, unexpected token: ${i.value}(${i.type})`)}parseMultiselectList(){let r=[];while(this.lookahead(0)!==s.TOK_RBRACKET){let i=this.expression(0);if(r.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:r}}parseMultiselectHash(){let r=[],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),r.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:r}}}let ye=new Te;var c;(function(r){r[r.TYPE_NUMBER=0]="TYPE_NUMBER",r[r.TYPE_ANY=1]="TYPE_ANY",r[r.TYPE_STRING=2]="TYPE_STRING",r[r.TYPE_ARRAY=3]="TYPE_ARRAY",r[r.TYPE_OBJECT=4]="TYPE_OBJECT",r[r.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",r[r.TYPE_EXPREF=6]="TYPE_EXPREF",r[r.TYPE_NULL=7]="TYPE_NULL",r[r.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",r[r.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(c||(c={}));class Se{constructor(r){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],f=i[1];for(let g=0;g<f.length;g+=1)a.push(u.visit(h,f[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 f=1;f<u.length;f+=1)if(h.localeCompare(u[f])<0)h=u[f];return h},this.functionMaxBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),f=-1/0,g,E;for(let T=0;T<u.length;T+=1)if(E=h&&h(u[T]),E!==void 0&&E>f)f=E,g=u[T];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 f=1;f<u.length;f+=1)if(u[f].localeCompare(h)<0)h=u[f];return h},this.functionMinBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),f=1/0,g,E;for(let T=0;T<u.length;T+=1)if(E=h&&h(u[T]),E!==void 0&&E<f)f=E,g=u[T];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,f="";for(let g=h.length-1;g>=0;g-=1)f+=h[g];return f}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],f=this.getTypeName(u.visit(h,a[0]));if(f!==void 0&&![c.TYPE_NUMBER,c.TYPE_STRING].includes(f))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[f]})`);let g=[];for(let E=0;E<a.length;E+=1)g.push([E,a[E]]);g.sort((E,T)=>{let b=u.visit(h,E[1]),y=u.visit(h,T[1]);if(this.getTypeName(b)!==f)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[f]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(b)]}`);else if(this.getTypeName(y)!==f)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[f]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(y)]}`);if(b>y)return 1;return b<y?-1:E[0]-T[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=r}registerFunction(r,i,a){if(r in this.functionTable)throw Error(`Function already defined: ${r}()`);this.functionTable[r]={_func:i.bind(this),_signature:a}}callFunction(r,i){let a=this.functionTable[r];if(a===void 0)throw Error(`Unknown function: ${r}()`);return this.validateArgs(r,i,a._signature),a._func.call(this,i)}validateInputSignatures(r,i){for(let a=0;a<i.length;a+=1)if("variadic"in i[a]&&a!==i.length-1)throw Error(`ArgumentError: ${r}() 'variadic' argument ${a+1} must occur last`)}validateArgs(r,i,a){var u,h;let f;this.validateInputSignatures(r,a);let g=a.filter((O)=>{var M;return(M=!O.optional)!==null&&M!==void 0?M:!1}).length,E=(h=(u=a[a.length-1])===null||u===void 0?void 0:u.variadic)!==null&&h!==void 0?h:!1,T=i.length<g,b=i.length>a.length,y=T&&(!E&&g>1||E)?"at least ":"";if(E&&T||!E&&(T||b))throw f=a.length>1,Error(`ArgumentError: ${r}() takes ${y}${g} argument${f&&"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 M;for(M=0;M<p.length;M+=1)if(R!==void 0&&this.typeMatches(R,p[M],i[O])){k=!0;break}if(!k&&R!==void 0){let H=p.map((D)=>this.TYPE_NAME_TABLE[D]).join(" | ");throw Error(`TypeError: ${r}() expected argument ${O+1} to be type (${H}) but received type ${this.TYPE_NAME_TABLE[R]} instead.`)}}}typeMatches(r,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 r===c.TYPE_ARRAY;if(r===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 f=this.getTypeName(a[h]);if(f!==void 0&&u!==void 0&&!this.typeMatches(f,u,a[h]))return!1}return!0}}else return r===i;return!1}getTypeName(r){switch(Object.prototype.toString.call(r)){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(r.jmespathType===s.TOK_EXPREF)return c.TYPE_EXPREF;return c.TYPE_OBJECT;default:return}}createKeyFunction(r,i){if(!this._interpreter)return;let a=this._interpreter;return(h)=>{let f=a.visit(r,h);if(!i.includes(this.getTypeName(f))){let g=`TypeError: expected one of (${i.map((E)=>this.TYPE_NAME_TABLE[E]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(f)]}`;throw Error(g)}return f}}}class Re{constructor(){this._rootValue=null,this.runtime=new Se(this)}search(r,i){return this._rootValue=i,this.visit(r,i)}visit(r,i){let a,u,h,f,g,E,T,b,y,p,R;switch(r.type){case"Field":if(i===null)return null;if(t(i)){if(E=i[r.name],E===void 0)return null;return E}return null;case"Subexpression":h=this.visit(r.children[0],i);for(p=1;p<r.children.length;p+=1)if(h=this.visit(r.children[1],h),h===null)return null;return h;case"IndexExpression":return T=this.visit(r.children[0],i),b=this.visit(r.children[1],T),b;case"Index":if(!Array.isArray(i))return null;let k=r.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=[...r.children],M=this.computeSliceParams(i.length,O),[H,D,X]=M;if(h=[],X>0)for(p=H;p<D;p+=X)h.push(i[p]);else for(p=H;p>D;p+=X)h.push(i[p]);return h;case"Projection":if(R=this.visit(r.children[0],i),!Array.isArray(R))return null;y=[];for(p=0;p<R.length;p+=1)if(u=this.visit(r.children[1],R[p]),u!==null)y.push(u);return y;case"ValueProjection":if(R=this.visit(r.children[0],i),!t(R))return null;y=[];let Be=Object.values(R);for(p=0;p<Be.length;p+=1)if(u=this.visit(r.children[1],Be[p]),u!==null)y.push(u);return y;case"FilterProjection":if(R=this.visit(r.children[0],i),!Array.isArray(R))return null;let Z=[],Je=[];for(p=0;p<R.length;p+=1)if(a=this.visit(r.children[2],R[p]),!o(a))Z.push(R[p]);for(let L=0;L<Z.length;L+=1)if(u=this.visit(r.children[1],Z[L]),u!==null)Je.push(u);return Je;case"Comparator":switch(f=this.visit(r.children[0],i),g=this.visit(r.children[1],i),r.name){case s.TOK_EQ:h=n(f,g);break;case s.TOK_NE:h=!n(f,g);break;case s.TOK_GT:h=f>g;break;case s.TOK_GTE:h=f>=g;break;case s.TOK_LT:h=f<g;break;case s.TOK_LTE:h=f<=g;break;default:throw Error(`Unknown comparator: ${r.name}`)}return h;case s.TOK_FLATTEN:let ee=this.visit(r.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;y=[];for(p=0;p<r.children.length;p+=1)y.push(this.visit(r.children[p],i));return y;case"MultiSelectHash":if(i===null)return null;y={};let te;for(p=0;p<r.children.length;p+=1)te=r.children[p],y[te.name]=this.visit(te.value,i);return y;case"OrExpression":if(a=this.visit(r.children[0],i),o(a))a=this.visit(r.children[1],i);return a;case"AndExpression":if(f=this.visit(r.children[0],i),o(f))return f;return this.visit(r.children[1],i);case"NotExpression":return f=this.visit(r.children[0],i),o(f);case"Literal":return r.value;case s.TOK_PIPE:return T=this.visit(r.children[0],i),this.visit(r.children[1],T);case s.TOK_CURRENT:return i;case s.TOK_ROOT:return this._rootValue;case"Function":let Fe=[];for(let L=0;L<r.children.length;L+=1)Fe.push(this.visit(r.children[L],i));return this.runtime.callFunction(r.name,Fe);case"ExpressionReference":let He=r.children[0];return He.jmespathType=s.TOK_EXPREF,He;default:throw Error(`Unknown node type: ${r.type}`)}}computeSliceParams(r,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 f=h<0?!0:!1;return a=a===null?f?r-1:0:this.capSliceRange(r,a,h),u=u===null?f?-1:r:this.capSliceRange(r,u,h),[a,u,h]}capSliceRange(r,i,a){let u=i;if(u<0){if(u+=r,u<0)u=a<0?-1:0}else if(u>=r)u=a<0?r-1:r;return u}}let z=new Re,we=c.TYPE_ANY,Pe=c.TYPE_ARRAY,Ae=c.TYPE_ARRAY_NUMBER,be=c.TYPE_ARRAY_STRING,Oe=c.TYPE_BOOLEAN,Me=c.TYPE_EXPREF,ve=c.TYPE_NULL,xe=c.TYPE_NUMBER,Ne=c.TYPE_OBJECT,Ce=c.TYPE_STRING;function ke(r){return ye.parse(r)}function Ie(r){return C.tokenize(r)}let Le=(r,i,a)=>{z.runtime.registerFunction(r,i,a)};function Ue(r,i){let a=ye.parse(i);return z.search(a,r)}let Ke=z,Ye={compile:ke,registerFunction:Le,search:Ue,tokenize:Ie,TreeInterpreter:Ke,TYPE_ANY:we,TYPE_ARRAY_NUMBER:Ae,TYPE_ARRAY_STRING:be,TYPE_ARRAY:Pe,TYPE_BOOLEAN:Oe,TYPE_EXPREF:Me,TYPE_NULL:ve,TYPE_NUMBER:xe,TYPE_OBJECT:Ne,TYPE_STRING:Ce};e.TYPE_ANY=we,e.TYPE_ARRAY=Pe,e.TYPE_ARRAY_NUMBER=Ae,e.TYPE_ARRAY_STRING=be,e.TYPE_BOOLEAN=Oe,e.TYPE_EXPREF=Me,e.TYPE_NULL=ve,e.TYPE_NUMBER=xe,e.TYPE_OBJECT=Ne,e.TYPE_STRING=Ce,e.TreeInterpreter=Ke,e.compile=ke,e.default=Ye,e.jmespath=Ye,e.registerFunction=Le,e.search=Ue,e.tokenize=Ie,Object.defineProperty(e,"__esModule",{value:!0})})});import{timingSafeEqual as ur}from"node:crypto";import{createServer as lr}from"node:http";import{Readable as cr}from"node:stream";function xt(){return typeof process>"u"?{}:process.env}function Qe(e=xt()){return e.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as or}from"node:fs";V();async function ht(e){let t=ge(await e),[n,o,{QuickJSWASMModule:l}]=await Promise.all([t.importModuleLoader().then(ge),t.importFFI(),Promise.resolve().then(() => (ct(),lt)).then(ge)]),d=await n();d.type="sync";let m=new o(d);return new l(d,m)}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 ft="engine";function Xt(e){let t=(n)=>new URL(n,e).href;return{type:"sync",importFFI:()=>import(t("ffi.mjs")).then((n)=>n.QuickJSFFI),importModuleLoader:()=>import(t("emscripten-module.mjs")).then((n)=>n.default)}}var dt=null;function mt(e){return()=>(dt??=ht(Xt(e)),dt)}var Zt=At(_t(),1);var tr="__mcpcloud_call_tool",hn=`globalThis.tool = (name, args) =>
8
8
  globalThis.${tr}(String(name), JSON.stringify(args ?? {}))
9
9
  .then((json) => JSON.parse(json));`;var rr=6,nr=["log","warn","error","info","debug"],ir="__mcpcloud_console",mn=`globalThis.console = {
10
10
  ${nr.map((e)=>` ${e}: (...args) => globalThis.${ir}(${JSON.stringify(e)}, JSON.stringify(args.slice(0, ${rr}).map((value) => (value instanceof Error ? { __mcpcloudError: value.name + ': ' + value.message } : value)))),`).join(`
@@ -16,4 +16,4 @@
16
16
  * question: not "what did we intend to deploy?" but "what is running?".
17
17
  * Comparing the two makes a failed-but-successful-looking deploy detectable.
18
18
  */
19
- export declare const RUNTIME_VERSION = "0.17.2";
19
+ export declare const RUNTIME_VERSION = "0.18.0";
package/dist/stdio.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @mcpcloud/runtime v0.17.2 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
1
+ /*! @mcpcloud/runtime v0.18.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
2
  var Df=Object.create;var{getPrototypeOf:Uf,defineProperty:la,getOwnPropertyNames:Ff}=Object;var Ku=Object.prototype.hasOwnProperty;function Zf(e){return this[e]}var Vf,Jf,Hf=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?Vf??=new WeakMap:Jf??=new WeakMap,i=o.get(e);if(i)return i}r=e!=null?Df(Uf(e)):{};let a=t||!e||!e.__esModule||!Ku.call(e,"default")?la(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let s of Ff(e))if(!Ku.call(a,s))la(a,s,{get:Zf.bind(e,s),enumerable:!0})}if(n)o.set(e,a);return a};var Kf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Bf=(e)=>e;function Yf(e,t){this[e]=Bf.bind(null,t)}var Gf=(e,t)=>{for(var r in t)la(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Yf.bind(t,r)})};var da=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var nr,Nu,oa,or,ho;var sa=da(()=>{nr={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},Nu={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},oa={Pending:0,Fulfilled:1,Rejected:2},or={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},ho={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function fo(...e){qu&&console.log("quickjs-emscripten:",...e)}function*wf(e){return yield e}function kv(e){return wf(Du(e))}function lf(e,t){return(...r)=>{let n=t.call(e,Lu,...r);return Du(n)}}function Ov(e,t){let r=t.call(e,Lu);return Du(r)}function Du(e){function t(r){return r.done?r.value:r.value instanceof Promise?r.value.then((n)=>t(e.next(n)),(n)=>t(e.throw(n))):t(e.next(r.value))}return t(e.next())}function xu(e,t){let r;try{e.dispose()}catch(n){r=n}if(t&&r)throw Object.assign(t,{message:`${t.message}
3
3
  Then, failed to dispose scope: ${r.message}`,disposeError:r}),t;if(t||r)throw t||r}function Cv(e){let t=e?Array.from(e):[];function r(){return t.forEach((o)=>o.alive?o.dispose():void 0)}function n(){return t.some((o)=>o.alive)}return Object.defineProperty(t,Mu,{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:n}),t}function aa(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Av(e){if(!e)return 0;let t=0;for(let[r,n]of Object.entries(e)){if(!(r in Nu))throw new vf(r);n&&(t|=Nu[r])}return t}function jv(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:r,strip:n,compileOnly:o,backtraceBarrier:i}=e,a=0;return t==="global"&&(a|=nr.JS_EVAL_TYPE_GLOBAL),t==="module"&&(a|=nr.JS_EVAL_TYPE_MODULE),r&&(a|=nr.JS_EVAL_FLAG_STRICT),n&&(a|=nr.JS_EVAL_FLAG_STRIP),o&&(a|=nr.JS_EVAL_FLAG_COMPILE_ONLY),i&&(a|=nr.JS_EVAL_FLAG_BACKTRACE_BARRIER),a}function Mv(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:r,quickjsPrivate:n,onlyEnumerable:o,numbers:i,numbersAsStrings:a}=e,s=0;return t&&(s|=or.JS_GPN_STRING_MASK),r&&(s|=or.JS_GPN_SYMBOL_MASK),n&&(s|=or.JS_GPN_PRIVATE_MASK),o&&(s|=or.JS_GPN_ENUM_ONLY),i&&(s|=or.QTS_GPN_NUMBER_MASK),a&&(s|=or.QTS_STANDARD_COMPLIANT_NUMBER),s}function qv(...e){let t=[];for(let r of e)r!==void 0&&(t=t.concat(r));return t}function Iu(e){return e>>8}function Zu(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function Vu(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var wv,$v=(e,t)=>{for(var r in t)wv(e,r,{get:t[r],enumerable:!0})},qu=!1,Ev,Au,gf,ju,_f,Sf,yf,Tv,Pv,vf,bf,Rf,zf,jt,Lu,ft,Mu,df,Be,sr,mf,lt,Uu,Nv,xv,Zr,Iv,$f=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((o)=>o.value)),r=t.length*t.BYTES_PER_ELEMENT,n=this.module._malloc(r);return new Uint8Array(this.module.HEAPU8.buffer,n,r).set(new Uint8Array(t.buffer)),new Be(n,void 0,(o)=>this.module._free(o))}newTypedArray(e,t){let r=new e(Array(t).fill(0)),n=r.length*r.BYTES_PER_ELEMENT,o=this.module._malloc(n),i=new e(this.module.HEAPU8.buffer,o,t);return i.set(r),new Be({typedArray:i,ptr:o},void 0,(a)=>this.module._free(a.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),r=t+1,n=this.module._malloc(r);return this.module.stringToUTF8(e,n,r),new Be({ptr:n,strlen:t},void 0,(o)=>this.module._free(o.ptr))}newHeapBufferPointer(e){let t=e.byteLength,r=this.module._malloc(t);return this.module.HEAPU8.set(e,r),new Be({pointer:r,numBytes:t},void 0,(n)=>this.module._free(n.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},iw,aw,Lv,pf=-2147483648,hf=2147483647,ia=0,Dv=class{constructor(){this.nextId=pf,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),r=Iu(t),n=this.groups.get(r);return n||(n=new Map,this.groups.set(r,n)),n.set(t,e),t}get(e){if(e===ia)throw new jt("no host reference id defined");let t=Iu(e),r=this.groups.get(t);if(!r)throw new jt(`host reference id ${e} is not defined`);let n=r.get(e);if(!n)throw new jt(`host reference id ${e} is not defined`);return n}delete(e){if(e===ia)throw new jt("no host reference id defined");let t=Iu(e),r=this.groups.get(t);if(!r)throw new jt(`host reference id ${e} is not defined`);r.delete(e),r.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===ia&&this.nextId++,this.nextId>hf)throw new zf(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${hf-pf}`);return this.nextId++}},ff,Uv,Fv,Zv,Vv=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},Fu=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new Vv({freeHostRef:(t,r,n)=>{let o=this.runtimeCallbacks.get(r);if(!o)throw Error(`QuickJSRuntime(rt = ${r}) not found when trying to free HostRef(id = ${n})`);o.freeHostRef(r,n)},callFunction:(t,r,n,o,i,a)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(r);if(!s)throw Error(`QuickJSContext(ctx = ${r}) not found for C function call "${a}"`);return s.callFunction(r,n,o,i,a)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,r)=>this.handleAsyncify(t,()=>{try{let n=this.runtimeCallbacks.get(r);if(!n)throw Error(`QuickJSRuntime(rt = ${r}) not found for C interrupt`);return n.shouldInterrupt(r)}catch(n){return console.error("[C to host interrupt: returning error]",n),1}}),loadModuleSource:(t,r,n,o)=>this.handleAsyncify(t,()=>{try{let i=this.runtimeCallbacks.get(r);if(!i)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let a=i.loadModuleSource;if(!a)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return a(r,n,o)}catch(i){return console.error("[C to host module loader error: returning null]",i),0}}),normalizeModule:(t,r,n,o,i)=>this.handleAsyncify(t,()=>{try{let a=this.runtimeCallbacks.get(r);if(!a)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let s=a.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return s(r,n,o,i)}catch(a){return console.error("[C to host module loader error: returning null]",a),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((n)=>{try{let o=t();if(!(o instanceof Promise)){fo("asyncify.handleSleep: not suspending:",o),n(o);return}if(this.suspended)throw new Sf(`Already suspended at: ${this.suspended.stack}
4
4
  Attempted to suspend at:`);this.suspended=new yf(`(${this.suspendedCount++})`),fo("asyncify.handleSleep: suspending:",this.suspended),o.then((i)=>{this.suspended=void 0,fo("asyncify.handleSleep: resolved:",i),n(i)},(i)=>{fo("asyncify.handleSleep: rejected:",i),console.error("QuickJS: cannot handle error in suspended function",i),this.suspended=void 0})}catch(o){throw fo("asyncify.handleSleep: error:",o),this.suspended=void 0,o}});let r=t();if(r instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return r}},Ef=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new Fu(e)}newRuntime(e={}){let t=new Be(this.ffi.QTS_NewRuntime(),void 0,(n)=>{this.ffi.QTS_FreeRuntime(n),this.callbacks.deleteRuntime(n)}),r=new Zv({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return Zu(r,e),e.moduleLoader&&r.setModuleLoader(e.moduleLoader),r}newContext(e={}){let t=this.newRuntime(),r=t.newContext({...e,ownedLifetimes:qv(t,e.ownedLifetimes)});return t.context=r,r}evalCode(e,t={}){return lt.withScope((r)=>{let n=r.manage(this.newContext());Vu(n.runtime,t);let o=n.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&n.runtime.setMemoryLimit(-1),o.error)throw n.dump(r.manage(o.error));return n.dump(r.manage(o.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var Tf=da(()=>{sa();sa();wv=Object.defineProperty;Ev={};$v(Ev,{QuickJSAsyncifyError:()=>Sf,QuickJSAsyncifySuspended:()=>yf,QuickJSEmptyGetOwnPropertyNames:()=>Rf,QuickJSEmscriptenModuleError:()=>Pv,QuickJSHostRefInvalid:()=>jt,QuickJSHostRefRangeExceeded:()=>zf,QuickJSMemoryLeakDetected:()=>Tv,QuickJSNotImplemented:()=>_f,QuickJSPromisePending:()=>bf,QuickJSUnknownIntrinsic:()=>vf,QuickJSUnwrapError:()=>Au,QuickJSUseAfterFree:()=>ju,QuickJSWrongOwner:()=>gf});Au=class extends Error{constructor(e,t){let r=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(r);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},gf=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},ju=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},_f=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},Sf=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},yf=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},Tv=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Pv=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},vf=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},bf=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},Rf=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},zf=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},jt=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};Lu=wf;Lu.of=kv;ft=class{[Symbol.dispose](){return this.dispose()}},Mu=Symbol.dispose??Symbol.for("Symbol.dispose"),df=ft.prototype;df[Mu]||(df[Mu]=function(){return this.dispose()});Be=class e extends ft{constructor(t,r,n,o){super();this._value=t,this.copier=r,this.disposer=n,this._owner=o,this._alive=!0,this._constructorStack=qu?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let r=t(this);return this.dispose(),r}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ju(`Lifetime not alive
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcpcloud/runtime",
3
- "version": "0.17.2",
3
+ "version": "0.18.0",
4
4
  "description": "MCPCloud generated-server runtime: transports, config, upstream auth/HTTP, validation, projection, and discovery for MCP servers built on MCPCloud.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",