@mcpcloud/runtime 0.7.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.js CHANGED
@@ -1,2 +1,12 @@
1
- /*! @mcpcloud/runtime v0.7.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
- import{timingSafeEqual as Z}from"node:crypto";import{createServer as _}from"node:http";import{Readable as $}from"node:stream";function Y(){return typeof process>"u"?{}:process.env}function Q(j=Y()){return j.MCP_BEARER_TOKEN?.trim()||null}function C(j,x){let G=Buffer.from(j),z=Buffer.from(x);return G.length===z.length&&Z(G,z)}function D(j,x){let G=Q(x);if(!G)return null;if(new URL(j.url).pathname==="/health")return null;let z=j.headers.get("authorization")??"",F=/^Bearer\s+(.+)$/i.exec(z.trim());if(F&&C(F[1].trim(),G))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 W(j,x){let G=new URL(j.url??"/",x),z=new Headers;for(let[I,J]of Object.entries(j.headers))if(Array.isArray(J))for(let N of J)z.append(I,N);else if(typeof J==="string")z.set(I,J);let F=j.method??"GET",L=F==="GET"||F==="HEAD"?void 0:$.toWeb(j);return new Request(G,{method:F,headers:z,body:L,...L?{duplex:"half"}:{}})}async function H(j,x){if(x.statusCode=j.status,j.headers.forEach((z,F)=>{x.setHeader(F,z)}),!j.body){x.end();return}let G=j.body.getReader();for(;;){let{done:z,value:F}=await G.read();if(z)break;x.write(F)}x.end()}function A(j,x={}){let G=x.port??Number(process.env.PORT??8080),z=x.hostname??"0.0.0.0",F=_((L,I)=>{let J=`http://${L.headers.host??`${z}:${G}`}`,N=W(L,J),O=D(N,x.env);(O?Promise.resolve(O):j.handleRequest(N,x.env)).then((X)=>H(X,I)).catch(()=>{I.statusCode=500,I.end(JSON.stringify({error:"internal_error"}))})});return F.listen(G,z),F}export{A as serve};
1
+ /*! @mcpcloud/runtime v0.12.1 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
+ var L9=Object.create;var{getPrototypeOf:O9,defineProperty:$8,getOwnPropertyNames:F9}=Object;var R9=Object.prototype.hasOwnProperty;function M9(Z){return this[Z]}var V9,_9,w9=(Z,$,W)=>{var Q=Z!=null&&typeof Z==="object";if(Q){var B=$?V9??=new WeakMap:_9??=new WeakMap,C=B.get(Z);if(C)return C}W=Z!=null?L9(O9(Z)):{};let H=$||!Z||!Z.__esModule?$8(W,"default",{value:Z,enumerable:!0}):W;for(let K of F9(Z))if(!R9.call(H,K))$8(H,K,{get:M9.bind(Z,K),enumerable:!0});if(Q)B.set(Z,H);return H};var P9=(Z,$)=>()=>($||Z(($={exports:{}}).exports,$),$.exports);var N9=(Z)=>Z;function E9(Z,$){this[Z]=N9.bind(null,$)}var S9=(Z,$)=>{for(var W in $)$8(Z,W,{get:$[W],enumerable:!0,configurable:!0,set:E9.bind($,W)})};var X8=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var k,W8,l,h,c;var i=X8(()=>{k={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},W8={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},l={Pending:0,Fulfilled:1,Rejected:2},h={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},c={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function m(...Z){B8&&console.log("quickjs-emscripten:",...Z)}function*X9(Z){return yield Z}function y9(Z){return X9(q8(Z))}function d8(Z,$){return(...W)=>{let Q=$.call(Z,J8,...W);return q8(Q)}}function k9(Z,$){let W=$.call(Z,J8);return q8(W)}function q8(Z){function $(W){return W.done?W.value:W.value instanceof Promise?W.value.then((Q)=>$(Z.next(Q)),(Q)=>$(Z.throw(Q))):$(Z.next(W.value))}return $(Z.next())}function z8(Z,$){let W;try{Z.dispose()}catch(Q){W=Q}if($&&W)throw Object.assign($,{message:`${$.message}
3
+ Then, failed to dispose scope: ${W.message}`,disposeError:W}),$;if($||W)throw $||W}function h9(Z){let $=Z?Array.from(Z):[];function W(){return $.forEach((B)=>B.alive?B.dispose():void 0)}function Q(){return $.some((B)=>B.alive)}return Object.defineProperty($,G8,{configurable:!0,enumerable:!1,value:W}),Object.defineProperty($,"dispose",{configurable:!0,enumerable:!1,value:W}),Object.defineProperty($,"alive",{configurable:!0,enumerable:!1,get:Q}),$}function n(Z){return!!(Z&&(typeof Z=="object"||typeof Z=="function")&&("alive"in Z)&&typeof Z.alive=="boolean"&&("dispose"in Z)&&typeof Z.dispose=="function")}function m9(Z){if(!Z)return 0;let $=0;for(let[W,Q]of Object.entries(Z)){if(!(W in W8))throw new r8(W);Q&&($|=W8[W])}return $}function d9(Z){if(typeof Z=="number")return Z;if(Z===void 0)return 0;let{type:$,strict:W,strip:Q,compileOnly:B,backtraceBarrier:C}=Z,H=0;return $==="global"&&(H|=k.JS_EVAL_TYPE_GLOBAL),$==="module"&&(H|=k.JS_EVAL_TYPE_MODULE),W&&(H|=k.JS_EVAL_FLAG_STRICT),Q&&(H|=k.JS_EVAL_FLAG_STRIP),B&&(H|=k.JS_EVAL_FLAG_COMPILE_ONLY),C&&(H|=k.JS_EVAL_FLAG_BACKTRACE_BARRIER),H}function p9(Z){if(typeof Z=="number")return Z;if(Z===void 0)return 0;let{strings:$,symbols:W,quickjsPrivate:Q,onlyEnumerable:B,numbers:C,numbersAsStrings:H}=Z,K=0;return $&&(K|=h.JS_GPN_STRING_MASK),W&&(K|=h.JS_GPN_SYMBOL_MASK),Q&&(K|=h.JS_GPN_PRIVATE_MASK),B&&(K|=h.JS_GPN_ENUM_ONLY),C&&(K|=h.QTS_GPN_NUMBER_MASK),H&&(K|=h.QTS_STANDARD_COMPLIANT_NUMBER),K}function u9(...Z){let $=[];for(let W of Z)W!==void 0&&($=$.concat(W));return $}function K8(Z){return Z>>8}function H8(Z,$){$.interruptHandler&&Z.setInterruptHandler($.interruptHandler),$.maxStackSizeBytes!==void 0&&Z.setMaxStackSize($.maxStackSizeBytes),$.memoryLimitBytes!==void 0&&Z.setMemoryLimit($.memoryLimitBytes)}function j8(Z,$){$.moduleLoader&&Z.setModuleLoader($.moduleLoader),$.shouldInterrupt&&Z.setInterruptHandler($.shouldInterrupt),$.memoryLimitBytes!==void 0&&Z.setMemoryLimit($.memoryLimitBytes),$.maxStackSizeBytes!==void 0&&Z.setMaxStackSize($.maxStackSizeBytes)}var x9,b9=(Z,$)=>{for(var W in $)x9(Z,W,{get:$[W],enumerable:!0})},B8=!1,A9,Y8,n8,Q8,a8,s8,t8,T9,f9,r8,e8,Z9,$9,f,J8,b,G8,p8,w,v,u8,I,C8,v9,g9,g,c9,W9=class{constructor(Z){this.module=Z}toPointerArray(Z){let $=new Int32Array(Z.map((B)=>B.value)),W=$.length*$.BYTES_PER_ELEMENT,Q=this.module._malloc(W);return new Uint8Array(this.module.HEAPU8.buffer,Q,W).set(new Uint8Array($.buffer)),new w(Q,void 0,(B)=>this.module._free(B))}newTypedArray(Z,$){let W=new Z(Array($).fill(0)),Q=W.length*W.BYTES_PER_ELEMENT,B=this.module._malloc(Q),C=new Z(this.module.HEAPU8.buffer,B,$);return C.set(W),new w({typedArray:C,ptr:B},void 0,(H)=>this.module._free(H.ptr))}newMutablePointerArray(Z){return this.newTypedArray(Int32Array,Z)}newHeapCharPointer(Z){let $=this.module.lengthBytesUTF8(Z),W=$+1,Q=this.module._malloc(W);return this.module.stringToUTF8(Z,Q,W),new w({ptr:Q,strlen:$},void 0,(B)=>this.module._free(B.ptr))}newHeapBufferPointer(Z){let $=Z.byteLength,W=this.module._malloc($);return this.module.HEAPU8.set(Z,W),new w({pointer:W,numBytes:$},void 0,(Q)=>this.module._free(Q.pointer))}consumeHeapCharPointer(Z){let $=this.module.UTF8ToString(Z);return this.module._free(Z),$}},RZ,MZ,l9,l8=-2147483648,i8=2147483647,o=0,i9=class{constructor(){this.nextId=l8,this.freelist=[],this.groups=new Map}put(Z){let $=this.allocateId(),W=K8($),Q=this.groups.get(W);return Q||(Q=new Map,this.groups.set(W,Q)),Q.set($,Z),$}get(Z){if(Z===o)throw new f("no host reference id defined");let $=K8(Z),W=this.groups.get($);if(!W)throw new f(`host reference id ${Z} is not defined`);let Q=W.get(Z);if(!Q)throw new f(`host reference id ${Z} is not defined`);return Q}delete(Z){if(Z===o)throw new f("no host reference id defined");let $=K8(Z),W=this.groups.get($);if(!W)throw new f(`host reference id ${Z} is not defined`);W.delete(Z),W.size===0&&this.groups.delete($),this.freelist.push(Z)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===o&&this.nextId++,this.nextId>i8)throw new $9(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${i8-l8}`);return this.nextId++}},o8,o9,n9,a9,s9=class{constructor(Z){this.freeHostRef=Z.freeHostRef,this.callFunction=Z.callFunction,this.shouldInterrupt=Z.shouldInterrupt,this.loadModuleSource=Z.loadModuleSource,this.normalizeModule=Z.normalizeModule}},U8=class{constructor(Z){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new s9({freeHostRef:($,W,Q)=>{let B=this.runtimeCallbacks.get(W);if(!B)throw Error(`QuickJSRuntime(rt = ${W}) not found when trying to free HostRef(id = ${Q})`);B.freeHostRef(W,Q)},callFunction:($,W,Q,B,C,H)=>this.handleAsyncify($,()=>{try{let K=this.contextCallbacks.get(W);if(!K)throw Error(`QuickJSContext(ctx = ${W}) not found for C function call "${H}"`);return K.callFunction(W,Q,B,C,H)}catch(K){return console.error("[C to host error: returning null]",K),0}}),shouldInterrupt:($,W)=>this.handleAsyncify($,()=>{try{let Q=this.runtimeCallbacks.get(W);if(!Q)throw Error(`QuickJSRuntime(rt = ${W}) not found for C interrupt`);return Q.shouldInterrupt(W)}catch(Q){return console.error("[C to host interrupt: returning error]",Q),1}}),loadModuleSource:($,W,Q,B)=>this.handleAsyncify($,()=>{try{let C=this.runtimeCallbacks.get(W);if(!C)throw Error(`QuickJSRuntime(rt = ${W}) not found for C module loader`);let H=C.loadModuleSource;if(!H)throw Error(`QuickJSRuntime(rt = ${W}) does not support module loading`);return H(W,Q,B)}catch(C){return console.error("[C to host module loader error: returning null]",C),0}}),normalizeModule:($,W,Q,B,C)=>this.handleAsyncify($,()=>{try{let H=this.runtimeCallbacks.get(W);if(!H)throw Error(`QuickJSRuntime(rt = ${W}) not found for C module loader`);let K=H.normalizeModule;if(!K)throw Error(`QuickJSRuntime(rt = ${W}) does not support module loading`);return K(W,Q,B,C)}catch(H){return console.error("[C to host module loader error: returning null]",H),0}})}),this.module=Z,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(Z,$){this.runtimeCallbacks.set(Z,$)}deleteRuntime(Z){this.runtimeCallbacks.delete(Z)}setContextCallbacks(Z,$){this.contextCallbacks.set(Z,$)}deleteContext(Z){this.contextCallbacks.delete(Z)}handleAsyncify(Z,$){if(Z)return Z.handleSleep((Q)=>{try{let B=$();if(!(B instanceof Promise)){m("asyncify.handleSleep: not suspending:",B),Q(B);return}if(this.suspended)throw new s8(`Already suspended at: ${this.suspended.stack}
4
+ Attempted to suspend at:`);this.suspended=new t8(`(${this.suspendedCount++})`),m("asyncify.handleSleep: suspending:",this.suspended),B.then((C)=>{this.suspended=void 0,m("asyncify.handleSleep: resolved:",C),Q(C)},(C)=>{m("asyncify.handleSleep: rejected:",C),console.error("QuickJS: cannot handle error in suspended function",C),this.suspended=void 0})}catch(B){throw m("asyncify.handleSleep: error:",B),this.suspended=void 0,B}});let W=$();if(W instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return W}},z9=class{constructor(Z,$){this.module=Z,this.ffi=$,this.callbacks=new U8(Z)}newRuntime(Z={}){let $=new w(this.ffi.QTS_NewRuntime(),void 0,(Q)=>{this.ffi.QTS_FreeRuntime(Q),this.callbacks.deleteRuntime(Q)}),W=new a9({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:$});return H8(W,Z),Z.moduleLoader&&W.setModuleLoader(Z.moduleLoader),W}newContext(Z={}){let $=this.newRuntime(),W=$.newContext({...Z,ownedLifetimes:u9($,Z.ownedLifetimes)});return $.context=W,W}evalCode(Z,$={}){return I.withScope((W)=>{let Q=W.manage(this.newContext());j8(Q.runtime,$);let B=Q.evalCode(Z,"eval.js");if($.memoryLimitBytes!==void 0&&Q.runtime.setMemoryLimit(-1),B.error)throw Q.dump(W.manage(B.error));return Q.dump(W.manage(B.value))})}getWasmMemory(){let Z=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!Z)throw Error("Variant does not support getting WebAssembly.Memory");return Z}getFFI(){return this.ffi}};var K9=X8(()=>{i();i();x9=Object.defineProperty;A9={};b9(A9,{QuickJSAsyncifyError:()=>s8,QuickJSAsyncifySuspended:()=>t8,QuickJSEmptyGetOwnPropertyNames:()=>Z9,QuickJSEmscriptenModuleError:()=>f9,QuickJSHostRefInvalid:()=>f,QuickJSHostRefRangeExceeded:()=>$9,QuickJSMemoryLeakDetected:()=>T9,QuickJSNotImplemented:()=>a8,QuickJSPromisePending:()=>e8,QuickJSUnknownIntrinsic:()=>r8,QuickJSUnwrapError:()=>Y8,QuickJSUseAfterFree:()=>Q8,QuickJSWrongOwner:()=>n8});Y8=class extends Error{constructor(Z,$){let W=typeof Z=="object"&&Z&&"message"in Z?String(Z.message):String(Z);super(W);this.cause=Z,this.context=$,this.name="QuickJSUnwrapError"}},n8=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},Q8=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},a8=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},s8=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},t8=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},T9=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},f9=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},r8=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},e8=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},Z9=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},$9=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},f=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};J8=X9;J8.of=y9;b=class{[Symbol.dispose](){return this.dispose()}},G8=Symbol.dispose??Symbol.for("Symbol.dispose"),p8=b.prototype;p8[G8]||(p8[G8]=function(){return this.dispose()});w=class Z extends b{constructor($,W,Q,B){super();this._value=$,this.copier=W,this.disposer=Q,this._owner=B,this._alive=!0,this._constructorStack=B8?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 Z(this.copier(this._value),this.copier,this.disposer,this._owner)}consume($){this.assertAlive();let W=$(this);return this.dispose(),W}map($){return this.assertAlive(),$(this)}tap($){return $(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new Q8(`Lifetime not alive
5
+ ${this._constructorStack}
6
+ Lifetime used`):new Q8("Lifetime not alive")}},v=class extends w{constructor(Z,$){super(Z,void 0,void 0,$)}get dupable(){return!0}dup(){return this}dispose(){}},u8=class extends w{constructor(Z,$,W,Q){super(Z,$,W,Q)}dispose(){this._alive=!1}};I=class Z extends b{constructor(){super(...arguments);this._disposables=new w(new Set),this.manage=($)=>(this._disposables.value.add($),$)}static withScope($){let W=new Z,Q;try{return $(W)}catch(B){throw Q=B,B}finally{z8(W,Q)}}static withScopeMaybeAsync($,W){return k9(void 0,function*(Q){let B=new Z,C;try{return yield*Q.of(W.call($,Q,B))}catch(H){throw C=H,H}finally{z8(B,C)}})}static async withScopeAsync($){let W=new Z,Q;try{return await $(W)}catch(B){throw Q=B,B}finally{z8(W,Q)}}get alive(){return this._disposables.alive}dispose(){let $=Array.from(this._disposables.value.values()).reverse();for(let W of $)W.alive&&W.dispose();this._disposables.dispose()}};C8=class Z extends b{static success($){return new v9($)}static fail($,W){return new g9($,W)}static is($){return $ instanceof Z}},v9=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}},g9=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,c9=class extends b{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()}},RZ=Symbol("Unstable"),MZ=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});l9=class extends b{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 W=this.callIteratorMethod($,Z);return $.dispose(),this.dispose(),W}throw(Z){if(!this.alive)return{done:!0,value:void 0};let $=Z instanceof w?Z:this.context.newError(Z),W=this.context.getProp(this.handle,"throw"),Q=this.callIteratorMethod(W,Z);return $.alive&&$.dispose(),W.dispose(),this.dispose(),Q}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Z,$){let W=$?this.context.callFunction(Z,this.handle,$):this.context.callFunction(Z,this.handle);if(W.error)return this.dispose(),{value:W};let Q=this.context.getProp(W.value,"done").consume((C)=>this.context.dump(C)),B=this.context.getProp(W.value,"value");return W.value.dispose(),Q&&this.dispose(),{value:g.success(B),done:Q}}};o8=class extends b{constructor(Z,$,W){if(W===o)throw new f("cannot create HostRef with undefined id");super();this.runtime=Z,this.handle=$,this.id=W}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},o9=class extends W9{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 W=$?(Q)=>{$(),this.freeJSValue(Q)}:this.freeJSValue;return new w(Z,this.copyJSValue,W,this.owner)}staticHeapValueHandle(Z){return this.manage(this.heapValueHandle(Z)),new v(Z,this.owner)}},n9=class extends b{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:($,W,Q,B,C)=>{if($!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let H=this.getFunction(C);return I.withScopeMaybeAsync(this,function*(K,D){let P=D.manage(new u8(W,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),x=Array(Q);for(let M=0;M<Q;M++){let A=this.ffi.QTS_ArgvGetJSValueConstPointer(B,M);x[M]=D.manage(new u8(A,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let M=yield*K(H.apply(P,x));if(M){if("error"in M&&M.error)throw this.runtime.debugLog("throw error",M.error),M.error;let A=D.manage(M instanceof w?M:M.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,A.value)}return 0}catch(M){return this.errorToHandle(M).consume((A)=>this.ffi.QTS_Throw(this.ctx.value,A.value))}})}},this.runtime=Z.runtime,this.module=Z.module,this.ffi=Z.ffi,this.rt=Z.rt,this.ctx=Z.ctx,this.memory=new o9({...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((W)=>this.ffi.QTS_NewString(this.ctx.value,W.value.ptr));return this.memory.heapValueHandle($)}newUniqueSymbol(Z){let $=(typeof Z=="symbol"?Z.description:Z)??"",W=this.memory.newHeapCharPointer($).consume((Q)=>this.ffi.QTS_NewSymbol(this.ctx.value,Q.value.ptr,0));return this.memory.heapValueHandle(W)}newSymbolFor(Z){let $=(typeof Z=="symbol"?Z.description:Z)??"",W=this.memory.newHeapCharPointer($).consume((Q)=>this.ffi.QTS_NewSymbol(this.ctx.value,Q.value.ptr,1));return this.memory.heapValueHandle(W)}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,W=String(Z);return this.newString(W).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),W=this.memory.newHeapBufferPointer($),Q=this.ffi.QTS_NewArrayBuffer(this.ctx.value,W.value.pointer,$.length);return this.memory.heapValueHandle(Q)}newPromise(Z){let $=I.withScope((W)=>{let Q=W.manage(this.memory.newMutablePointerArray(2)),B=this.ffi.QTS_NewPromiseCapability(this.ctx.value,Q.value.ptr),C=this.memory.heapValueHandle(B),[H,K]=Array.from(Q.value.typedArray).map((D)=>this.memory.heapValueHandle(D));return new c9({context:this,promiseHandle:C,resolveHandle:H,rejectHandle:K})});return Z&&typeof Z=="function"&&(Z=new Promise(Z)),Z&&Promise.resolve(Z).then($.resolve,(W)=>W instanceof w?$.reject(W):this.newError(W).consume($.reject)),$}newFunction(Z,$){let W=typeof Z=="function"?Z:$;if(!W)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof Z=="string"?Z:void 0,length:W.length,isConstructor:!1,fn:W})}newConstructorFunction(Z,$){let W=typeof Z=="function"?Z:$;if(!W)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof Z=="string"?Z:void 0,length:W.length,isConstructor:!0,fn:W})}newFunctionWithOptions(Z){let{name:$,length:W,isConstructor:Q,fn:B}=Z,C=this.runtime.hostRefs.put(B);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,$??"",W,Q,C))}catch(H){throw this.runtime.hostRefs.delete(C),H}}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((W)=>this.setProp($,"name",W)),Z.message!==void 0&&this.newString(Z.message).consume((W)=>this.setProp($,"message",W))):typeof Z=="string"?this.newString(Z).consume((W)=>this.setProp($,"message",W)):Z!==void 0&&this.newString(String(Z)).consume((W)=>this.setProp($,"message",W)),$}newHostRef(Z){let $=this.runtime.hostRefs.put(Z);try{let W=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,$));return new o8(this.runtime,W,$)}catch(W){throw this.runtime.hostRefs.delete($),W}}toHostRef(Z){let $=this.ffi.QTS_GetHostRefId(Z.value);if($!==0)return this.runtime.hostRefs.get($),new o8(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),W=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Z.value);if(!W)throw Error("Couldn't allocate memory to get ArrayBuffer");return new w(this.module.HEAPU8.subarray(W,W+$),void 0,()=>this.module._free(W))}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 e8("Cannot unwrap a pending promise")}};let W=this.ffi.QTS_PromiseResult(this.ctx.value,Z.value),Q=this.memory.heapValueHandle(W);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((W)=>{let Q=W.manage(this.getProp(this.global,"Promise")),B=W.manage(this.getProp(Q,"resolve"));return this.callFunction(B,Q,Z)});return $.error?Promise.resolve($):new Promise((W)=>{I.withScope((Q)=>{let B=Q.manage(this.newFunction("resolve",(D)=>{W(this.success(D&&D.dup()))})),C=Q.manage(this.newFunction("reject",(D)=>{W(this.fail(D&&D.dup()))})),H=Q.manage($.value),K=Q.manage(this.getProp(H,"then"));this.callFunction(K,H,B,C).unwrap().dispose()})})}isEqual(Z,$,W=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,W);if(Q===-1)throw new a8("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 W;return typeof $=="number"&&$>=0?W=this.ffi.QTS_GetPropNumber(this.ctx.value,Z.value,$):W=this.borrowPropertyKey($).consume((Q)=>this.ffi.QTS_GetProp(this.ctx.value,Z.value,Q.value)),this.memory.heapValueHandle(W)}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 W=p9($);if(W===0)throw new Z9("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,W);if(C)return this.fail(this.memory.heapValueHandle(C));let H=this.uint32Out.value.typedArray[0],K=B.value.typedArray[0],D=new Uint32Array(this.module.HEAP8.buffer,K,H),P=Array.from(D).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,K),this.success(h9(P))})}getIterator(Z){let $=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return I.withScope((W)=>{let Q=W.manage(this.getProp(Z,$)),B=this.callFunction(Q,Z);return B.error?B:this.success(new l9(B.value,this))})}setProp(Z,$,W){this.runtime.assertOwned(Z),this.borrowPropertyKey($).consume((Q)=>this.ffi.QTS_SetProp(this.ctx.value,Z.value,Q.value,W.value))}defineProp(Z,$,W){this.runtime.assertOwned(Z),I.withScope((Q)=>{let B=Q.manage(this.borrowPropertyKey($)),C=W.value||this.undefined,H=!!W.configurable,K=!!W.enumerable,D=!!W.value,P=W.get?Q.manage(this.newFunction(W.get.name,W.get)):this.undefined,x=W.set?Q.manage(this.newFunction(W.set.name,W.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Z.value,B.value,C.value,P.value,x.value,H,K,D)})}callFunction(Z,$,...W){this.runtime.assertOwned(Z);let Q,B=W[0];B===void 0||Array.isArray(B)?Q=B??[]:Q=W;let C=this.memory.toPointerArray(Q).consume((K)=>this.ffi.QTS_Call(this.ctx.value,Z.value,$.value,Q.length,K.value)),H=this.ffi.QTS_ResolveException(this.ctx.value,C);return H?(this.ffi.QTS_FreeValuePointer(this.ctx.value,C),this.fail(this.memory.heapValueHandle(H))):this.success(this.memory.heapValueHandle(C))}callMethod(Z,$,W=[]){return this.getProp(Z,$).consume((Q)=>this.callFunction(Q,Z,W))}evalCode(Z,$="eval.js",W){let Q=W===void 0?1:0,B=d9(W),C=this.memory.newHeapCharPointer(Z).consume((K)=>this.ffi.QTS_Eval(this.ctx.value,K.value.ptr,K.value.strlen,$,Q,B)),H=this.ffi.QTS_ResolveException(this.ctx.value,C);return H?(this.ffi.QTS_FreeValuePointer(this.ctx.value,C),this.fail(this.memory.heapValueHandle(H))):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 W=this.getPromiseState(Z);if(W.type==="fulfilled"&&!W.notAPromise)return Z.dispose(),{type:W.type,value:W.value.consume(this.dump)};if(W.type==="pending")return Z.dispose(),{type:W.type};if(W.type==="rejected")return Z.dispose(),{type:W.type,error:W.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,W=Z.error.consume((Q)=>this.dump(Q));if(W&&typeof W=="object"&&typeof W.message=="string"){let{message:Q,name:B,stack:C,...H}=W,K=new Y8(W,$);typeof B=="string"&&(K.name=W.name),K.message=Q;let D=K.stack;throw typeof C=="string"&&(K.stack=`${B}: ${Q}
7
+ ${W.stack}Host: ${D}`),Object.assign(K,H),K}throw new Y8(W)}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($))}},a9=class extends b{constructor(Z){super();this.scope=new I,this.contextMap=new Map,this.hostRefs=new i9,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:($,W)=>{if($!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(W)},shouldInterrupt:($)=>{if($!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let W=this.interruptHandler;if(!W)throw Error("QuickJSContext had no interrupt handler");return W(this)?1:0},loadModuleSource:d8(this,function*($,W,Q,B){let C=this.moduleLoader;if(!C)throw Error("Runtime has no module loader");if(W!==this.rt.value)throw Error("Runtime pointer mismatch");let H=this.contextMap.get(Q)??this.newContext({contextPointer:Q});try{let K=yield*$(C(B,H));if(typeof K=="object"&&"error"in K&&K.error)throw this.debugLog("cToHostLoadModule: loader returned error",K.error),K.error;let D=typeof K=="string"?K:("value"in K)?K.value:K;return this.memory.newHeapCharPointer(D).value.ptr}catch(K){return this.debugLog("cToHostLoadModule: caught error",K),H.throw(K),0}}),normalizeModule:d8(this,function*($,W,Q,B,C){let H=this.moduleNormalizer;if(!H)throw Error("Runtime has no module normalizer");if(W!==this.rt.value)throw Error("Runtime pointer mismatch");let K=this.contextMap.get(Q)??this.newContext({contextPointer:Q});try{let D=yield*$(H(B,C,K));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 K.getMemory(this.rt.value).newHeapCharPointer(P).value.ptr}catch(D){return this.debugLog("normalizeModule: caught error",D),K.throw(D),0}})},Z.ownedLifetimes?.forEach(($)=>this.scope.manage($)),this.module=Z.module,this.memory=new W9(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 $=m9(Z.intrinsics),W=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 n9({module:this.module,ctx:W,ffi:this.ffi,rt:this.rt,ownedLifetimes:Z.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(W.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),W=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,W),g.success(0);let B=this.contextMap.get(Q)??this.newContext({contextPointer:Q}),C=B.getMemory(this.rt.value).heapValueHandle(W);if(B.typeof(C)==="number"){let H=B.getNumber(C);return C.dispose(),g.success(H)}else{let H=Object.assign(C,{context:B});return g.fail(H,(K)=>B.unwrapResult(K))}}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 n8(`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 Y9={};S9(Y9,{applyModuleEvalRuntimeOptions:()=>j8,applyBaseRuntimeOptions:()=>H8,QuickJSWASMModule:()=>z9,QuickJSModuleCallbacks:()=>U8});var Q9=X8(()=>{K9()});var U9=P9((a,C9)=>{(function(Z,$){typeof a==="object"&&typeof C9<"u"?$(a):typeof define==="function"&&define.amd?define(["exports"],$):(Z=typeof globalThis<"u"?globalThis:Z||self,$(Z.jmespath={}))})(a,function(Z){let $=(X)=>{return X!==null&&Object.prototype.toString.call(X)==="[object Object]"},W=(X,z)=>{if(X===z)return!0;if(typeof X!==typeof z)return!1;if(Array.isArray(X)&&Array.isArray(z)){if(X.length!==z.length)return!1;for(let Y=0;Y<X.length;Y+=1)if(!W(X[Y],z[Y]))return!1;return!0}if($(X)&&$(z)){let Y=Object.entries(X),G=new Set(Object.keys(z));if(Y.length!==G.size)return!1;for(let[q,U]of Y){if(!W(U,z[q]))return!1;G.delete(q)}return G.size===0}return!1},Q=(X)=>{if(X===""||X===!1||X===null||X===void 0)return!0;if(Array.isArray(X)&&X.length===0)return!0;if($(X)){for(let z in X)if(X.hasOwnProperty(z))return!1;return!0}return!1},B=(X)=>{return X>="a"&&X<="z"||X>="A"&&X<="Z"||X==="_"},C=(X)=>{return X>="0"&&X<="9"||X==="-"},H=(X)=>{return X>="a"&&X<="z"||X>="A"&&X<="Z"||X>="0"&&X<="9"||X==="_"};var K;(function(X){X.TOK_EOF="EOF",X.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",X.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",X.TOK_RBRACKET="Rbracket",X.TOK_RPAREN="Rparen",X.TOK_COMMA="Comma",X.TOK_COLON="Colon",X.TOK_RBRACE="Rbrace",X.TOK_NUMBER="Number",X.TOK_CURRENT="Current",X.TOK_ROOT="Root",X.TOK_EXPREF="Expref",X.TOK_PIPE="Pipe",X.TOK_OR="Or",X.TOK_AND="And",X.TOK_EQ="EQ",X.TOK_GT="GT",X.TOK_LT="LT",X.TOK_GTE="GTE",X.TOK_LTE="LTE",X.TOK_NE="NE",X.TOK_FLATTEN="Flatten",X.TOK_STAR="Star",X.TOK_FILTER="Filter",X.TOK_DOT="Dot",X.TOK_NOT="Not",X.TOK_LBRACE="Lbrace",X.TOK_LBRACKET="Lbracket",X.TOK_LPAREN="Lparen",X.TOK_LITERAL="Literal"})(K||(K={}));let D={"(":K.TOK_LPAREN,")":K.TOK_RPAREN,"*":K.TOK_STAR,",":K.TOK_COMMA,".":K.TOK_DOT,":":K.TOK_COLON,"@":K.TOK_CURRENT,["$"]:K.TOK_ROOT,"]":K.TOK_RBRACKET,"{":K.TOK_LBRACE,"}":K.TOK_RBRACE},P={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class M{constructor(){this._current=0}tokenize(X){let z=[];this._current=0;let Y,G,q;while(this._current<X.length)if(B(X[this._current]))Y=this._current,G=this.consumeUnquotedIdentifier(X),z.push({start:Y,type:K.TOK_UNQUOTEDIDENTIFIER,value:G});else if(D[X[this._current]]!==void 0)z.push({start:this._current,type:D[X[this._current]],value:X[this._current]}),this._current+=1;else if(C(X[this._current]))q=this.consumeNumber(X),z.push(q);else if(X[this._current]==="[")q=this.consumeLBracket(X),z.push(q);else if(X[this._current]==='"')Y=this._current,G=this.consumeQuotedIdentifier(X),z.push({start:Y,type:K.TOK_QUOTEDIDENTIFIER,value:G});else if(X[this._current]==="'")Y=this._current,G=this.consumeRawStringLiteral(X),z.push({start:Y,type:K.TOK_LITERAL,value:G});else if(X[this._current]==="`"){Y=this._current;let U=this.consumeLiteral(X);z.push({start:Y,type:K.TOK_LITERAL,value:U})}else if(P[X[this._current]]!==void 0)q=this.consumeOperator(X),q&&z.push(q);else if(x[X[this._current]]!==void 0)this._current+=1;else if(X[this._current]==="&")if(Y=this._current,this._current+=1,X[this._current]==="&")this._current+=1,z.push({start:Y,type:K.TOK_AND,value:"&&"});else z.push({start:Y,type:K.TOK_EXPREF,value:"&"});else if(X[this._current]==="|")if(Y=this._current,this._current+=1,X[this._current]==="|")this._current+=1,z.push({start:Y,type:K.TOK_OR,value:"||"});else z.push({start:Y,type:K.TOK_PIPE,value:"|"});else{let U=Error(`Unknown character: ${X[this._current]}`);throw U.name="LexerError",U}return z}consumeUnquotedIdentifier(X){let z=this._current;this._current+=1;while(this._current<X.length&&H(X[this._current]))this._current+=1;return X.slice(z,this._current)}consumeQuotedIdentifier(X){let z=this._current;this._current+=1;let Y=X.length;while(X[this._current]!=='"'&&this._current<Y){let G=this._current;if(X[G]==="\\"&&(X[G+1]==="\\"||X[G+1]==='"'))G+=2;else G+=1;this._current=G}return this._current+=1,JSON.parse(X.slice(z,this._current))}consumeRawStringLiteral(X){let z=this._current;this._current+=1;let Y=X.length;while(X[this._current]!=="'"&&this._current<Y){let q=this._current;if(X[q]==="\\"&&(X[q+1]==="\\"||X[q+1]==="'"))q+=2;else q+=1;this._current=q}return this._current+=1,X.slice(z+1,this._current-1).replace("\\'","'")}consumeNumber(X){let z=this._current;this._current+=1;let Y=X.length;while(C(X[this._current])&&this._current<Y)this._current+=1;let G=parseInt(X.slice(z,this._current),10);return{start:z,value:G,type:K.TOK_NUMBER}}consumeLBracket(X){let z=this._current;if(this._current+=1,X[this._current]==="?")return this._current+=1,{start:z,type:K.TOK_FILTER,value:"[?"};if(X[this._current]==="]")return this._current+=1,{start:z,type:K.TOK_FLATTEN,value:"[]"};return{start:z,type:K.TOK_LBRACKET,value:"["}}consumeOperator(X){let z=this._current,Y=X[z];if(this._current+=1,Y==="!"){if(X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_NE,value:"!="};return{start:z,type:K.TOK_NOT,value:"!"}}if(Y==="<"){if(X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_LTE,value:"<="};return{start:z,type:K.TOK_LT,value:"<"}}if(Y===">"){if(X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_GTE,value:">="};return{start:z,type:K.TOK_GT,value:">"}}if(Y==="="&&X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_EQ,value:"=="}}consumeLiteral(X){this._current+=1;let z=this._current,Y=X.length;while(X[this._current]!=="`"&&this._current<Y){let U=this._current;if(X[U]==="\\"&&(X[U+1]==="\\"||X[U+1]==="`"))U+=2;else U+=1;this._current=U}let G=X.slice(z,this._current).trimLeft();G=G.replace("\\`","`");let q=this.looksLikeJSON(G)?JSON.parse(G):JSON.parse(`"${G}"`);return this._current+=1,q}looksLikeJSON(X){let Y=["true","false","null"],G="-0123456789";if(X==="")return!1;if('[{"'.includes(X[0]))return!0;if(Y.includes(X))return!0;if("-0123456789".includes(X[0]))try{return JSON.parse(X),!0}catch(q){return!1}return!1}}let A=new M,_={[K.TOK_EOF]:0,[K.TOK_UNQUOTEDIDENTIFIER]:0,[K.TOK_QUOTEDIDENTIFIER]:0,[K.TOK_RBRACKET]:0,[K.TOK_RPAREN]:0,[K.TOK_COMMA]:0,[K.TOK_RBRACE]:0,[K.TOK_NUMBER]:0,[K.TOK_CURRENT]:0,[K.TOK_EXPREF]:0,[K.TOK_ROOT]:0,[K.TOK_PIPE]:1,[K.TOK_OR]:2,[K.TOK_AND]:3,[K.TOK_EQ]:5,[K.TOK_GT]:5,[K.TOK_LT]:5,[K.TOK_GTE]:5,[K.TOK_LTE]:5,[K.TOK_NE]:5,[K.TOK_FLATTEN]:9,[K.TOK_STAR]:20,[K.TOK_FILTER]:21,[K.TOK_DOT]:40,[K.TOK_NOT]:45,[K.TOK_LBRACE]:50,[K.TOK_LBRACKET]:55,[K.TOK_LPAREN]:60};class L8{constructor(){this.index=0,this.tokens=[]}parse(X){this.loadTokens(X),this.index=0;let z=this.expression(0);if(this.lookahead(0)!==K.TOK_EOF){let Y=this.lookaheadToken(0);this.errorToken(Y,`Unexpected token type: ${Y.type}, value: ${Y.value}`)}return z}loadTokens(X){this.tokens=[...A.tokenize(X),{type:K.TOK_EOF,value:"",start:X.length}]}expression(X){let z=this.lookaheadToken(0);this.advance();let Y=this.nud(z),G=this.lookahead(0);while(X<_[G])this.advance(),Y=this.led(G,Y),G=this.lookahead(0);return Y}lookahead(X){return this.tokens[this.index+X].type}lookaheadToken(X){return this.tokens[this.index+X]}advance(){this.index+=1}nud(X){let z,Y,G;switch(X.type){case K.TOK_LITERAL:return{type:"Literal",value:X.value};case K.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:X.value};case K.TOK_QUOTEDIDENTIFIER:let q={type:"Field",name:X.value};if(this.lookahead(0)===K.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return q;case K.TOK_NOT:return Y=this.expression(_.Not),{type:"NotExpression",children:[Y]};case K.TOK_STAR:return z={type:"Identity"},Y=this.lookahead(0)===K.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(_.Star),{type:"ValueProjection",children:[z,Y]};case K.TOK_FILTER:return this.led(X.type,{type:"Identity"});case K.TOK_LBRACE:return this.parseMultiselectHash();case K.TOK_FLATTEN:return z={type:K.TOK_FLATTEN,children:[{type:"Identity"}]},Y=this.parseProjectionRHS(_.Flatten),{type:"Projection",children:[z,Y]};case K.TOK_LBRACKET:if(this.lookahead(0)===K.TOK_NUMBER||this.lookahead(0)===K.TOK_COLON)return Y=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},Y);if(this.lookahead(0)===K.TOK_STAR&&this.lookahead(1)===K.TOK_RBRACKET)return this.advance(),this.advance(),Y=this.parseProjectionRHS(_.Star),{children:[{type:"Identity"},Y],type:"Projection"};return this.parseMultiselectList();case K.TOK_CURRENT:return{type:K.TOK_CURRENT};case K.TOK_ROOT:return{type:K.TOK_ROOT};case K.TOK_EXPREF:return G=this.expression(_.Expref),{type:"ExpressionReference",children:[G]};case K.TOK_LPAREN:let U=[];while(this.lookahead(0)!==K.TOK_RPAREN){if(this.lookahead(0)===K.TOK_CURRENT)G={type:K.TOK_CURRENT},this.advance();else G=this.expression(0);U.push(G)}return this.match(K.TOK_RPAREN),U[0];default:this.errorToken(X)}}led(X,z){let Y;switch(X){case K.TOK_DOT:let G=_.Dot;if(this.lookahead(0)!==K.TOK_STAR)return Y=this.parseDotRHS(G),{type:"Subexpression",children:[z,Y]};return this.advance(),Y=this.parseProjectionRHS(G),{type:"ValueProjection",children:[z,Y]};case K.TOK_PIPE:return Y=this.expression(_.Pipe),{type:K.TOK_PIPE,children:[z,Y]};case K.TOK_OR:return Y=this.expression(_.Or),{type:"OrExpression",children:[z,Y]};case K.TOK_AND:return Y=this.expression(_.And),{type:"AndExpression",children:[z,Y]};case K.TOK_LPAREN:let q=z.name,U=[],L;while(this.lookahead(0)!==K.TOK_RPAREN){if(this.lookahead(0)===K.TOK_CURRENT)L={type:K.TOK_CURRENT},this.advance();else L=this.expression(0);if(this.lookahead(0)===K.TOK_COMMA)this.match(K.TOK_COMMA);U.push(L)}return this.match(K.TOK_RPAREN),{name:q,type:"Function",children:U};case K.TOK_FILTER:let F=this.expression(0);return this.match(K.TOK_RBRACKET),Y=this.lookahead(0)===K.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(_.Filter),{type:"FilterProjection",children:[z,Y,F]};case K.TOK_FLATTEN:let N={type:K.TOK_FLATTEN,children:[z]},R=this.parseProjectionRHS(_.Flatten);return{type:"Projection",children:[N,R]};case K.TOK_EQ:case K.TOK_NE:case K.TOK_GT:case K.TOK_GTE:case K.TOK_LT:case K.TOK_LTE:return this.parseComparator(z,X);case K.TOK_LBRACKET:let j=this.lookaheadToken(0);if(j.type===K.TOK_NUMBER||j.type===K.TOK_COLON)return Y=this.parseIndexExpression(),this.projectIfSlice(z,Y);return this.match(K.TOK_STAR),this.match(K.TOK_RBRACKET),Y=this.parseProjectionRHS(_.Star),{type:"Projection",children:[z,Y]};default:return this.errorToken(this.lookaheadToken(0))}}match(X){if(this.lookahead(0)===X){this.advance();return}else{let z=this.lookaheadToken(0);this.errorToken(z,`Expected ${X}, got: ${z.type}`)}}errorToken(X,z=""){let Y=Error(z||`Invalid token (${X.type}): "${X.value}"`);throw Y.name="ParserError",Y}parseIndexExpression(){if(this.lookahead(0)===K.TOK_COLON||this.lookahead(1)===K.TOK_COLON)return this.parseSliceExpression();let X={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(K.TOK_RBRACKET),X}projectIfSlice(X,z){let Y={type:"IndexExpression",children:[X,z]};if(z.type==="Slice")return{children:[Y,this.parseProjectionRHS(_.Star)],type:"Projection"};return Y}parseSliceExpression(){let X=[null,null,null],z=0,Y=this.lookahead(0);while(Y!==K.TOK_RBRACKET&&z<3){if(Y===K.TOK_COLON)z+=1,this.advance();else if(Y===K.TOK_NUMBER)X[z]=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(K.TOK_RBRACKET),{children:X,type:"Slice"}}parseComparator(X,z){let Y=this.expression(_[z]);return{type:"Comparator",name:z,children:[X,Y]}}parseDotRHS(X){let z=this.lookahead(0);if([K.TOK_UNQUOTEDIDENTIFIER,K.TOK_QUOTEDIDENTIFIER,K.TOK_STAR].includes(z))return this.expression(X);if(z===K.TOK_LBRACKET)return this.match(K.TOK_LBRACKET),this.parseMultiselectList();if(z===K.TOK_LBRACE)return this.match(K.TOK_LBRACE),this.parseMultiselectHash();let G=this.lookaheadToken(0);this.errorToken(G,`Syntax error, unexpected token: ${G.value}(${G.type})`)}parseProjectionRHS(X){if(_[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===K.TOK_LBRACKET)return this.expression(X);if(this.lookahead(0)===K.TOK_FILTER)return this.expression(X);if(this.lookahead(0)===K.TOK_DOT)return this.match(K.TOK_DOT),this.parseDotRHS(X);let z=this.lookaheadToken(0);this.errorToken(z,`Syntax error, unexpected token: ${z.value}(${z.type})`)}parseMultiselectList(){let X=[];while(this.lookahead(0)!==K.TOK_RBRACKET){let z=this.expression(0);if(X.push(z),this.lookahead(0)===K.TOK_COMMA){if(this.match(K.TOK_COMMA),this.lookahead(0)===K.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(K.TOK_RBRACKET),{type:"MultiSelectList",children:X}}parseMultiselectHash(){let X=[],z=[K.TOK_UNQUOTEDIDENTIFIER,K.TOK_QUOTEDIDENTIFIER],Y,G,q;for(;;){if(Y=this.lookaheadToken(0),!z.includes(Y.type))throw Error(`Expecting an identifier token, got: ${Y.type}`);if(G=Y.value,this.advance(),this.match(K.TOK_COLON),q=this.expression(0),X.push({value:q,type:"KeyValuePair",name:G}),this.lookahead(0)===K.TOK_COMMA)this.match(K.TOK_COMMA);else if(this.lookahead(0)===K.TOK_RBRACE){this.match(K.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:X}}}let O8=new L8;var J;(function(X){X[X.TYPE_NUMBER=0]="TYPE_NUMBER",X[X.TYPE_ANY=1]="TYPE_ANY",X[X.TYPE_STRING=2]="TYPE_STRING",X[X.TYPE_ARRAY=3]="TYPE_ARRAY",X[X.TYPE_OBJECT=4]="TYPE_OBJECT",X[X.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",X[X.TYPE_EXPREF=6]="TYPE_EXPREF",X[X.TYPE_NULL=7]="TYPE_NULL",X[X.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",X[X.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(J||(J={}));class F8{constructor(X){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=([z])=>{return Math.abs(z)},this.functionAvg=([z])=>{let Y=0;for(let G=0;G<z.length;G+=1)Y+=z[G];return Y/z.length},this.functionCeil=([z])=>{return Math.ceil(z)},this.functionContains=(z)=>{let[Y,G]=z;return Y.includes(G)},this.functionEndsWith=(z)=>{let[Y,G]=z;return Y.includes(G,Y.length-G.length)},this.functionFloor=([z])=>{return Math.floor(z)},this.functionJoin=(z)=>{let[Y,G]=z;return G.join(Y)},this.functionKeys=([z])=>{return Object.keys(z)},this.functionLength=([z])=>{if(!$(z))return z.length;return Object.keys(z).length},this.functionMap=(z)=>{if(!this._interpreter)return[];let Y=[],G=this._interpreter,q=z[0],U=z[1];for(let L=0;L<U.length;L+=1)Y.push(G.visit(q,U[L]));return Y},this.functionMax=([z])=>{if(!z.length)return null;if(this.getTypeName(z[0])===J.TYPE_NUMBER)return Math.max(...z);let G=z,q=G[0];for(let U=1;U<G.length;U+=1)if(q.localeCompare(G[U])<0)q=G[U];return q},this.functionMaxBy=(z)=>{let Y=z[1],G=z[0],q=this.createKeyFunction(Y,[J.TYPE_NUMBER,J.TYPE_STRING]),U=-1/0,L,O;for(let F=0;F<G.length;F+=1)if(O=q&&q(G[F]),O!==void 0&&O>U)U=O,L=G[F];return L},this.functionMerge=(z)=>{let Y={};for(let G=0;G<z.length;G+=1){let q=z[G];Y=Object.assign(Y,q)}return Y},this.functionMin=([z])=>{if(!z.length)return null;if(this.getTypeName(z[0])===J.TYPE_NUMBER)return Math.min(...z);let G=z,q=G[0];for(let U=1;U<G.length;U+=1)if(G[U].localeCompare(q)<0)q=G[U];return q},this.functionMinBy=(z)=>{let Y=z[1],G=z[0],q=this.createKeyFunction(Y,[J.TYPE_NUMBER,J.TYPE_STRING]),U=1/0,L,O;for(let F=0;F<G.length;F+=1)if(O=q&&q(G[F]),O!==void 0&&O<U)U=O,L=G[F];return L},this.functionNotNull=(z)=>{for(let Y=0;Y<z.length;Y+=1)if(this.getTypeName(z[Y])!==J.TYPE_NULL)return z[Y];return null},this.functionReverse=([z])=>{if(this.getTypeName(z)===J.TYPE_STRING){let q=z,U="";for(let L=q.length-1;L>=0;L-=1)U+=q[L];return U}let G=z.slice(0);return G.reverse(),G},this.functionSort=([z])=>{return[...z].sort()},this.functionSortBy=(z)=>{if(!this._interpreter)return[];let Y=z[0].slice(0);if(Y.length===0)return Y;let G=this._interpreter,q=z[1],U=this.getTypeName(G.visit(q,Y[0]));if(U!==void 0&&![J.TYPE_NUMBER,J.TYPE_STRING].includes(U))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[U]})`);let L=[];for(let O=0;O<Y.length;O+=1)L.push([O,Y[O]]);L.sort((O,F)=>{let N=G.visit(q,O[1]),R=G.visit(q,F[1]);if(this.getTypeName(N)!==U)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[U]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(N)]}`);else if(this.getTypeName(R)!==U)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[U]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(R)]}`);if(N>R)return 1;return N<R?-1:O[0]-F[0]});for(let O=0;O<L.length;O+=1)Y[O]=L[O][1];return Y},this.functionStartsWith=([z,Y])=>{return z.startsWith(Y)},this.functionSum=([z])=>{return z.reduce((Y,G)=>Y+G,0)},this.functionToArray=([z])=>{if(this.getTypeName(z)===J.TYPE_ARRAY)return z;return[z]},this.functionToNumber=([z])=>{let Y=this.getTypeName(z),G;if(Y===J.TYPE_NUMBER)return z;if(Y===J.TYPE_STRING){if(G=+z,!isNaN(G))return G}return null},this.functionToString=([z])=>{if(this.getTypeName(z)===J.TYPE_STRING)return z;return JSON.stringify(z)},this.functionType=([z])=>{switch(this.getTypeName(z)){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=([z])=>{return Object.values(z)},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=X}registerFunction(X,z,Y){if(X in this.functionTable)throw Error(`Function already defined: ${X}()`);this.functionTable[X]={_func:z.bind(this),_signature:Y}}callFunction(X,z){let Y=this.functionTable[X];if(Y===void 0)throw Error(`Unknown function: ${X}()`);return this.validateArgs(X,z,Y._signature),Y._func.call(this,z)}validateInputSignatures(X,z){for(let Y=0;Y<z.length;Y+=1)if("variadic"in z[Y]&&Y!==z.length-1)throw Error(`ArgumentError: ${X}() 'variadic' argument ${Y+1} must occur last`)}validateArgs(X,z,Y){var G,q;let U;this.validateInputSignatures(X,Y);let L=Y.filter((E)=>{var S;return(S=!E.optional)!==null&&S!==void 0?S:!1}).length,O=(q=(G=Y[Y.length-1])===null||G===void 0?void 0:G.variadic)!==null&&q!==void 0?q:!1,F=z.length<L,N=z.length>Y.length,R=F&&(!O&&L>1||O)?"at least ":"";if(O&&F||!O&&(F||N))throw U=Y.length>1,Error(`ArgumentError: ${X}() takes ${R}${L} argument${U&&"s"||""} but received ${z.length}`);let j,V,T;for(let E=0;E<Y.length;E+=1){T=!1,j=Y[E].types,V=this.getTypeName(z[E]);let S;for(S=0;S<j.length;S+=1)if(V!==void 0&&this.typeMatches(V,j[S],z[E])){T=!0;break}if(!T&&V!==void 0){let d=j.map((p)=>{return this.TYPE_NAME_TABLE[p]}).join(" | ");throw Error(`TypeError: ${X}() expected argument ${E+1} to be type (${d}) but received type ${this.TYPE_NAME_TABLE[V]} instead.`)}}}typeMatches(X,z,Y){if(z===J.TYPE_ANY)return!0;if(z===J.TYPE_ARRAY_STRING||z===J.TYPE_ARRAY_NUMBER||z===J.TYPE_ARRAY){if(z===J.TYPE_ARRAY)return X===J.TYPE_ARRAY;if(X===J.TYPE_ARRAY){let G;if(z===J.TYPE_ARRAY_NUMBER)G=J.TYPE_NUMBER;else if(z===J.TYPE_ARRAY_STRING)G=J.TYPE_STRING;for(let q=0;q<Y.length;q+=1){let U=this.getTypeName(Y[q]);if(U!==void 0&&G!==void 0&&!this.typeMatches(U,G,Y[q]))return!1}return!0}}else return X===z;return!1}getTypeName(X){switch(Object.prototype.toString.call(X)){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(X.jmespathType===K.TOK_EXPREF)return J.TYPE_EXPREF;return J.TYPE_OBJECT;default:return}}createKeyFunction(X,z){if(!this._interpreter)return;let Y=this._interpreter;return(q)=>{let U=Y.visit(X,q);if(!z.includes(this.getTypeName(U))){let L=`TypeError: expected one of (${z.map((O)=>this.TYPE_NAME_TABLE[O]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(U)]}`;throw Error(L)}return U}}}class R8{constructor(){this._rootValue=null,this.runtime=new F8(this)}search(X,z){return this._rootValue=z,this.visit(X,z)}visit(X,z){let Y,G,q,U,L,O,F,N,R,j,V;switch(X.type){case"Field":if(z===null)return null;if($(z)){if(O=z[X.name],O===void 0)return null;return O}return null;case"Subexpression":q=this.visit(X.children[0],z);for(j=1;j<X.children.length;j+=1)if(q=this.visit(X.children[1],q),q===null)return null;return q;case"IndexExpression":return F=this.visit(X.children[0],z),N=this.visit(X.children[1],F),N;case"Index":if(!Array.isArray(z))return null;let T=X.value;if(T<0)T=z.length+T;if(q=z[T],q===void 0)q=null;return q;case"Slice":if(!Array.isArray(z))return null;let E=[...X.children],S=this.computeSliceParams(z.length,E),[d,p,t]=S;if(q=[],t>0)for(j=d;j<p;j+=t)q.push(z[j]);else for(j=d;j>p;j+=t)q.push(z[j]);return q;case"Projection":if(V=this.visit(X.children[0],z),!Array.isArray(V))return null;R=[];for(j=0;j<V.length;j+=1)if(G=this.visit(X.children[1],V[j]),G!==null)R.push(G);return R;case"ValueProjection":if(V=this.visit(X.children[0],z),!$(V))return null;R=[];let h8=Object.values(V);for(j=0;j<h8.length;j+=1)if(G=this.visit(X.children[1],h8[j]),G!==null)R.push(G);return R;case"FilterProjection":if(V=this.visit(X.children[0],z),!Array.isArray(V))return null;let r=[],v8=[];for(j=0;j<V.length;j+=1)if(Y=this.visit(X.children[2],V[j]),!Q(Y))r.push(V[j]);for(let y=0;y<r.length;y+=1)if(G=this.visit(X.children[1],r[y]),G!==null)v8.push(G);return v8;case"Comparator":switch(U=this.visit(X.children[0],z),L=this.visit(X.children[1],z),X.name){case K.TOK_EQ:q=W(U,L);break;case K.TOK_NE:q=!W(U,L);break;case K.TOK_GT:q=U>L;break;case K.TOK_GTE:q=U>=L;break;case K.TOK_LT:q=U<L;break;case K.TOK_LTE:q=U<=L;break;default:throw Error(`Unknown comparator: ${X.name}`)}return q;case K.TOK_FLATTEN:let e=this.visit(X.children[0],z);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 z;case"MultiSelectList":if(z===null)return null;R=[];for(j=0;j<X.children.length;j+=1)R.push(this.visit(X.children[j],z));return R;case"MultiSelectHash":if(z===null)return null;R={};let Z8;for(j=0;j<X.children.length;j+=1)Z8=X.children[j],R[Z8.name]=this.visit(Z8.value,z);return R;case"OrExpression":if(Y=this.visit(X.children[0],z),Q(Y))Y=this.visit(X.children[1],z);return Y;case"AndExpression":if(U=this.visit(X.children[0],z),Q(U))return U;return this.visit(X.children[1],z);case"NotExpression":return U=this.visit(X.children[0],z),Q(U);case"Literal":return X.value;case K.TOK_PIPE:return F=this.visit(X.children[0],z),this.visit(X.children[1],F);case K.TOK_CURRENT:return z;case K.TOK_ROOT:return this._rootValue;case"Function":let g8=[];for(let y=0;y<X.children.length;y+=1)g8.push(this.visit(X.children[y],z));return this.runtime.callFunction(X.name,g8);case"ExpressionReference":let c8=X.children[0];return c8.jmespathType=K.TOK_EXPREF,c8;default:throw Error(`Unknown node type: ${X.type}`)}}computeSliceParams(X,z){let[Y,G,q]=z;if(q===null)q=1;else if(q===0){let L=Error("Invalid slice, step cannot be 0");throw L.name="RuntimeError",L}let U=q<0?!0:!1;return Y=Y===null?U?X-1:0:this.capSliceRange(X,Y,q),G=G===null?U?-1:X:this.capSliceRange(X,G,q),[Y,G,q]}capSliceRange(X,z,Y){let G=z;if(G<0){if(G+=X,G<0)G=Y<0?-1:0}else if(G>=X)G=Y<0?X-1:X;return G}}let s=new R8,M8=J.TYPE_ANY,V8=J.TYPE_ARRAY,_8=J.TYPE_ARRAY_NUMBER,w8=J.TYPE_ARRAY_STRING,P8=J.TYPE_BOOLEAN,N8=J.TYPE_EXPREF,E8=J.TYPE_NULL,S8=J.TYPE_NUMBER,I8=J.TYPE_OBJECT,x8=J.TYPE_STRING;function b8(X){return O8.parse(X)}function A8(X){return A.tokenize(X)}let T8=(X,z,Y)=>{s.runtime.registerFunction(X,z,Y)};function f8(X,z){let Y=O8.parse(z);return s.search(Y,X)}let y8=s,k8={compile:b8,registerFunction:T8,search:f8,tokenize:A8,TreeInterpreter:y8,TYPE_ANY:M8,TYPE_ARRAY_NUMBER:_8,TYPE_ARRAY_STRING:w8,TYPE_ARRAY:V8,TYPE_BOOLEAN:P8,TYPE_EXPREF:N8,TYPE_NULL:E8,TYPE_NUMBER:S8,TYPE_OBJECT:I8,TYPE_STRING:x8};Z.TYPE_ANY=M8,Z.TYPE_ARRAY=V8,Z.TYPE_ARRAY_NUMBER=_8,Z.TYPE_ARRAY_STRING=w8,Z.TYPE_BOOLEAN=P8,Z.TYPE_EXPREF=N8,Z.TYPE_NULL=E8,Z.TYPE_NUMBER=S8,Z.TYPE_OBJECT=I8,Z.TYPE_STRING=x8,Z.TreeInterpreter=y8,Z.compile=b8,Z.default=k8,Z.jmespath=k8,Z.registerFunction=T8,Z.search=f8,Z.tokenize=A8,Object.defineProperty(Z,"__esModule",{value:!0})})});import{timingSafeEqual as QZ}from"node:crypto";import{createServer as GZ}from"node:http";import{Readable as BZ}from"node:stream";function I9(){return typeof process>"u"?{}:process.env}function m8(Z=I9()){return Z.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as KZ}from"node:fs";i();async function G9(Z){let $=D8(await Z),[W,Q,{QuickJSWASMModule:B}]=await Promise.all([$.importModuleLoader().then(D8),$.importFFI(),Promise.resolve().then(() => (Q9(),Y9)).then(D8)]),C=await W();C.type="sync";let H=new Q(C);return new B(C,H)}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 J9="engine";function t9(Z){let $=(W)=>new URL(W,Z).href;return{type:"sync",importFFI:()=>import($("ffi.mjs")).then((W)=>W.QuickJSFFI),importModuleLoader:()=>import($("emscripten-module.mjs")).then((W)=>W.default)}}var B9=null;function q9(Z){return()=>{return B9??=G9(t9(Z)),B9}}var r9=w9(U9(),1);var ZZ="__mcpcloud_call_tool",B1=`globalThis.tool = (name, args) =>
8
+ globalThis.${ZZ}(String(name), JSON.stringify(args ?? {}))
9
+ .then((json) => JSON.parse(json));`;var $Z=6,XZ=["log","warn","error","info","debug"],WZ="__mcpcloud_console",C1=`globalThis.console = {
10
+ ${XZ.map((Z)=>` ${Z}: (...args) => globalThis.${WZ}(${JSON.stringify(Z)}, JSON.stringify(args.slice(0, ${$Z}).map((value) => (value instanceof Error ? { __mcpcloudError: value.name + ': ' + value.message } : value)))),`).join(`
11
+ `)}
12
+ };`;var zZ=null;function H9(Z){zZ=Z}var j9=[`./${J9}/`,"../engine/vendor/","../../engine/vendor/"];function YZ(Z=new URL(import.meta.url)){for(let $ of j9){let W=new URL($,Z);if(KZ(new URL("emscripten-module.wasm",W)))return W}throw Error(`Code Mode engine not found. Looked for emscripten-module.wasm in: ${j9.join(", ")} (relative to ${Z.href}).`)}function D9(){H9(()=>q9(YZ())())}function JZ(Z,$){let W=Buffer.from(Z),Q=Buffer.from($);return W.length===Q.length&&QZ(W,Q)}function qZ(Z,$){let W=m8($);if(!W)return null;if(new URL(Z.url).pathname==="/health")return null;let Q=Z.headers.get("authorization")??"",B=/^Bearer\s+(.+)$/i.exec(Q.trim());if(B&&JZ(B[1].trim(),W))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 CZ(Z,$){let W=new URL(Z.url??"/",$),Q=new Headers;for(let[H,K]of Object.entries(Z.headers))if(Array.isArray(K))for(let D of K)Q.append(H,D);else if(typeof K==="string")Q.set(H,K);let B=Z.method??"GET",C=B==="GET"||B==="HEAD"?void 0:BZ.toWeb(Z);return new Request(W,{method:B,headers:Q,body:C,...C?{duplex:"half"}:{}})}async function UZ(Z,$){if($.statusCode=Z.status,Z.headers.forEach((Q,B)=>{$.setHeader(B,Q)}),!Z.body){$.end();return}let W=Z.body.getReader();for(;;){let{done:Q,value:B}=await W.read();if(Q)break;$.write(B)}$.end()}function HZ(Z,$={}){D9();let W=$.port??Number(process.env.PORT??8080),Q=$.hostname??"0.0.0.0",B=GZ((C,H)=>{let K=`http://${C.headers.host??`${Q}:${W}`}`,D=CZ(C,K),P=qZ(D,$.env);(P?Promise.resolve(P):Z.handleRequest(D,$.env)).then((M)=>UZ(M,H)).catch(()=>{H.statusCode=500,H.end(JSON.stringify({error:"internal_error"}))})});return B.listen(W,Q),B}export{HZ as serve};
@@ -7,6 +7,15 @@ import type { ToolDefinition } from './types';
7
7
  * never break the tool call.
8
8
  */
9
9
  export declare function applyResponseProjection(tool: ToolDefinition, payload: unknown): unknown;
10
+ /**
11
+ * Projection by raw expression, for callers that hold one without a whole
12
+ * ToolDefinition — the Code Mode sandbox knows tool NAMES, not definitions.
13
+ *
14
+ * Extracted so the sandbox and the direct-call path cannot drift on the
15
+ * fail-open semantics: a malformed projection must never break a tool call, and
16
+ * having two implementations of "never" is how you end up with one that does.
17
+ */
18
+ export declare function projectWithExpression(expression: string | null | undefined, payload: unknown): unknown;
10
19
  /**
11
20
  * `applyResponseProjection`, plus the measurement the savings chart needs.
12
21
  *
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The only thing guest code can reach.
3
+ *
4
+ * §5: "Nothing is exposed to guest code by default… We build the guest's entire
5
+ * universe by hand, and that hand-built surface is where every policy decision
6
+ * lands." This module is that surface — one host function, plus a thin guest
7
+ * shim so agent code writes `await tool('name', {...})` against real objects.
8
+ *
9
+ * The sandbox knows NOTHING about policy. It takes a callback and calls it. RBAC,
10
+ * rate limits, key injection, metering and audit belong to whoever supplies that
11
+ * callback (the dispatch worker), which keeps the policy chokepoint exactly where
12
+ * it already is instead of reimplementing it in here.
13
+ */
14
+ import type { QuickJSContext, QuickJSRuntime } from 'quickjs-emscripten-core';
15
+ import type { SandboxSpan } from './types';
16
+ /**
17
+ * Mirrors `ToolEffectClass` in shared/serverSandboxSafety.ts.
18
+ *
19
+ * Duplicated rather than imported because `packages/runtime` is a standalone
20
+ * published package and does not reach into `shared/` — the same reason
21
+ * key-rotation keeps its own copy, with a test welding the two together.
22
+ */
23
+ export type SandboxEffectClass = 'read' | 'write' | 'delete' | 'external_effect';
24
+ /**
25
+ * What Code Mode may call unless a server says otherwise.
26
+ *
27
+ * §7.4: a delete removes state and an external effect (mail, webhook, payment)
28
+ * cannot be taken back once it leaves. Both deserve a human decision, and Code
29
+ * Mode has no human in the loop at all.
30
+ */
31
+ export declare const DEFAULT_ALLOWED_EFFECTS: readonly SandboxEffectClass[];
32
+ export interface ToolCallRequest {
33
+ name: string;
34
+ args: Record<string, unknown>;
35
+ }
36
+ export interface SandboxBindings {
37
+ /**
38
+ * Routes one call through the caller's policy path and resolves with the
39
+ * result. Rejecting is normal — the guest sees a rejected promise and may
40
+ * catch it, exactly as it would with any async API.
41
+ */
42
+ callTool: (request: ToolCallRequest) => Promise<unknown>;
43
+ /**
44
+ * Whether a tool changes upstream state. Absent, or absent for a given name,
45
+ * resolves to TRUE — misclassifying a mutation as a read is the one error with
46
+ * irreversible consequences (§7.4), so the default has to fail closed.
47
+ */
48
+ isMutation?: (name: string) => boolean;
49
+ /**
50
+ * The tool's JMESPath response projection, if it declares one.
51
+ *
52
+ * Applied on the HOST side of the boundary, before the payload is marshalled
53
+ * in. §4 measured that as a 2.8x execution win under workerd (122 KB -> 10 KB
54
+ * cut 2.00 ms to 703 us) — not merely a token win, because everything pruned
55
+ * here is never serialised, never copied into the guest heap, and never
56
+ * walked by the interpreter.
57
+ *
58
+ * Doing it structurally rather than leaving it to each caller's callTool is
59
+ * deliberate: the ordering IS the optimisation, and an ordering you have to
60
+ * remember is one that eventually gets forgotten.
61
+ */
62
+ projectionFor?: (name: string) => string | null | undefined;
63
+ /**
64
+ * The tool's settled effect class, from the edge policy entry.
65
+ *
66
+ * Supplying this TURNS THE GATE ON. Omit it and no gating happens at all,
67
+ * which is the caller explicitly opting out rather than an accident.
68
+ */
69
+ /**
70
+ * Whether the tool exists at all.
71
+ *
72
+ * Checked BEFORE the effect gate, because a misspelled tool name is a
73
+ * corrigible mistake in the agent's code, not a policy refusal. Reporting a
74
+ * typo as `policy_denied` would tell the agent to escalate when it should
75
+ * simply fix the name — §7.2's classes exist precisely to keep those apart.
76
+ */
77
+ isKnownTool?: (name: string) => boolean;
78
+ /** Message for an unknown tool — the place to list what IS available. */
79
+ describeUnknownTool?: (name: string) => string;
80
+ /**
81
+ * Refuse a call for a reason that is neither "no such tool" nor "wrong effect
82
+ * class" — per-caller authorization, chiefly.
83
+ *
84
+ * Returns the refusal message, or null to allow. Checked in the SAME place as
85
+ * the effect gate, so an RBAC denial classifies as `policy_denied` rather than
86
+ * as a guest exception: the agent is told to stop and escalate, not to rewrite
87
+ * code that was already correct (§7.2).
88
+ */
89
+ refuseToolCall?: (name: string) => string | null;
90
+ effectClassFor?: (name: string) => SandboxEffectClass | null | undefined;
91
+ /**
92
+ * Effect classes this execution may call. Defaults to read + write.
93
+ *
94
+ * Widening it is a per-server decision that belongs in the Code Mode settings
95
+ * surface (§8.1), not a default.
96
+ */
97
+ allowedEffects?: readonly SandboxEffectClass[];
98
+ }
99
+ export interface InstallBindingsResult {
100
+ /** Spans in call order, readable after the execution settles. */
101
+ spans: SandboxSpan[];
102
+ /** True once the per-execution call cap was hit. */
103
+ exceededCap: () => boolean;
104
+ /** True once a call was refused by the effect-class gate. */
105
+ deniedByPolicy: () => boolean;
106
+ }
107
+ /**
108
+ * Give the guest a `tool()` function.
109
+ *
110
+ * The async pattern is `newPromise()` + `executePendingJobs()`, NOT asyncify.
111
+ * §4 measured asyncify at 2x size and 40% slower, and — decisively — it permits
112
+ * only a single suspend, which forbids `Promise.all` in guest code. Fan-out is
113
+ * the entire reason Code Mode beats sequential tool calling, so a mechanism that
114
+ * cannot express it is not a trade-off, it is a disqualification.
115
+ */
116
+ export declare function installBindings(runtime: QuickJSRuntime, vm: QuickJSContext, bindings: SandboxBindings, maxToolCalls: number): InstallBindingsResult;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * `codemode.execute` — the agent-visible surface.
3
+ *
4
+ * Everything else in this directory is a library; this is the caller. An agent
5
+ * submits JavaScript, it runs in the sandbox, and its tool calls go through the
6
+ * SAME generated handlers a direct `tools/call` would use.
7
+ *
8
+ * That last point is what makes §8's marketing claim literally true rather than
9
+ * approximately true: "every call the sandbox makes is still authorized,
10
+ * rate-limited, key-injected and audited individually — because the sandbox runs
11
+ * inside the same policy layer everything else does." A second path that merely
12
+ * resembled the first would be a lie with extra steps.
13
+ */
14
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
15
+ import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
16
+ import type { CallerContext, RuntimeConfig } from '../config';
17
+ import type { RegisteredTool } from '../server';
18
+ import type { SandboxEffectClass } from './bindings';
19
+ import type { McpToolAnnotations } from '../types';
20
+ import type { SandboxLimits, SandboxResult } from './types';
21
+ /**
22
+ * How prominently a server offers Code Mode (§8.1).
23
+ *
24
+ * `opt-in` and `default` grant IDENTICAL capability — an agent can call
25
+ * `codemode_execute` under either. They differ only in list position and in how
26
+ * the description steers, because ordering and wording are the only mechanisms
27
+ * MCP actually gives us; there is no protocol-level "offer this one first".
28
+ * Pretending otherwise would be inventing a distinction the wire cannot carry.
29
+ */
30
+ export type CodeModeMode = 'off' | 'opt-in' | 'default';
31
+ export interface CodeModeOptions {
32
+ /**
33
+ * The operator's choice, from the server's `codeModeMode` setting.
34
+ *
35
+ * Defaults to `opt-in` when Code Mode options are supplied at all, since
36
+ * supplying them is already the opt-in.
37
+ */
38
+ mode?: CodeModeMode;
39
+ /**
40
+ * Supplies the engine.
41
+ *
42
+ * Injected rather than imported so the runtime package does not bundle a
43
+ * 559 KB wasm into every generated server — a per-server copy would also
44
+ * cold-start constantly on low-traffic servers. §5 calls for one warm copy in
45
+ * the dispatch worker; that host does not exist yet, so on the Workers edge
46
+ * this is currently always absent.
47
+ *
48
+ * Independent of `mode`: the mode is what the operator asked for, the engine
49
+ * is whether this host can actually deliver it. Registration needs both, and
50
+ * neither implies the other.
51
+ */
52
+ engine?: () => Promise<QuickJSWASMModule>;
53
+ limits?: Partial<SandboxLimits>;
54
+ /** Widen what Code Mode may call. Defaults to read + write (§7.4). */
55
+ allowedEffects?: readonly SandboxEffectClass[];
56
+ }
57
+ /** Whether this server should register the tool at all. */
58
+ export declare function shouldRegisterCodeMode(options: CodeModeOptions | undefined): options is CodeModeOptions & {
59
+ engine: () => Promise<QuickJSWASMModule>;
60
+ };
61
+ export declare function setCodeModeEngineProvider(provider: (() => Promise<QuickJSWASMModule>) | null): void;
62
+ /**
63
+ * Fill in the host's engine when the bundle did not carry one.
64
+ *
65
+ * An explicit `engine` always wins — a caller that passed one meant it. Called
66
+ * per server creation rather than once at module load, so a host that registers
67
+ * during startup is never racing an early request.
68
+ */
69
+ export declare function resolveCodeModeOptions(options: CodeModeOptions | undefined): CodeModeOptions | undefined;
70
+ /**
71
+ * Effect class from the MCP annotations the tool already advertises.
72
+ *
73
+ * `ToolDefinition` carries no riskClass — that lives in Convex and the edge
74
+ * policy — but annotations are emitted from exactly that data at codegen time,
75
+ * so they are the same judgement travelling by a different route.
76
+ *
77
+ * Absent annotations yield null, which the gate refuses. That is the right
78
+ * outcome: a server whose tools are unclassified should not be running
79
+ * destructive operations unattended.
80
+ */
81
+ export declare function effectClassFromAnnotations(annotations: McpToolAnnotations | null | undefined): SandboxEffectClass | null;
82
+ /**
83
+ * The unknown-tool message the guest sees.
84
+ *
85
+ * Ranked by edit distance rather than dumping the first N registered names —
86
+ * on a large server the intended tool was usually absent from that dump, while
87
+ * the dump itself weighed hundreds of bytes in every failure digest. Bounded
88
+ * (a suggestion plus at most five names) and deterministic (distance, then
89
+ * alphabetical), regardless of catalog size or registration order.
90
+ */
91
+ export declare function describeUnknownTool(name: string, knownNames: readonly string[]): string;
92
+ /**
93
+ * What the model gets back when execution fails.
94
+ *
95
+ * §7.3, first cut. The digest is ITSELF an intermediate payload, so it is capped
96
+ * — overflowing it reintroduces exactly the cost Code Mode exists to remove.
97
+ * Spans are elided from the middle, keeping the first few and the last few,
98
+ * because the beginning explains the setup and the end is where it broke.
99
+ */
100
+ export declare function buildFailureDigest(result: SandboxResult, source?: string): string;
101
+ /** The tool's implementation. Call `shouldRegisterCodeMode` before wiring it. */
102
+ export declare function buildCodeModeHandler(tools: RegisteredTool[], config: RuntimeConfig, caller: CallerContext, options: CodeModeOptions & {
103
+ engine: () => Promise<QuickJSWASMModule>;
104
+ }): (input: unknown) => Promise<CallToolResult>;
105
+ export declare const CODE_MODE_TOOL_NAME = "codemode_execute";
106
+ /**
107
+ * The description, which is where `default` actually differs from `opt-in`.
108
+ *
109
+ * A description is not decoration here — it is the steer. `default` says prefer
110
+ * this; `opt-in` says it exists. Both leave the choice to the model, because
111
+ * both must: the ordinary tools stay registered either way, and a server that
112
+ * silently hid them would break every client that already calls them by name.
113
+ */
114
+ export declare function codeModeDescription(mode: CodeModeMode): string;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * `console` for guest code (§7.5).
3
+ *
4
+ * The sandbox exposes nothing by default, so without this a guest that calls
5
+ * `console.log` dies with a TypeError — for a reason that has nothing to do with
6
+ * what it was trying to do. That is the worst kind of failure: the agent gets a
7
+ * runtime_error, concludes its logic is wrong, and rewrites code that was fine.
8
+ * Agents write logs by habit, so this is as much about not breaking as it is
9
+ * about observability.
10
+ *
11
+ * §7.5 calls it "the one genuinely useful mid-execution affordance", and the
12
+ * distinction matters: `trace.get` is deliberately NOT callable mid-execution
13
+ * because the guest already holds its values in scope. A log is different — it
14
+ * is the guest telling US something at a moment we cannot otherwise observe.
15
+ *
16
+ * WHAT IS KEPT, AND WHY IT DIFFERS BY TYPE. Strings pass through literally,
17
+ * capped; everything else is shape-summarized. Same reasoning that lets spans
18
+ * record `args` as values but results as shapes: a log string is agent-authored,
19
+ * so echoing it back leaks nothing the agent did not already write, and it is
20
+ * usually the entire point ("reached the second page"). A logged OBJECT is
21
+ * typically a tool result the agent is inspecting, which is exactly the content
22
+ * the token wall exists to keep out of context.
23
+ *
24
+ * SURFACED ONLY ON FAILURE. A successful execution returned what was asked for;
25
+ * dumping its logs into the model's context would reintroduce the cost Code Mode
26
+ * removes. They stay in the trace either way, fetchable.
27
+ */
28
+ import type { SandboxLogEntry } from './types';
29
+ export interface InstallConsoleResult {
30
+ /** Entries in call order, readable after the execution settles. */
31
+ entries: SandboxLogEntry[];
32
+ }
33
+ export declare function installConsole(vm: {
34
+ newFunction: (name: string, fn: (...args: never[]) => void) => {
35
+ dispose: () => void;
36
+ };
37
+ setProp: (target: unknown, key: string, value: unknown) => void;
38
+ global: unknown;
39
+ getString: (handle: never) => string;
40
+ evalCode: (code: string, filename?: string) => {
41
+ error?: {
42
+ dispose: () => void;
43
+ };
44
+ value: {
45
+ dispose: () => void;
46
+ };
47
+ };
48
+ dump: (handle: unknown) => unknown;
49
+ }): InstallConsoleResult;
50
+ /** True once logging was cut short, so the digest can say so honestly. */
51
+ export declare function consoleWasTruncated(entries: SandboxLogEntry[]): boolean;
@@ -11,12 +11,23 @@
11
11
  * not the published variant, which ships 0.12.1 and ten advisories.
12
12
  */
13
13
  import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
14
+ import type { SandboxBindings } from './bindings';
14
15
  import type { SandboxLimits, SandboxResult } from './types';
15
16
  export declare const DEFAULT_SANDBOX_LIMITS: SandboxLimits;
17
+ /** First guest frame's 1-based line and column, when the engine gave one. */
18
+ export declare function parseGuestErrorLocation(stack: string | undefined): {
19
+ line: number;
20
+ column: number;
21
+ } | null;
16
22
  export interface CreateSandboxOptions {
17
23
  /** Loaded once per isolate and reused; instantiation is the expensive part. */
18
24
  engine: QuickJSWASMModule;
19
25
  limits?: Partial<SandboxLimits>;
26
+ /**
27
+ * Gives the guest a `tool()` function. Omit and the guest has no way out at
28
+ * all — which is the correct default, and what P1's tests assert.
29
+ */
30
+ bindings?: SandboxBindings;
20
31
  }
21
32
  /**
22
33
  * Execute `source` and return a discriminated result.
@@ -30,4 +41,8 @@ export interface CreateSandboxOptions {
30
41
  * tool call, so this is structural rather than a discipline to remember. The one
31
42
  * deliberate exception is the poisoned path — see STACK_ESCAPE_NOTE.
32
43
  */
33
- export declare function runInSandbox(options: CreateSandboxOptions, source: string): SandboxResult;
44
+ /**
45
+ * Async because tool calls are. A guest that makes no calls still returns a
46
+ * promise here, which keeps one code path instead of two.
47
+ */
48
+ export declare function runInSandbox(options: CreateSandboxOptions, source: string): Promise<SandboxResult>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The QuickJS engine, for hosts that are not the Workers edge.
3
+ *
4
+ * §3 chose to build this sandbox rather than rent Dynamic Workers on one
5
+ * argument above the others: it has to run on all three targets — the Workers
6
+ * edge, dedicated containers, and a customer's own Docker/Node from the
7
+ * self-host export. The edge got an engine when the sandbox moved into
8
+ * dispatch. This is the other two.
9
+ *
10
+ * WHY THE ENGINE CANNOT SIMPLY BE BUNDLED. The Node emscripten glue resolves
11
+ * `emscripten-module.wasm` by literal filename from disk, so the file has to
12
+ * ship as a file — no amount of bundling substitutes for it. That is also why
13
+ * the vendor directory is passed in as a URL rather than reached through a
14
+ * relative specifier: a bundler rewrites specifiers it can see, and this one
15
+ * must survive to run time. Source and dist put the vendor directory in
16
+ * different places, so the location is DATA, resolved by the caller.
17
+ */
18
+ import type { QuickJSSyncVariant, QuickJSWASMModule } from 'quickjs-emscripten-core';
19
+ /**
20
+ * Where the built package keeps the vendored engine, relative to `dist/*.js`.
21
+ *
22
+ * The build copies `engine/vendor/` here; see scripts/build.ts. Kept as a bare
23
+ * string so the packaging test and the build agree on one spelling.
24
+ */
25
+ export declare const DIST_VENDOR_DIRNAME = "engine";
26
+ /** A variant that loads the vendored engine from `vendorDir` at run time. */
27
+ export declare function createNodeEngineVariant(vendorDir: URL): QuickJSSyncVariant;
28
+ export declare function createNodeEngineLoader(vendorDir: URL): () => Promise<QuickJSWASMModule>;
29
+ /** Test seam. Never call this from production code. */
30
+ export declare function resetNodeEngineForTests(): void;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Describe a value's STRUCTURE without reproducing its content.
3
+ *
4
+ * §7.2 of the Code Mode plan: execution traces are themselves intermediate
5
+ * payloads, so handing them to a model reintroduces the exact cost Code Mode
6
+ * removes — and worse than average, because failures correlate with oversized
7
+ * and malformed data. The rule is "record everything, surface almost nothing".
8
+ * This is the "surface almost nothing" half.
9
+ *
10
+ * Shape is also what actually fixes the bug. `Cannot read properties of null`
11
+ * is resolved by knowing WHICH field is null and HOW OFTEN, never by reading
12
+ * the records. Roughly twenty tokens where the payload is forty thousand.
13
+ *
14
+ * Deliberately pure: no engine, no I/O, no truncated JSON anywhere. Nothing in
15
+ * here can leak a value it was not explicitly asked to reveal.
16
+ */
17
+ export interface ShapeOptions {
18
+ /**
19
+ * Uniform depth. Two is the default because real agent-authored access paths
20
+ * against REST payloads are shallow (`pr.head.sha`, `c.conclusion`); deeper
21
+ * costs tokens for orientation nobody reads.
22
+ */
23
+ maxDepth?: number;
24
+ /**
25
+ * Property path the throw actually touched, followed to FULL depth regardless
26
+ * of maxDepth. Depth is asymmetric on purpose — the one path that matters is
27
+ * however deep the failure happened to reach, and that is the only place
28
+ * extra depth pays for itself.
29
+ */
30
+ focusPath?: readonly string[];
31
+ /** Objects wider than this are summarised. Default 12. */
32
+ maxKeys?: number;
33
+ /** Distinct array element shapes before collapsing to a count. Default 3. */
34
+ maxVariants?: number;
35
+ }
36
+ /**
37
+ * A compact structural description: `{id: string, assignee: null | object}[247]`.
38
+ *
39
+ * Never includes a value — only type names, key names and counts. Key names are
40
+ * structure, not content; a field called `email` reveals that the shape has an
41
+ * email field, not anyone's address.
42
+ */
43
+ export declare function summarizeShape(value: unknown, options?: ShapeOptions): string;
44
+ export interface DistributionFact {
45
+ /** Dotted path to the field, relative to an array element. */
46
+ field: string;
47
+ /** How many elements had it null or absent. */
48
+ missing: number;
49
+ total: number;
50
+ /** Rendered for the digest: `34/247 items have assignee === null`. */
51
+ text: string;
52
+ }
53
+ /**
54
+ * Find the fields that are null or absent in SOME but not all elements.
55
+ *
56
+ * This is the single most useful line in a failure digest and it is a depth-1
57
+ * observation: `Cannot read properties of null (reading 'name')` is explained by
58
+ * "34/247 items have assignee === null" and by nothing else. Fields that are
59
+ * always present are silent (nothing to warn about) and fields that are always
60
+ * null are reported too — a column that is null every time is its own kind of
61
+ * bug, and cheap to say.
62
+ *
63
+ * Ordered by how surprising the gap is, so the digest can take the top N and
64
+ * still show the fact that matters.
65
+ */
66
+ export declare function describeDistribution(rows: unknown, options?: {
67
+ limit?: number;
68
+ }): DistributionFact[];