@mcpcloud/runtime 0.12.4 → 0.14.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/compat-stdio.d.ts +1 -1
- package/dist/compat-stdio.js +46 -35
- package/dist/compat-worker.d.ts +2 -3
- package/dist/compat-worker.js +54 -63
- package/dist/config.d.ts +14 -0
- package/dist/container-host.js +10 -10
- package/dist/index.d.ts +3 -4
- package/dist/index.js +71 -72
- package/dist/node.js +10 -10
- package/dist/sandbox/codeModeTool.d.ts +1 -1
- package/dist/server.d.ts +28 -2
- package/dist/stdio.d.ts +1 -1
- package/dist/stdio.js +53 -42
- package/dist/tool-errors.d.ts +24 -4
- package/package.json +3 -2
package/dist/config.d.ts
CHANGED
|
@@ -75,6 +75,20 @@ export interface ProjectionUsageAccumulator {
|
|
|
75
75
|
export interface CallerContext {
|
|
76
76
|
userId: string | null;
|
|
77
77
|
runtimeToken: string | null;
|
|
78
|
+
/**
|
|
79
|
+
* Which protocol era this request is being served on.
|
|
80
|
+
*
|
|
81
|
+
* Needed because URL elicitation has two incompatible wire shapes and the
|
|
82
|
+
* decision point is deep inside upstream auth resolution, far from the
|
|
83
|
+
* transport that knows the era. 2025-era clients get the `-32042` error;
|
|
84
|
+
* 2026-07-28 clients get an `input_required` RESULT, and the SDK refuses the
|
|
85
|
+
* error outright on that revision.
|
|
86
|
+
*
|
|
87
|
+
* Optional, and absent means `legacy`: that is the shape every existing
|
|
88
|
+
* client and every already-deployed bundle expects, so an omission degrades
|
|
89
|
+
* to today's behavior rather than to a shape nothing understands.
|
|
90
|
+
*/
|
|
91
|
+
era?: 'legacy' | 'modern';
|
|
78
92
|
/**
|
|
79
93
|
* Mutable and request-scoped. `CallerContext` is created fresh per request
|
|
80
94
|
* (the MCP server is too), so accumulating here cannot leak between
|
package/dist/container-host.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
/*! @mcpcloud/runtime v0.
|
|
2
|
-
var
|
|
3
|
-
Then, failed to dispose scope: ${
|
|
4
|
-
Attempted to suspend at:`);this.suspended=new
|
|
1
|
+
/*! @mcpcloud/runtime v0.14.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
|
|
2
|
+
var At=Object.create;var{getPrototypeOf:bt,defineProperty:re,getOwnPropertyNames:Pt}=Object;var Ot=Object.prototype.hasOwnProperty;function vt(e){return this[e]}var Mt,xt,Nt=(e,t,r)=>{var o=e!=null&&typeof e==="object";if(o){var l=t?Mt??=new WeakMap:xt??=new WeakMap,d=l.get(e);if(d)return d}r=e!=null?At(bt(e)):{};let f=t||!e||!e.__esModule?re(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let s of Pt(e))if(!Ot.call(f,s))re(f,s,{get:vt.bind(e,s),enumerable:!0})}if(o)l.set(e,f);return f};var kt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ct=(e)=>e;function It(e,t){this[e]=Ct.bind(null,t)}var Lt=(e,t)=>{for(var r in t)re(e,r,{get:t[r],enumerable:!0,configurable:!0,set:It.bind(t,r)})};var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var U,ie,j,K,H;var V=ne(()=>{U={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},ie={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},j={Pending:0,Fulfilled:1,Rejected:2},K={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},H={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function J(...e){ce&&console.log("quickjs-emscripten:",...e)}function*st(e){return yield e}function Ft(e){return st(de(e))}function je(e,t){return(...r)=>{let o=t.call(e,he,...r);return de(o)}}function Dt(e,t){let r=t.call(e,he);return de(r)}function de(e){function t(r){return r.done?r.value:r.value instanceof Promise?r.value.then((o)=>t(e.next(o)),(o)=>t(e.throw(o))):t(e.next(r.value))}return t(e.next())}function se(e,t){let r;try{e.dispose()}catch(o){r=o}if(t&&r)throw Object.assign(t,{message:`${t.message}
|
|
3
|
+
Then, failed to dispose scope: ${r.message}`,disposeError:r}),t;if(t||r)throw t||r}function Qt(e){let t=e?Array.from(e):[];function r(){return t.forEach((l)=>l.alive?l.dispose():void 0)}function o(){return t.some((l)=>l.alive)}return Object.defineProperty(t,le,{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:o}),t}function W(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Gt(e){if(!e)return 0;let t=0;for(let[r,o]of Object.entries(e)){if(!(r in ie))throw new tt(r);o&&(t|=ie[r])}return t}function Wt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:r,strip:o,compileOnly:l,backtraceBarrier:d}=e,f=0;return t==="global"&&(f|=U.JS_EVAL_TYPE_GLOBAL),t==="module"&&(f|=U.JS_EVAL_TYPE_MODULE),r&&(f|=U.JS_EVAL_FLAG_STRICT),o&&(f|=U.JS_EVAL_FLAG_STRIP),l&&(f|=U.JS_EVAL_FLAG_COMPILE_ONLY),d&&(f|=U.JS_EVAL_FLAG_BACKTRACE_BARRIER),f}function qt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:r,quickjsPrivate:o,onlyEnumerable:l,numbers:d,numbersAsStrings:f}=e,s=0;return t&&(s|=K.JS_GPN_STRING_MASK),r&&(s|=K.JS_GPN_SYMBOL_MASK),o&&(s|=K.JS_GPN_PRIVATE_MASK),l&&(s|=K.JS_GPN_ENUM_ONLY),d&&(s|=K.QTS_GPN_NUMBER_MASK),f&&(s|=K.QTS_STANDARD_COMPLIANT_NUMBER),s}function zt(...e){let t=[];for(let r of e)r!==void 0&&(t=t.concat(r));return t}function oe(e){return e>>8}function pe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function _e(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var Kt,Bt=(e,t)=>{for(var r in t)Kt(e,r,{get:t[r],enumerable:!0})},ce=!1,Yt,ae,ze,ue,Xe,Ze,et,Ht,Jt,tt,rt,nt,it,I,he,N,le,$e,A,B,Ve,M,fe,jt,$t,Y,Vt,ot=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((l)=>l.value)),r=t.length*t.BYTES_PER_ELEMENT,o=this.module._malloc(r);return new Uint8Array(this.module.HEAPU8.buffer,o,r).set(new Uint8Array(t.buffer)),new A(o,void 0,(l)=>this.module._free(l))}newTypedArray(e,t){let r=new e(Array(t).fill(0)),o=r.length*r.BYTES_PER_ELEMENT,l=this.module._malloc(o),d=new e(this.module.HEAPU8.buffer,l,t);return d.set(r),new A({typedArray:d,ptr:l},void 0,(f)=>this.module._free(f.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),r=t+1,o=this.module._malloc(r);return this.module.stringToUTF8(e,o,r),new A({ptr:o,strlen:t},void 0,(l)=>this.module._free(l.ptr))}newHeapBufferPointer(e){let t=e.byteLength,r=this.module._malloc(t);return this.module.HEAPU8.set(e,r),new A({pointer:r,numBytes:t},void 0,(o)=>this.module._free(o.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Lr,Ur,Xt,Ge=-2147483648,We=2147483647,G=0,Zt=class{constructor(){this.nextId=Ge,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),r=oe(t),o=this.groups.get(r);return o||(o=new Map,this.groups.set(r,o)),o.set(t,e),t}get(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),r=this.groups.get(t);if(!r)throw new I(`host reference id ${e} is not defined`);let o=r.get(e);if(!o)throw new I(`host reference id ${e} is not defined`);return o}delete(e){if(e===G)throw new I("no host reference id defined");let t=oe(e),r=this.groups.get(t);if(!r)throw new I(`host reference id ${e} is not defined`);r.delete(e),r.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===G&&this.nextId++,this.nextId>We)throw new it(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${We-Ge}`);return this.nextId++}},qe,er,tr,rr,nr=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},me=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new nr({freeHostRef:(t,r,o)=>{let l=this.runtimeCallbacks.get(r);if(!l)throw Error(`QuickJSRuntime(rt = ${r}) not found when trying to free HostRef(id = ${o})`);l.freeHostRef(r,o)},callFunction:(t,r,o,l,d,f)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(r);if(!s)throw Error(`QuickJSContext(ctx = ${r}) not found for C function call "${f}"`);return s.callFunction(r,o,l,d,f)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,r)=>this.handleAsyncify(t,()=>{try{let o=this.runtimeCallbacks.get(r);if(!o)throw Error(`QuickJSRuntime(rt = ${r}) not found for C interrupt`);return o.shouldInterrupt(r)}catch(o){return console.error("[C to host interrupt: returning error]",o),1}}),loadModuleSource:(t,r,o,l)=>this.handleAsyncify(t,()=>{try{let d=this.runtimeCallbacks.get(r);if(!d)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let f=d.loadModuleSource;if(!f)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return f(r,o,l)}catch(d){return console.error("[C to host module loader error: returning null]",d),0}}),normalizeModule:(t,r,o,l,d)=>this.handleAsyncify(t,()=>{try{let f=this.runtimeCallbacks.get(r);if(!f)throw Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let s=f.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return s(r,o,l,d)}catch(f){return console.error("[C to host module loader error: returning null]",f),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((o)=>{try{let l=t();if(!(l instanceof Promise)){J("asyncify.handleSleep: not suspending:",l),o(l);return}if(this.suspended)throw new Ze(`Already suspended at: ${this.suspended.stack}
|
|
4
|
+
Attempted to suspend at:`);this.suspended=new et(`(${this.suspendedCount++})`),J("asyncify.handleSleep: suspending:",this.suspended),l.then((d)=>{this.suspended=void 0,J("asyncify.handleSleep: resolved:",d),o(d)},(d)=>{J("asyncify.handleSleep: rejected:",d),console.error("QuickJS: cannot handle error in suspended function",d),this.suspended=void 0})}catch(l){throw J("asyncify.handleSleep: error:",l),this.suspended=void 0,l}});let r=t();if(r instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return r}},at=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new me(e)}newRuntime(e={}){let t=new A(this.ffi.QTS_NewRuntime(),void 0,(o)=>{this.ffi.QTS_FreeRuntime(o),this.callbacks.deleteRuntime(o)}),r=new rr({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return pe(r,e),e.moduleLoader&&r.setModuleLoader(e.moduleLoader),r}newContext(e={}){let t=this.newRuntime(),r=t.newContext({...e,ownedLifetimes:zt(t,e.ownedLifetimes)});return t.context=r,r}evalCode(e,t={}){return M.withScope((r)=>{let o=r.manage(this.newContext());_e(o.runtime,t);let l=o.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&o.runtime.setMemoryLimit(-1),l.error)throw o.dump(r.manage(l.error));return o.dump(r.manage(l.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var ut=ne(()=>{V();V();Kt=Object.defineProperty;Yt={};Bt(Yt,{QuickJSAsyncifyError:()=>Ze,QuickJSAsyncifySuspended:()=>et,QuickJSEmptyGetOwnPropertyNames:()=>nt,QuickJSEmscriptenModuleError:()=>Jt,QuickJSHostRefInvalid:()=>I,QuickJSHostRefRangeExceeded:()=>it,QuickJSMemoryLeakDetected:()=>Ht,QuickJSNotImplemented:()=>Xe,QuickJSPromisePending:()=>rt,QuickJSUnknownIntrinsic:()=>tt,QuickJSUnwrapError:()=>ae,QuickJSUseAfterFree:()=>ue,QuickJSWrongOwner:()=>ze});ae=class extends Error{constructor(e,t){let r=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(r);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},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"}},Ht=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Jt=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=Ft;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()});A=class e extends N{constructor(t,r,o,l){super();this._value=t,this.copier=r,this.disposer=o,this._owner=l,this._alive=!0,this._constructorStack=ce?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let r=t(this);return this.dispose(),r}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ue(`Lifetime not alive
|
|
5
5
|
${this._constructorStack}
|
|
6
|
-
Lifetime used`):new Y8("Lifetime not alive")}},v=class extends w{constructor(Z,$){super(Z,void 0,void 0,$)}get dupable(){return!0}dup(){return this}dispose(){}},i8=class extends w{constructor(Z,$,X,Q){super(Z,$,X,Q)}dispose(){this._alive=!1}};I=class Z extends A{constructor(){super(...arguments);this._disposables=new w(new Set),this.manage=($)=>(this._disposables.value.add($),$)}static withScope($){let X=new Z,Q;try{return $(X)}catch(B){throw Q=B,B}finally{K8(X,Q)}}static withScopeMaybeAsync($,X){return d9(void 0,function*(Q){let B=new Z,C;try{return yield*Q.of(X.call($,Q,B))}catch(U){throw C=U,U}finally{K8(B,C)}})}static async withScopeAsync($){let X=new Z,Q;try{return await $(X)}catch(B){throw Q=B,B}finally{K8(X,Q)}}get alive(){return this._disposables.alive}dispose(){let $=Array.from(this._disposables.value.values()).reverse();for(let X of $)X.alive&&X.dispose();this._disposables.dispose()}};C8=class Z extends A{static success($){return new u9($)}static fail($,X){return new l9($,X)}static is($){return $ instanceof Z}},u9=class extends C8{constructor(Z){super();this.value=Z}get alive(){return n(this.value)?this.value.alive:!0}dispose(){n(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(Z){return this.value}},l9=class extends C8{constructor(Z,$){super();this.error=Z,this.onUnwrap=$}get alive(){return n(this.error)?this.error.alive:!0}dispose(){n(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(Z){return Z}},g=C8,i9=class extends A{constructor(Z){super();this.resolve=($)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,$||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=($)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,$||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=Z.context,this.owner=Z.context.runtime,this.handle=Z.promiseHandle,this.settled=new Promise(($)=>{this.onSettled=$}),this.resolveHandle=Z.resolveHandle,this.rejectHandle=Z.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()}},fZ=Symbol("Unstable"),yZ=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});t9=class extends A{constructor(Z,$){super();this.handle=Z,this.context=$,this._isDone=!1,this.owner=$.runtime}[Symbol.iterator](){return this}next(Z){if(!this.alive||this._isDone)return{done:!0,value:void 0};let $=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod($,Z)}return(Z){if(!this.alive)return{done:!0,value:void 0};let $=this.context.getProp(this.handle,"return");if($===this.context.undefined&&Z===void 0)return this.dispose(),{done:!0,value:void 0};let X=this.callIteratorMethod($,Z);return $.dispose(),this.dispose(),X}throw(Z){if(!this.alive)return{done:!0,value:void 0};let $=Z instanceof w?Z:this.context.newError(Z),X=this.context.getProp(this.handle,"throw"),Q=this.callIteratorMethod(X,Z);return $.alive&&$.dispose(),X.dispose(),this.dispose(),Q}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Z,$){let X=$?this.context.callFunction(Z,this.handle,$):this.context.callFunction(Z,this.handle);if(X.error)return this.dispose(),{value:X};let Q=this.context.getProp(X.value,"done").consume((C)=>this.context.dump(C)),B=this.context.getProp(X.value,"value");return X.value.dispose(),Q&&this.dispose(),{value:g.success(B),done:Q}}};a8=class extends A{constructor(Z,$,X){if(X===o)throw new f("cannot create HostRef with undefined id");super();this.runtime=Z,this.handle=$,this.id=X}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},e9=class extends z9{constructor(Z){super(Z.module);this.scope=new I,this.copyJSValue=($)=>this.ffi.QTS_DupValuePointer(this.ctx.value,$),this.freeJSValue=($)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,$)},Z.ownedLifetimes?.forEach(($)=>this.scope.manage($)),this.owner=Z.owner,this.module=Z.module,this.ffi=Z.ffi,this.rt=Z.rt,this.ctx=this.scope.manage(Z.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(Z){return this.scope.manage(Z)}consumeJSCharPointer(Z){let $=this.module.UTF8ToString(Z);return this.ffi.QTS_FreeCString(this.ctx.value,Z),$}heapValueHandle(Z,$){let X=$?(Q)=>{$(),this.freeJSValue(Q)}:this.freeJSValue;return new w(Z,this.copyJSValue,X,this.owner)}staticHeapValueHandle(Z){return this.manage(this.heapValueHandle(Z)),new v(Z,this.owner)}},ZZ=class extends A{constructor(Z){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:($,X,Q,B,C)=>{if($!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let U=this.getFunction(C);return I.withScopeMaybeAsync(this,function*(z,D){let P=D.manage(new i8(X,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),x=Array(Q);for(let M=0;M<Q;M++){let b=this.ffi.QTS_ArgvGetJSValueConstPointer(B,M);x[M]=D.manage(new i8(b,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let M=yield*z(U.apply(P,x));if(M){if("error"in M&&M.error)throw this.runtime.debugLog("throw error",M.error),M.error;let b=D.manage(M instanceof w?M:M.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,b.value)}return 0}catch(M){return this.errorToHandle(M).consume((b)=>this.ffi.QTS_Throw(this.ctx.value,b.value))}})}},this.runtime=Z.runtime,this.module=Z.module,this.ffi=Z.ffi,this.rt=Z.rt,this.ctx=Z.ctx,this.memory=new e9({...Z,owner:this.runtime}),Z.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 Z=this.ffi.QTS_GetUndefined();return this._undefined=new v(Z)}get null(){if(this._null)return this._null;let Z=this.ffi.QTS_GetNull();return this._null=new v(Z)}get true(){if(this._true)return this._true;let Z=this.ffi.QTS_GetTrue();return this._true=new v(Z)}get false(){if(this._false)return this._false;let Z=this.ffi.QTS_GetFalse();return this._false=new v(Z)}get global(){if(this._global)return this._global;let Z=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(Z),this._global}newNumber(Z){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,Z))}newString(Z){let $=this.memory.newHeapCharPointer(Z).consume((X)=>this.ffi.QTS_NewString(this.ctx.value,X.value.ptr));return this.memory.heapValueHandle($)}newUniqueSymbol(Z){let $=(typeof Z=="symbol"?Z.description:Z)??"",X=this.memory.newHeapCharPointer($).consume((Q)=>this.ffi.QTS_NewSymbol(this.ctx.value,Q.value.ptr,0));return this.memory.heapValueHandle(X)}newSymbolFor(Z){let $=(typeof Z=="symbol"?Z.description:Z)??"",X=this.memory.newHeapCharPointer($).consume((Q)=>this.ffi.QTS_NewSymbol(this.ctx.value,Q.value.ptr,1));return this.memory.heapValueHandle(X)}getWellKnownSymbol(Z){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,Z)}newBigInt(Z){if(!this._BigInt){let Q=this.getProp(this.global,"BigInt");this.memory.manage(Q),this._BigInt=new v(Q.value,this.runtime)}let $=this._BigInt,X=String(Z);return this.newString(X).consume((Q)=>this.unwrapResult(this.callFunction($,this.undefined,Q)))}newObject(Z){Z&&this.runtime.assertOwned(Z);let $=Z?this.ffi.QTS_NewObjectProto(this.ctx.value,Z.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle($)}newArray(){let Z=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(Z)}newArrayBuffer(Z){let $=new Uint8Array(Z),X=this.memory.newHeapBufferPointer($),Q=this.ffi.QTS_NewArrayBuffer(this.ctx.value,X.value.pointer,$.length);return this.memory.heapValueHandle(Q)}newPromise(Z){let $=I.withScope((X)=>{let Q=X.manage(this.memory.newMutablePointerArray(2)),B=this.ffi.QTS_NewPromiseCapability(this.ctx.value,Q.value.ptr),C=this.memory.heapValueHandle(B),[U,z]=Array.from(Q.value.typedArray).map((D)=>this.memory.heapValueHandle(D));return new i9({context:this,promiseHandle:C,resolveHandle:U,rejectHandle:z})});return Z&&typeof Z=="function"&&(Z=new Promise(Z)),Z&&Promise.resolve(Z).then($.resolve,(X)=>X instanceof w?$.reject(X):this.newError(X).consume($.reject)),$}newFunction(Z,$){let X=typeof Z=="function"?Z:$;if(!X)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof Z=="string"?Z:void 0,length:X.length,isConstructor:!1,fn:X})}newConstructorFunction(Z,$){let X=typeof Z=="function"?Z:$;if(!X)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof Z=="string"?Z:void 0,length:X.length,isConstructor:!0,fn:X})}newFunctionWithOptions(Z){let{name:$,length:X,isConstructor:Q,fn:B}=Z,C=this.runtime.hostRefs.put(B);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,$??"",X,Q,C))}catch(U){throw this.runtime.hostRefs.delete(C),U}}newError(Z){let $=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return Z&&typeof Z=="object"?(Z.name!==void 0&&this.newString(Z.name).consume((X)=>this.setProp($,"name",X)),Z.message!==void 0&&this.newString(Z.message).consume((X)=>this.setProp($,"message",X))):typeof Z=="string"?this.newString(Z).consume((X)=>this.setProp($,"message",X)):Z!==void 0&&this.newString(String(Z)).consume((X)=>this.setProp($,"message",X)),$}newHostRef(Z){let $=this.runtime.hostRefs.put(Z);try{let X=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,$));return new a8(this.runtime,X,$)}catch(X){throw this.runtime.hostRefs.delete($),X}}toHostRef(Z){let $=this.ffi.QTS_GetHostRefId(Z.value);if($!==0)return this.runtime.hostRefs.get($),new a8(this.runtime,Z.dup(),$)}unwrapHostRef(Z){let $=this.ffi.QTS_GetHostRefId(Z.value);if($===0)throw new f("handle is not a HostRef");return this.runtime.hostRefs.get($)}typeof(Z){return this.runtime.assertOwned(Z),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,Z.value))}getNumber(Z){return this.runtime.assertOwned(Z),this.ffi.QTS_GetFloat64(this.ctx.value,Z.value)}getString(Z){return this.runtime.assertOwned(Z),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,Z.value))}getSymbol(Z){this.runtime.assertOwned(Z);let $=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,Z.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,Z.value)?Symbol.for($):Symbol($)}getBigInt(Z){this.runtime.assertOwned(Z);let $=this.getString(Z);return BigInt($)}getArrayBuffer(Z){this.runtime.assertOwned(Z);let $=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,Z.value),X=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Z.value);if(!X)throw Error("Couldn't allocate memory to get ArrayBuffer");return new w(this.module.HEAPU8.subarray(X,X+$),void 0,()=>this.module._free(X))}getPromiseState(Z){this.runtime.assertOwned(Z);let $=this.ffi.QTS_PromiseState(this.ctx.value,Z.value);if($<0)return{type:"fulfilled",value:Z,notAPromise:!0};if($===l.Pending)return{type:"pending",get error(){return new $9("Cannot unwrap a pending promise")}};let X=this.ffi.QTS_PromiseResult(this.ctx.value,Z.value),Q=this.memory.heapValueHandle(X);if($===l.Fulfilled)return{type:"fulfilled",value:Q};if($===l.Rejected)return{type:"rejected",error:Q};throw Q.dispose(),Error(`Unknown JSPromiseStateEnum: ${$}`)}resolvePromise(Z){this.runtime.assertOwned(Z);let $=I.withScope((X)=>{let Q=X.manage(this.getProp(this.global,"Promise")),B=X.manage(this.getProp(Q,"resolve"));return this.callFunction(B,Q,Z)});return $.error?Promise.resolve($):new Promise((X)=>{I.withScope((Q)=>{let B=Q.manage(this.newFunction("resolve",(D)=>{X(this.success(D&&D.dup()))})),C=Q.manage(this.newFunction("reject",(D)=>{X(this.fail(D&&D.dup()))})),U=Q.manage($.value),z=Q.manage(this.getProp(U,"then"));this.callFunction(z,U,B,C).unwrap().dispose()})})}isEqual(Z,$,X=c.IsStrictlyEqual){if(Z===$)return!0;this.runtime.assertOwned(Z),this.runtime.assertOwned($);let Q=this.ffi.QTS_IsEqual(this.ctx.value,Z.value,$.value,X);if(Q===-1)throw new t8("WASM variant does not expose equality");return!!Q}eq(Z,$){return this.isEqual(Z,$,c.IsStrictlyEqual)}sameValue(Z,$){return this.isEqual(Z,$,c.IsSameValue)}sameValueZero(Z,$){return this.isEqual(Z,$,c.IsSameValueZero)}getProp(Z,$){this.runtime.assertOwned(Z);let X;return typeof $=="number"&&$>=0?X=this.ffi.QTS_GetPropNumber(this.ctx.value,Z.value,$):X=this.borrowPropertyKey($).consume((Q)=>this.ffi.QTS_GetProp(this.ctx.value,Z.value,Q.value)),this.memory.heapValueHandle(X)}getLength(Z){if(this.runtime.assertOwned(Z),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,Z.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(Z,$={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(Z),Z.value;let X=a9($);if(X===0)throw new X9("No options set, will return an empty array");return I.withScope((Q)=>{let B=Q.manage(this.memory.newMutablePointerArray(1)),C=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,B.value.ptr,this.uint32Out.value.ptr,Z.value,X);if(C)return this.fail(this.memory.heapValueHandle(C));let U=this.uint32Out.value.typedArray[0],z=B.value.typedArray[0],D=new Uint32Array(this.module.HEAP8.buffer,z,U),P=Array.from(D).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,z),this.success(p9(P))})}getIterator(Z){let $=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return I.withScope((X)=>{let Q=X.manage(this.getProp(Z,$)),B=this.callFunction(Q,Z);return B.error?B:this.success(new t9(B.value,this))})}setProp(Z,$,X){this.runtime.assertOwned(Z),this.borrowPropertyKey($).consume((Q)=>this.ffi.QTS_SetProp(this.ctx.value,Z.value,Q.value,X.value))}defineProp(Z,$,X){this.runtime.assertOwned(Z),I.withScope((Q)=>{let B=Q.manage(this.borrowPropertyKey($)),C=X.value||this.undefined,U=!!X.configurable,z=!!X.enumerable,D=!!X.value,P=X.get?Q.manage(this.newFunction(X.get.name,X.get)):this.undefined,x=X.set?Q.manage(this.newFunction(X.set.name,X.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Z.value,B.value,C.value,P.value,x.value,U,z,D)})}callFunction(Z,$,...X){this.runtime.assertOwned(Z);let Q,B=X[0];B===void 0||Array.isArray(B)?Q=B??[]:Q=X;let C=this.memory.toPointerArray(Q).consume((z)=>this.ffi.QTS_Call(this.ctx.value,Z.value,$.value,Q.length,z.value)),U=this.ffi.QTS_ResolveException(this.ctx.value,C);return U?(this.ffi.QTS_FreeValuePointer(this.ctx.value,C),this.fail(this.memory.heapValueHandle(U))):this.success(this.memory.heapValueHandle(C))}callMethod(Z,$,X=[]){return this.getProp(Z,$).consume((Q)=>this.callFunction(Q,Z,X))}evalCode(Z,$="eval.js",X){let Q=X===void 0?1:0,B=n9(X),C=this.memory.newHeapCharPointer(Z).consume((z)=>this.ffi.QTS_Eval(this.ctx.value,z.value.ptr,z.value.strlen,$,Q,B)),U=this.ffi.QTS_ResolveException(this.ctx.value,C);return U?(this.ffi.QTS_FreeValuePointer(this.ctx.value,C),this.fail(this.memory.heapValueHandle(U))):this.success(this.memory.heapValueHandle(C))}throw(Z){return this.errorToHandle(Z).consume(($)=>this.ffi.QTS_Throw(this.ctx.value,$.value))}borrowPropertyKey(Z){return typeof Z=="number"?this.newNumber(Z):typeof Z=="string"?this.newString(Z):new v(Z.value,this.runtime)}getMemory(Z){if(Z===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(Z){this.runtime.assertOwned(Z);let $=this.typeof(Z);if($==="string")return this.getString(Z);if($==="number")return this.getNumber(Z);if($==="bigint")return this.getBigInt(Z);if($==="undefined")return;if($==="symbol")return this.getSymbol(Z);let X=this.getPromiseState(Z);if(X.type==="fulfilled"&&!X.notAPromise)return Z.dispose(),{type:X.type,value:X.value.consume(this.dump)};if(X.type==="pending")return Z.dispose(),{type:X.type};if(X.type==="rejected")return Z.dispose(),{type:X.type,error:X.error.consume(this.dump)};let Q=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,Z.value));try{return JSON.parse(Q)}catch{return Q}}unwrapResult(Z){if(Z.error){let $="context"in Z.error?Z.error.context:this,X=Z.error.consume((Q)=>this.dump(Q));if(X&&typeof X=="object"&&typeof X.message=="string"){let{message:Q,name:B,stack:C,...U}=X,z=new Q8(X,$);typeof B=="string"&&(z.name=X.name),z.message=Q;let D=z.stack;throw typeof C=="string"&&(z.stack=`${B}: ${Q}
|
|
7
|
-
${X.stack}Host: ${D}`),Object.assign(z,U),z}throw new Q8(X)}return Z.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(Z){let $=this.runtime.hostRefs.get(Z);if(typeof $!="function")throw Error(`Host reference ${Z} is not a function`);return $}errorToHandle(Z){return Z instanceof w?Z:this.newError(Z)}encodeBinaryJSON(Z){let $=this.ffi.QTS_bjson_encode(this.ctx.value,Z.value);return this.memory.heapValueHandle($)}decodeBinaryJSON(Z){let $=this.ffi.QTS_bjson_decode(this.ctx.value,Z.value);return this.memory.heapValueHandle($)}success(Z){return g.success(Z)}fail(Z){return g.fail(Z,($)=>this.unwrapResult($))}},$Z=class extends A{constructor(Z){super();this.scope=new I,this.contextMap=new Map,this.hostRefs=new r9,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:($,X)=>{if($!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(X)},shouldInterrupt:($)=>{if($!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let X=this.interruptHandler;if(!X)throw Error("QuickJSContext had no interrupt handler");return X(this)?1:0},loadModuleSource:u8(this,function*($,X,Q,B){let C=this.moduleLoader;if(!C)throw Error("Runtime has no module loader");if(X!==this.rt.value)throw Error("Runtime pointer mismatch");let U=this.contextMap.get(Q)??this.newContext({contextPointer:Q});try{let z=yield*$(C(B,U));if(typeof z=="object"&&"error"in z&&z.error)throw this.debugLog("cToHostLoadModule: loader returned error",z.error),z.error;let D=typeof z=="string"?z:("value"in z)?z.value:z;return this.memory.newHeapCharPointer(D).value.ptr}catch(z){return this.debugLog("cToHostLoadModule: caught error",z),U.throw(z),0}}),normalizeModule:u8(this,function*($,X,Q,B,C){let U=this.moduleNormalizer;if(!U)throw Error("Runtime has no module normalizer");if(X!==this.rt.value)throw Error("Runtime pointer mismatch");let z=this.contextMap.get(Q)??this.newContext({contextPointer:Q});try{let D=yield*$(U(B,C,z));if(typeof D=="object"&&"error"in D&&D.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",D.error),D.error;let P=typeof D=="string"?D:D.value;return z.getMemory(this.rt.value).newHeapCharPointer(P).value.ptr}catch(D){return this.debugLog("normalizeModule: caught error",D),z.throw(D),0}})},Z.ownedLifetimes?.forEach(($)=>this.scope.manage($)),this.module=Z.module,this.memory=new z9(this.module),this.ffi=Z.ffi,this.rt=Z.rt,this.callbacks=Z.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),B8&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(Z={}){let $=o9(Z.intrinsics),X=new w(Z.contextPointer||this.ffi.QTS_NewContext(this.rt.value,$),void 0,(B)=>{this.contextMap.delete(B),this.callbacks.deleteContext(B),this.ffi.QTS_FreeContext(B)}),Q=new ZZ({module:this.module,ctx:X,ffi:this.ffi,rt:this.rt,ownedLifetimes:Z.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(X.value,Q),Q}setModuleLoader(Z,$){this.moduleLoader=Z,this.moduleNormalizer=$,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(Z){let $=this.interruptHandler;this.interruptHandler=Z,$||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(Z=-1){let $=this.memory.newMutablePointerArray(1),X=this.ffi.QTS_ExecutePendingJob(this.rt.value,Z??-1,$.value.ptr),Q=$.value.typedArray[0];if($.dispose(),Q===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,X),g.success(0);let B=this.contextMap.get(Q)??this.newContext({contextPointer:Q}),C=B.getMemory(this.rt.value).heapValueHandle(X);if(B.typeof(C)==="number"){let U=B.getNumber(C);return C.dispose(),g.success(U)}else{let U=Object.assign(C,{context:B});return g.fail(U,(z)=>B.unwrapResult(z))}}setMemoryLimit(Z){if(Z<0&&Z!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,Z)}computeMemoryUsage(){let Z=this.getSystemContext().getMemory(this.rt.value);return Z.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,Z.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(Z){if(Z<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,Z)}assertOwned(Z){if(Z.owner&&Z.owner.rt!==this.rt)throw new s8(`Handle is not owned by this runtime: ${Z.owner.rt.value} != ${this.rt.value}`)}setDebugMode(Z){this._debugMode=Z,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,Z?1:0)}isDebugMode(){return this._debugMode}debugLog(...Z){this._debugMode&&console.log("quickjs-emscripten:",...Z)}[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 G9={};f9(G9,{applyModuleEvalRuntimeOptions:()=>j8,applyBaseRuntimeOptions:()=>H8,QuickJSWASMModule:()=>Q9,QuickJSModuleCallbacks:()=>U8});var B9=X8(()=>{Y9()});var j9=A9((a,H9)=>{(function(Z,$){typeof a==="object"&&typeof H9<"u"?$(a):typeof define==="function"&&define.amd?define(["exports"],$):(Z=typeof globalThis<"u"?globalThis:Z||self,$(Z.jmespath={}))})(a,function(Z){let $=(W)=>{return W!==null&&Object.prototype.toString.call(W)==="[object Object]"},X=(W,K)=>{if(W===K)return!0;if(typeof W!==typeof K)return!1;if(Array.isArray(W)&&Array.isArray(K)){if(W.length!==K.length)return!1;for(let Y=0;Y<W.length;Y+=1)if(!X(W[Y],K[Y]))return!1;return!0}if($(W)&&$(K)){let Y=Object.entries(W),G=new Set(Object.keys(K));if(Y.length!==G.size)return!1;for(let[q,H]of Y){if(!X(H,K[q]))return!1;G.delete(q)}return G.size===0}return!1},Q=(W)=>{if(W===""||W===!1||W===null||W===void 0)return!0;if(Array.isArray(W)&&W.length===0)return!0;if($(W)){for(let K in W)if(W.hasOwnProperty(K))return!1;return!0}return!1},B=(W)=>{return W>="a"&&W<="z"||W>="A"&&W<="Z"||W==="_"},C=(W)=>{return W>="0"&&W<="9"||W==="-"},U=(W)=>{return W>="a"&&W<="z"||W>="A"&&W<="Z"||W>="0"&&W<="9"||W==="_"};var z;(function(W){W.TOK_EOF="EOF",W.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",W.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",W.TOK_RBRACKET="Rbracket",W.TOK_RPAREN="Rparen",W.TOK_COMMA="Comma",W.TOK_COLON="Colon",W.TOK_RBRACE="Rbrace",W.TOK_NUMBER="Number",W.TOK_CURRENT="Current",W.TOK_ROOT="Root",W.TOK_EXPREF="Expref",W.TOK_PIPE="Pipe",W.TOK_OR="Or",W.TOK_AND="And",W.TOK_EQ="EQ",W.TOK_GT="GT",W.TOK_LT="LT",W.TOK_GTE="GTE",W.TOK_LTE="LTE",W.TOK_NE="NE",W.TOK_FLATTEN="Flatten",W.TOK_STAR="Star",W.TOK_FILTER="Filter",W.TOK_DOT="Dot",W.TOK_NOT="Not",W.TOK_LBRACE="Lbrace",W.TOK_LBRACKET="Lbracket",W.TOK_LPAREN="Lparen",W.TOK_LITERAL="Literal"})(z||(z={}));let D={"(":z.TOK_LPAREN,")":z.TOK_RPAREN,"*":z.TOK_STAR,",":z.TOK_COMMA,".":z.TOK_DOT,":":z.TOK_COLON,"@":z.TOK_CURRENT,["$"]:z.TOK_ROOT,"]":z.TOK_RBRACKET,"{":z.TOK_LBRACE,"}":z.TOK_RBRACE},P={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class M{constructor(){this._current=0}tokenize(W){let K=[];this._current=0;let Y,G,q;while(this._current<W.length)if(B(W[this._current]))Y=this._current,G=this.consumeUnquotedIdentifier(W),K.push({start:Y,type:z.TOK_UNQUOTEDIDENTIFIER,value:G});else if(D[W[this._current]]!==void 0)K.push({start:this._current,type:D[W[this._current]],value:W[this._current]}),this._current+=1;else if(C(W[this._current]))q=this.consumeNumber(W),K.push(q);else if(W[this._current]==="[")q=this.consumeLBracket(W),K.push(q);else if(W[this._current]==='"')Y=this._current,G=this.consumeQuotedIdentifier(W),K.push({start:Y,type:z.TOK_QUOTEDIDENTIFIER,value:G});else if(W[this._current]==="'")Y=this._current,G=this.consumeRawStringLiteral(W),K.push({start:Y,type:z.TOK_LITERAL,value:G});else if(W[this._current]==="`"){Y=this._current;let H=this.consumeLiteral(W);K.push({start:Y,type:z.TOK_LITERAL,value:H})}else if(P[W[this._current]]!==void 0)q=this.consumeOperator(W),q&&K.push(q);else if(x[W[this._current]]!==void 0)this._current+=1;else if(W[this._current]==="&")if(Y=this._current,this._current+=1,W[this._current]==="&")this._current+=1,K.push({start:Y,type:z.TOK_AND,value:"&&"});else K.push({start:Y,type:z.TOK_EXPREF,value:"&"});else if(W[this._current]==="|")if(Y=this._current,this._current+=1,W[this._current]==="|")this._current+=1,K.push({start:Y,type:z.TOK_OR,value:"||"});else K.push({start:Y,type:z.TOK_PIPE,value:"|"});else{let H=Error(`Unknown character: ${W[this._current]}`);throw H.name="LexerError",H}return K}consumeUnquotedIdentifier(W){let K=this._current;this._current+=1;while(this._current<W.length&&U(W[this._current]))this._current+=1;return W.slice(K,this._current)}consumeQuotedIdentifier(W){let K=this._current;this._current+=1;let Y=W.length;while(W[this._current]!=='"'&&this._current<Y){let G=this._current;if(W[G]==="\\"&&(W[G+1]==="\\"||W[G+1]==='"'))G+=2;else G+=1;this._current=G}return this._current+=1,JSON.parse(W.slice(K,this._current))}consumeRawStringLiteral(W){let K=this._current;this._current+=1;let Y=W.length;while(W[this._current]!=="'"&&this._current<Y){let q=this._current;if(W[q]==="\\"&&(W[q+1]==="\\"||W[q+1]==="'"))q+=2;else q+=1;this._current=q}return this._current+=1,W.slice(K+1,this._current-1).replace("\\'","'")}consumeNumber(W){let K=this._current;this._current+=1;let Y=W.length;while(C(W[this._current])&&this._current<Y)this._current+=1;let G=parseInt(W.slice(K,this._current),10);return{start:K,value:G,type:z.TOK_NUMBER}}consumeLBracket(W){let K=this._current;if(this._current+=1,W[this._current]==="?")return this._current+=1,{start:K,type:z.TOK_FILTER,value:"[?"};if(W[this._current]==="]")return this._current+=1,{start:K,type:z.TOK_FLATTEN,value:"[]"};return{start:K,type:z.TOK_LBRACKET,value:"["}}consumeOperator(W){let K=this._current,Y=W[K];if(this._current+=1,Y==="!"){if(W[this._current]==="=")return this._current+=1,{start:K,type:z.TOK_NE,value:"!="};return{start:K,type:z.TOK_NOT,value:"!"}}if(Y==="<"){if(W[this._current]==="=")return this._current+=1,{start:K,type:z.TOK_LTE,value:"<="};return{start:K,type:z.TOK_LT,value:"<"}}if(Y===">"){if(W[this._current]==="=")return this._current+=1,{start:K,type:z.TOK_GTE,value:">="};return{start:K,type:z.TOK_GT,value:">"}}if(Y==="="&&W[this._current]==="=")return this._current+=1,{start:K,type:z.TOK_EQ,value:"=="}}consumeLiteral(W){this._current+=1;let K=this._current,Y=W.length;while(W[this._current]!=="`"&&this._current<Y){let H=this._current;if(W[H]==="\\"&&(W[H+1]==="\\"||W[H+1]==="`"))H+=2;else H+=1;this._current=H}let G=W.slice(K,this._current).trimLeft();G=G.replace("\\`","`");let q=this.looksLikeJSON(G)?JSON.parse(G):JSON.parse(`"${G}"`);return this._current+=1,q}looksLikeJSON(W){let Y=["true","false","null"],G="-0123456789";if(W==="")return!1;if('[{"'.includes(W[0]))return!0;if(Y.includes(W))return!0;if("-0123456789".includes(W[0]))try{return JSON.parse(W),!0}catch(q){return!1}return!1}}let b=new M,_={[z.TOK_EOF]:0,[z.TOK_UNQUOTEDIDENTIFIER]:0,[z.TOK_QUOTEDIDENTIFIER]:0,[z.TOK_RBRACKET]:0,[z.TOK_RPAREN]:0,[z.TOK_COMMA]:0,[z.TOK_RBRACE]:0,[z.TOK_NUMBER]:0,[z.TOK_CURRENT]:0,[z.TOK_EXPREF]:0,[z.TOK_ROOT]:0,[z.TOK_PIPE]:1,[z.TOK_OR]:2,[z.TOK_AND]:3,[z.TOK_EQ]:5,[z.TOK_GT]:5,[z.TOK_LT]:5,[z.TOK_GTE]:5,[z.TOK_LTE]:5,[z.TOK_NE]:5,[z.TOK_FLATTEN]:9,[z.TOK_STAR]:20,[z.TOK_FILTER]:21,[z.TOK_DOT]:40,[z.TOK_NOT]:45,[z.TOK_LBRACE]:50,[z.TOK_LBRACKET]:55,[z.TOK_LPAREN]:60};class O8{constructor(){this.index=0,this.tokens=[]}parse(W){this.loadTokens(W),this.index=0;let K=this.expression(0);if(this.lookahead(0)!==z.TOK_EOF){let Y=this.lookaheadToken(0);this.errorToken(Y,`Unexpected token type: ${Y.type}, value: ${Y.value}`)}return K}loadTokens(W){this.tokens=[...b.tokenize(W),{type:z.TOK_EOF,value:"",start:W.length}]}expression(W){let K=this.lookaheadToken(0);this.advance();let Y=this.nud(K),G=this.lookahead(0);while(W<_[G])this.advance(),Y=this.led(G,Y),G=this.lookahead(0);return Y}lookahead(W){return this.tokens[this.index+W].type}lookaheadToken(W){return this.tokens[this.index+W]}advance(){this.index+=1}nud(W){let K,Y,G;switch(W.type){case z.TOK_LITERAL:return{type:"Literal",value:W.value};case z.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:W.value};case z.TOK_QUOTEDIDENTIFIER:let q={type:"Field",name:W.value};if(this.lookahead(0)===z.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return q;case z.TOK_NOT:return Y=this.expression(_.Not),{type:"NotExpression",children:[Y]};case z.TOK_STAR:return K={type:"Identity"},Y=this.lookahead(0)===z.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(_.Star),{type:"ValueProjection",children:[K,Y]};case z.TOK_FILTER:return this.led(W.type,{type:"Identity"});case z.TOK_LBRACE:return this.parseMultiselectHash();case z.TOK_FLATTEN:return K={type:z.TOK_FLATTEN,children:[{type:"Identity"}]},Y=this.parseProjectionRHS(_.Flatten),{type:"Projection",children:[K,Y]};case z.TOK_LBRACKET:if(this.lookahead(0)===z.TOK_NUMBER||this.lookahead(0)===z.TOK_COLON)return Y=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},Y);if(this.lookahead(0)===z.TOK_STAR&&this.lookahead(1)===z.TOK_RBRACKET)return this.advance(),this.advance(),Y=this.parseProjectionRHS(_.Star),{children:[{type:"Identity"},Y],type:"Projection"};return this.parseMultiselectList();case z.TOK_CURRENT:return{type:z.TOK_CURRENT};case z.TOK_ROOT:return{type:z.TOK_ROOT};case z.TOK_EXPREF:return G=this.expression(_.Expref),{type:"ExpressionReference",children:[G]};case z.TOK_LPAREN:let H=[];while(this.lookahead(0)!==z.TOK_RPAREN){if(this.lookahead(0)===z.TOK_CURRENT)G={type:z.TOK_CURRENT},this.advance();else G=this.expression(0);H.push(G)}return this.match(z.TOK_RPAREN),H[0];default:this.errorToken(W)}}led(W,K){let Y;switch(W){case z.TOK_DOT:let G=_.Dot;if(this.lookahead(0)!==z.TOK_STAR)return Y=this.parseDotRHS(G),{type:"Subexpression",children:[K,Y]};return this.advance(),Y=this.parseProjectionRHS(G),{type:"ValueProjection",children:[K,Y]};case z.TOK_PIPE:return Y=this.expression(_.Pipe),{type:z.TOK_PIPE,children:[K,Y]};case z.TOK_OR:return Y=this.expression(_.Or),{type:"OrExpression",children:[K,Y]};case z.TOK_AND:return Y=this.expression(_.And),{type:"AndExpression",children:[K,Y]};case z.TOK_LPAREN:let q=K.name,H=[],L;while(this.lookahead(0)!==z.TOK_RPAREN){if(this.lookahead(0)===z.TOK_CURRENT)L={type:z.TOK_CURRENT},this.advance();else L=this.expression(0);if(this.lookahead(0)===z.TOK_COMMA)this.match(z.TOK_COMMA);H.push(L)}return this.match(z.TOK_RPAREN),{name:q,type:"Function",children:H};case z.TOK_FILTER:let O=this.expression(0);return this.match(z.TOK_RBRACKET),Y=this.lookahead(0)===z.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(_.Filter),{type:"FilterProjection",children:[K,Y,O]};case z.TOK_FLATTEN:let N={type:z.TOK_FLATTEN,children:[K]},R=this.parseProjectionRHS(_.Flatten);return{type:"Projection",children:[N,R]};case z.TOK_EQ:case z.TOK_NE:case z.TOK_GT:case z.TOK_GTE:case z.TOK_LT:case z.TOK_LTE:return this.parseComparator(K,W);case z.TOK_LBRACKET:let j=this.lookaheadToken(0);if(j.type===z.TOK_NUMBER||j.type===z.TOK_COLON)return Y=this.parseIndexExpression(),this.projectIfSlice(K,Y);return this.match(z.TOK_STAR),this.match(z.TOK_RBRACKET),Y=this.parseProjectionRHS(_.Star),{type:"Projection",children:[K,Y]};default:return this.errorToken(this.lookaheadToken(0))}}match(W){if(this.lookahead(0)===W){this.advance();return}else{let K=this.lookaheadToken(0);this.errorToken(K,`Expected ${W}, got: ${K.type}`)}}errorToken(W,K=""){let Y=Error(K||`Invalid token (${W.type}): "${W.value}"`);throw Y.name="ParserError",Y}parseIndexExpression(){if(this.lookahead(0)===z.TOK_COLON||this.lookahead(1)===z.TOK_COLON)return this.parseSliceExpression();let W={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(z.TOK_RBRACKET),W}projectIfSlice(W,K){let Y={type:"IndexExpression",children:[W,K]};if(K.type==="Slice")return{children:[Y,this.parseProjectionRHS(_.Star)],type:"Projection"};return Y}parseSliceExpression(){let W=[null,null,null],K=0,Y=this.lookahead(0);while(Y!==z.TOK_RBRACKET&&K<3){if(Y===z.TOK_COLON)K+=1,this.advance();else if(Y===z.TOK_NUMBER)W[K]=this.lookaheadToken(0).value,this.advance();else{let G=this.lookaheadToken(0);this.errorToken(G,`Syntax error, unexpected token: ${G.value}(${G.type})`)}Y=this.lookahead(0)}return this.match(z.TOK_RBRACKET),{children:W,type:"Slice"}}parseComparator(W,K){let Y=this.expression(_[K]);return{type:"Comparator",name:K,children:[W,Y]}}parseDotRHS(W){let K=this.lookahead(0);if([z.TOK_UNQUOTEDIDENTIFIER,z.TOK_QUOTEDIDENTIFIER,z.TOK_STAR].includes(K))return this.expression(W);if(K===z.TOK_LBRACKET)return this.match(z.TOK_LBRACKET),this.parseMultiselectList();if(K===z.TOK_LBRACE)return this.match(z.TOK_LBRACE),this.parseMultiselectHash();let G=this.lookaheadToken(0);this.errorToken(G,`Syntax error, unexpected token: ${G.value}(${G.type})`)}parseProjectionRHS(W){if(_[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===z.TOK_LBRACKET)return this.expression(W);if(this.lookahead(0)===z.TOK_FILTER)return this.expression(W);if(this.lookahead(0)===z.TOK_DOT)return this.match(z.TOK_DOT),this.parseDotRHS(W);let K=this.lookaheadToken(0);this.errorToken(K,`Syntax error, unexpected token: ${K.value}(${K.type})`)}parseMultiselectList(){let W=[];while(this.lookahead(0)!==z.TOK_RBRACKET){let K=this.expression(0);if(W.push(K),this.lookahead(0)===z.TOK_COMMA){if(this.match(z.TOK_COMMA),this.lookahead(0)===z.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(z.TOK_RBRACKET),{type:"MultiSelectList",children:W}}parseMultiselectHash(){let W=[],K=[z.TOK_UNQUOTEDIDENTIFIER,z.TOK_QUOTEDIDENTIFIER],Y,G,q;for(;;){if(Y=this.lookaheadToken(0),!K.includes(Y.type))throw Error(`Expecting an identifier token, got: ${Y.type}`);if(G=Y.value,this.advance(),this.match(z.TOK_COLON),q=this.expression(0),W.push({value:q,type:"KeyValuePair",name:G}),this.lookahead(0)===z.TOK_COMMA)this.match(z.TOK_COMMA);else if(this.lookahead(0)===z.TOK_RBRACE){this.match(z.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:W}}}let R8=new O8;var J;(function(W){W[W.TYPE_NUMBER=0]="TYPE_NUMBER",W[W.TYPE_ANY=1]="TYPE_ANY",W[W.TYPE_STRING=2]="TYPE_STRING",W[W.TYPE_ARRAY=3]="TYPE_ARRAY",W[W.TYPE_OBJECT=4]="TYPE_OBJECT",W[W.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",W[W.TYPE_EXPREF=6]="TYPE_EXPREF",W[W.TYPE_NULL=7]="TYPE_NULL",W[W.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",W[W.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(J||(J={}));class M8{constructor(W){this.TYPE_NAME_TABLE={[J.TYPE_NUMBER]:"number",[J.TYPE_ANY]:"any",[J.TYPE_STRING]:"string",[J.TYPE_ARRAY]:"array",[J.TYPE_OBJECT]:"object",[J.TYPE_BOOLEAN]:"boolean",[J.TYPE_EXPREF]:"expression",[J.TYPE_NULL]:"null",[J.TYPE_ARRAY_NUMBER]:"Array<number>",[J.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([K])=>{return Math.abs(K)},this.functionAvg=([K])=>{let Y=0;for(let G=0;G<K.length;G+=1)Y+=K[G];return Y/K.length},this.functionCeil=([K])=>{return Math.ceil(K)},this.functionContains=(K)=>{let[Y,G]=K;return Y.includes(G)},this.functionEndsWith=(K)=>{let[Y,G]=K;return Y.includes(G,Y.length-G.length)},this.functionFloor=([K])=>{return Math.floor(K)},this.functionJoin=(K)=>{let[Y,G]=K;return G.join(Y)},this.functionKeys=([K])=>{return Object.keys(K)},this.functionLength=([K])=>{if(!$(K))return K.length;return Object.keys(K).length},this.functionMap=(K)=>{if(!this._interpreter)return[];let Y=[],G=this._interpreter,q=K[0],H=K[1];for(let L=0;L<H.length;L+=1)Y.push(G.visit(q,H[L]));return Y},this.functionMax=([K])=>{if(!K.length)return null;if(this.getTypeName(K[0])===J.TYPE_NUMBER)return Math.max(...K);let G=K,q=G[0];for(let H=1;H<G.length;H+=1)if(q.localeCompare(G[H])<0)q=G[H];return q},this.functionMaxBy=(K)=>{let Y=K[1],G=K[0],q=this.createKeyFunction(Y,[J.TYPE_NUMBER,J.TYPE_STRING]),H=-1/0,L,F;for(let O=0;O<G.length;O+=1)if(F=q&&q(G[O]),F!==void 0&&F>H)H=F,L=G[O];return L},this.functionMerge=(K)=>{let Y={};for(let G=0;G<K.length;G+=1){let q=K[G];Y=Object.assign(Y,q)}return Y},this.functionMin=([K])=>{if(!K.length)return null;if(this.getTypeName(K[0])===J.TYPE_NUMBER)return Math.min(...K);let G=K,q=G[0];for(let H=1;H<G.length;H+=1)if(G[H].localeCompare(q)<0)q=G[H];return q},this.functionMinBy=(K)=>{let Y=K[1],G=K[0],q=this.createKeyFunction(Y,[J.TYPE_NUMBER,J.TYPE_STRING]),H=1/0,L,F;for(let O=0;O<G.length;O+=1)if(F=q&&q(G[O]),F!==void 0&&F<H)H=F,L=G[O];return L},this.functionNotNull=(K)=>{for(let Y=0;Y<K.length;Y+=1)if(this.getTypeName(K[Y])!==J.TYPE_NULL)return K[Y];return null},this.functionReverse=([K])=>{if(this.getTypeName(K)===J.TYPE_STRING){let q=K,H="";for(let L=q.length-1;L>=0;L-=1)H+=q[L];return H}let G=K.slice(0);return G.reverse(),G},this.functionSort=([K])=>{return[...K].sort()},this.functionSortBy=(K)=>{if(!this._interpreter)return[];let Y=K[0].slice(0);if(Y.length===0)return Y;let G=this._interpreter,q=K[1],H=this.getTypeName(G.visit(q,Y[0]));if(H!==void 0&&![J.TYPE_NUMBER,J.TYPE_STRING].includes(H))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[H]})`);let L=[];for(let F=0;F<Y.length;F+=1)L.push([F,Y[F]]);L.sort((F,O)=>{let N=G.visit(q,F[1]),R=G.visit(q,O[1]);if(this.getTypeName(N)!==H)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[H]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(N)]}`);else if(this.getTypeName(R)!==H)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[H]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(R)]}`);if(N>R)return 1;return N<R?-1:F[0]-O[0]});for(let F=0;F<L.length;F+=1)Y[F]=L[F][1];return Y},this.functionStartsWith=([K,Y])=>{return K.startsWith(Y)},this.functionSum=([K])=>{return K.reduce((Y,G)=>Y+G,0)},this.functionToArray=([K])=>{if(this.getTypeName(K)===J.TYPE_ARRAY)return K;return[K]},this.functionToNumber=([K])=>{let Y=this.getTypeName(K),G;if(Y===J.TYPE_NUMBER)return K;if(Y===J.TYPE_STRING){if(G=+K,!isNaN(G))return G}return null},this.functionToString=([K])=>{if(this.getTypeName(K)===J.TYPE_STRING)return K;return JSON.stringify(K)},this.functionType=([K])=>{switch(this.getTypeName(K)){case J.TYPE_NUMBER:return"number";case J.TYPE_STRING:return"string";case J.TYPE_ARRAY:return"array";case J.TYPE_OBJECT:return"object";case J.TYPE_BOOLEAN:return"boolean";case J.TYPE_EXPREF:return"expref";case J.TYPE_NULL:return"null";default:return}},this.functionValues=([K])=>{return Object.values(K)},this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[J.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[J.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[J.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[J.TYPE_STRING,J.TYPE_ARRAY]},{types:[J.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[J.TYPE_STRING]},{types:[J.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[J.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[J.TYPE_STRING]},{types:[J.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[J.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[J.TYPE_STRING,J.TYPE_ARRAY,J.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[J.TYPE_EXPREF]},{types:[J.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[J.TYPE_ARRAY_NUMBER,J.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[J.TYPE_ARRAY]},{types:[J.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[J.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[J.TYPE_ARRAY_NUMBER,J.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[J.TYPE_ARRAY]},{types:[J.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[J.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[J.TYPE_STRING,J.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[J.TYPE_ARRAY_STRING,J.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[J.TYPE_ARRAY]},{types:[J.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[J.TYPE_STRING]},{types:[J.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[J.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[J.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[J.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[J.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[J.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[J.TYPE_OBJECT]}]}},this._interpreter=W}registerFunction(W,K,Y){if(W in this.functionTable)throw Error(`Function already defined: ${W}()`);this.functionTable[W]={_func:K.bind(this),_signature:Y}}callFunction(W,K){let Y=this.functionTable[W];if(Y===void 0)throw Error(`Unknown function: ${W}()`);return this.validateArgs(W,K,Y._signature),Y._func.call(this,K)}validateInputSignatures(W,K){for(let Y=0;Y<K.length;Y+=1)if("variadic"in K[Y]&&Y!==K.length-1)throw Error(`ArgumentError: ${W}() 'variadic' argument ${Y+1} must occur last`)}validateArgs(W,K,Y){var G,q;let H;this.validateInputSignatures(W,Y);let L=Y.filter((E)=>{var S;return(S=!E.optional)!==null&&S!==void 0?S:!1}).length,F=(q=(G=Y[Y.length-1])===null||G===void 0?void 0:G.variadic)!==null&&q!==void 0?q:!1,O=K.length<L,N=K.length>Y.length,R=O&&(!F&&L>1||F)?"at least ":"";if(F&&O||!F&&(O||N))throw H=Y.length>1,Error(`ArgumentError: ${W}() takes ${R}${L} argument${H&&"s"||""} but received ${K.length}`);let j,V,T;for(let E=0;E<Y.length;E+=1){T=!1,j=Y[E].types,V=this.getTypeName(K[E]);let S;for(S=0;S<j.length;S+=1)if(V!==void 0&&this.typeMatches(V,j[S],K[E])){T=!0;break}if(!T&&V!==void 0){let d=j.map((p)=>{return this.TYPE_NAME_TABLE[p]}).join(" | ");throw Error(`TypeError: ${W}() expected argument ${E+1} to be type (${d}) but received type ${this.TYPE_NAME_TABLE[V]} instead.`)}}}typeMatches(W,K,Y){if(K===J.TYPE_ANY)return!0;if(K===J.TYPE_ARRAY_STRING||K===J.TYPE_ARRAY_NUMBER||K===J.TYPE_ARRAY){if(K===J.TYPE_ARRAY)return W===J.TYPE_ARRAY;if(W===J.TYPE_ARRAY){let G;if(K===J.TYPE_ARRAY_NUMBER)G=J.TYPE_NUMBER;else if(K===J.TYPE_ARRAY_STRING)G=J.TYPE_STRING;for(let q=0;q<Y.length;q+=1){let H=this.getTypeName(Y[q]);if(H!==void 0&&G!==void 0&&!this.typeMatches(H,G,Y[q]))return!1}return!0}}else return W===K;return!1}getTypeName(W){switch(Object.prototype.toString.call(W)){case"[object String]":return J.TYPE_STRING;case"[object Number]":return J.TYPE_NUMBER;case"[object Array]":return J.TYPE_ARRAY;case"[object Boolean]":return J.TYPE_BOOLEAN;case"[object Null]":return J.TYPE_NULL;case"[object Object]":if(W.jmespathType===z.TOK_EXPREF)return J.TYPE_EXPREF;return J.TYPE_OBJECT;default:return}}createKeyFunction(W,K){if(!this._interpreter)return;let Y=this._interpreter;return(q)=>{let H=Y.visit(W,q);if(!K.includes(this.getTypeName(H))){let L=`TypeError: expected one of (${K.map((F)=>this.TYPE_NAME_TABLE[F]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(H)]}`;throw Error(L)}return H}}}class V8{constructor(){this._rootValue=null,this.runtime=new M8(this)}search(W,K){return this._rootValue=K,this.visit(W,K)}visit(W,K){let Y,G,q,H,L,F,O,N,R,j,V;switch(W.type){case"Field":if(K===null)return null;if($(K)){if(F=K[W.name],F===void 0)return null;return F}return null;case"Subexpression":q=this.visit(W.children[0],K);for(j=1;j<W.children.length;j+=1)if(q=this.visit(W.children[1],q),q===null)return null;return q;case"IndexExpression":return O=this.visit(W.children[0],K),N=this.visit(W.children[1],O),N;case"Index":if(!Array.isArray(K))return null;let T=W.value;if(T<0)T=K.length+T;if(q=K[T],q===void 0)q=null;return q;case"Slice":if(!Array.isArray(K))return null;let E=[...W.children],S=this.computeSliceParams(K.length,E),[d,p,t]=S;if(q=[],t>0)for(j=d;j<p;j+=t)q.push(K[j]);else for(j=d;j>p;j+=t)q.push(K[j]);return q;case"Projection":if(V=this.visit(W.children[0],K),!Array.isArray(V))return null;R=[];for(j=0;j<V.length;j+=1)if(G=this.visit(W.children[1],V[j]),G!==null)R.push(G);return R;case"ValueProjection":if(V=this.visit(W.children[0],K),!$(V))return null;R=[];let g8=Object.values(V);for(j=0;j<g8.length;j+=1)if(G=this.visit(W.children[1],g8[j]),G!==null)R.push(G);return R;case"FilterProjection":if(V=this.visit(W.children[0],K),!Array.isArray(V))return null;let r=[],c8=[];for(j=0;j<V.length;j+=1)if(Y=this.visit(W.children[2],V[j]),!Q(Y))r.push(V[j]);for(let y=0;y<r.length;y+=1)if(G=this.visit(W.children[1],r[y]),G!==null)c8.push(G);return c8;case"Comparator":switch(H=this.visit(W.children[0],K),L=this.visit(W.children[1],K),W.name){case z.TOK_EQ:q=X(H,L);break;case z.TOK_NE:q=!X(H,L);break;case z.TOK_GT:q=H>L;break;case z.TOK_GTE:q=H>=L;break;case z.TOK_LT:q=H<L;break;case z.TOK_LTE:q=H<=L;break;default:throw Error(`Unknown comparator: ${W.name}`)}return q;case z.TOK_FLATTEN:let e=this.visit(W.children[0],K);if(!Array.isArray(e))return null;let u=[];for(j=0;j<e.length;j+=1)if(G=e[j],Array.isArray(G))u=[...u,...G];else u.push(G);return u;case"Identity":return K;case"MultiSelectList":if(K===null)return null;R=[];for(j=0;j<W.children.length;j+=1)R.push(this.visit(W.children[j],K));return R;case"MultiSelectHash":if(K===null)return null;R={};let Z8;for(j=0;j<W.children.length;j+=1)Z8=W.children[j],R[Z8.name]=this.visit(Z8.value,K);return R;case"OrExpression":if(Y=this.visit(W.children[0],K),Q(Y))Y=this.visit(W.children[1],K);return Y;case"AndExpression":if(H=this.visit(W.children[0],K),Q(H))return H;return this.visit(W.children[1],K);case"NotExpression":return H=this.visit(W.children[0],K),Q(H);case"Literal":return W.value;case z.TOK_PIPE:return O=this.visit(W.children[0],K),this.visit(W.children[1],O);case z.TOK_CURRENT:return K;case z.TOK_ROOT:return this._rootValue;case"Function":let m8=[];for(let y=0;y<W.children.length;y+=1)m8.push(this.visit(W.children[y],K));return this.runtime.callFunction(W.name,m8);case"ExpressionReference":let d8=W.children[0];return d8.jmespathType=z.TOK_EXPREF,d8;default:throw Error(`Unknown node type: ${W.type}`)}}computeSliceParams(W,K){let[Y,G,q]=K;if(q===null)q=1;else if(q===0){let L=Error("Invalid slice, step cannot be 0");throw L.name="RuntimeError",L}let H=q<0?!0:!1;return Y=Y===null?H?W-1:0:this.capSliceRange(W,Y,q),G=G===null?H?-1:W:this.capSliceRange(W,G,q),[Y,G,q]}capSliceRange(W,K,Y){let G=K;if(G<0){if(G+=W,G<0)G=Y<0?-1:0}else if(G>=W)G=Y<0?W-1:W;return G}}let s=new V8,_8=J.TYPE_ANY,w8=J.TYPE_ARRAY,P8=J.TYPE_ARRAY_NUMBER,N8=J.TYPE_ARRAY_STRING,E8=J.TYPE_BOOLEAN,S8=J.TYPE_EXPREF,I8=J.TYPE_NULL,x8=J.TYPE_NUMBER,A8=J.TYPE_OBJECT,b8=J.TYPE_STRING;function T8(W){return R8.parse(W)}function f8(W){return b.tokenize(W)}let y8=(W,K,Y)=>{s.runtime.registerFunction(W,K,Y)};function k8(W,K){let Y=R8.parse(K);return s.search(Y,W)}let h8=s,v8={compile:T8,registerFunction:y8,search:k8,tokenize:f8,TreeInterpreter:h8,TYPE_ANY:_8,TYPE_ARRAY_NUMBER:P8,TYPE_ARRAY_STRING:N8,TYPE_ARRAY:w8,TYPE_BOOLEAN:E8,TYPE_EXPREF:S8,TYPE_NULL:I8,TYPE_NUMBER:x8,TYPE_OBJECT:A8,TYPE_STRING:b8};Z.TYPE_ANY=_8,Z.TYPE_ARRAY=w8,Z.TYPE_ARRAY_NUMBER=P8,Z.TYPE_ARRAY_STRING=N8,Z.TYPE_BOOLEAN=E8,Z.TYPE_EXPREF=S8,Z.TYPE_NULL=I8,Z.TYPE_NUMBER=x8,Z.TYPE_OBJECT=A8,Z.TYPE_STRING=b8,Z.TreeInterpreter=h8,Z.compile=T8,Z.default=v8,Z.jmespath=v8,Z.registerFunction=y8,Z.search=k8,Z.tokenize=f8,Object.defineProperty(Z,"__esModule",{value:!0})})});import{mkdirSync as RZ,mkdtempSync as MZ,writeFileSync as VZ}from"node:fs";import{tmpdir as _Z}from"node:os";import{dirname as wZ,join as L8}from"node:path";import{pathToFileURL as PZ}from"node:url";import{timingSafeEqual as UZ}from"node:crypto";import{createServer as HZ}from"node:http";import{Readable as jZ}from"node:stream";function y9(){return typeof process>"u"?{}:process.env}function p8(Z=y9()){return Z.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as qZ}from"node:fs";i();async function J9(Z){let $=D8(await Z),[X,Q,{QuickJSWASMModule:B}]=await Promise.all([$.importModuleLoader().then(D8),$.importFFI(),Promise.resolve().then(() => (B9(),G9)).then(D8)]),C=await X();C.type="sync";let U=new Q(C);return new B(C,U)}function D8(Z){return Z&&"default"in Z&&Z.default?Z.default&&"default"in Z.default&&Z.default.default?Z.default.default:Z.default:Z}var C9="engine";function WZ(Z){let $=(X)=>new URL(X,Z).href;return{type:"sync",importFFI:()=>import($("ffi.mjs")).then((X)=>X.QuickJSFFI),importModuleLoader:()=>import($("emscripten-module.mjs")).then((X)=>X.default)}}var q9=null;function U9(Z){return()=>{return q9??=J9(WZ(Z)),q9}}var KZ=x9(j9(),1);var QZ="__mcpcloud_call_tool",_1=`globalThis.tool = (name, args) =>
|
|
8
|
-
globalThis.${
|
|
9
|
-
.then((json) => JSON.parse(json));`;var
|
|
10
|
-
${
|
|
6
|
+
Lifetime used`):new ue("Lifetime not alive")}},B=class extends A{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},Ve=class extends A{constructor(e,t,r,o){super(e,t,r,o)}dispose(){this._alive=!1}};M=class e extends N{constructor(){super(...arguments);this._disposables=new A(new Set),this.manage=(t)=>(this._disposables.value.add(t),t)}static withScope(t){let r=new e,o;try{return t(r)}catch(l){throw o=l,l}finally{se(r,o)}}static withScopeMaybeAsync(t,r){return Dt(void 0,function*(o){let l=new e,d;try{return yield*o.of(r.call(t,o,l))}catch(f){throw d=f,f}finally{se(l,d)}})}static async withScopeAsync(t){let r=new e,o;try{return await t(r)}catch(l){throw o=l,l}finally{se(r,o)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let r of t)r.alive&&r.dispose();this._disposables.dispose()}};fe=class e extends N{static success(t){return new jt(t)}static fail(t,r){return new $t(t,r)}static is(t){return t instanceof e}},jt=class extends fe{constructor(e){super();this.value=e}get alive(){return W(this.value)?this.value.alive:!0}dispose(){W(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},$t=class extends fe{constructor(e,t){super();this.error=e,this.onUnwrap=t}get alive(){return W(this.error)?this.error.alive:!0}dispose(){W(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},Y=fe,Vt=class extends N{constructor(e){super();this.resolve=(t)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(t)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise((t)=>{this.onSettled=t}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},Lr=Symbol("Unstable"),Ur=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});Xt=class extends N{constructor(e,t){super();this.handle=e,this.context=t,this._isDone=!1,this.owner=t.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let t=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(t,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let t=this.context.getProp(this.handle,"return");if(t===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let r=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),r}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof A?e:this.context.newError(e),r=this.context.getProp(this.handle,"throw"),o=this.callIteratorMethod(r,e);return t.alive&&t.dispose(),r.dispose(),this.dispose(),o}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let r=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(r.error)return this.dispose(),{value:r};let o=this.context.getProp(r.value,"done").consume((d)=>this.context.dump(d)),l=this.context.getProp(r.value,"value");return r.value.dispose(),o&&this.dispose(),{value:Y.success(l),done:o}}};qe=class extends N{constructor(e,t,r){if(r===G)throw new I("cannot create HostRef with undefined id");super();this.runtime=e,this.handle=t,this.id=r}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},er=class extends ot{constructor(e){super(e.module);this.scope=new M,this.copyJSValue=(t)=>this.ffi.QTS_DupValuePointer(this.ctx.value,t),this.freeJSValue=(t)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,t)},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let t=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),t}heapValueHandle(e,t){let r=t?(o)=>{t(),this.freeJSValue(o)}:this.freeJSValue;return new A(e,this.copyJSValue,r,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new B(e,this.owner)}},tr=class extends N{constructor(e){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:(t,r,o,l,d)=>{if(t!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let f=this.getFunction(d);return M.withScopeMaybeAsync(this,function*(s,_){let b=_.manage(new Ve(r,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),x=Array(o);for(let S=0;S<o;S++){let k=this.ffi.QTS_ArgvGetJSValueConstPointer(l,S);x[S]=_.manage(new Ve(k,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let S=yield*s(f.apply(b,x));if(S){if("error"in S&&S.error)throw this.runtime.debugLog("throw error",S.error),S.error;let k=_.manage(S instanceof A?S:S.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,k.value)}return 0}catch(S){return this.errorToHandle(S).consume((k)=>this.ffi.QTS_Throw(this.ctx.value,k.value))}})}},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new er({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new B(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new B(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new B(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new B(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let t=this.memory.newHeapCharPointer(e).consume((r)=>this.ffi.QTS_NewString(this.ctx.value,r.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,0));return this.memory.heapValueHandle(r)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume((o)=>this.ffi.QTS_NewSymbol(this.ctx.value,o.value.ptr,1));return this.memory.heapValueHandle(r)}getWellKnownSymbol(e){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let o=this.getProp(this.global,"BigInt");this.memory.manage(o),this._BigInt=new B(o.value,this.runtime)}let t=this._BigInt,r=String(e);return this.newString(r).consume((o)=>this.unwrapResult(this.callFunction(t,this.undefined,o)))}newObject(e){e&&this.runtime.assertOwned(e);let t=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(t)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let t=new Uint8Array(e),r=this.memory.newHeapBufferPointer(t),o=this.ffi.QTS_NewArrayBuffer(this.ctx.value,r.value.pointer,t.length);return this.memory.heapValueHandle(o)}newPromise(e){let t=M.withScope((r)=>{let o=r.manage(this.memory.newMutablePointerArray(2)),l=this.ffi.QTS_NewPromiseCapability(this.ctx.value,o.value.ptr),d=this.memory.heapValueHandle(l),[f,s]=Array.from(o.value.typedArray).map((_)=>this.memory.heapValueHandle(_));return new Vt({context:this,promiseHandle:d,resolveHandle:f,rejectHandle:s})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,(r)=>r instanceof A?t.reject(r):this.newError(r).consume(t.reject)),t}newFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!1,fn:r})}newConstructorFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!0,fn:r})}newFunctionWithOptions(e){let{name:t,length:r,isConstructor:o,fn:l}=e,d=this.runtime.hostRefs.put(l);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",r,o,d))}catch(f){throw this.runtime.hostRefs.delete(d),f}}newError(e){let t=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e=="object"?(e.name!==void 0&&this.newString(e.name).consume((r)=>this.setProp(t,"name",r)),e.message!==void 0&&this.newString(e.message).consume((r)=>this.setProp(t,"message",r))):typeof e=="string"?this.newString(e).consume((r)=>this.setProp(t,"message",r)):e!==void 0&&this.newString(String(e)).consume((r)=>this.setProp(t,"message",r)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let r=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new qe(this.runtime,r,t)}catch(r){throw this.runtime.hostRefs.delete(t),r}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new 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),r=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!r)throw Error("Couldn't allocate memory to get ArrayBuffer");return new A(this.module.HEAPU8.subarray(r,r+t),void 0,()=>this.module._free(r))}getPromiseState(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(t<0)return{type:"fulfilled",value:e,notAPromise:!0};if(t===j.Pending)return{type:"pending",get error(){return new rt("Cannot unwrap a pending promise")}};let r=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),o=this.memory.heapValueHandle(r);if(t===j.Fulfilled)return{type:"fulfilled",value:o};if(t===j.Rejected)return{type:"rejected",error:o};throw o.dispose(),Error(`Unknown JSPromiseStateEnum: ${t}`)}resolvePromise(e){this.runtime.assertOwned(e);let t=M.withScope((r)=>{let o=r.manage(this.getProp(this.global,"Promise")),l=r.manage(this.getProp(o,"resolve"));return this.callFunction(l,o,e)});return t.error?Promise.resolve(t):new Promise((r)=>{M.withScope((o)=>{let l=o.manage(this.newFunction("resolve",(_)=>{r(this.success(_&&_.dup()))})),d=o.manage(this.newFunction("reject",(_)=>{r(this.fail(_&&_.dup()))})),f=o.manage(t.value),s=o.manage(this.getProp(f,"then"));this.callFunction(s,f,l,d).unwrap().dispose()})})}isEqual(e,t,r=H.IsStrictlyEqual){if(e===t)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(t);let o=this.ffi.QTS_IsEqual(this.ctx.value,e.value,t.value,r);if(o===-1)throw new Xe("WASM variant does not expose equality");return!!o}eq(e,t){return this.isEqual(e,t,H.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,H.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,H.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let r;return typeof t=="number"&&t>=0?r=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):r=this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_GetProp(this.ctx.value,e.value,o.value)),this.memory.heapValueHandle(r)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,t={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let r=qt(t);if(r===0)throw new nt("No options set, will return an empty array");return M.withScope((o)=>{let l=o.manage(this.memory.newMutablePointerArray(1)),d=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,l.value.ptr,this.uint32Out.value.ptr,e.value,r);if(d)return this.fail(this.memory.heapValueHandle(d));let f=this.uint32Out.value.typedArray[0],s=l.value.typedArray[0],_=new Uint32Array(this.module.HEAP8.buffer,s,f),b=Array.from(_).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,s),this.success(Qt(b))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return M.withScope((r)=>{let o=r.manage(this.getProp(e,t)),l=this.callFunction(o,e);return l.error?l:this.success(new Xt(l.value,this))})}setProp(e,t,r){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume((o)=>this.ffi.QTS_SetProp(this.ctx.value,e.value,o.value,r.value))}defineProp(e,t,r){this.runtime.assertOwned(e),M.withScope((o)=>{let l=o.manage(this.borrowPropertyKey(t)),d=r.value||this.undefined,f=!!r.configurable,s=!!r.enumerable,_=!!r.value,b=r.get?o.manage(this.newFunction(r.get.name,r.get)):this.undefined,x=r.set?o.manage(this.newFunction(r.set.name,r.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,l.value,d.value,b.value,x.value,f,s,_)})}callFunction(e,t,...r){this.runtime.assertOwned(e);let o,l=r[0];l===void 0||Array.isArray(l)?o=l??[]:o=r;let d=this.memory.toPointerArray(o).consume((s)=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,o.length,s.value)),f=this.ffi.QTS_ResolveException(this.ctx.value,d);return f?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(f))):this.success(this.memory.heapValueHandle(d))}callMethod(e,t,r=[]){return this.getProp(e,t).consume((o)=>this.callFunction(o,e,r))}evalCode(e,t="eval.js",r){let o=r===void 0?1:0,l=Wt(r),d=this.memory.newHeapCharPointer(e).consume((s)=>this.ffi.QTS_Eval(this.ctx.value,s.value.ptr,s.value.strlen,t,o,l)),f=this.ffi.QTS_ResolveException(this.ctx.value,d);return f?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(f))):this.success(this.memory.heapValueHandle(d))}throw(e){return this.errorToHandle(e).consume((t)=>this.ffi.QTS_Throw(this.ctx.value,t.value))}borrowPropertyKey(e){return typeof e=="number"?this.newNumber(e):typeof e=="string"?this.newString(e):new B(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(e){this.runtime.assertOwned(e);let t=this.typeof(e);if(t==="string")return this.getString(e);if(t==="number")return this.getNumber(e);if(t==="bigint")return this.getBigInt(e);if(t==="undefined")return;if(t==="symbol")return this.getSymbol(e);let r=this.getPromiseState(e);if(r.type==="fulfilled"&&!r.notAPromise)return e.dispose(),{type:r.type,value:r.value.consume(this.dump)};if(r.type==="pending")return e.dispose(),{type:r.type};if(r.type==="rejected")return e.dispose(),{type:r.type,error:r.error.consume(this.dump)};let o=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(o)}catch{return o}}unwrapResult(e){if(e.error){let t="context"in e.error?e.error.context:this,r=e.error.consume((o)=>this.dump(o));if(r&&typeof r=="object"&&typeof r.message=="string"){let{message:o,name:l,stack:d,...f}=r,s=new ae(r,t);typeof l=="string"&&(s.name=r.name),s.message=o;let _=s.stack;throw typeof d=="string"&&(s.stack=`${l}: ${o}
|
|
7
|
+
${r.stack}Host: ${_}`),Object.assign(s,f),s}throw new ae(r)}return e.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(e){let t=this.runtime.hostRefs.get(e);if(typeof t!="function")throw Error(`Host reference ${e} is not a function`);return t}errorToHandle(e){return e instanceof A?e:this.newError(e)}encodeBinaryJSON(e){let t=this.ffi.QTS_bjson_encode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}decodeBinaryJSON(e){let t=this.ffi.QTS_bjson_decode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}success(e){return Y.success(e)}fail(e){return Y.fail(e,(t)=>this.unwrapResult(t))}},rr=class extends N{constructor(e){super();this.scope=new M,this.contextMap=new Map,this.hostRefs=new Zt,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(t,r)=>{if(t!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(r)},shouldInterrupt:(t)=>{if(t!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let r=this.interruptHandler;if(!r)throw Error("QuickJSContext had no interrupt handler");return r(this)?1:0},loadModuleSource:je(this,function*(t,r,o,l){let d=this.moduleLoader;if(!d)throw Error("Runtime has no module loader");if(r!==this.rt.value)throw Error("Runtime pointer mismatch");let f=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let s=yield*t(d(l,f));if(typeof s=="object"&&"error"in s&&s.error)throw this.debugLog("cToHostLoadModule: loader returned error",s.error),s.error;let _=typeof s=="string"?s:("value"in s)?s.value:s;return this.memory.newHeapCharPointer(_).value.ptr}catch(s){return this.debugLog("cToHostLoadModule: caught error",s),f.throw(s),0}}),normalizeModule:je(this,function*(t,r,o,l,d){let f=this.moduleNormalizer;if(!f)throw Error("Runtime has no module normalizer");if(r!==this.rt.value)throw Error("Runtime pointer mismatch");let s=this.contextMap.get(o)??this.newContext({contextPointer:o});try{let _=yield*t(f(l,d,s));if(typeof _=="object"&&"error"in _&&_.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",_.error),_.error;let b=typeof _=="string"?_:_.value;return s.getMemory(this.rt.value).newHeapCharPointer(b).value.ptr}catch(_){return this.debugLog("normalizeModule: caught error",_),s.throw(_),0}})},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.module=e.module,this.memory=new 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=Gt(e.intrinsics),r=new A(e.contextPointer||this.ffi.QTS_NewContext(this.rt.value,t),void 0,(l)=>{this.contextMap.delete(l),this.callbacks.deleteContext(l),this.ffi.QTS_FreeContext(l)}),o=new tr({module:this.module,ctx:r,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(r.value,o),o}setModuleLoader(e,t){this.moduleLoader=e,this.moduleNormalizer=t,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(e){let t=this.interruptHandler;this.interruptHandler=e,t||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(e=-1){let t=this.memory.newMutablePointerArray(1),r=this.ffi.QTS_ExecutePendingJob(this.rt.value,e??-1,t.value.ptr),o=t.value.typedArray[0];if(t.dispose(),o===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,r),Y.success(0);let l=this.contextMap.get(o)??this.newContext({contextPointer:o}),d=l.getMemory(this.rt.value).heapValueHandle(r);if(l.typeof(d)==="number"){let f=l.getNumber(d);return d.dispose(),Y.success(f)}else{let f=Object.assign(d,{context:l});return Y.fail(f,(s)=>l.unwrapResult(s))}}setMemoryLimit(e){if(e<0&&e!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,e)}computeMemoryUsage(){let e=this.getSystemContext().getMemory(this.rt.value);return e.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,e.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(e){if(e<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,e)}assertOwned(e){if(e.owner&&e.owner.rt!==this.rt)throw new 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={};Lt(lt,{QuickJSModuleCallbacks:()=>me,QuickJSWASMModule:()=>at,applyBaseRuntimeOptions:()=>pe,applyModuleEvalRuntimeOptions:()=>_e});var ct=ne(()=>{ut()});var _t=kt(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=(n)=>n!==null&&Object.prototype.toString.call(n)==="[object Object]",r=(n,i)=>{if(n===i)return!0;if(typeof n!==typeof i)return!1;if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return!1;for(let a=0;a<n.length;a+=1)if(!r(n[a],i[a]))return!1;return!0}if(t(n)&&t(i)){let a=Object.entries(n),u=new Set(Object.keys(i));if(a.length!==u.size)return!1;for(let[h,m]of a){if(!r(m,i[h]))return!1;u.delete(h)}return u.size===0}return!1},o=(n)=>{if(n===""||n===!1||n===null||n===void 0)return!0;if(Array.isArray(n)&&n.length===0)return!0;if(t(n)){for(let i in n)if(n.hasOwnProperty(i))return!1;return!0}return!1},l=(n)=>n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="_",d=(n)=>n>="0"&&n<="9"||n==="-",f=(n)=>n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||n==="_";var s;(function(n){n.TOK_EOF="EOF",n.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",n.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",n.TOK_RBRACKET="Rbracket",n.TOK_RPAREN="Rparen",n.TOK_COMMA="Comma",n.TOK_COLON="Colon",n.TOK_RBRACE="Rbrace",n.TOK_NUMBER="Number",n.TOK_CURRENT="Current",n.TOK_ROOT="Root",n.TOK_EXPREF="Expref",n.TOK_PIPE="Pipe",n.TOK_OR="Or",n.TOK_AND="And",n.TOK_EQ="EQ",n.TOK_GT="GT",n.TOK_LT="LT",n.TOK_GTE="GTE",n.TOK_LTE="LTE",n.TOK_NE="NE",n.TOK_FLATTEN="Flatten",n.TOK_STAR="Star",n.TOK_FILTER="Filter",n.TOK_DOT="Dot",n.TOK_NOT="Not",n.TOK_LBRACE="Lbrace",n.TOK_LBRACKET="Lbracket",n.TOK_LPAREN="Lparen",n.TOK_LITERAL="Literal"})(s||(s={}));let _={"(":s.TOK_LPAREN,")":s.TOK_RPAREN,"*":s.TOK_STAR,",":s.TOK_COMMA,".":s.TOK_DOT,":":s.TOK_COLON,"@":s.TOK_CURRENT,["$"]:s.TOK_ROOT,"]":s.TOK_RBRACKET,"{":s.TOK_LBRACE,"}":s.TOK_RBRACE},b={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class S{constructor(){this._current=0}tokenize(n){let i=[];this._current=0;let a,u,h;while(this._current<n.length)if(l(n[this._current]))a=this._current,u=this.consumeUnquotedIdentifier(n),i.push({start:a,type:s.TOK_UNQUOTEDIDENTIFIER,value:u});else if(_[n[this._current]]!==void 0)i.push({start:this._current,type:_[n[this._current]],value:n[this._current]}),this._current+=1;else if(d(n[this._current]))h=this.consumeNumber(n),i.push(h);else if(n[this._current]==="[")h=this.consumeLBracket(n),i.push(h);else if(n[this._current]==='"')a=this._current,u=this.consumeQuotedIdentifier(n),i.push({start:a,type:s.TOK_QUOTEDIDENTIFIER,value:u});else if(n[this._current]==="'")a=this._current,u=this.consumeRawStringLiteral(n),i.push({start:a,type:s.TOK_LITERAL,value:u});else if(n[this._current]==="`"){a=this._current;let m=this.consumeLiteral(n);i.push({start:a,type:s.TOK_LITERAL,value:m})}else if(b[n[this._current]]!==void 0)h=this.consumeOperator(n),h&&i.push(h);else if(x[n[this._current]]!==void 0)this._current+=1;else if(n[this._current]==="&")if(a=this._current,this._current+=1,n[this._current]==="&")this._current+=1,i.push({start:a,type:s.TOK_AND,value:"&&"});else i.push({start:a,type:s.TOK_EXPREF,value:"&"});else if(n[this._current]==="|")if(a=this._current,this._current+=1,n[this._current]==="|")this._current+=1,i.push({start:a,type:s.TOK_OR,value:"||"});else i.push({start:a,type:s.TOK_PIPE,value:"|"});else{let m=Error(`Unknown character: ${n[this._current]}`);throw m.name="LexerError",m}return i}consumeUnquotedIdentifier(n){let i=this._current;this._current+=1;while(this._current<n.length&&f(n[this._current]))this._current+=1;return n.slice(i,this._current)}consumeQuotedIdentifier(n){let i=this._current;this._current+=1;let a=n.length;while(n[this._current]!=='"'&&this._current<a){let u=this._current;if(n[u]==="\\"&&(n[u+1]==="\\"||n[u+1]==='"'))u+=2;else u+=1;this._current=u}return this._current+=1,JSON.parse(n.slice(i,this._current))}consumeRawStringLiteral(n){let i=this._current;this._current+=1;let a=n.length;while(n[this._current]!=="'"&&this._current<a){let h=this._current;if(n[h]==="\\"&&(n[h+1]==="\\"||n[h+1]==="'"))h+=2;else h+=1;this._current=h}return this._current+=1,n.slice(i+1,this._current-1).replace("\\'","'")}consumeNumber(n){let i=this._current;this._current+=1;let a=n.length;while(d(n[this._current])&&this._current<a)this._current+=1;let u=parseInt(n.slice(i,this._current),10);return{start:i,value:u,type:s.TOK_NUMBER}}consumeLBracket(n){let i=this._current;if(this._current+=1,n[this._current]==="?")return this._current+=1,{start:i,type:s.TOK_FILTER,value:"[?"};if(n[this._current]==="]")return this._current+=1,{start:i,type:s.TOK_FLATTEN,value:"[]"};return{start:i,type:s.TOK_LBRACKET,value:"["}}consumeOperator(n){let i=this._current,a=n[i];if(this._current+=1,a==="!"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_NE,value:"!="};return{start:i,type:s.TOK_NOT,value:"!"}}if(a==="<"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_LTE,value:"<="};return{start:i,type:s.TOK_LT,value:"<"}}if(a===">"){if(n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_GTE,value:">="};return{start:i,type:s.TOK_GT,value:">"}}if(a==="="&&n[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_EQ,value:"=="}}consumeLiteral(n){this._current+=1;let i=this._current,a=n.length;while(n[this._current]!=="`"&&this._current<a){let m=this._current;if(n[m]==="\\"&&(n[m+1]==="\\"||n[m+1]==="`"))m+=2;else m+=1;this._current=m}let u=n.slice(i,this._current).trimLeft();u=u.replace("\\`","`");let h=this.looksLikeJSON(u)?JSON.parse(u):JSON.parse(`"${u}"`);return this._current+=1,h}looksLikeJSON(n){let a=["true","false","null"],u="-0123456789";if(n==="")return!1;if('[{"'.includes(n[0]))return!0;if(a.includes(n))return!0;if("-0123456789".includes(n[0]))try{return JSON.parse(n),!0}catch(h){return!1}return!1}}let k=new S,w={[s.TOK_EOF]:0,[s.TOK_UNQUOTEDIDENTIFIER]:0,[s.TOK_QUOTEDIDENTIFIER]:0,[s.TOK_RBRACKET]:0,[s.TOK_RPAREN]:0,[s.TOK_COMMA]:0,[s.TOK_RBRACE]:0,[s.TOK_NUMBER]:0,[s.TOK_CURRENT]:0,[s.TOK_EXPREF]:0,[s.TOK_ROOT]:0,[s.TOK_PIPE]:1,[s.TOK_OR]:2,[s.TOK_AND]:3,[s.TOK_EQ]:5,[s.TOK_GT]:5,[s.TOK_LT]:5,[s.TOK_GTE]:5,[s.TOK_LTE]:5,[s.TOK_NE]:5,[s.TOK_FLATTEN]:9,[s.TOK_STAR]:20,[s.TOK_FILTER]:21,[s.TOK_DOT]:40,[s.TOK_NOT]:45,[s.TOK_LBRACE]:50,[s.TOK_LBRACKET]:55,[s.TOK_LPAREN]:60};class Te{constructor(){this.index=0,this.tokens=[]}parse(n){this.loadTokens(n),this.index=0;let i=this.expression(0);if(this.lookahead(0)!==s.TOK_EOF){let a=this.lookaheadToken(0);this.errorToken(a,`Unexpected token type: ${a.type}, value: ${a.value}`)}return i}loadTokens(n){this.tokens=[...k.tokenize(n),{type:s.TOK_EOF,value:"",start:n.length}]}expression(n){let i=this.lookaheadToken(0);this.advance();let a=this.nud(i),u=this.lookahead(0);while(n<w[u])this.advance(),a=this.led(u,a),u=this.lookahead(0);return a}lookahead(n){return this.tokens[this.index+n].type}lookaheadToken(n){return this.tokens[this.index+n]}advance(){this.index+=1}nud(n){let i,a,u;switch(n.type){case s.TOK_LITERAL:return{type:"Literal",value:n.value};case s.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:n.value};case s.TOK_QUOTEDIDENTIFIER:let h={type:"Field",name:n.value};if(this.lookahead(0)===s.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return h;case s.TOK_NOT:return a=this.expression(w.Not),{type:"NotExpression",children:[a]};case s.TOK_STAR:return i={type:"Identity"},a=this.lookahead(0)===s.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(w.Star),{type:"ValueProjection",children:[i,a]};case s.TOK_FILTER:return this.led(n.type,{type:"Identity"});case s.TOK_LBRACE:return this.parseMultiselectHash();case s.TOK_FLATTEN:return i={type:s.TOK_FLATTEN,children:[{type:"Identity"}]},a=this.parseProjectionRHS(w.Flatten),{type:"Projection",children:[i,a]};case s.TOK_LBRACKET:if(this.lookahead(0)===s.TOK_NUMBER||this.lookahead(0)===s.TOK_COLON)return a=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},a);if(this.lookahead(0)===s.TOK_STAR&&this.lookahead(1)===s.TOK_RBRACKET)return this.advance(),this.advance(),a=this.parseProjectionRHS(w.Star),{children:[{type:"Identity"},a],type:"Projection"};return this.parseMultiselectList();case s.TOK_CURRENT:return{type:s.TOK_CURRENT};case s.TOK_ROOT:return{type:s.TOK_ROOT};case s.TOK_EXPREF:return u=this.expression(w.Expref),{type:"ExpressionReference",children:[u]};case s.TOK_LPAREN:let m=[];while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)u={type:s.TOK_CURRENT},this.advance();else u=this.expression(0);m.push(u)}return this.match(s.TOK_RPAREN),m[0];default:this.errorToken(n)}}led(n,i){let a;switch(n){case s.TOK_DOT:let u=w.Dot;if(this.lookahead(0)!==s.TOK_STAR)return a=this.parseDotRHS(u),{type:"Subexpression",children:[i,a]};return this.advance(),a=this.parseProjectionRHS(u),{type:"ValueProjection",children:[i,a]};case s.TOK_PIPE:return a=this.expression(w.Pipe),{type:s.TOK_PIPE,children:[i,a]};case s.TOK_OR:return a=this.expression(w.Or),{type:"OrExpression",children:[i,a]};case s.TOK_AND:return a=this.expression(w.And),{type:"AndExpression",children:[i,a]};case s.TOK_LPAREN:let h=i.name,m=[],g;while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)g={type:s.TOK_CURRENT},this.advance();else g=this.expression(0);if(this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);m.push(g)}return this.match(s.TOK_RPAREN),{name:h,type:"Function",children:m};case s.TOK_FILTER:let E=this.expression(0);return this.match(s.TOK_RBRACKET),a=this.lookahead(0)===s.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(w.Filter),{type:"FilterProjection",children:[i,a,E]};case s.TOK_FLATTEN:let P={type:s.TOK_FLATTEN,children:[i]},T=this.parseProjectionRHS(w.Flatten);return{type:"Projection",children:[P,T]};case s.TOK_EQ:case s.TOK_NE:case s.TOK_GT:case s.TOK_GTE:case s.TOK_LT:case s.TOK_LTE:return this.parseComparator(i,n);case s.TOK_LBRACKET:let p=this.lookaheadToken(0);if(p.type===s.TOK_NUMBER||p.type===s.TOK_COLON)return a=this.parseIndexExpression(),this.projectIfSlice(i,a);return this.match(s.TOK_STAR),this.match(s.TOK_RBRACKET),a=this.parseProjectionRHS(w.Star),{type:"Projection",children:[i,a]};default:return this.errorToken(this.lookaheadToken(0))}}match(n){if(this.lookahead(0)===n){this.advance();return}else{let i=this.lookaheadToken(0);this.errorToken(i,`Expected ${n}, got: ${i.type}`)}}errorToken(n,i=""){let a=Error(i||`Invalid token (${n.type}): "${n.value}"`);throw a.name="ParserError",a}parseIndexExpression(){if(this.lookahead(0)===s.TOK_COLON||this.lookahead(1)===s.TOK_COLON)return this.parseSliceExpression();let n={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(s.TOK_RBRACKET),n}projectIfSlice(n,i){let a={type:"IndexExpression",children:[n,i]};if(i.type==="Slice")return{children:[a,this.parseProjectionRHS(w.Star)],type:"Projection"};return a}parseSliceExpression(){let n=[null,null,null],i=0,a=this.lookahead(0);while(a!==s.TOK_RBRACKET&&i<3){if(a===s.TOK_COLON)i+=1,this.advance();else if(a===s.TOK_NUMBER)n[i]=this.lookaheadToken(0).value,this.advance();else{let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}a=this.lookahead(0)}return this.match(s.TOK_RBRACKET),{children:n,type:"Slice"}}parseComparator(n,i){let a=this.expression(w[i]);return{type:"Comparator",name:i,children:[n,a]}}parseDotRHS(n){let i=this.lookahead(0);if([s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER,s.TOK_STAR].includes(i))return this.expression(n);if(i===s.TOK_LBRACKET)return this.match(s.TOK_LBRACKET),this.parseMultiselectList();if(i===s.TOK_LBRACE)return this.match(s.TOK_LBRACE),this.parseMultiselectHash();let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}parseProjectionRHS(n){if(w[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===s.TOK_LBRACKET)return this.expression(n);if(this.lookahead(0)===s.TOK_FILTER)return this.expression(n);if(this.lookahead(0)===s.TOK_DOT)return this.match(s.TOK_DOT),this.parseDotRHS(n);let i=this.lookaheadToken(0);this.errorToken(i,`Syntax error, unexpected token: ${i.value}(${i.type})`)}parseMultiselectList(){let n=[];while(this.lookahead(0)!==s.TOK_RBRACKET){let i=this.expression(0);if(n.push(i),this.lookahead(0)===s.TOK_COMMA){if(this.match(s.TOK_COMMA),this.lookahead(0)===s.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(s.TOK_RBRACKET),{type:"MultiSelectList",children:n}}parseMultiselectHash(){let n=[],i=[s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER],a,u,h;for(;;){if(a=this.lookaheadToken(0),!i.includes(a.type))throw Error(`Expecting an identifier token, got: ${a.type}`);if(u=a.value,this.advance(),this.match(s.TOK_COLON),h=this.expression(0),n.push({value:h,type:"KeyValuePair",name:u}),this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);else if(this.lookahead(0)===s.TOK_RBRACE){this.match(s.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:n}}}let Se=new Te;var c;(function(n){n[n.TYPE_NUMBER=0]="TYPE_NUMBER",n[n.TYPE_ANY=1]="TYPE_ANY",n[n.TYPE_STRING=2]="TYPE_STRING",n[n.TYPE_ARRAY=3]="TYPE_ARRAY",n[n.TYPE_OBJECT=4]="TYPE_OBJECT",n[n.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",n[n.TYPE_EXPREF=6]="TYPE_EXPREF",n[n.TYPE_NULL=7]="TYPE_NULL",n[n.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",n[n.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(c||(c={}));class Re{constructor(n){this.TYPE_NAME_TABLE={[c.TYPE_NUMBER]:"number",[c.TYPE_ANY]:"any",[c.TYPE_STRING]:"string",[c.TYPE_ARRAY]:"array",[c.TYPE_OBJECT]:"object",[c.TYPE_BOOLEAN]:"boolean",[c.TYPE_EXPREF]:"expression",[c.TYPE_NULL]:"null",[c.TYPE_ARRAY_NUMBER]:"Array<number>",[c.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([i])=>Math.abs(i),this.functionAvg=([i])=>{let a=0;for(let u=0;u<i.length;u+=1)a+=i[u];return a/i.length},this.functionCeil=([i])=>Math.ceil(i),this.functionContains=(i)=>{let[a,u]=i;return a.includes(u)},this.functionEndsWith=(i)=>{let[a,u]=i;return a.includes(u,a.length-u.length)},this.functionFloor=([i])=>Math.floor(i),this.functionJoin=(i)=>{let[a,u]=i;return u.join(a)},this.functionKeys=([i])=>Object.keys(i),this.functionLength=([i])=>{if(!t(i))return i.length;return Object.keys(i).length},this.functionMap=(i)=>{if(!this._interpreter)return[];let a=[],u=this._interpreter,h=i[0],m=i[1];for(let g=0;g<m.length;g+=1)a.push(u.visit(h,m[g]));return a},this.functionMax=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.max(...i);let u=i,h=u[0];for(let m=1;m<u.length;m+=1)if(h.localeCompare(u[m])<0)h=u[m];return h},this.functionMaxBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),m=-1/0,g,y;for(let E=0;E<u.length;E+=1)if(y=h&&h(u[E]),y!==void 0&&y>m)m=y,g=u[E];return g},this.functionMerge=(i)=>{let a={};for(let u=0;u<i.length;u+=1){let h=i[u];a=Object.assign(a,h)}return a},this.functionMin=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.min(...i);let u=i,h=u[0];for(let m=1;m<u.length;m+=1)if(u[m].localeCompare(h)<0)h=u[m];return h},this.functionMinBy=(i)=>{let a=i[1],u=i[0],h=this.createKeyFunction(a,[c.TYPE_NUMBER,c.TYPE_STRING]),m=1/0,g,y;for(let E=0;E<u.length;E+=1)if(y=h&&h(u[E]),y!==void 0&&y<m)m=y,g=u[E];return g},this.functionNotNull=(i)=>{for(let a=0;a<i.length;a+=1)if(this.getTypeName(i[a])!==c.TYPE_NULL)return i[a];return null},this.functionReverse=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING){let h=i,m="";for(let g=h.length-1;g>=0;g-=1)m+=h[g];return m}let u=i.slice(0);return u.reverse(),u},this.functionSort=([i])=>[...i].sort(),this.functionSortBy=(i)=>{if(!this._interpreter)return[];let a=i[0].slice(0);if(a.length===0)return a;let u=this._interpreter,h=i[1],m=this.getTypeName(u.visit(h,a[0]));if(m!==void 0&&![c.TYPE_NUMBER,c.TYPE_STRING].includes(m))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[m]})`);let g=[];for(let y=0;y<a.length;y+=1)g.push([y,a[y]]);g.sort((y,E)=>{let P=u.visit(h,y[1]),T=u.visit(h,E[1]);if(this.getTypeName(P)!==m)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[m]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(P)]}`);else if(this.getTypeName(T)!==m)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[m]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(T)]}`);if(P>T)return 1;return P<T?-1:y[0]-E[0]});for(let y=0;y<g.length;y+=1)a[y]=g[y][1];return a},this.functionStartsWith=([i,a])=>i.startsWith(a),this.functionSum=([i])=>i.reduce((a,u)=>a+u,0),this.functionToArray=([i])=>{if(this.getTypeName(i)===c.TYPE_ARRAY)return i;return[i]},this.functionToNumber=([i])=>{let a=this.getTypeName(i),u;if(a===c.TYPE_NUMBER)return i;if(a===c.TYPE_STRING){if(u=+i,!isNaN(u))return u}return null},this.functionToString=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING)return i;return JSON.stringify(i)},this.functionType=([i])=>{switch(this.getTypeName(i)){case c.TYPE_NUMBER:return"number";case c.TYPE_STRING:return"string";case c.TYPE_ARRAY:return"array";case c.TYPE_OBJECT:return"object";case c.TYPE_BOOLEAN:return"boolean";case c.TYPE_EXPREF:return"expref";case c.TYPE_NULL:return"null";default:return}},this.functionValues=([i])=>Object.values(i),this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[c.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[c.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]},{types:[c.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[c.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[c.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY,c.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[c.TYPE_EXPREF]},{types:[c.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[c.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[c.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[c.TYPE_ARRAY_STRING,c.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[c.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[c.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[c.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[c.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[c.TYPE_OBJECT]}]}},this._interpreter=n}registerFunction(n,i,a){if(n in this.functionTable)throw Error(`Function already defined: ${n}()`);this.functionTable[n]={_func:i.bind(this),_signature:a}}callFunction(n,i){let a=this.functionTable[n];if(a===void 0)throw Error(`Unknown function: ${n}()`);return this.validateArgs(n,i,a._signature),a._func.call(this,i)}validateInputSignatures(n,i){for(let a=0;a<i.length;a+=1)if("variadic"in i[a]&&a!==i.length-1)throw Error(`ArgumentError: ${n}() 'variadic' argument ${a+1} must occur last`)}validateArgs(n,i,a){var u,h;let m;this.validateInputSignatures(n,a);let g=a.filter((O)=>{var v;return(v=!O.optional)!==null&&v!==void 0?v:!1}).length,y=(h=(u=a[a.length-1])===null||u===void 0?void 0:u.variadic)!==null&&h!==void 0?h:!1,E=i.length<g,P=i.length>a.length,T=E&&(!y&&g>1||y)?"at least ":"";if(y&&E||!y&&(E||P))throw m=a.length>1,Error(`ArgumentError: ${n}() takes ${T}${g} argument${m&&"s"||""} but received ${i.length}`);let p,R,C;for(let O=0;O<a.length;O+=1){C=!1,p=a[O].types,R=this.getTypeName(i[O]);let v;for(v=0;v<p.length;v+=1)if(R!==void 0&&this.typeMatches(R,p[v],i[O])){C=!0;break}if(!C&&R!==void 0){let F=p.map((D)=>this.TYPE_NAME_TABLE[D]).join(" | ");throw Error(`TypeError: ${n}() expected argument ${O+1} to be type (${F}) but received type ${this.TYPE_NAME_TABLE[R]} instead.`)}}}typeMatches(n,i,a){if(i===c.TYPE_ANY)return!0;if(i===c.TYPE_ARRAY_STRING||i===c.TYPE_ARRAY_NUMBER||i===c.TYPE_ARRAY){if(i===c.TYPE_ARRAY)return n===c.TYPE_ARRAY;if(n===c.TYPE_ARRAY){let u;if(i===c.TYPE_ARRAY_NUMBER)u=c.TYPE_NUMBER;else if(i===c.TYPE_ARRAY_STRING)u=c.TYPE_STRING;for(let h=0;h<a.length;h+=1){let m=this.getTypeName(a[h]);if(m!==void 0&&u!==void 0&&!this.typeMatches(m,u,a[h]))return!1}return!0}}else return n===i;return!1}getTypeName(n){switch(Object.prototype.toString.call(n)){case"[object String]":return c.TYPE_STRING;case"[object Number]":return c.TYPE_NUMBER;case"[object Array]":return c.TYPE_ARRAY;case"[object Boolean]":return c.TYPE_BOOLEAN;case"[object Null]":return c.TYPE_NULL;case"[object Object]":if(n.jmespathType===s.TOK_EXPREF)return c.TYPE_EXPREF;return c.TYPE_OBJECT;default:return}}createKeyFunction(n,i){if(!this._interpreter)return;let a=this._interpreter;return(h)=>{let m=a.visit(n,h);if(!i.includes(this.getTypeName(m))){let g=`TypeError: expected one of (${i.map((y)=>this.TYPE_NAME_TABLE[y]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(m)]}`;throw Error(g)}return m}}}class we{constructor(){this._rootValue=null,this.runtime=new Re(this)}search(n,i){return this._rootValue=i,this.visit(n,i)}visit(n,i){let a,u,h,m,g,y,E,P,T,p,R;switch(n.type){case"Field":if(i===null)return null;if(t(i)){if(y=i[n.name],y===void 0)return null;return y}return null;case"Subexpression":h=this.visit(n.children[0],i);for(p=1;p<n.children.length;p+=1)if(h=this.visit(n.children[1],h),h===null)return null;return h;case"IndexExpression":return E=this.visit(n.children[0],i),P=this.visit(n.children[1],E),P;case"Index":if(!Array.isArray(i))return null;let C=n.value;if(C<0)C=i.length+C;if(h=i[C],h===void 0)h=null;return h;case"Slice":if(!Array.isArray(i))return null;let O=[...n.children],v=this.computeSliceParams(i.length,O),[F,D,X]=v;if(h=[],X>0)for(p=F;p<D;p+=X)h.push(i[p]);else for(p=F;p>D;p+=X)h.push(i[p]);return h;case"Projection":if(R=this.visit(n.children[0],i),!Array.isArray(R))return null;T=[];for(p=0;p<R.length;p+=1)if(u=this.visit(n.children[1],R[p]),u!==null)T.push(u);return T;case"ValueProjection":if(R=this.visit(n.children[0],i),!t(R))return null;T=[];let He=Object.values(R);for(p=0;p<He.length;p+=1)if(u=this.visit(n.children[1],He[p]),u!==null)T.push(u);return T;case"FilterProjection":if(R=this.visit(n.children[0],i),!Array.isArray(R))return null;let Z=[],Je=[];for(p=0;p<R.length;p+=1)if(a=this.visit(n.children[2],R[p]),!o(a))Z.push(R[p]);for(let L=0;L<Z.length;L+=1)if(u=this.visit(n.children[1],Z[L]),u!==null)Je.push(u);return Je;case"Comparator":switch(m=this.visit(n.children[0],i),g=this.visit(n.children[1],i),n.name){case s.TOK_EQ:h=r(m,g);break;case s.TOK_NE:h=!r(m,g);break;case s.TOK_GT:h=m>g;break;case s.TOK_GTE:h=m>=g;break;case s.TOK_LT:h=m<g;break;case s.TOK_LTE:h=m<=g;break;default:throw Error(`Unknown comparator: ${n.name}`)}return h;case s.TOK_FLATTEN:let ee=this.visit(n.children[0],i);if(!Array.isArray(ee))return null;let Q=[];for(p=0;p<ee.length;p+=1)if(u=ee[p],Array.isArray(u))Q=[...Q,...u];else Q.push(u);return Q;case"Identity":return i;case"MultiSelectList":if(i===null)return null;T=[];for(p=0;p<n.children.length;p+=1)T.push(this.visit(n.children[p],i));return T;case"MultiSelectHash":if(i===null)return null;T={};let te;for(p=0;p<n.children.length;p+=1)te=n.children[p],T[te.name]=this.visit(te.value,i);return T;case"OrExpression":if(a=this.visit(n.children[0],i),o(a))a=this.visit(n.children[1],i);return a;case"AndExpression":if(m=this.visit(n.children[0],i),o(m))return m;return this.visit(n.children[1],i);case"NotExpression":return m=this.visit(n.children[0],i),o(m);case"Literal":return n.value;case s.TOK_PIPE:return E=this.visit(n.children[0],i),this.visit(n.children[1],E);case s.TOK_CURRENT:return i;case s.TOK_ROOT:return this._rootValue;case"Function":let Fe=[];for(let L=0;L<n.children.length;L+=1)Fe.push(this.visit(n.children[L],i));return this.runtime.callFunction(n.name,Fe);case"ExpressionReference":let De=n.children[0];return De.jmespathType=s.TOK_EXPREF,De;default:throw Error(`Unknown node type: ${n.type}`)}}computeSliceParams(n,i){let[a,u,h]=i;if(h===null)h=1;else if(h===0){let g=Error("Invalid slice, step cannot be 0");throw g.name="RuntimeError",g}let m=h<0?!0:!1;return a=a===null?m?n-1:0:this.capSliceRange(n,a,h),u=u===null?m?-1:n:this.capSliceRange(n,u,h),[a,u,h]}capSliceRange(n,i,a){let u=i;if(u<0){if(u+=n,u<0)u=a<0?-1:0}else if(u>=n)u=a<0?n-1:n;return u}}let z=new we,Ae=c.TYPE_ANY,be=c.TYPE_ARRAY,Pe=c.TYPE_ARRAY_NUMBER,Oe=c.TYPE_ARRAY_STRING,ve=c.TYPE_BOOLEAN,Me=c.TYPE_EXPREF,xe=c.TYPE_NULL,Ne=c.TYPE_NUMBER,ke=c.TYPE_OBJECT,Ce=c.TYPE_STRING;function Ie(n){return Se.parse(n)}function Le(n){return k.tokenize(n)}let Ue=(n,i,a)=>{z.runtime.registerFunction(n,i,a)};function Ke(n,i){let a=Se.parse(i);return z.search(a,n)}let Be=z,Ye={compile:Ie,registerFunction:Ue,search:Ke,tokenize:Le,TreeInterpreter:Be,TYPE_ANY:Ae,TYPE_ARRAY_NUMBER:Pe,TYPE_ARRAY_STRING:Oe,TYPE_ARRAY:be,TYPE_BOOLEAN:ve,TYPE_EXPREF:Me,TYPE_NULL:xe,TYPE_NUMBER:Ne,TYPE_OBJECT:ke,TYPE_STRING:Ce};e.TYPE_ANY=Ae,e.TYPE_ARRAY=be,e.TYPE_ARRAY_NUMBER=Pe,e.TYPE_ARRAY_STRING=Oe,e.TYPE_BOOLEAN=ve,e.TYPE_EXPREF=Me,e.TYPE_NULL=xe,e.TYPE_NUMBER=Ne,e.TYPE_OBJECT=ke,e.TYPE_STRING=Ce,e.TreeInterpreter=Be,e.compile=Ie,e.default=Ye,e.jmespath=Ye,e.registerFunction=Ue,e.search=Ke,e.tokenize=Le,Object.defineProperty(e,"__esModule",{value:!0})})});import{mkdirSync as Sr,mkdtempSync as Rr,writeFileSync as wr}from"node:fs";import{tmpdir as Ar}from"node:os";import{dirname as br,join as ye}from"node:path";import{pathToFileURL as Pr}from"node:url";import{timingSafeEqual as mr}from"node:crypto";import{createServer as pr}from"node:http";import{Readable as _r}from"node:stream";function Ut(){return typeof process>"u"?{}:process.env}function Qe(e=Ut()){return e.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as dr}from"node:fs";V();async function ht(e){let t=ge(await e),[r,o,{QuickJSWASMModule:l}]=await Promise.all([t.importModuleLoader().then(ge),t.importFFI(),Promise.resolve().then(() => (ct(),lt)).then(ge)]),d=await r();d.type="sync";let f=new o(d);return new l(d,f)}function ge(e){return e&&"default"in e&&e.default?e.default&&"default"in e.default&&e.default.default?e.default.default:e.default:e}var ft="engine";function ir(e){let t=(r)=>new URL(r,e).href;return{type:"sync",importFFI:()=>import(t("ffi.mjs")).then((r)=>r.QuickJSFFI),importModuleLoader:()=>import(t("emscripten-module.mjs")).then((r)=>r.default)}}var dt=null;function mt(e){return()=>(dt??=ht(ir(e)),dt)}var sr=Nt(_t(),1);var ar="__mcpcloud_call_tool",bn=`globalThis.tool = (name, args) =>
|
|
8
|
+
globalThis.${ar}(String(name), JSON.stringify(args ?? {}))
|
|
9
|
+
.then((json) => JSON.parse(json));`;var ur=6,lr=["log","warn","error","info","debug"],cr="__mcpcloud_console",vn=`globalThis.console = {
|
|
10
|
+
${lr.map((e)=>` ${e}: (...args) => globalThis.${cr}(${JSON.stringify(e)}, JSON.stringify(args.slice(0, ${ur}).map((value) => (value instanceof Error ? { __mcpcloudError: value.name + ': ' + value.message } : value)))),`).join(`
|
|
11
11
|
`)}
|
|
12
|
-
};`;var
|
|
12
|
+
};`;var hr=Symbol.for("@mcpcloud/runtime.codeModeEngineProvider");function gt(e){globalThis[hr]=e}var yt=[`./${ft}/`,"../engine/vendor/","../../engine/vendor/"];function fr(e=new URL(import.meta.url)){for(let t of yt){let r=new URL(t,e);if(dr(new URL("emscripten-module.wasm",r)))return r}throw Error(`Code Mode engine not found. Looked for emscripten-module.wasm in: ${yt.join(", ")} (relative to ${e.href}).`)}function Et(){gt(()=>mt(fr())())}function gr(e,t){let r=Buffer.from(e),o=Buffer.from(t);return r.length===o.length&&mr(r,o)}function yr(e,t){let r=Qe(t);if(!r)return null;if(new URL(e.url).pathname==="/health")return null;let o=e.headers.get("authorization")??"",l=/^Bearer\s+(.+)$/i.exec(o.trim());if(l&&gr(l[1].trim(),r))return null;return Response.json({error:"unauthorized",message:"This MCP endpoint requires a bearer token (set in Authorization: Bearer <token>)."},{status:401,headers:{"www-authenticate":"Bearer"}})}function Er(e,t){let r=new URL(e.url??"/",t),o=new Headers;for(let[f,s]of Object.entries(e.headers))if(Array.isArray(s))for(let _ of s)o.append(f,_);else if(typeof s==="string")o.set(f,s);let l=e.method??"GET",d=l==="GET"||l==="HEAD"?void 0:_r.toWeb(e);return new Request(r,{method:l,headers:o,body:d,...d?{duplex:"half"}:{}})}async function Tr(e,t){if(t.statusCode=e.status,e.headers.forEach((o,l)=>{t.setHeader(l,o)}),!e.body){t.end();return}let r=e.body.getReader();for(;;){let{done:o,value:l}=await r.read();if(o)break;t.write(l)}t.end()}function Tt(e,t={}){Et();let r=t.port??Number(process.env.PORT??8080),o=t.hostname??"0.0.0.0",l=pr((d,f)=>{let s=`http://${d.headers.host??`${o}:${r}`}`,_=Er(d,s),b=yr(_,t.env);(b?Promise.resolve(b):e.handleRequest(_,t.env)).then((S)=>Tr(S,f)).catch(()=>{f.statusCode=500,f.end(JSON.stringify({error:"internal_error"}))})});return l.listen(r,o),l}var Ee=1;function St(e=process.env){let t=e.BUNDLE_URL?.trim(),r=e.BUNDLE_SHA256?.trim();if(!t)throw Error("BUNDLE_URL is not set; the runtime host has no code to run.");if(!r)throw Error("BUNDLE_SHA256 is not set; refusing to boot unverified code.");let o=Number(e.PORT??8080);if(!Number.isInteger(o)||o<=0)throw Error(`Invalid PORT: ${String(e.PORT)}`);return{bundleUrl:t,bundleSha256:r,port:o}}async function Or(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((o)=>o.toString(16).padStart(2,"0")).join("")}function vr(e){let t=JSON.parse(new TextDecoder().decode(e));if(!t||typeof t!=="object")throw Error("Boot artifact must be a JSON object.");let r=t;if(r.schemaVersion!==Ee)throw Error(`Unsupported boot artifact schemaVersion: ${String(r.schemaVersion)}.`);if(typeof r.runtimeVersion!=="string"||typeof r.mainEntry!=="string"||!Array.isArray(r.files))throw Error("Boot artifact is malformed.");let o=r.files.map((l)=>{if(!l||typeof l!=="object"||typeof l.path!=="string"||typeof l.content!=="string")throw Error("Boot artifact files must be { path, content }.");let d=l;return{path:d.path,content:d.content}});return{schemaVersion:Ee,runtimeVersion:r.runtimeVersion,mainEntry:r.mainEntry,files:o}}async function Rt(e,t=fetch){let r=await t(e.bundleUrl);if(!r.ok)throw Error(`Bundle fetch failed (HTTP ${r.status}).`);let o=new Uint8Array(await r.arrayBuffer()),l=await Or(o);if(l!==e.bundleSha256.toLowerCase())throw Error(`Bundle sha256 mismatch (expected ${e.bundleSha256}, got ${l}).`);return vr(o)}function wt(e,t){for(let r of e.files){let o=ye(t,r.path);Sr(br(o),{recursive:!0}),wr(o,r.content)}return{entryPath:ye(t,e.mainEntry)}}async function Mr(e={}){let t=e.bootConfig??St(),r=await Rt(t,e.fetchImpl),o=e.workDir??Rr(ye(Ar(),"mcpcloud-server-")),{entryPath:l}=wt(r,o),d=await import(Pr(l).href),f=d.server??d.default;if(!f)throw Error(`Boot module ${r.mainEntry} does not export a \`server\`.`);let s={port:t.port,...e.hostname?{hostname:e.hostname}:{},...e.env?{env:e.env}:{}};return Tt(f,s)}export{Ee as BOOT_ARTIFACT_SCHEMA_VERSION,Rt as fetchAndVerifyBundle,wt as materializeBundle,St as resolveBootConfig,Mr as serveFromBundle};
|
package/dist/index.d.ts
CHANGED
|
@@ -30,8 +30,7 @@ export { summarizeShape, describeDistribution } from './sandbox/shape';
|
|
|
30
30
|
export type { SandboxBindings, SandboxEffectClass } from './sandbox/bindings';
|
|
31
31
|
export type { SandboxLimits, SandboxResult, SandboxSpan, SandboxFailureKind, } from './sandbox/types';
|
|
32
32
|
export { toWorkerHandler } from './adapters/worker';
|
|
33
|
-
export { McpServer } from '@modelcontextprotocol/
|
|
34
|
-
export {
|
|
35
|
-
export {
|
|
36
|
-
export type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
|
|
33
|
+
export { McpServer, WebStandardStreamableHTTPServerTransport, } from '@modelcontextprotocol/server';
|
|
34
|
+
export { ProtocolError, ProtocolError as McpError, } from '@modelcontextprotocol/server';
|
|
35
|
+
export type { CallToolResult } from '@modelcontextprotocol/server';
|
|
37
36
|
export { z } from 'zod';
|