@decocms/mesh 2.22.0 → 2.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -279,7 +279,7 @@ data:
279
279
  `;if(J)G+=`id: ${J}
280
280
  `;return G+=`data: ${JSON.stringify(Q)}
281
281
 
282
- `,X.enqueue(Y.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(X,Y){try{let Q=X.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=X.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(X.headers.entries())},Z;if(Y?.parsedBody!==void 0)Z=Y.parsedBody;else try{Z=await X.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let W;try{if(Array.isArray(Z))W=Z.map((O)=>qQ.parse(O));else W=[qQ.parse(Z)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let K=W.some(os);if(K){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(W.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!K){let O=this.validateSession(X);if(O)return O;let w=this.validateProtocolVersion(X);if(w)return w}if(!W.some(MG)){for(let O of W)this.onmessage?.(O,{authInfo:Y?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=W.find((O)=>os(O)),q=F?F.params.protocolVersion:X.headers.get("mcp-protocol-version")??pr0;if(this._enableJsonResponse)return new Promise((O)=>{this._streamMapping.set(H,{resolveJson:O,cleanup:()=>{this._streamMapping.delete(H)}});for(let w of W)if(MG(w))this._requestToStreamMapping.set(w.id,H);for(let w of W)this.onmessage?.(w,{authInfo:Y?.authInfo,requestInfo:G})});let V=new TextEncoder,U,D=new ReadableStream({start:(O)=>{U=O},cancel:()=>{this._streamMapping.delete(H)}}),N={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)N["mcp-session-id"]=this.sessionId;for(let O of W)if(MG(O))this._streamMapping.set(H,{controller:U,encoder:V,cleanup:()=>{this._streamMapping.delete(H);try{U.close()}catch{}}}),this._requestToStreamMapping.set(O.id,H);await this.writePrimingEvent(U,V,H,q);for(let O of W){let w,E;if(MG(O)&&this._eventStore&&q>="2025-11-25")w=()=>{this.closeSSEStream(O.id)},E=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(O,{authInfo:Y?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:E})}return new Response(D,{status:200,headers:N})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(X){let Y=this.validateSession(X);if(Y)return Y;let Q=this.validateProtocolVersion(X);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(X){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Y=X.headers.get("mcp-session-id");if(!Y)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Y!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(X){let Y=X.headers.get("mcp-protocol-version");if(Y!==null&&!h3.includes(Y))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Y} (supported versions: ${h3.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:X})=>{X()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(X){let Y=this._requestToStreamMapping.get(X);if(!Y)return;let Q=this._streamMapping.get(Y);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let X=this._streamMapping.get(this._standaloneSseStreamId);if(X)X.cleanup()}async send(X,Y){let Q=Y?.relatedRequestId;if(rJ(X)||xV(X))Q=X.id;if(Q===void 0){if(rJ(X)||xV(X))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let Z;if(this._eventStore)Z=await this._eventStore.storeEvent(this._standaloneSseStreamId,X);let W=this._streamMapping.get(this._standaloneSseStreamId);if(W===void 0)return;if(W.controller&&W.encoder)this.writeSSEEvent(W.controller,W.encoder,X,Z);return}let J=this._requestToStreamMapping.get(Q);if(!J)throw Error(`No connection established for request ID: ${String(Q)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let Z;if(this._eventStore)Z=await this._eventStore.storeEvent(J,X);this.writeSSEEvent(G.controller,G.encoder,X,Z)}if(rJ(X)||xV(X)){this._requestResponseMap.set(Q,X);let Z=Array.from(this._requestToStreamMapping.entries()).filter(([K,$])=>$===J).map(([K])=>K);if(Z.every((K)=>this._requestResponseMap.has(K))){if(!G)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&G.resolveJson){let K={"Content-Type":"application/json"};if(this.sessionId!==void 0)K["mcp-session-id"]=this.sessionId;let $=Z.map((H)=>this._requestResponseMap.get(H));if($.length===1)G.resolveJson(new Response(JSON.stringify($[0]),{status:200,headers:K}));else G.resolveJson(new Response(JSON.stringify($),{status:200,headers:K}))}else G.cleanup();for(let K of Z)this._requestResponseMap.delete(K),this._requestToStreamMapping.delete(K)}}}}var c64=d(()=>{VQ()});var n64=(...X)=>{return function(Q,J){let G=(Z)=>{let W=X[Z];if(!W)return J();return W(Q,()=>G(Z+1))};return G(0)}};class i64{config;tools=[];callToolMiddlewares=[];constructor(X){this.config={...X,capabilities:X.capabilities??{tools:{}}}}withTool(X){return this.tools.push(X),this}withTools(X){return this.tools.push(...X),this}callToolMiddleware(...X){return this.callToolMiddlewares.push(...X),this}build(){let X=this.callToolMiddlewares.length>0?n64(...this.callToolMiddlewares):null,Y=()=>{let Q=new n00({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async($)=>{try{let H=await J.handler($);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},Z=X?async($)=>{let H={method:"tools/call",params:{name:J.name,arguments:$}};return await X(H,()=>G($))}:G,W="shape"in J.inputSchema?J.inputSchema.shape:L.object({}).shape,K=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:L.object({}).shape;Q.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:W,outputSchema:K},Z)}return Q};return{callStreamableTool:async(Q,J)=>{let G=this.tools.find((W)=>W.name===Q);if(!G)throw Error(`Tool ${Q} not found`);let Z=await G.handler(J);if(!(Z instanceof Response))throw Error(`Tool ${Q} returned a non-response`);return Z},client:{listTools:async()=>{return{tools:this.tools.map((Q)=>({name:Q.name,description:Q.description??"",inputSchema:L.toJSONSchema(Q.inputSchema),outputSchema:Q.outputSchema?L.toJSONSchema(Q.outputSchema):void 0}))}},callTool:async(Q)=>{let J=this.tools.find((G)=>G.name===Q.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Q.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Q)=>{let J=new i00({enableJsonResponse:Q.headers.get("Accept")?.includes("application/json")??!1});await Y().connect(J);try{return await J.handleRequest(Q)}finally{try{await J.close?.()}catch{}}}}}}function a64(X){return new i64(X)}var r64=d(()=>{p64();c64();t0()});function r0(X){return{...X,execute:async(Y,Q)=>{let J=Date.now();return await Q.timings.measure(`tool.${X.name}`,async()=>Q.tracer.startActiveSpan(`tool.${X.name}`,{attributes:{"tool.name":X.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Q.toolName=X.name,Q.access.setToolName?.(X.name);let Z=await X.handler(Y,Q),W=Date.now()-J;return Q.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(W,{"tool.name":X.name,"organization.id":Q.organization?.id??"system",status:"success"}),Q.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":X.name,status:"success"}),G.setStatus({code:a00.SpanStatusCode.OK}),Z}catch(Z){throw Q.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":X.name,"error.type":Z.constructor.name}),G.setStatus({code:a00.SpanStatusCode.ERROR,message:Z.message}),G.recordException(Z),Z}finally{G.end()}}))}}}var a00;var o4=d(()=>{a00=n1(Z4(),1)});function I4(X){if(!X.organization)throw Error("This operation requires organization scope");return X.organization}function A8(X){return X.auth.user?.id??X.auth.apiKey?.userId}function iM6(X){return!!(X.auth.user||X.auth.apiKey)}function H4(X){if(!iM6(X))throw Error("Authentication required")}var Ik,o64,s64,t64,e64,X14,Y14,Q14,J14,G14;var Uz=d(()=>{t0();Ik=L.record(L.string(),L.array(L.string())),o64=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),userId:L.string().describe("ID of the user who owns this API key"),permissions:Ik.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:L.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L.string().datetime().describe("When the API key was created (ISO 8601)")}),s64=L.object({name:L.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Ik.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:L.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:L.record(L.string(),L.unknown()).optional().describe("Additional metadata to store with the API key")}),t64=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),key:L.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:Ik.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:L.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L.string().datetime().describe("When the API key was created (ISO 8601)")}),e64=L.object({}),X14=L.object({items:L.array(o64).describe("List of API keys (without key values)")}),Y14=L.object({keyId:L.string().describe("ID of the API key to update"),name:L.string().min(1).max(64).optional().describe("New name for the API key"),permissions:Ik.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:L.record(L.string(),L.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),Q14=L.object({item:o64.describe("The updated API key (without key value)")}),J14=L.object({keyId:L.string().describe("ID of the API key to delete")}),G14=L.object({success:L.boolean().describe("Whether the deletion was successful"),keyId:L.string().describe("ID of the deleted API key")})});var r00;var W14=d(()=>{o4();Uz();r00=r0({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:s64,outputSchema:t64,handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.create({name:X.name,permissions:X.permissions,expiresIn:X.expiresIn,metadata:{...X.metadata,organization:Y.organization}}),J=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,G=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt;return{id:Q.id,name:Q.name??X.name,key:Q.key,permissions:Q.permissions??{},expiresAt:J,createdAt:G}}})});var o00;var Z14=d(()=>{o4();Uz();o00=r0({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:J14,outputSchema:G14,handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),!A8(Y))throw Error("User ID required to delete API key");let G=(await Y.boundAuth.apiKey.list())?.find(($)=>$.id===X.keyId);if(!G)throw Error("API key not found");let W=G.metadata?.organization?.id,K=Y.organization?.id;if(W!==K)throw Error("Cannot delete API key from another organization");return await Y.boundAuth.apiKey.delete(X.keyId),{success:!0,keyId:X.keyId}}})});var s00;var K14=d(()=>{o4();Uz();s00=r0({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:e64,outputSchema:X14,handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.list(),J=Y.organization?.id;return{items:(Q??[]).filter((Z)=>{return Z.metadata?.organization?.id===J}).map((Z)=>({id:Z.id,name:Z.name??"Unnamed Key",userId:Z.userId,permissions:Z.permissions??{},expiresAt:Z.expiresAt?Z.expiresAt instanceof Date?Z.expiresAt.toISOString():Z.expiresAt:null,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var t00;var $14=d(()=>{o4();Uz();t00=r0({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:Y14,outputSchema:Q14,handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),!A8(Y))throw Error("User ID required to update API key");let G=(await Y.boundAuth.apiKey.list())?.find((H)=>H.id===X.keyId);if(!G)throw Error(`API key not found: ${X.keyId}`);let W=G.metadata?.organization?.id,K=Y.organization?.id;if(W!==K)throw Error("Cannot update API key from another organization");let $=await Y.boundAuth.apiKey.update({keyId:X.keyId,name:X.name,permissions:X.permissions,metadata:{...X.metadata,organization:Y.organization}});if(!$)throw Error(`Failed to update API key: ${X.keyId}`);return{item:{id:$.id,name:$.name??X.name??"Unnamed Key",userId:$.userId,permissions:$.permissions??{},expiresAt:$.expiresAt?$.expiresAt instanceof Date?$.expiresAt.toISOString():$.expiresAt:null,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt}}}})});var H14=d(()=>{W14();Z14();K14();$14();Uz()});var F14,q14,V14,z14,U14,B14;var Bw=d(()=>{t0();F14=L.object({query:L.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:L.number().default(10).describe("Maximum results to return (default: 10)")}),q14=L.object({query:L.string(),results:L.array(L.object({name:L.string(),description:L.string().optional(),connection:L.string()})),totalAvailable:L.number()}),V14=L.object({tools:L.array(L.string()).min(1).describe("Array of tool names to get detailed schemas for")}),z14=L.object({tools:L.array(L.object({name:L.string(),description:L.string().optional(),connection:L.string(),inputSchema:L.unknown(),outputSchema:L.unknown().optional()})),notFound:L.array(L.string())}),U14=L.object({code:L.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:L.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),B14=L.object({returnValue:L.unknown().optional(),error:L.string().optional(),consoleLogs:L.array(L.object({type:L.enum(["log","warn","error"]),content:L.string()}))})});class jk{proxies=new Map;constructor(){}static async create(X,Y){let Q=new jk,J=await Promise.allSettled(X.map(async({connection:G,selectedTools:Z,selectedResources:W,selectedPrompts:K})=>{try{let $=await Y.createMCPProxy(G);return{connection:G,proxy:$,selectedTools:Z,selectedResources:W,selectedPrompts:K}}catch($){return console.error(`[aggregator] Failed to create proxy for connection ${G.id}:`,$),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Q.proxies.set(G.value.connection.id,G.value);return Q}get(X){return this.proxies.get(X)}entries(){return this.proxies.entries()}forEach(X){this.proxies.forEach((Y,Q)=>X(Y,Q))}async mapAsync(X){let Y=[];for(let[Q,J]of this.proxies.entries())Y.push(X(J,Q));return await Promise.all(Y)}async mapSettled(X){return Promise.allSettled(Array.from(this.proxies.entries()).map(([Y,Q])=>X(Q,Y)))}get size(){return this.proxies.size}}function D14(X){let Y=[],Q=[],J=($)=>{let H=X.newFunction($,(...F)=>{try{let q=F.map((V)=>X.dump(V));Y.push({type:$??"log",content:q.map(String).join(" ")})}finally{F.forEach((q)=>q.dispose())}return X.undefined});return Q.push(H),H},G=X.newObject();Q.push(G);let Z=J("log"),W=J("warn"),K=J("error");return X.setProp(G,"log",Z),X.setProp(G,"warn",W),X.setProp(G,"error",K),X.setProp(X.global,"console",G),{logs:Y,[Symbol.dispose](){Q.forEach(($)=>$.dispose())}}}var i3,e00,Ck,a3,Dw;var Rk=d(()=>{i3={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},e00={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},Ck={Pending:0,Fulfilled:1,Rejected:2},a3={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},Dw={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function Bz(...X){W40&&console.log("quickjs-emscripten:",...X)}function*R14(X){return yield X}function sM6(X){return R14(K40(X))}function N14(X,Y){return(...Q)=>{let J=Y.call(X,Z40,...Q);return K40(J)}}function tM6(X,Y){let Q=Y.call(X,Z40);return K40(Q)}function K40(X){function Y(Q){return Q.done?Q.value:Q.value instanceof Promise?Q.value.then((J)=>Y(X.next(J)),(J)=>Y(X.throw(J))):Y(X.next(Q.value))}return Y(X.next())}function X40(X,Y){let Q;try{X.dispose()}catch(J){Q=J}if(Y&&Q)throw Object.assign(Y,{message:`${Y.message}
282
+ `,X.enqueue(Y.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(X,Y){try{let Q=X.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=X.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(X.headers.entries())},Z;if(Y?.parsedBody!==void 0)Z=Y.parsedBody;else try{Z=await X.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let W;try{if(Array.isArray(Z))W=Z.map((O)=>qQ.parse(O));else W=[qQ.parse(Z)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let K=W.some(os);if(K){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(W.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!K){let O=this.validateSession(X);if(O)return O;let w=this.validateProtocolVersion(X);if(w)return w}if(!W.some(MG)){for(let O of W)this.onmessage?.(O,{authInfo:Y?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=W.find((O)=>os(O)),q=F?F.params.protocolVersion:X.headers.get("mcp-protocol-version")??pr0;if(this._enableJsonResponse)return new Promise((O)=>{this._streamMapping.set(H,{resolveJson:O,cleanup:()=>{this._streamMapping.delete(H)}});for(let w of W)if(MG(w))this._requestToStreamMapping.set(w.id,H);for(let w of W)this.onmessage?.(w,{authInfo:Y?.authInfo,requestInfo:G})});let V=new TextEncoder,U,D=new ReadableStream({start:(O)=>{U=O},cancel:()=>{this._streamMapping.delete(H)}}),N={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)N["mcp-session-id"]=this.sessionId;for(let O of W)if(MG(O))this._streamMapping.set(H,{controller:U,encoder:V,cleanup:()=>{this._streamMapping.delete(H);try{U.close()}catch{}}}),this._requestToStreamMapping.set(O.id,H);await this.writePrimingEvent(U,V,H,q);for(let O of W){let w,E;if(MG(O)&&this._eventStore&&q>="2025-11-25")w=()=>{this.closeSSEStream(O.id)},E=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(O,{authInfo:Y?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:E})}return new Response(D,{status:200,headers:N})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(X){let Y=this.validateSession(X);if(Y)return Y;let Q=this.validateProtocolVersion(X);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(X){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Y=X.headers.get("mcp-session-id");if(!Y)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Y!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(X){let Y=X.headers.get("mcp-protocol-version");if(Y!==null&&!h3.includes(Y))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Y} (supported versions: ${h3.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:X})=>{X()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(X){let Y=this._requestToStreamMapping.get(X);if(!Y)return;let Q=this._streamMapping.get(Y);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let X=this._streamMapping.get(this._standaloneSseStreamId);if(X)X.cleanup()}async send(X,Y){let Q=Y?.relatedRequestId;if(rJ(X)||xV(X))Q=X.id;if(Q===void 0){if(rJ(X)||xV(X))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let Z;if(this._eventStore)Z=await this._eventStore.storeEvent(this._standaloneSseStreamId,X);let W=this._streamMapping.get(this._standaloneSseStreamId);if(W===void 0)return;if(W.controller&&W.encoder)this.writeSSEEvent(W.controller,W.encoder,X,Z);return}let J=this._requestToStreamMapping.get(Q);if(!J)throw Error(`No connection established for request ID: ${String(Q)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let Z;if(this._eventStore)Z=await this._eventStore.storeEvent(J,X);this.writeSSEEvent(G.controller,G.encoder,X,Z)}if(rJ(X)||xV(X)){this._requestResponseMap.set(Q,X);let Z=Array.from(this._requestToStreamMapping.entries()).filter(([K,$])=>$===J).map(([K])=>K);if(Z.every((K)=>this._requestResponseMap.has(K))){if(!G)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&G.resolveJson){let K={"Content-Type":"application/json"};if(this.sessionId!==void 0)K["mcp-session-id"]=this.sessionId;let $=Z.map((H)=>this._requestResponseMap.get(H));if($.length===1)G.resolveJson(new Response(JSON.stringify($[0]),{status:200,headers:K}));else G.resolveJson(new Response(JSON.stringify($),{status:200,headers:K}))}else G.cleanup();for(let K of Z)this._requestResponseMap.delete(K),this._requestToStreamMapping.delete(K)}}}}var c64=d(()=>{VQ()});var n64=(...X)=>{return function(Q,J){let G=(Z)=>{let W=X[Z];if(!W)return J();return W(Q,()=>G(Z+1))};return G(0)}};class i64{config;tools=[];callToolMiddlewares=[];jsonSchemaCache=new Map;constructor(X){this.config={...X,capabilities:X.capabilities??{tools:{}}}}getCachedJsonSchema(X){let Y=this.jsonSchemaCache.get(X);if(!Y)Y=L.toJSONSchema(X),this.jsonSchemaCache.set(X,Y);return Y}withTool(X){return this.tools.push(X),this}withTools(X){return this.tools.push(...X),this}callToolMiddleware(...X){return this.callToolMiddlewares.push(...X),this}build(){let X=this.callToolMiddlewares.length>0?n64(...this.callToolMiddlewares):null,Y=()=>{let Q=new n00({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async($)=>{try{let H=await J.handler($);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},Z=X?async($)=>{let H={method:"tools/call",params:{name:J.name,arguments:$}};return await X(H,()=>G($))}:G,W="shape"in J.inputSchema?J.inputSchema.shape:L.object({}).shape,K=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:L.object({}).shape;Q.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:W,outputSchema:K},Z)}return Q};return{callStreamableTool:async(Q,J)=>{let G=this.tools.find((W)=>W.name===Q);if(!G)throw Error(`Tool ${Q} not found`);let Z=await G.handler(J);if(!(Z instanceof Response))throw Error(`Tool ${Q} returned a non-response`);return Z},client:{listTools:async()=>{return{tools:this.tools.map((Q)=>({name:Q.name,description:Q.description??"",inputSchema:this.getCachedJsonSchema(Q.inputSchema),outputSchema:Q.outputSchema?this.getCachedJsonSchema(Q.outputSchema):void 0}))}},callTool:async(Q)=>{let J=this.tools.find((G)=>G.name===Q.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Q.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Q)=>{let J=new i00({enableJsonResponse:Q.headers.get("Accept")?.includes("application/json")??!1});await Y().connect(J);try{return await J.handleRequest(Q)}finally{try{await J.close?.()}catch{}}}}}}function a64(X){return new i64(X)}var r64=d(()=>{p64();c64();t0()});function r0(X){return{...X,execute:async(Y,Q)=>{let J=Date.now();return await Q.timings.measure(`tool.${X.name}`,async()=>Q.tracer.startActiveSpan(`tool.${X.name}`,{attributes:{"tool.name":X.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Q.toolName=X.name,Q.access.setToolName?.(X.name);let Z=await X.handler(Y,Q),W=Date.now()-J;return Q.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(W,{"tool.name":X.name,"organization.id":Q.organization?.id??"system",status:"success"}),Q.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":X.name,status:"success"}),G.setStatus({code:a00.SpanStatusCode.OK}),Z}catch(Z){throw Q.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":X.name,"error.type":Z.constructor.name}),G.setStatus({code:a00.SpanStatusCode.ERROR,message:Z.message}),G.recordException(Z),Z}finally{G.end()}}))}}}var a00;var o4=d(()=>{a00=n1(Z4(),1)});function I4(X){if(!X.organization)throw Error("This operation requires organization scope");return X.organization}function A8(X){return X.auth.user?.id??X.auth.apiKey?.userId}function iM6(X){return!!(X.auth.user||X.auth.apiKey)}function H4(X){if(!iM6(X))throw Error("Authentication required")}var Ik,o64,s64,t64,e64,X14,Y14,Q14,J14,G14;var Uz=d(()=>{t0();Ik=L.record(L.string(),L.array(L.string())),o64=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),userId:L.string().describe("ID of the user who owns this API key"),permissions:Ik.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:L.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L.string().datetime().describe("When the API key was created (ISO 8601)")}),s64=L.object({name:L.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Ik.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:L.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:L.record(L.string(),L.unknown()).optional().describe("Additional metadata to store with the API key")}),t64=L.object({id:L.string().describe("Unique identifier for the API key"),name:L.string().describe("Human-readable name for the API key"),key:L.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:Ik.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:L.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L.string().datetime().describe("When the API key was created (ISO 8601)")}),e64=L.object({}),X14=L.object({items:L.array(o64).describe("List of API keys (without key values)")}),Y14=L.object({keyId:L.string().describe("ID of the API key to update"),name:L.string().min(1).max(64).optional().describe("New name for the API key"),permissions:Ik.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:L.record(L.string(),L.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),Q14=L.object({item:o64.describe("The updated API key (without key value)")}),J14=L.object({keyId:L.string().describe("ID of the API key to delete")}),G14=L.object({success:L.boolean().describe("Whether the deletion was successful"),keyId:L.string().describe("ID of the deleted API key")})});var r00;var W14=d(()=>{o4();Uz();r00=r0({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:s64,outputSchema:t64,handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.create({name:X.name,permissions:X.permissions,expiresIn:X.expiresIn,metadata:{...X.metadata,organization:Y.organization}}),J=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,G=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt;return{id:Q.id,name:Q.name??X.name,key:Q.key,permissions:Q.permissions??{},expiresAt:J,createdAt:G}}})});var o00;var Z14=d(()=>{o4();Uz();o00=r0({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:J14,outputSchema:G14,handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),!A8(Y))throw Error("User ID required to delete API key");let G=(await Y.boundAuth.apiKey.list())?.find(($)=>$.id===X.keyId);if(!G)throw Error("API key not found");let W=G.metadata?.organization?.id,K=Y.organization?.id;if(W!==K)throw Error("Cannot delete API key from another organization");return await Y.boundAuth.apiKey.delete(X.keyId),{success:!0,keyId:X.keyId}}})});var s00;var K14=d(()=>{o4();Uz();s00=r0({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:e64,outputSchema:X14,handler:async(X,Y)=>{H4(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.list(),J=Y.organization?.id;return{items:(Q??[]).filter((Z)=>{return Z.metadata?.organization?.id===J}).map((Z)=>({id:Z.id,name:Z.name??"Unnamed Key",userId:Z.userId,permissions:Z.permissions??{},expiresAt:Z.expiresAt?Z.expiresAt instanceof Date?Z.expiresAt.toISOString():Z.expiresAt:null,createdAt:Z.createdAt instanceof Date?Z.createdAt.toISOString():Z.createdAt}))}}})});var t00;var $14=d(()=>{o4();Uz();t00=r0({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:Y14,outputSchema:Q14,handler:async(X,Y)=>{if(H4(Y),await Y.access.check(),!A8(Y))throw Error("User ID required to update API key");let G=(await Y.boundAuth.apiKey.list())?.find((H)=>H.id===X.keyId);if(!G)throw Error(`API key not found: ${X.keyId}`);let W=G.metadata?.organization?.id,K=Y.organization?.id;if(W!==K)throw Error("Cannot update API key from another organization");let $=await Y.boundAuth.apiKey.update({keyId:X.keyId,name:X.name,permissions:X.permissions,metadata:{...X.metadata,organization:Y.organization}});if(!$)throw Error(`Failed to update API key: ${X.keyId}`);return{item:{id:$.id,name:$.name??X.name??"Unnamed Key",userId:$.userId,permissions:$.permissions??{},expiresAt:$.expiresAt?$.expiresAt instanceof Date?$.expiresAt.toISOString():$.expiresAt:null,createdAt:$.createdAt instanceof Date?$.createdAt.toISOString():$.createdAt}}}})});var H14=d(()=>{W14();Z14();K14();$14();Uz()});var F14,q14,V14,z14,U14,B14;var Bw=d(()=>{t0();F14=L.object({query:L.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:L.number().default(10).describe("Maximum results to return (default: 10)")}),q14=L.object({query:L.string(),results:L.array(L.object({name:L.string(),description:L.string().optional(),connection:L.string()})),totalAvailable:L.number()}),V14=L.object({tools:L.array(L.string()).min(1).describe("Array of tool names to get detailed schemas for")}),z14=L.object({tools:L.array(L.object({name:L.string(),description:L.string().optional(),connection:L.string(),inputSchema:L.unknown(),outputSchema:L.unknown().optional()})),notFound:L.array(L.string())}),U14=L.object({code:L.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:L.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),B14=L.object({returnValue:L.unknown().optional(),error:L.string().optional(),consoleLogs:L.array(L.object({type:L.enum(["log","warn","error"]),content:L.string()}))})});class jk{proxies=new Map;constructor(){}static async create(X,Y){let Q=new jk,J=await Promise.allSettled(X.map(async({connection:G,selectedTools:Z,selectedResources:W,selectedPrompts:K})=>{try{let $=await Y.createMCPProxy(G);return{connection:G,proxy:$,selectedTools:Z,selectedResources:W,selectedPrompts:K}}catch($){return console.error(`[aggregator] Failed to create proxy for connection ${G.id}:`,$),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Q.proxies.set(G.value.connection.id,G.value);return Q}get(X){return this.proxies.get(X)}entries(){return this.proxies.entries()}forEach(X){this.proxies.forEach((Y,Q)=>X(Y,Q))}async mapAsync(X){let Y=[];for(let[Q,J]of this.proxies.entries())Y.push(X(J,Q));return await Promise.all(Y)}async mapSettled(X){return Promise.allSettled(Array.from(this.proxies.entries()).map(([Y,Q])=>X(Q,Y)))}get size(){return this.proxies.size}}function D14(X){let Y=[],Q=[],J=($)=>{let H=X.newFunction($,(...F)=>{try{let q=F.map((V)=>X.dump(V));Y.push({type:$??"log",content:q.map(String).join(" ")})}finally{F.forEach((q)=>q.dispose())}return X.undefined});return Q.push(H),H},G=X.newObject();Q.push(G);let Z=J("log"),W=J("warn"),K=J("error");return X.setProp(G,"log",Z),X.setProp(G,"warn",W),X.setProp(G,"error",K),X.setProp(X.global,"console",G),{logs:Y,[Symbol.dispose](){Q.forEach(($)=>$.dispose())}}}var i3,e00,Ck,a3,Dw;var Rk=d(()=>{i3={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},e00={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},Ck={Pending:0,Fulfilled:1,Rejected:2},a3={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},Dw={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function Bz(...X){W40&&console.log("quickjs-emscripten:",...X)}function*R14(X){return yield X}function sM6(X){return R14(K40(X))}function N14(X,Y){return(...Q)=>{let J=Y.call(X,Z40,...Q);return K40(J)}}function tM6(X,Y){let Q=Y.call(X,Z40);return K40(Q)}function K40(X){function Y(Q){return Q.done?Q.value:Q.value instanceof Promise?Q.value.then((J)=>Y(X.next(J)),(J)=>Y(X.throw(J))):Y(X.next(Q.value))}return Y(X.next())}function X40(X,Y){let Q;try{X.dispose()}catch(J){Q=J}if(Y&&Q)throw Object.assign(Y,{message:`${Y.message}
283
283
  Then, failed to dispose scope: ${Q.message}`,disposeError:Q}),Y;if(Y||Q)throw Y||Q}function S14(X){let Y=X?Array.from(X):[];function Q(){return Y.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return Y.some((G)=>G.alive)}return Object.defineProperty(Y,J40,{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(Y,"dispose",{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(Y,"alive",{configurable:!0,enumerable:!1,get:J}),Y}function Sk(X){return!!(X&&(typeof X=="object"||typeof X=="function")&&("alive"in X)&&typeof X.alive=="boolean"&&("dispose"in X)&&typeof X.dispose=="function")}function eM6(X){if(!X)return 0;let Y=0;for(let[Q,J]of Object.entries(X)){if(!(Q in e00))throw new I14(Q);J&&(Y|=e00[Q])}return Y}function XP6(X){if(typeof X=="number")return X;if(X===void 0)return 0;let{type:Y,strict:Q,strip:J,compileOnly:G,backtraceBarrier:Z}=X,W=0;return Y==="global"&&(W|=i3.JS_EVAL_TYPE_GLOBAL),Y==="module"&&(W|=i3.JS_EVAL_TYPE_MODULE),Q&&(W|=i3.JS_EVAL_FLAG_STRICT),J&&(W|=i3.JS_EVAL_FLAG_STRIP),G&&(W|=i3.JS_EVAL_FLAG_COMPILE_ONLY),Z&&(W|=i3.JS_EVAL_FLAG_BACKTRACE_BARRIER),W}function YP6(X){if(typeof X=="number")return X;if(X===void 0)return 0;let{strings:Y,symbols:Q,quickjsPrivate:J,onlyEnumerable:G,numbers:Z,numbersAsStrings:W}=X,K=0;return Y&&(K|=a3.JS_GPN_STRING_MASK),Q&&(K|=a3.JS_GPN_SYMBOL_MASK),J&&(K|=a3.JS_GPN_PRIVATE_MASK),G&&(K|=a3.JS_GPN_ENUM_ONLY),Z&&(K|=a3.QTS_GPN_NUMBER_MASK),W&&(K|=a3.QTS_STANDARD_COMPLIANT_NUMBER),K}function QP6(...X){let Y=[];for(let Q of X)Q!==void 0&&(Y=Y.concat(Q));return Y}function q40(X,Y){Y.interruptHandler&&X.setInterruptHandler(Y.interruptHandler),Y.maxStackSizeBytes!==void 0&&X.setMaxStackSize(Y.maxStackSizeBytes),Y.memoryLimitBytes!==void 0&&X.setMemoryLimit(Y.memoryLimitBytes)}function V40(X,Y){Y.moduleLoader&&X.setModuleLoader(Y.moduleLoader),Y.shouldInterrupt&&X.setInterruptHandler(Y.shouldInterrupt),Y.memoryLimitBytes!==void 0&&X.setMemoryLimit(Y.memoryLimitBytes),Y.maxStackSizeBytes!==void 0&&X.setMaxStackSize(Y.maxStackSizeBytes)}var rM6,oM6=(X,Y)=>{for(var Q in Y)rM6(X,Q,{get:Y[Q],enumerable:!0})},W40=!1,L14,Y40,w14,Q40,M14,P14,T14,A14,E14,I14,j14,C14,Z40,o7,J40,O14,PX,YK,G40,W5,$40,v14,k14,r3,_14,y14=class{constructor(X){this.module=X}toPointerArray(X){let Y=new Int32Array(X.map((G)=>G.value)),Q=Y.length*Y.BYTES_PER_ELEMENT,J=this.module._malloc(Q);return new Uint8Array(this.module.HEAPU8.buffer,J,Q).set(new Uint8Array(Y.buffer)),new PX(J,void 0,(G)=>this.module._free(G))}newTypedArray(X,Y){let Q=new X(Array(Y).fill(0)),J=Q.length*Q.BYTES_PER_ELEMENT,G=this.module._malloc(J),Z=new X(this.module.HEAPU8.buffer,G,Y);return Z.set(Q),new PX({typedArray:Z,ptr:G},void 0,(W)=>this.module._free(W.ptr))}newMutablePointerArray(X){return this.newTypedArray(Int32Array,X)}newHeapCharPointer(X){let Y=this.module.lengthBytesUTF8(X),Q=Y+1,J=this.module._malloc(Q);return this.module.stringToUTF8(X,J,Q),new PX({ptr:J,strlen:Y},void 0,(G)=>this.module._free(G.ptr))}newHeapBufferPointer(X){let Y=X.byteLength,Q=this.module._malloc(Y);return this.module.HEAPU8.set(X,Q),new PX({pointer:Q,numBytes:Y},void 0,(J)=>this.module._free(J.pointer))}consumeHeapCharPointer(X){let Y=this.module.UTF8ToString(X);return this.module._free(X),Y}},eO1,H40,JP6,GP6,b14,f14,WP6=class{constructor(X){this.callFunction=X.callFunction,this.shouldInterrupt=X.shouldInterrupt,this.loadModuleSource=X.loadModuleSource,this.normalizeModule=X.normalizeModule}},F40=class{constructor(X){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new WP6({callFunction:(Y,Q,J,G,Z,W)=>this.handleAsyncify(Y,()=>{try{let K=this.contextCallbacks.get(Q);if(!K)throw Error(`QuickJSContext(ctx = ${Q}) not found for C function call "${W}"`);return K.callFunction(Q,J,G,Z,W)}catch(K){return console.error("[C to host error: returning null]",K),0}}),shouldInterrupt:(Y,Q)=>this.handleAsyncify(Y,()=>{try{let J=this.runtimeCallbacks.get(Q);if(!J)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C interrupt`);return J.shouldInterrupt(Q)}catch(J){return console.error("[C to host interrupt: returning error]",J),1}}),loadModuleSource:(Y,Q,J,G)=>this.handleAsyncify(Y,()=>{try{let Z=this.runtimeCallbacks.get(Q);if(!Z)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let W=Z.loadModuleSource;if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return W(Q,J,G)}catch(Z){return console.error("[C to host module loader error: returning null]",Z),0}}),normalizeModule:(Y,Q,J,G,Z)=>this.handleAsyncify(Y,()=>{try{let W=this.runtimeCallbacks.get(Q);if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let K=W.normalizeModule;if(!K)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return K(Q,J,G,Z)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}})}),this.module=X,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(X,Y){this.runtimeCallbacks.set(X,Y)}deleteRuntime(X){this.runtimeCallbacks.delete(X)}setContextCallbacks(X,Y){this.contextCallbacks.set(X,Y)}deleteContext(X){this.contextCallbacks.delete(X)}handleAsyncify(X,Y){if(X)return X.handleSleep((J)=>{try{let G=Y();if(!(G instanceof Promise)){Bz("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new P14(`Already suspended at: ${this.suspended.stack}
284
284
  Attempted to suspend at:`);this.suspended=new T14(`(${this.suspendedCount++})`),Bz("asyncify.handleSleep: suspending:",this.suspended),G.then((Z)=>{this.suspended=void 0,Bz("asyncify.handleSleep: resolved:",Z),J(Z)},(Z)=>{Bz("asyncify.handleSleep: rejected:",Z),console.error("QuickJS: cannot handle error in suspended function",Z),this.suspended=void 0})}catch(G){throw Bz("asyncify.handleSleep: error:",G),this.suspended=void 0,G}});let Q=Y();if(Q instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return Q}},z40=class{constructor(X,Y){this.module=X,this.ffi=Y,this.callbacks=new F40(X)}newRuntime(X={}){let Y=new PX(this.ffi.QTS_NewRuntime(),void 0,(J)=>{this.callbacks.deleteRuntime(J),this.ffi.QTS_FreeRuntime(J)}),Q=new f14({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:Y});return q40(Q,X),X.moduleLoader&&Q.setModuleLoader(X.moduleLoader),Q}newContext(X={}){let Y=this.newRuntime(),Q=Y.newContext({...X,ownedLifetimes:QP6(Y,X.ownedLifetimes)});return Y.context=Q,Q}evalCode(X,Y={}){return W5.withScope((Q)=>{let J=Q.manage(this.newContext());V40(J.runtime,Y);let G=J.evalCode(X,"eval.js");if(Y.memoryLimitBytes!==void 0&&J.runtime.setMemoryLimit(-1),G.error)throw J.dump(Q.manage(G.error));return J.dump(Q.manage(G.value))})}getWasmMemory(){let X=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!X)throw Error("Variant does not support getting WebAssembly.Memory");return X}getFFI(){return this.ffi}};var U40=d(()=>{Rk();Rk();rM6=Object.defineProperty;L14={};oM6(L14,{QuickJSAsyncifyError:()=>P14,QuickJSAsyncifySuspended:()=>T14,QuickJSEmptyGetOwnPropertyNames:()=>C14,QuickJSEmscriptenModuleError:()=>E14,QuickJSMemoryLeakDetected:()=>A14,QuickJSNotImplemented:()=>M14,QuickJSPromisePending:()=>j14,QuickJSUnknownIntrinsic:()=>I14,QuickJSUnwrapError:()=>Y40,QuickJSUseAfterFree:()=>Q40,QuickJSWrongOwner:()=>w14});Y40=class extends Error{constructor(X,Y){let Q=typeof X=="object"&&X&&"message"in X?String(X.message):String(X);super(Q);this.cause=X,this.context=Y,this.name="QuickJSUnwrapError"}},w14=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},Q40=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},M14=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},P14=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},T14=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},A14=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},E14=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},I14=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},j14=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},C14=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}};Z40=R14;Z40.of=sM6;o7=class{[Symbol.dispose](){return this.dispose()}},J40=Symbol.dispose??Symbol.for("Symbol.dispose"),O14=o7.prototype;O14[J40]||(O14[J40]=function(){return this.dispose()});PX=class X extends o7{constructor(Y,Q,J,G){super();this._value=Y,this.copier=Q,this.disposer=J,this._owner=G,this._alive=!0,this._constructorStack=W40?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 X(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(Y){this.assertAlive();let Q=Y(this);return this.dispose(),Q}map(Y){return this.assertAlive(),Y(this)}tap(Y){return Y(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new Q40(`Lifetime not alive
285
285
  ${this._constructorStack}