@decocms/mesh 2.8.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{AlertCircle-Dq394GOj.js → AlertCircle-DST9a9vh.js} +1 -1
- package/dist/client/assets/{ArrowLeft-Cy4AhM24.js → ArrowLeft-DPtymxR-.js} +1 -1
- package/dist/client/assets/Check-B3jZM0OP.js +1 -0
- package/dist/client/assets/{ChevronDown-CmpF3JPN.js → ChevronDown-Bi1kqv-9.js} +1 -1
- package/dist/client/assets/{Clock-CsUnrq_y.js → Clock-BynE89Zl.js} +1 -1
- package/dist/client/assets/Code01-BMUDEJ4t.js +1 -0
- package/dist/client/assets/{Copy01-CeZXAIR1.js → Copy01-DUDgHeaT.js} +1 -1
- package/dist/client/assets/{DotsHorizontal-BJYMZ_bT.js → DotsHorizontal-DO21zZi8.js} +1 -1
- package/dist/client/assets/{DotsVertical--VBBwSd_.js → DotsVertical-DikAa5AR.js} +1 -1
- package/dist/client/assets/{File06-B3H2JkAs.js → File06-7Osp6kua.js} +1 -1
- package/dist/client/assets/{FilterLines-CgywcFf-.js → FilterLines-DieVG1pT.js} +1 -1
- package/dist/client/assets/{FlipBackward-YL5zje2G.js → FlipBackward-U1Nw6QGY.js} +1 -1
- package/dist/client/assets/{GitBranch01-B_llM8fW.js → GitBranch01-CTCXO68x.js} +1 -1
- package/dist/client/assets/{Grid01-Cxk17PdB.js → Grid01-DI-Q2VEp.js} +1 -1
- package/dist/client/assets/{Inbox01-D4NF7IbV.js → Inbox01-Cme2B_Za.js} +1 -1
- package/dist/client/assets/{InfoCircle-DhjyjETW.js → InfoCircle-Bz1TUoGx.js} +1 -1
- package/dist/client/assets/{Key01-BkL_aoS3.js → Key01-COwuV6OE.js} +1 -1
- package/dist/client/assets/{LinkExternal01-Ba2KQ_mb.js → LinkExternal01-BaHJAM0O.js} +1 -1
- package/dist/client/assets/{Loading01-DiWXzgA5.js → Loading01-C5e9Xing.js} +1 -1
- package/dist/client/assets/{Lock01-DgI3hntm.js → Lock01-BLY_4cHD.js} +1 -1
- package/dist/client/assets/Play-BSr93GMI.js +1 -0
- package/dist/client/assets/{Plus-BWImneTG.js → Plus-pmQCIiux.js} +1 -1
- package/dist/client/assets/SearchMd-C8MbVAuA.js +1 -0
- package/dist/client/assets/{Terminal-CQt5F5YW.js → Terminal-BSyq_KGG.js} +1 -1
- package/dist/client/assets/{Trash01-BvRWVRVk.js → Trash01-DqQrX192.js} +1 -1
- package/dist/client/assets/{X-DFkdjEJ_.js → X-CJAJyKbZ.js} +1 -1
- package/dist/client/assets/{XClose-BGvlobN4.js → XClose-CF1lddkv.js} +1 -1
- package/dist/client/assets/{alert-dialog-Bo0wCHTm.js → alert-dialog-BnwjYq4n.js} +2 -2
- package/dist/client/assets/auth-DhJcJDq8.js +1 -0
- package/dist/client/assets/{auth-catchall-Dw01-6hX.js → auth-catchall-C2IFDAAQ.js} +1 -1
- package/dist/client/assets/{avatar-BwmT_HCo.js → avatar-Cd72kdsa.js} +1 -1
- package/dist/client/assets/{badge-DShTaqk1.js → badge-iCoQ1dgD.js} +1 -1
- package/dist/client/assets/{card-XACXpswn.js → card-CjWJyjfT.js} +1 -1
- package/dist/client/assets/checkbox-5O25feEA.js +1 -0
- package/dist/client/assets/{collection-detail-CKqS5X46.js → collection-detail-BCydbsMr.js} +39 -39
- package/dist/client/assets/collection-display-button-D1R0tnBY.js +1 -0
- package/dist/client/assets/{collection-header-CQEHu0Vm.js → collection-header-0lxlEg2I.js} +1 -1
- package/dist/client/assets/{collection-page-DfGICiNY.js → collection-page-s3MvuRc-.js} +1 -1
- package/dist/client/assets/collection-search-Btyw61UY.js +1 -0
- package/dist/client/assets/{collection-tab-8GGRvmhO.js → collection-tab-DWktiPIU.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-BRXa6W9R.js → collection-table-wrapper-gfEw2g5n.js} +1 -1
- package/dist/client/assets/{connection-card-VJb0odHn.js → connection-card-DfdBq4FD.js} +1 -1
- package/dist/client/assets/connection-detail--2aMjf2x.js +1 -0
- package/dist/client/assets/connections-B3fFvefT.js +1 -0
- package/dist/client/assets/constants-CjRmBn5H.js +1 -0
- package/dist/client/assets/{create-organization-dialog-mrlE4rym.js → create-organization-dialog-DWi5c4Eh.js} +1 -1
- package/dist/client/assets/dialog-D76JDRim.js +1 -0
- package/dist/client/assets/{dropdown-menu-4ZllijNh.js → dropdown-menu-BjkFG8SE.js} +1 -1
- package/dist/client/assets/{empty-state-C3ZsBFjJ.js → empty-state-V7JRwEdF.js} +1 -1
- package/dist/client/assets/env-vars-editor-BJ7tjYIq.js +1 -0
- package/dist/client/assets/{error-boundary-Dku9jcSQ.js → error-boundary-D0j0sONw.js} +1 -1
- package/dist/client/assets/{extract-connection-data-BG3d1jBl.js → extract-connection-data-BrdC23jw.js} +1 -1
- package/dist/client/assets/form-B8Xq72cU.js +1 -0
- package/dist/client/assets/gateway-detail-5Qd5lfiW.js +1 -0
- package/dist/client/assets/gateways-CEtb1fnf.js +1 -0
- package/dist/client/assets/home-nnEPBFaz.js +1 -0
- package/dist/client/assets/index-B01CV87W.js +88 -0
- package/dist/client/assets/index-Cqq-bHxo.js +163 -0
- package/dist/client/assets/index-DdOgSb-W.js +1 -0
- package/dist/client/assets/index-Dv5zkaTK.js +25 -0
- package/dist/client/assets/index-KJvlasGf.css +1 -0
- package/dist/client/assets/{index-Bp_cCr-y.js → index-xkjtAq50.js} +1 -1
- package/dist/client/assets/{input-rmH5DIfC.js → input-DJ7wqUvo.js} +1 -1
- package/dist/client/assets/{layout-CZ09RD83.js → layout-CfefGJu5.js} +1 -1
- package/dist/client/assets/{lazy-highlighter-B6E7Xc6t.js → lazy-highlighter-CaSijfHb.js} +1 -1
- package/dist/client/assets/localstorage-keys-TnX0RxDe.js +1 -0
- package/dist/client/assets/{login-DE_zGqKN.js → login-CGyq3Vs1.js} +1 -1
- package/dist/client/assets/{mcp-oauth-DgTE8-Le.js → mcp-oauth-CJD4q5rM.js} +1 -1
- package/dist/client/assets/mcp-server-detail-CbOhDFHk.js +1 -0
- package/dist/client/assets/members-DLByeMDT.js +3 -0
- package/dist/client/assets/{monaco-editor-CgmyVbSt.js → monaco-editor-CoD_oW78.js} +4 -4
- package/dist/client/assets/{monitoring-DABfw2L2.js → monitoring-5cDa-J-b.js} +7 -7
- package/dist/client/assets/{oauth-callback-CLVMkaxX.js → oauth-callback-Cgb1o01u.js} +1 -1
- package/dist/client/assets/page-COBajbLE.js +1 -0
- package/dist/client/assets/{page-BB7B3mZl.js → page-Dlp1hzYF.js} +2 -2
- package/dist/client/assets/{pin-to-sidebar-button-DpBpp5xE.js → pin-to-sidebar-button-Cp43fkli.js} +1 -1
- package/dist/client/assets/{popover-CdZf1a6e.js → popover-mdWNDupQ.js} +1 -1
- package/dist/client/assets/project-context-provider-Gi9sytDH.js +1 -0
- package/dist/client/assets/{resizable-B5HlicxS.js → resizable-BdJcZRXn.js} +1 -1
- package/dist/client/assets/{resource-tabs-D4f0A0M5.js → resource-tabs-DlB9LUax.js} +1 -1
- package/dist/client/assets/select-B5Ou5lZC.js +1 -0
- package/dist/client/assets/settings-CjdyGe2Y.js +1 -0
- package/dist/client/assets/shell-layout-DftkJMI3.js +3 -0
- package/dist/client/assets/{spinner-DHB4L2Fs.js → spinner-CchSlqhZ.js} +1 -1
- package/dist/client/assets/switch-17EJ9BZl.js +1 -0
- package/dist/client/assets/{textarea-CC9tejXR.js → textarea-BngAuS5G.js} +1 -1
- package/dist/client/assets/{thread-history-popover-CiRrI2DA.js → thread-history-popover-BNoPu7hE.js} +31 -7
- package/dist/client/assets/tool-set-selector-ia7ItE5G.js +1 -0
- package/dist/client/assets/{tools-list-gZ7R3Pii.js → tools-list-HOpPAfsi.js} +1 -1
- package/dist/client/assets/{use-binding-DK1a3_Qy.js → use-binding-iszUdbOZ.js} +7 -7
- package/dist/client/assets/use-connection-Dp5C8sLQ.js +2 -0
- package/dist/client/assets/use-connection-resources-DU3H93Az.js +1 -0
- package/dist/client/assets/{use-gateway-DV-fzrfg.js → use-gateway-CSxRa3Bg.js} +1 -1
- package/dist/client/assets/{use-gateway-system-prompt-Bp36i1V_.js → use-gateway-system-prompt-BqldEOSK.js} +1 -1
- package/dist/client/assets/{use-list-state-DndBNJy3.js → use-list-state-FSUrDOEN.js} +1 -1
- package/dist/client/assets/{use-mcp-BF6NYpCZ.js → use-mcp-D5TIO_2s.js} +1 -1
- package/dist/client/assets/{use-members-DLvSDcRE.js → use-members-DlA8UjAf.js} +1 -1
- package/dist/client/assets/{use-mobile-m2kl2-uH.js → use-mobile-D6_iVdHq.js} +1 -1
- package/dist/client/assets/{use-organization-settings-Bmp2ntDK.js → use-organization-settings-DVpbHPw1.js} +1 -1
- package/dist/client/assets/{use-tool-call-DZ0ZbMPs.js → use-tool-call-DsLdhDUf.js} +1 -1
- package/dist/client/assets/useQuery-UvQ_L9Pc.js +1 -0
- package/dist/client/assets/{value-BpB2LzX8.js → value-Bc9uIuB3.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-xLI4kETG.js → view-mode-toggle-ljeOi0U5.js} +1 -1
- package/dist/client/assets/workflow-DOWIsfb9.js +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/cli.js +131 -131
- package/dist/server/migrate.js +99 -99
- package/dist/server/server.js +16 -16
- package/package.json +1 -1
- package/dist/client/assets/Play-CL14Rg1E.js +0 -1
- package/dist/client/assets/auth-Bn2kG2C_.js +0 -1
- package/dist/client/assets/checkbox-Zx2Kj0MJ.js +0 -1
- package/dist/client/assets/collection-display-button-DV6veU5b.js +0 -1
- package/dist/client/assets/collection-search-DIntm-5W.js +0 -1
- package/dist/client/assets/connection-detail-D2jlGrQl.js +0 -1
- package/dist/client/assets/connections-DhCYl5sj.js +0 -1
- package/dist/client/assets/constants-CDSKdq1h.js +0 -1
- package/dist/client/assets/dialog-BGoXDX0_.js +0 -1
- package/dist/client/assets/env-vars-editor-DgV8E-ii.js +0 -1
- package/dist/client/assets/form-CEFZ3Pjo.js +0 -1
- package/dist/client/assets/gateway-detail-D1EDkZCK.js +0 -1
- package/dist/client/assets/gateways-DMTv1ova.js +0 -1
- package/dist/client/assets/home-OQcy0joO.js +0 -1
- package/dist/client/assets/index-BV_tzcZC.css +0 -1
- package/dist/client/assets/index-Cw2tgmiQ.js +0 -88
- package/dist/client/assets/index-DXyyF4Kh.js +0 -163
- package/dist/client/assets/index-hiFGh_VX.js +0 -25
- package/dist/client/assets/localstorage-keys-CfUvCV28.js +0 -1
- package/dist/client/assets/mcp-server-detail-BXjm6S5M.js +0 -1
- package/dist/client/assets/members-DiKpQyqm.js +0 -3
- package/dist/client/assets/page-yVx5IrV0.js +0 -1
- package/dist/client/assets/project-context-provider-CiKTLK5w.js +0 -1
- package/dist/client/assets/select-DkyEajFr.js +0 -1
- package/dist/client/assets/settings-C9bDN2OV.js +0 -1
- package/dist/client/assets/shell-layout-Db7MZzNn.js +0 -1
- package/dist/client/assets/switch-C52IsWgN.js +0 -1
- package/dist/client/assets/use-connection-BjQ7rQpy.js +0 -2
- package/dist/client/assets/use-connection-resources-BwfqTIS2.js +0 -1
- package/dist/client/assets/useQueries-DPsMIoOD.js +0 -1
- package/dist/client/assets/useQuery-oHrwmpwH.js +0 -1
- package/dist/client/assets/workflow-BYSB48K6.js +0 -1
package/dist/server/server.js
CHANGED
|
@@ -252,13 +252,13 @@ data:
|
|
|
252
252
|
|
|
253
253
|
`,Q.enqueue(X.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(Q,X){try{let Y=Q.headers.get("accept");if(!Y?.includes("application/json")||!Y.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=Q.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(Q.headers.entries())},W;if(X?.parsedBody!==void 0)W=X.parsedBody;else try{W=await Q.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let Z;try{if(Array.isArray(W))Z=W.map((L)=>bY.parse(L));else Z=[bY.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(Y00);if($){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(Z.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(!$){let L=this.validateSession(Q);if(L)return L;let M=this.validateProtocolVersion(Q);if(M)return M}if(!Z.some(sG)){for(let L of Z)this.onmessage?.(L,{authInfo:X?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=Z.find((L)=>Y00(L)),V=F?F.params.protocolVersion:Q.headers.get("mcp-protocol-version")??it0;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let M of Z)if(sG(M))this._requestToStreamMapping.set(M.id,H);for(let M of Z)this.onmessage?.(M,{authInfo:X?.authInfo,requestInfo:G})});let q=new TextEncoder,z,B=new ReadableStream({start:(L)=>{z=L},cancel:()=>{this._streamMapping.delete(H)}}),D={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)D["mcp-session-id"]=this.sessionId;for(let L of Z)if(sG(L))this._streamMapping.set(H,{controller:z,encoder:q,cleanup:()=>{this._streamMapping.delete(H);try{z.close()}catch{}}}),this._requestToStreamMapping.set(L.id,H);await this.writePrimingEvent(z,q,H,V);for(let L of Z){let M,C;if(sG(L)&&this._eventStore&&V>="2025-11-25")M=()=>{this.closeSSEStream(L.id)},C=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:X?.authInfo,requestInfo:G,closeSSEStream:M,closeStandaloneSSEStream:C})}return new Response(B,{status:200,headers:D})}catch(Y){return this.onerror?.(Y),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Y)})}}async handleDeleteRequest(Q){let X=this.validateSession(Q);if(X)return X;let Y=this.validateProtocolVersion(Q);if(Y)return Y;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Q){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let X=Q.headers.get("mcp-session-id");if(!X)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(X!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Q){let X=Q.headers.get("mcp-protocol-version");if(X!==null&&!m3.includes(X))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${X} (supported versions: ${m3.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Q})=>{Q()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Q){let X=this._requestToStreamMapping.get(Q);if(!X)return;let Y=this._streamMapping.get(X);if(Y)Y.cleanup()}closeStandaloneSSEStream(){let Q=this._streamMapping.get(this._standaloneSseStreamId);if(Q)Q.cleanup()}async send(Q,X){let Y=X?.relatedRequestId;if(P5(Q)||ez(Q))Y=Q.id;if(Y===void 0){if(P5(Q)||ez(Q))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let W;if(this._eventStore)W=await this._eventStore.storeEvent(this._standaloneSseStreamId,Q);let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z===void 0)return;if(Z.controller&&Z.encoder)this.writeSSEEvent(Z.controller,Z.encoder,Q,W);return}let J=this._requestToStreamMapping.get(Y);if(!J)throw Error(`No connection established for request ID: ${String(Y)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let W;if(this._eventStore)W=await this._eventStore.storeEvent(J,Q);this.writeSSEEvent(G.controller,G.encoder,Q,W)}if(P5(Q)||ez(Q)){this._requestResponseMap.set(Y,Q);let W=Array.from(this._requestToStreamMapping.entries()).filter(([$,K])=>K===J).map(([$])=>$);if(W.every(($)=>this._requestResponseMap.has($))){if(!G)throw Error(`No connection established for request ID: ${String(Y)}`);if(this._enableJsonResponse&&G.resolveJson){let $={"Content-Type":"application/json"};if(this.sessionId!==void 0)$["mcp-session-id"]=this.sessionId;let K=W.map((H)=>this._requestResponseMap.get(H));if(K.length===1)G.resolveJson(new Response(JSON.stringify(K[0]),{status:200,headers:$}));else G.resolveJson(new Response(JSON.stringify(K),{status:200,headers:$}))}else G.cleanup();for(let $ of W)this._requestResponseMap.delete($),this._requestToStreamMapping.delete($)}}}}var Ny=o(()=>{h9()});var rM=(...Q)=>{return function(Y,J){let G=(W)=>{let Z=Q[W];if(!Z)return J();return Z(Y,()=>G(W+1))};return G(0)}};class cQ1{config;tools=[];callToolMiddlewares=[];constructor(Q){this.config={...Q,capabilities:Q.capabilities??{tools:{}}}}withTool(Q){return this.tools.push(Q),this}withTools(Q){return this.tools.push(...Q),this}callToolMiddleware(...Q){return this.callToolMiddlewares.push(...Q),this}build(){let Q=this.callToolMiddlewares.length>0?rM(...this.callToolMiddlewares):null,X=()=>{let Y=new s3({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(K)=>{try{let H=await J.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},W=Q?async(K)=>{let H={method:"tools/call",params:{name:J.name,arguments:K}};return await Q(H,()=>G(K))}:G,Z="shape"in J.inputSchema?J.inputSchema.shape:N.object({}).shape,$=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:N.object({}).shape;Y.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:Z,outputSchema:$},W)}return Y};return{callStreamableTool:async(Y,J)=>{let G=this.tools.find((Z)=>Z.name===Y);if(!G)throw Error(`Tool ${Y} not found`);let W=await G.handler(J);if(!(W instanceof Response))throw Error(`Tool ${Y} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((Y)=>({name:Y.name,description:Y.description??"",inputSchema:N.toJSONSchema(Y.inputSchema),outputSchema:Y.outputSchema?N.toJSONSchema(Y.outputSchema):void 0}))}},callTool:async(Y)=>{let J=this.tools.find((G)=>G.name===Y.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Y.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Y)=>{let J=new t3({enableJsonResponse:Y.headers.get("Accept")?.includes("application/json")??!1});return await X().connect(J),await J.handleRequest(Y)}}}}function nQ1(Q){return new cQ1(Q)}var iQ1=o(()=>{Dy();Ny();G1()});function B1(Q){return{...Q,execute:async(X,Y)=>{let J=Date.now();return await Y.timings.measure(`tool.${Q.name}`,async()=>Y.tracer.startActiveSpan(`tool.${Q.name}`,{attributes:{"tool.name":Q.name,"organization.id":Y.organization?.id??"system","user.id":Y.auth.user?.id??Y.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Y.toolName=Q.name,Y.access.setToolName?.(Q.name);let W=await Q.handler(X,Y),Z=Date.now()-J;return Y.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(Z,{"tool.name":Q.name,"organization.id":Y.organization?.id??"system",status:"success"}),Y.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":Q.name,status:"success"}),G.setStatus({code:r60.SpanStatusCode.OK}),W}catch(W){throw Y.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":Q.name,"error.type":W.constructor.name}),G.setStatus({code:r60.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}}))}}}var r60;var E6=o(()=>{r60=m6(Z1(),1)});function L6(Q){if(!Q.organization)throw Error("This operation requires organization scope");return Q.organization}function lQ(Q){return Q.auth.user?.id??Q.auth.apiKey?.userId}function bC6(Q){return!!(Q.auth.user||Q.auth.apiKey)}function C1(Q){if(!bC6(Q))throw Error("Authentication required")}var Oy,aQ1,rQ1,oQ1,sQ1,tQ1,eQ1,Q91,X91,Y91;var RU=o(()=>{G1();Oy=N.record(N.string(),N.array(N.string())),aQ1=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),userId:N.string().describe("ID of the user who owns this API key"),permissions:Oy.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:N.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:N.string().datetime().describe("When the API key was created (ISO 8601)")}),rQ1=N.object({name:N.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Oy.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:N.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:N.record(N.string(),N.unknown()).optional().describe("Additional metadata to store with the API key")}),oQ1=N.object({id:N.string().describe("Unique identifier for the API key"),name:N.string().describe("Human-readable name for the API key"),key:N.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:Oy.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:N.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:N.string().datetime().describe("When the API key was created (ISO 8601)")}),sQ1=N.object({}),tQ1=N.object({items:N.array(aQ1).describe("List of API keys (without key values)")}),eQ1=N.object({keyId:N.string().describe("ID of the API key to update"),name:N.string().min(1).max(64).optional().describe("New name for the API key"),permissions:Oy.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:N.record(N.string(),N.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),Q91=N.object({item:aQ1.describe("The updated API key (without key value)")}),X91=N.object({keyId:N.string().describe("ID of the API key to delete")}),Y91=N.object({success:N.boolean().describe("Whether the deletion was successful"),keyId:N.string().describe("ID of the deleted API key")})});var o60;var J91=o(()=>{E6();RU();o60=B1({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:rQ1,outputSchema:oQ1,handler:async(Q,X)=>{C1(X),await X.access.check();let Y=await X.boundAuth.apiKey.create({name:Q.name,permissions:Q.permissions,expiresIn:Q.expiresIn,metadata:{...Q.metadata,organization:X.organization}}),J=Y.expiresAt?Y.expiresAt instanceof Date?Y.expiresAt.toISOString():Y.expiresAt:null,G=Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt;return{id:Y.id,name:Y.name??Q.name,key:Y.key,permissions:Y.permissions??{},expiresAt:J,createdAt:G}}})});var s60;var G91=o(()=>{E6();RU();s60=B1({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:X91,outputSchema:Y91,handler:async(Q,X)=>{if(C1(X),await X.access.check(),!lQ(X))throw Error("User ID required to delete API key");let G=(await X.boundAuth.apiKey.list())?.find((K)=>K.id===Q.keyId);if(!G)throw Error("API key not found");let Z=G.metadata?.organization?.id,$=X.organization?.id;if(Z!==$)throw Error("Cannot delete API key from another organization");return await X.boundAuth.apiKey.delete(Q.keyId),{success:!0,keyId:Q.keyId}}})});var t60;var W91=o(()=>{E6();RU();t60=B1({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:sQ1,outputSchema:tQ1,handler:async(Q,X)=>{C1(X),await X.access.check();let Y=await X.boundAuth.apiKey.list(),J=X.organization?.id;return{items:(Y??[]).filter((W)=>{return W.metadata?.organization?.id===J}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt?W.expiresAt instanceof Date?W.expiresAt.toISOString():W.expiresAt:null,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var e60;var Z91=o(()=>{E6();RU();e60=B1({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:eQ1,outputSchema:Q91,handler:async(Q,X)=>{if(C1(X),await X.access.check(),!lQ(X))throw Error("User ID required to update API key");let G=(await X.boundAuth.apiKey.list())?.find((H)=>H.id===Q.keyId);if(!G)throw Error(`API key not found: ${Q.keyId}`);let Z=G.metadata?.organization?.id,$=X.organization?.id;if(Z!==$)throw Error("Cannot update API key from another organization");let K=await X.boundAuth.apiKey.update({keyId:Q.keyId,name:Q.name,permissions:Q.permissions,metadata:{...Q.metadata,organization:X.organization}});if(!K)throw Error(`Failed to update API key: ${Q.keyId}`);return{item:{id:K.id,name:K.name??Q.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var $91=o(()=>{J91();G91();W91();Z91();RU()});var hC6,xC6,Q40;var K91=o(()=>{y3();G1();E6();By();O7();hC6=N.object({data:Pt0.describe("Data for the new connection (id is auto-generated if not provided)")}),xC6=N.object({item:vJ.describe("The created connection entity")}),Q40=B1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:hC6,outputSchema:xC6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=lQ(X);if(!J)throw Error("User ID required to create connection");let G={...Q.data,organization_id:Y.id,created_by:J},W=await IU({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),Z=W?.length?W:null,$=await X.storage.connections.create({...G,tools:Z});return await X.eventBus.publish(Y.id,lz.SELF(Y.id),{type:"connection.created",data:$}),{item:$}}})});function oM(Q,X){if(Q===X)return!0;if(Q==null||X==null)return Q===X;if(typeof Q!==typeof X)return!1;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;return Q.every((Y,J)=>oM(Y,X[J]))}if(typeof Q==="object"&&typeof X==="object"){let Y=Object.keys(Q),J=Object.keys(X);if(Y.length!==J.length)return!1;return Y.every((G)=>J.includes(G)&&oM(Q[G],X[G]))}return!1}function $I6(){return(Q)=>{if(!Array.isArray(Q))return!0;let X=[];return Q.every((Y)=>{if(X.some((G)=>oM(Y,G)))return!1;return X.push(Y),!0})}}function Ly(Q,X){return Q.safeParse(X).success}function D9(Q){if(typeof Q==="boolean")return Q?N.any():N.never();let X={};for(let G of MI6)G.apply(X,Q);let Y=[];if(X.string!==!1)Y.push(X.string||N.string());if(X.number!==!1)Y.push(X.number||N.number());if(X.boolean!==!1)Y.push(X.boolean||N.boolean());if(X.null!==!1)Y.push(X.null||N.null());if(X.array!==!1)Y.push(X.array||N.array(N.any()));if(X.tuple!==!1&&X.tuple!==void 0)Y.push(X.tuple);if(X.object!==!1)if(X.object)Y.push(X.object);else{let G=N.custom((W)=>{return typeof W==="object"&&W!==null&&!Array.isArray(W)},"Must be an object, not an array");Y.push(G)}if(X.file!==!1&&X.file!==void 0)Y.push(X.file);let J;if(Y.length===0)J=N.never();else if(Y.length===1)J=Y[0];else if(!Object.keys(Q).some((W)=>W!=="$schema"&&W!=="title"&&W!=="description"))J=N.any();else J=N.union(Y);for(let G of PI6)J=G.apply(J,Q);return J}var gC6=class{apply(Q,X){if(!X.type)return;let Y=Array.isArray(X.type)?X.type:[X.type],J=new Set(Y);if(!J.has("string"))Q.string=!1;if(!J.has("number")&&!J.has("integer"))Q.number=!1;if(!J.has("boolean"))Q.boolean=!1;if(!J.has("null"))Q.null=!1;if(!J.has("array"))Q.array=!1;if(!J.has("object"))Q.object=!1;if(J.has("integer")&&Q.number!==!1){let G=Q.number||N.number();if(G instanceof N.ZodNumber)Q.number=G.int()}}},uC6=class{apply(Q,X){if(X.const===void 0)return;let Y=X.const;if(Q.string=!1,Q.number=!1,Q.boolean=!1,Q.null=!1,Q.array=!1,Q.object=!1,typeof Y==="string")Q.string=N.literal(Y);else if(typeof Y==="number")Q.number=N.literal(Y);else if(typeof Y==="boolean")Q.boolean=N.literal(Y);else if(Y===null)Q.null=N.null();else if(Array.isArray(Y))Q.array=void 0;else if(typeof Y==="object")Q.object=void 0}},mC6=class{apply(Q,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Q.string=!1,Q.number=!1,Q.boolean=!1,Q.null=!1,Q.array=!1,Q.object=!1;return}let Y={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Q.string=this.createTypeSchema(Y.string,"string"),Q.number=this.createTypeSchema(Y.number,"number"),Q.boolean=this.createTypeSchema(Y.boolean,"boolean"),Q.null=Y.null.length>0?N.null():!1,Q.array=Y.array.length>0?void 0:!1,Q.object=Y.object.length>0?void 0:!1}createTypeSchema(Q,X){if(Q.length===0)return!1;if(Q.length===1)return N.literal(Q[0]);if(X==="string")return N.enum(Q);if(X==="number"){let[Y,J,...G]=Q;return N.union([N.literal(Y),N.literal(J),...G.map((W)=>N.literal(W))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},lC6=class{apply(Q,X){let Y=X;if(Y.type==="string"&&Y.format==="binary"&&Y.contentEncoding==="binary"){let J=N.file();if(Y.minLength!==void 0)J=J.min(Y.minLength);if(Y.maxLength!==void 0)J=J.max(Y.maxLength);if(Y.contentMediaType!==void 0)J=J.mime(Y.contentMediaType);Q.file=J,Q.string=!1}}},dC6=class{apply(Q,X){let Y=X;if(X.type===void 0&&(Y.minLength!==void 0||Y.maxLength!==void 0||Y.pattern!==void 0)){if(Q.string===void 0)Q.string=N.string()}}},pC6=class{apply(Q,X){let Y=X;if(Y.minLength===void 0)return;if(Q.string!==!1){let J=Q.string||N.string();if(J instanceof N.ZodString)Q.string=J.refine((G)=>{return Array.from(G).length>=Y.minLength},{message:`String must be at least ${Y.minLength} characters long`})}}},cC6=class{apply(Q,X){let Y=X;if(Y.maxLength===void 0)return;if(Q.string!==!1){let J=Q.string||N.string();if(J instanceof N.ZodString)Q.string=J.refine((G)=>{return Array.from(G).length<=Y.maxLength},{message:`String must be at most ${Y.maxLength} characters long`})}}},nC6=class{apply(Q,X){let Y=X;if(!Y.pattern)return;if(Q.string!==!1){let J=Q.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Y.pattern);Q.string=J.regex(G)}}}},iC6=class{apply(Q,X){let Y=X;if(Y.minimum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)Q.number=J.min(Y.minimum)}}},aC6=class{apply(Q,X){let Y=X;if(Y.maximum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)Q.number=J.max(Y.maximum)}}},rC6=class{apply(Q,X){let Y=X;if(Y.exclusiveMinimum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)if(typeof Y.exclusiveMinimum==="number")Q.number=J.gt(Y.exclusiveMinimum);else Q.number=!1}}},oC6=class{apply(Q,X){let Y=X;if(Y.exclusiveMaximum===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)if(typeof Y.exclusiveMaximum==="number")Q.number=J.lt(Y.exclusiveMaximum);else Q.number=!1}}},sC6=class{apply(Q,X){let Y=X;if(Y.multipleOf===void 0)return;if(Q.number!==!1){let J=Q.number||N.number();if(J instanceof N.ZodNumber)Q.number=J.refine((G)=>{if(Y.multipleOf===0)return!1;let W=G/Y.multipleOf,Z=Math.round(W),$=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Y.multipleOf)*Number.EPSILON*10);return Math.abs(W-Z)<=$/Math.abs(Y.multipleOf)},{message:`Must be a multiple of ${Y.multipleOf}`})}}},tC6=class{apply(Q,X){let Y=X;if(X.type===void 0&&(Y.minItems!==void 0||Y.maxItems!==void 0||Y.items!==void 0||Y.prefixItems!==void 0)){if(Q.array===void 0)Q.array=N.array(N.any())}}},eC6=class{apply(Q,X){let Y=X;if(Y.minItems===void 0)return;if(Q.array!==!1)Q.array=(Q.array||N.array(N.any())).min(Y.minItems)}},QI6=class{apply(Q,X){let Y=X;if(Y.maxItems===void 0)return;if(Q.array!==!1)Q.array=(Q.array||N.array(N.any())).max(Y.maxItems)}},XI6=class{apply(Q,X){let Y=X;if(Q.array===!1)return;if(Array.isArray(Y.items))Q.array=Q.array||N.array(N.any());else if(Y.items&&typeof Y.items!=="boolean"&&!Y.prefixItems){let J=D9(Y.items),G=N.array(J);if(Q.array&&Q.array instanceof N.ZodArray){let W=Q.array._def;if(W.checks)W.checks.forEach((Z)=>{if(Z._zod&&Z._zod.def){let $=Z._zod.def;if($.check==="min_length"&&$.minimum!==void 0)G=G.min($.minimum);else if($.check==="max_length"&&$.maximum!==void 0)G=G.max($.maximum)}})}Q.array=G}else if(typeof Y.items==="boolean"&&Y.items===!1)if(!Y.prefixItems)Q.array=N.array(N.any()).max(0);else Q.array=Q.array||N.array(N.any());else if(typeof Y.items==="boolean"&&Y.items===!0)Q.array=Q.array||N.array(N.any());else if(Y.prefixItems)Q.array=Q.array||N.array(N.any())}},YI6=class{apply(Q,X){if(X.type!=="array")return;let Y=X;if(!Array.isArray(Y.items))return;if(Q.array===!1)return;let J=Y.items.map((W)=>D9(W)),G;if(J.length===0)G=N.tuple([]);else G=N.tuple(J);if(Y.minItems!==void 0&&Y.minItems>J.length)G=!1;if(Y.maxItems!==void 0&&Y.maxItems<J.length)G=!1;Q.tuple=G,Q.array=!1}},JI6=class{apply(Q,X){let Y=X;if(Q.object===!1)return;if(Y.properties||Y.required||Y.additionalProperties!==void 0)Q.object=Q.object||N.object({}).passthrough()}},GI6=class{apply(Q,X){let Y=X;if(X.type===void 0&&(Y.maxProperties!==void 0||Y.minProperties!==void 0)){if(Q.object===void 0)Q.object=N.object({}).passthrough()}}},WI6=class{apply(Q,X){let Y=X;if(Y.maxProperties===void 0)return;if(Q.object!==!1){let J=Q.object||N.object({}).passthrough();Q.object=J.refine((G)=>Object.keys(G).length<=Y.maxProperties,{message:`Object must have at most ${Y.maxProperties} properties`})}}},ZI6=class{apply(Q,X){let Y=X;if(Y.minProperties===void 0)return;if(Q.object!==!1){let J=Q.object||N.object({}).passthrough();Q.object=J.refine((G)=>Object.keys(G).length>=Y.minProperties,{message:`Object must have at least ${Y.minProperties} properties`})}}},KI6=class{apply(Q,X){if(!X.not)return Q;let Y=D9(X.not);return Q.refine((J)=>!Ly(Y,J),{message:"Value must not match the 'not' schema"})}},HI6=class{apply(Q,X){if(X.uniqueItems!==!0)return Q;return Q.refine($I6(),{message:"Array items must be unique"})}},FI6=class{apply(Q,X){if(!X.allOf||X.allOf.length===0)return Q;return X.allOf.map((J)=>D9(J)).reduce((J,G)=>N.intersection(J,G),Q)}},VI6=class{apply(Q,X){if(!X.anyOf||X.anyOf.length===0)return Q;let Y=X.anyOf.length===1?D9(X.anyOf[0]):N.union([D9(X.anyOf[0]),D9(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>D9(J))]);return N.intersection(Q,Y)}},qI6=class{apply(Q,X){if(!X.oneOf||X.oneOf.length===0)return Q;let Y=X.oneOf.map((J)=>D9(J));return Q.refine((J)=>{let G=0;for(let W of Y)if(W.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},zI6=class{apply(Q,X){let Y=X;if(Y.prefixItems&&Array.isArray(Y.prefixItems)){let G=Y.prefixItems.map((W)=>D9(W));return Q.refine((W)=>{if(!Array.isArray(W))return!0;for(let Z=0;Z<Math.min(W.length,G.length);Z++)if(!Ly(G[Z],W[Z]))return!1;if(W.length>G.length){if(typeof Y.items==="boolean"&&Y.items===!1)return!1;else if(Y.items&&typeof Y.items==="object"&&!Array.isArray(Y.items)){let Z=D9(Y.items);for(let $=G.length;$<W.length;$++)if(!Ly(Z,W[$]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Q}},UI6=class{apply(Q,X){let Y=X;if(!Y.properties&&!Y.required&&Y.additionalProperties!==!1)return Q;if(Q instanceof N.ZodObject||Q instanceof N.ZodRecord){let J={};if(Y.properties){for(let[G,W]of Object.entries(Y.properties))if(W!==void 0)J[G]=D9(W)}if(Y.required&&Array.isArray(Y.required)){let G=new Set(Y.required);for(let W of Object.keys(J))if(!G.has(W))J[W]=J[W].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Y.additionalProperties===!1)return N.object(J);else return N.object(J).passthrough()}return Q.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Y.properties){for(let[G,W]of Object.entries(Y.properties))if(W!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!D9(W).safeParse(J[G]).success)return!1}}}if(Y.required&&Array.isArray(Y.required)){for(let G of Y.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Y.additionalProperties===!1&&Y.properties){let G=new Set(Object.keys(Y.properties));for(let W in J)if(!G.has(W))return!1}return!0},{message:"Object constraints validation failed"})}},BI6=class{apply(Q,X){if(!X.enum||X.enum.length===0)return Q;let Y=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Y.length===0)return Q;return Q.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Y.some((G)=>oM(J,G))},{message:"Value must match one of the enum values"})}},DI6=class{apply(Q,X){if(X.const===void 0)return Q;let Y=X.const;if(typeof Y!=="object"||Y===null)return Q;return Q.refine((J)=>oM(J,Y),{message:"Value must equal the const value"})}},NI6=class{apply(Q,X){if(X.description)Q=Q.describe(X.description);return Q}},OI6=class{apply(Q,X){var Y;let J=X;if(!((Y=J.required)==null?void 0:Y.includes("__proto__"))||X.type!==void 0)return Q;return N.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Q,X){if(typeof Q!=="object"||Q===null||Array.isArray(Q))return!0;return X.every((Y)=>Object.prototype.hasOwnProperty.call(Q,Y))}},LI6=class{apply(Q,X){var Y;let J=X;if(J.contains===void 0)return Q;let G=D9(J.contains),W=(Y=J.minContains)!=null?Y:1,Z=J.maxContains;return Q.refine(($)=>{if(!Array.isArray($))return!0;let K=0;for(let H of $)if(Ly(G,H))K++;if(K<W)return!1;if(Z!==void 0&&K>Z)return!1;return!0},{message:"Array must contain required items matching the schema"})}},wI6=class{apply(Q,X){let{default:Y}=X;if(Y===void 0)return Q;if(!Q.safeParse(Y).success)return Q;return Q.default(Y)}},MI6,PI6;var H91=o(()=>{r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();r6();MI6=[new uC6,new mC6,new gC6,new lC6,new dC6,new tC6,new GI6,new pC6,new cC6,new nC6,new iC6,new aC6,new rC6,new oC6,new sC6,new YI6,new eC6,new QI6,new XI6,new WI6,new ZI6,new JI6],PI6=[new OI6,new BI6,new DI6,new FI6,new VI6,new qI6,new zI6,new UI6,new LI6,new KI6,new HI6,new wI6,new NI6]});class X40{constructor(Q){this._url=Q}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Q,X)=>{this._socket=new WebSocket(this._url,TI6),this._socket.onerror=(Y)=>{let J="error"in Y?Y.error:Error(`WebSocket error: ${JSON.stringify(Y)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Q()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Y)=>{let J;try{J=bY.parse(JSON.parse(Y.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Q){return new Promise((X,Y)=>{if(!this._socket){Y(Error("Not connected"));return}this._socket?.send(JSON.stringify(Q)),X()})}}var TI6="mcp";var F91=o(()=>{h9()});function AI6(Q){let X=Q;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Y=X?.params?.protocolVersion;if(!Y)return null;return{type:"emit",message:{result:{protocolVersion:Y,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var Y40;var V91=o(()=>{iM();Y40=class Y40 extends _7{constructor(Q,X){super(Q,X)}send(Q,X){let Y=AI6(Q);if(Y?.type==="emit")return this.onmessage?.(Y.message),Promise.resolve();if(Y?.type==="suppress")return Promise.resolve();return super.send(Q,X)}}});var q91,z91=async(Q,X,Y)=>{let J=EI6(Q.connection,X,Y);if(!J)throw Error("Unknown MCP connection type");let G=new q91({name:Q?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(W,Z)=>{if(Q.connection.type!=="HTTP")throw Error("HTTP connection required");let $=new Headers(Y);if(!$.has("Authorization"))$.set("Authorization",`Bearer ${Q.connection.token}`);for(let[F,V]of Object.entries(Q.connection.headers??{}))$.set(F,V);let K=new URL(Q.connection.url),H=K.pathname.replace(/\/+$/,"")||"/";return K.pathname=`${H}/call-tool/${encodeURIComponent(W)}`,fetch(K.href,{method:"POST",redirect:"manual",body:JSON.stringify(Z),headers:$})}}},EI6=(Q,X,Y)=>{if(Q.type==="Websocket")return new X40(new URL(Q.url));if(Q.type!=="SSE"&&Q.type!=="HTTP")return null;let G={...Q.token?{authorization:`Bearer ${Q.token}`}:{},...Y??{},..."headers"in Q?Q.headers||{}:{}};if(Q.type==="SSE"){let W={requestInit:{headers:G,signal:X}};if(Q.token)W.eventSourceInit={fetch:(Z,$)=>{return fetch(Z,{...$,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new r3(new URL(Q.url),W)}return new Y40(new URL(Q.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var U91=o(()=>{zU();qy();F91();h9();V91();q91=class q91 extends QY{constructor(Q,X){super(Q,X)}async listTools(Q,X){return await this.request({method:"tools/list",params:Q},qM,X)}}});function D91(Q){let X=(Y)=>{if("connection"in Q)return z91({connection:Q.connection},void 0,Y);return Q.client};return new Proxy({},{get(Y,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return $;async function G(K,H=J){let F=Q?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:z}=await X(V);if(Q?.streamable?.[String(H)])return z(String(H),K);let{structuredContent:B,isError:D,content:L}=await q.callTool({name:String(H),arguments:K});if(D){let M=L?.[0]?.text,C=typeof M==="string"?jI6(M):null,A=C?.code&&typeof Q?.getErrorByStatusCode==="function"?Q.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(A)throw A;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(B??L)}`)}return B}async function W(){let{client:K}=await X(),{tools:H}=await K.listTools();return H}async function Z(){if(!("connection"in Q))return W();let K=Q.connection,H=JSON.stringify(K);try{if(!wy.has(H))wy.set(H,W());return await wy.get(H)}catch(F){console.error("Failed to list tools",F),wy.delete(H);return}}async function $(){return(await Z()??[]).map((H)=>B91(H,G))}return G.asTool=async()=>{let H=(await Z()??[]).find((F)=>F.name===J);if(!H)throw Error(`Tool ${J} not found`);return B91(H,G)},G}})}var jI6=(Q)=>{try{return JSON.parse(Q)}catch{return Q}},wy,B91=(Q,X)=>{return{...Q,id:Q.name,inputSchema:Q.inputSchema?D9(Q.inputSchema):void 0,outputSchema:Q.outputSchema?D9(Q.outputSchema):void 0,execute:(Y)=>{return X(Y.context,Q.name)}}};var N91=o(()=>{H91();U91();wy=new Map});function My(Q){return D91(Q)}var w_4;var O91=o(()=>{N91();w_4=new Proxy({},{get(Q,X){if(X==="toJSON")return null;if(X==="forConnection")return(Y)=>My({connection:Y});return global[X]}})});function Py(Q){return{isImplementedBy:(X)=>{for(let Y of Q){let J=typeof Y.name==="string"?new RegExp(`^${Y.name}$`):Y.name,G=X.find((W)=>J.test(W.name));if(!G&&Y.opt)continue;if(!G)return!1}return!0}}}var SU=(Q)=>{return{...Py(Q),forClient:(X)=>{return My({client:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})},forConnection:(X)=>{return My({connection:X,streamable:Q.reduce((Y,J)=>{return Y[J.name]=J.streamable===!0,Y},{})})}}};var sM=o(()=>{O91()});function eM(Q){return N.object({items:N.array(Q).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function G40(Q){return N.object({item:Q.nullable().describe("The retrieved item, or null if not found")})}function RI6(Q){return N.object({data:Q.partial().describe("Data for the new entity (id may be auto-generated)")})}function SI6(Q){return N.object({item:Q.describe("The created entity with generated id")})}function vI6(Q){return N.object({id:N.string().describe("ID of the entity to update"),data:Q.partial().describe("Partial entity data to update")})}function kI6(Q){return N.object({item:Q.describe("The updated entity")})}function Z40(Q){return N.object({item:Q.describe("The deleted entity")})}function kU(Q,X,Y){let J=Q.toUpperCase(),G=Y?.readOnly??!1,W=[{name:`COLLECTION_${J}_LIST`,inputSchema:tM,outputSchema:eM(X)},{name:`COLLECTION_${J}_GET`,inputSchema:J40,outputSchema:G40(X)}];if(!G)W.push({name:`COLLECTION_${J}_CREATE`,inputSchema:RI6(X),outputSchema:SI6(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:vI6(X),outputSchema:kI6(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:W40,outputSchema:Z40(X),opt:!0});return W}var vU,CI6,L91,II6,tM,J40,W40;var i$=o(()=>{G1();vU=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),CI6=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),L91=N.lazy(()=>N.union([CI6,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(L91)})])),II6=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),tM=N.object({where:L91.optional().describe("Filter expression"),orderBy:N.array(II6).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});J40=N.object({id:N.string().describe("ID of the entity to retrieve")});W40=N.object({id:N.string().describe("ID of the entity to delete")})});var _I6,w91,R_4;var M91=o(()=>{G1();i$();_I6=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),w91=vU.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(_I6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),R_4=kU("registry_app",w91,{readOnly:!0})});var P91,T91,A91,E91,j91,$40;var C91=o(()=>{G1();sM();P91=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),T91=N.object({events:N.array(P91).min(1).describe("Batch of CloudEvents to process")}),A91=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),E91=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),A91).optional().describe("Per-event results keyed by event ID")}),j91=[{name:"ON_EVENTS",inputSchema:T91,outputSchema:E91}],$40=SU(j91)});var QP,XP,YP,JP,I91,R91,GP,WP,ZP,$P,KP,HP,FP,VP,S91,yI6;var v91=o(()=>{G1();sM();QP=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),XP=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),YP=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),JP=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")})}),I91=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),R91=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),GP=N.object({subscriptions:N.array(I91).describe("Desired subscriptions - system will create/update/delete to match")}),WP=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(R91).describe("Current subscriptions after sync")}),ZP=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),$P=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),KP=N.object({eventId:N.string().describe("Event ID to cancel")}),HP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),FP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),VP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),S91=[{name:"EVENT_PUBLISH",inputSchema:QP,outputSchema:XP},{name:"EVENT_SUBSCRIBE",inputSchema:YP,outputSchema:JP},{name:"EVENT_UNSUBSCRIBE",inputSchema:ZP,outputSchema:$P},{name:"EVENT_CANCEL",inputSchema:KP,outputSchema:HP},{name:"EVENT_ACK",inputSchema:FP,outputSchema:VP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:GP,outputSchema:WP}],yI6=SU(S91)});var Ty=o(()=>{sM();M91();C91();v91()});var bI6,fI6,k91;var _91=o(()=>{G1();i$();bI6=vU.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),gateway_id:N.string().describe("Gateway ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),fI6=kU("assistant",bI6),k91=[...fI6]});var qP,y7,b91,hI6,xI6,f91,gI6,uI6,mI6,lI6,dI6,pI6,h91,cI6,nI6,iI6,aI6,rI6,oI6,sI6,tI6,eI6,QR6,r_4,XR6,o_4,y91,YR6,JR6,K40,x91;var H40=o(()=>{G1();sM();i$();qP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),qP),N.array(qP)])),y7=N.record(N.string(),N.record(N.string(),qP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),b91=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:y7}),hI6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),xI6=N.string().describe("File data as URL string"),f91=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:xI6,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:y7}),gI6=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),uI6=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:y7}),mI6=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),lI6=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:y7}),dI6=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),pI6=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:qP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:qP}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),h91=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:pI6.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:y7}),cI6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),nI6=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),iI6=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:y7}),aI6=N.object({role:N.literal("user"),content:N.array(N.union([b91,f91])).describe("User message content parts (text or file)"),providerOptions:y7}),rI6=N.object({role:N.literal("assistant"),content:N.array(N.union([b91,f91,uI6,lI6,h91])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:y7}),oI6=N.object({role:N.literal("tool"),content:N.array(h91).describe("Tool message content (tool results)"),providerOptions:y7}),sI6=N.union([iI6,aI6,rI6,oI6]),tI6=N.array(sI6).describe("A list of messages forming the prompt"),eI6=N.object({prompt:tI6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),QR6=N.object({content:N.array(N.union([hI6,gI6,mI6,dI6,cI6,nI6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),r_4=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),XR6=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),o_4=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),y91=N.object({modelId:N.string().describe("The ID of the model"),callOptions:eI6}),YR6=vU.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),JR6=kU("llm",YR6,{readOnly:!0}),K40=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:XR6},{name:"LLM_DO_STREAM",inputSchema:y91,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:y91,outputSchema:QR6},...JR6],x91=SU(K40)});function WR6(Q){let X=[],Y=0;while(Y<Q.length){let J=Q[Y];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Y++}return X.join("")}function a$(Q){return typeof Q==="string"||typeof Q==="number"}function Ay(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>Ay(Q,H));case"or":return K.some((H)=>Ay(Q,H));case"not":return!K.every((H)=>Ay(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join("."),Z=F40(Q,W);switch(J){case"eq":return Z===G;case"gt":return a$(Z)&&a$(G)&&Z>G;case"gte":return a$(Z)&&a$(G)&&Z>=G;case"lt":return a$(Z)&&a$(G)&&Z<G;case"lte":return a$(Z)&&a$(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=WR6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function F40(Q,X){let Y=X.split("."),J=Q;for(let G of Y){if(J==null||typeof J!=="object")return;J=J[G]}return J}function ZR6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=F40(Y,W),$=F40(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var GR6,$R6,KR6,V40;var g91=o(()=>{Ty();_91();i$();H40();G1();E6();O7();GR6={LLM:K40,ASSISTANTS:k91};$R6=tM.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),KR6=eM(vJ),V40=B1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:$R6,outputSchema:KR6,handler:async(Q,X)=>{await X.access.check();let Y=L6(X),J=Q.binding?typeof Q.binding==="string"?(()=>{let q=GR6[Q.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Q.binding}`);return q})():Q.binding:void 0,G=J?Py(J):void 0,W=await X.storage.connections.list(Y.id),Z=G?await Promise.all(W.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((B)=>({name:B.name,inputSchema:B.inputSchema,outputSchema:B.outputSchema})))?q:null})).then((q)=>q.filter((z)=>z!==null)):W;if(Q.where)Z=Z.filter((q)=>Ay(q,Q.where));if(Q.orderBy&&Q.orderBy.length>0)Z=ZR6(Z,Q.orderBy);let $=Z.length,K=Q.offset??0,H=Q.limit??100,F=Z.slice(K,K+H),V=K+H<$;return{items:F,totalCount:$,hasMore:V}}})});var HR6,q40;var u91=o(()=>{i$();E6();O7();HR6=G40(vJ),q40=B1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:J40,outputSchema:HR6,handler:async(Q,X)=>{let Y=L6(X);await X.access.check();let J=await X.storage.connections.findById(Q.id);if(!J||J.organization_id!==Y.id)return{item:null};return{item:J}}})});var Ey=(Q,X)=>{if(X===null||X===void 0)return;let Y=Q.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Y){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function m91(Q){let X=Q.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Q}. Expected format: "KEY::SCOPE"`);return X}function FR6(Q){let X=Q.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function VR6(Q){if(typeof Q==="object"&&Q!==null&&"value"in Q){let X=Q.value;if(typeof X==="string")return X}return null}function z40(Q,X){let Y={};if(!Q||!X)return Y;for(let J of X){if(J==="*"){Y["*"]=["*"];continue}let G=FR6(J);if(!G)continue;let[W,Z]=G,$=Ey(W,Q),K=VR6($);if(K){if(!Y[K])Y[K]=[];Y[K].push(Z)}}return Y}function l91(Q,X){let Y=z40(Q,X);return new Set(Object.keys(Y).filter((J)=>J!=="*"))}var U40=()=>{};class b7{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async get(Q){let X=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Q).executeTakeFirst();if(!X)return null;return this.decryptToken(X)}async upsert(Q){let X=new Date().toISOString(),Y=await this.vault.encrypt(Q.accessToken),J=Q.refreshToken?await this.vault.encrypt(Q.refreshToken):null,G=Q.clientSecret?await this.vault.encrypt(Q.clientSecret):null;return await this.db.transaction().execute(async(W)=>{let Z=await W.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Q.connectionId).executeTakeFirst();if(Z)return await W.updateTable("downstream_tokens").set({accessToken:Y,refreshToken:J,scope:Q.scope,expiresAt:Q.expiresAt?.toISOString()??null,clientId:Q.clientId,clientSecret:G,tokenEndpoint:Q.tokenEndpoint,updatedAt:X}).where("id","=",Z.id).execute(),{id:Z.id,connectionId:Q.connectionId,accessToken:Q.accessToken,refreshToken:Q.refreshToken,scope:Q.scope,expiresAt:Q.expiresAt,createdAt:Z.createdAt,updatedAt:X,clientId:Q.clientId,clientSecret:Q.clientSecret,tokenEndpoint:Q.tokenEndpoint};let $=kJ("dtok");return await W.insertInto("downstream_tokens").values({id:$,connectionId:Q.connectionId,accessToken:Y,refreshToken:J,scope:Q.scope,expiresAt:Q.expiresAt?.toISOString()??null,clientId:Q.clientId,clientSecret:G,tokenEndpoint:Q.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:$,connectionId:Q.connectionId,accessToken:Q.accessToken,refreshToken:Q.refreshToken,scope:Q.scope,expiresAt:Q.expiresAt,createdAt:X,updatedAt:X,clientId:Q.clientId,clientSecret:Q.clientSecret,tokenEndpoint:Q.tokenEndpoint}})}async delete(Q){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Q).execute()}isExpired(Q,X=0){if(!Q.expiresAt)return!1;let J=(Q.expiresAt instanceof Date?Q.expiresAt:new Date(Q.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-X<Date.now()}async decryptToken(Q){let X=await this.vault.decrypt(Q.accessToken),Y=Q.refreshToken?await this.vault.decrypt(Q.refreshToken):null,J=Q.clientSecret?await this.vault.decrypt(Q.clientSecret):null;return{id:Q.id,connectionId:Q.connectionId,accessToken:X,refreshToken:Y,scope:Q.scope,expiresAt:Q.expiresAt,createdAt:Q.createdAt,updatedAt:Q.updatedAt,clientId:Q.clientId,clientSecret:J,tokenEndpoint:Q.tokenEndpoint}}}var jy=o(()=>{mw()});async function UR6(Q,X,Y,J){for(let W of X){if(W==="*")continue;let[Z]=m91(W),$=Ey(Z,Q);if($===void 0||$===null)throw Error(`Scope references key "${Z}" but it's not present in state`)}let G=l91(Q,X);for(let W of G){if(W===w5.SELF)continue;let Z=await J.storage.connections.findById(W);if(!Z||Z.organization_id!==Y)throw Error(`Referenced connection not found: ${W}`);try{await J.access.check(W)}catch($){throw Error(`Access denied to referenced connection: ${W}. ${$.message}`)}}}var qR6,zR6,B40;var d91=o(()=>{U40();y3();jy();G1();E6();By();O7();qR6=N.object({id:N.string().describe("ID of the connection to update"),data:Tt0.describe("Partial connection data to update")}),zR6=N.object({item:vJ.describe("The updated connection entity")});B40=B1({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:qR6,outputSchema:zR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);if(await X.access.check(),!lQ(X))throw Error("User ID required to update connection");let{id:G,data:W}=Q,Z=await X.storage.connections.findById(G);if(!Z||Z.organization_id!==Y.id)throw Error("Connection not found in organization");let $=W.configuration_state??Z.configuration_state,K=W.configuration_scopes??Z.configuration_scopes??[];if(W.configuration_state!==void 0||W.configuration_scopes!==void 0){if(W.configuration_state!==void 0)$=W.configuration_state;else if($===null)$={};if(W.configuration_scopes!==void 0)K=W.configuration_scopes??[];if(K.length>0&&$)await UR6($,K,Y.id,X)}let H=W.connection_token??Z.connection_token;if(!H)try{let D=await new b7(X.db,X.vault).get(G);if(D?.accessToken)H=D.accessToken}catch{}let F=await IU({id:Z.id,title:W.title??Z.title,connection_type:W.connection_type??Z.connection_type,connection_url:W.connection_url??Z.connection_url,connection_token:H,connection_headers:W.connection_headers??Z.connection_headers}).catch(()=>null),V=F?.length?F:null,q={...W,tools:V,configuration_state:$,configuration_scopes:K},z=await X.storage.connections.update(G,q);if((W.configuration_state!==void 0||W.configuration_scopes!==void 0)&&$&&K.length>0)try{await(await X.createMCPProxy(G)).client.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:$,scopes:K}})}catch(B){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",B)}return{item:z}}})});var D40;var p91=o(()=>{i$();E6();O7();D40=B1({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:W40,outputSchema:Z40(vJ),handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=await X.storage.connections.findById(Q.id);if(!J)throw Error(`Connection not found: ${Q.id}`);if(J.organization_id!==Y.id)throw Error("Connection not found in organization");return await X.storage.connections.delete(Q.id),{item:J}}})});var N40;var c91=o(()=>{G1();E6();N40=B1({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Q,X)=>{let Y=L6(X);await X.access.check();let J=await X.storage.connections.findById(Q.id);if(!J||J.organization_id!==Y.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Q.id);return{id:Q.id,...G}}})});var n91=o(()=>{K91();g91();u91();d91();p91();c91()});import{sql as t6}from"kysely";function i91(Q){if(Q===null||Q===void 0)return"NULL";if(typeof Q==="number")return String(Q);if(typeof Q==="boolean")return Q?"TRUE":"FALSE";if(typeof Q==="string")return`'${Q.replace(/'/g,"''")}'`;if(Q instanceof Date)return`'${Q.toISOString()}'`;return`'${JSON.stringify(Q).replace(/'/g,"''")}'`}function NR6(Q,X){let Y=Q;for(let G=X.length;G>=1;G--){let W=`$${G}`;if(Y.includes(W))Y=Y.replaceAll(W,i91(X[G-1]))}let J=[];for(let G=0;G<Y.length;G++)if(Y[G]==="?")J.push(G);for(let G=Math.min(J.length,X.length)-1;G>=0;G--){let W=J[G],Z=i91(X[G]);Y=Y.slice(0,W)+Z+Y.slice(W+1)}return Y}function a91(Q){return Q.replace(/-/g,"_")}function LR6(Q){return`app_${a91(Q)}`}function wR6(Q){return`app_role_${a91(Q)}`}function MR6(Q){if(Q instanceof Error){let X=Q.message.toLowerCase(),Y=Q.code;return Y==="3F000"||Y==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function PR6(Q,X,Y){if(await t6`CREATE SCHEMA IF NOT EXISTS ${t6.id(X)}`.execute(Q),!(await t6`
|
|
254
254
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Y}) as exists
|
|
255
|
-
`.execute(Q)).rows[0]?.exists)await t6`CREATE ROLE ${t6.id(Y)} NOLOGIN`.execute(Q);await t6`GRANT ${t6.id(Y)} TO CURRENT_USER`.execute(Q),await t6`GRANT USAGE, CREATE ON SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL TABLES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON TABLES TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON SEQUENCES TO ${t6.id(Y)}`.execute(Q),await t6`REVOKE ALL ON SCHEMA public FROM ${t6.id(Y)}`.execute(Q)}async function TR6(Q,X,Y,J){try{return await Q.transaction().execute(async(G)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(G),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(G),await t6.raw(J).execute(G)})}catch(G){if(MR6(G))return await PR6(Q,X,Y),await Q.transaction().execute(async(W)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(W),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(W),await t6.raw(J).execute(W)});throw G}}var DR6,OR6,r91;var o91=o(()=>{G1();E6();DR6=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});OR6=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});r91=B1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:OR6,outputSchema:N.object({result:N.array(DR6)}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=NR6(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=LR6(X.connectionId),G=wR6(X.connectionId);return{result:[{results:(await TR6(X.db,J,G,Y)).rows,success:!0}]}}})});var s91,ER6,t91;var f7=o(()=>{G1();Ty();s91=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),ER6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),t91=N.object({subscriptions:N.array(ER6).describe("List of subscriptions")})});var O40;var e91=o(()=>{E6();f7();O40=B1({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:QP,outputSchema:XP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await X.eventBus.publish(Y.id,J,{type:Q.type,subject:Q.subject,data:Q.data,deliverAt:Q.deliverAt,cron:Q.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var L40;var QX1=o(()=>{E6();f7();L40=B1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:YP,outputSchema:JP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await X.eventBus.subscribe(Y.id,{connectionId:J,eventType:Q.eventType,publisher:Q.publisher,filter:Q.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var w40;var XX1=o(()=>{E6();f7();w40=B1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:ZP,outputSchema:$P,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await X.eventBus.getSubscription(Y.id,Q.subscriptionId);if(!G)throw Error(`Subscription not found: ${Q.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(Y.id,Q.subscriptionId)).success,subscriptionId:Q.subscriptionId}}})});var M40;var YX1=o(()=>{E6();f7();M40=B1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:KP,outputSchema:HP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(Y.id,Q.eventId))throw Error(`Event not found: ${Q.eventId}`);if(!(await X.eventBus.cancelEvent(Y.id,Q.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Q.eventId}}})});var P40;var JX1=o(()=>{E6();f7();P40=B1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:FP,outputSchema:VP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(Y.id,Q.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Q.eventId}}})});var T40;var GX1=o(()=>{E6();f7();T40=B1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:s91,outputSchema:t91,handler:async(Q,X)=>{C1(X);let Y=L6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(Y.id,Q.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var A40;var WX1=o(()=>{E6();f7();A40=B1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:GP,outputSchema:WP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await X.eventBus.syncSubscriptions(Y.id,{connectionId:J,subscriptions:Q.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var ZX1=o(()=>{e91();QX1();XX1();YX1();JX1();GX1();WX1();f7()});var E40,j40,CR6,JW,$X1,KX1;var _U=o(()=>{G1();E40=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),j40=N.enum(["passthrough","smart_tool_selection","code_execution"]).describe("Gateway tool selection strategy: 'passthrough' (default), 'smart_tool_selection', or 'code_execution'"),CR6=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),JW=N.object({id:N.string().describe("Unique identifier for the gateway"),title:N.string().describe("Human-readable name for the gateway"),description:N.string().nullable().describe("Description of the gateway"),icon:N.string().nullable().optional().describe("Icon URL for the gateway"),created_at:N.string().describe("When the gateway was created"),updated_at:N.string().describe("When the gateway was last updated"),created_by:N.string().describe("User ID who created the gateway"),updated_by:N.string().optional().describe("User ID who last updated the gateway"),organization_id:N.string().describe("Organization ID this gateway belongs to"),tool_selection_strategy:j40.describe("Gateway behavior strategy (metadata for now): 'passthrough', 'smart_tool_selection', or 'code_execution'"),tool_selection_mode:E40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),is_default:N.boolean().describe("Whether this is the Organization Agent for the organization"),connections:N.array(CR6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),$X1=N.object({title:N.string().min(1).max(255).describe("Name for the gateway"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_strategy:j40.optional().default("passthrough").describe("Gateway behavior strategy (defaults to 'passthrough')"),tool_selection_mode:E40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),is_default:N.boolean().optional().default(!1).describe("Whether this is the Organization Agent for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),KX1=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_strategy:j40.optional().describe("New gateway behavior strategy"),tool_selection_mode:E40.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),is_default:N.boolean().optional().describe("Set as Organization Agent for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var IR6,RR6,C40;var HX1=o(()=>{G1();E6();_U();IR6=N.object({data:$X1.describe("Data for the new gateway")}),RR6=N.object({item:JW.describe("The created gateway entity")}),C40=B1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:IR6,outputSchema:RR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=lQ(X);if(!J)throw Error("User ID required to create gateway");let G={title:Q.data.title,description:Q.data.description??null,toolSelectionStrategy:Q.data.tool_selection_strategy??"passthrough",toolSelectionMode:Q.data.tool_selection_mode??"inclusion",icon:Q.data.icon??null,status:Q.data.status,isDefault:Q.data.is_default??!1,connections:Q.data.connections.map((Z)=>({connectionId:Z.connection_id,selectedTools:Z.selected_tools??null,selectedResources:Z.selected_resources??null,selectedPrompts:Z.selected_prompts??null}))},W=await X.storage.gateways.create(Y.id,J,G);return{item:{id:W.id,title:W.title,description:W.description,icon:W.icon,organization_id:W.organizationId,tool_selection_strategy:W.toolSelectionStrategy,tool_selection_mode:W.toolSelectionMode,status:W.status,is_default:W.isDefault,connections:W.connections.map((Z)=>({connection_id:Z.connectionId,selected_tools:Z.selectedTools,selected_resources:Z.selectedResources,selected_prompts:Z.selectedPrompts})),created_at:W.createdAt,updated_at:W.updatedAt,created_by:W.createdBy,updated_by:W.updatedBy??void 0}}}})});function SR6(Q){let X=[],Y=0;while(Y<Q.length){let J=Q[Y];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Y++}return X.join("")}function r$(Q){return typeof Q==="string"||typeof Q==="number"}function I40(Q,X){let Y=X.split("."),J=Q;for(let G of Y){if(J==null||typeof J!=="object")return;J=J[G]}return J}function vR6(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function Cy(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>Cy(Q,H));case"or":return K.some((H)=>Cy(Q,H));case"not":return!K.every((H)=>Cy(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return vR6(Q,G)}let Z=I40(Q,W);switch(J){case"eq":return Z===G;case"gt":return r$(Z)&&r$(G)&&Z>G;case"gte":return r$(Z)&&r$(G)&&Z>=G;case"lt":return r$(Z)&&r$(G)&&Z<G;case"lte":return r$(Z)&&r$(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=SR6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function kR6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=I40(Y,W),$=I40(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var _R6,yR6,R40;var FX1=o(()=>{i$();E6();_U();_R6=tM,yR6=eM(JW),R40=B1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:_R6,outputSchema:yR6,handler:async(Q,X)=>{await X.access.check();let Y=L6(X),J=Q.where&&!("conditions"in Q.where)&&Q.where.field.join(".")==="connection_id"&&Q.where.operator==="eq"&&typeof Q.where.value==="string"?Q.where.value:void 0,W=(J?await X.storage.gateways.listByConnectionId(Y.id,J):await X.storage.gateways.list(Y.id)).map((V)=>({id:V.id,title:V.title,description:V.description,icon:V.icon,is_default:V.isDefault,organization_id:V.organizationId,tool_selection_strategy:V.toolSelectionStrategy,tool_selection_mode:V.toolSelectionMode,status:V.status,connections:V.connections.map((q)=>({connection_id:q.connectionId,selected_tools:q.selectedTools,selected_resources:q.selectedResources,selected_prompts:q.selectedPrompts})),created_at:V.createdAt,updated_at:V.updatedAt,created_by:V.createdBy,updated_by:V.updatedBy??void 0}));if(Q.where)W=W.filter((V)=>Cy(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=kR6(W,Q.orderBy);let Z=W.length,$=Q.offset??0,K=Q.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var bR6,fR6,S40;var VX1=o(()=>{G1();E6();_U();bR6=N.object({id:N.string().describe("ID of the gateway to retrieve")}),fR6=N.object({item:JW.nullable().describe("The retrieved gateway, or null if not found")}),S40=B1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:bR6,outputSchema:fR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(J&&J.organizationId!==Y.id)return{item:null};if(!J)return{item:null};return{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_strategy:J.toolSelectionStrategy,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt,updated_at:J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var hR6,xR6,v40;var qX1=o(()=>{G1();E6();_U();hR6=N.object({id:N.string().describe("ID of the gateway to update"),data:KX1.describe("Partial gateway data to update")}),xR6=N.object({item:JW.describe("The updated gateway entity")}),v40=B1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:hR6,outputSchema:xR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=lQ(X);if(!J)throw Error("User ID required to update gateway");let G=await X.storage.gateways.findById(Q.id);if(!G)throw Error(`Gateway not found: ${Q.id}`);if(G.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);let W={};if(Q.data.title!==void 0)W.title=Q.data.title;if(Q.data.description!==void 0)W.description=Q.data.description;if(Q.data.tool_selection_strategy!==void 0)W.toolSelectionStrategy=Q.data.tool_selection_strategy;if(Q.data.tool_selection_mode!==void 0)W.toolSelectionMode=Q.data.tool_selection_mode;if(Q.data.icon!==void 0)W.icon=Q.data.icon;if(Q.data.status!==void 0)W.status=Q.data.status;if(Q.data.is_default!==void 0)W.isDefault=Q.data.is_default;if(Q.data.connections!==void 0)W.connections=Q.data.connections.map(($)=>({connectionId:$.connection_id,selectedTools:$.selected_tools??null,selectedResources:$.selected_resources??null,selectedPrompts:$.selected_prompts??null}));let Z=await X.storage.gateways.update(Q.id,J,W);return{item:{id:Z.id,title:Z.title,description:Z.description,icon:Z.icon,organization_id:Z.organizationId,tool_selection_strategy:Z.toolSelectionStrategy,tool_selection_mode:Z.toolSelectionMode,status:Z.status,is_default:Z.isDefault,connections:Z.connections.map(($)=>({connection_id:$.connectionId,selected_tools:$.selectedTools,selected_resources:$.selectedResources,selected_prompts:$.selectedPrompts})),created_at:Z.createdAt,updated_at:Z.updatedAt,created_by:Z.createdBy,updated_by:Z.updatedBy??void 0}}}})});var gR6,uR6,k40;var zX1=o(()=>{G1();E6();_U();gR6=N.object({id:N.string().describe("ID of the gateway to delete")}),uR6=N.object({item:JW.describe("The deleted gateway entity")}),k40=B1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:gR6,outputSchema:uR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(!J)throw Error(`Gateway not found: ${Q.id}`);if(J.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);if(J.isDefault)throw Error("Cannot delete the Organization Agent. Set another Agent as the Organization Agent first.");return await X.storage.gateways.delete(Q.id),{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_strategy:J.toolSelectionStrategy,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updated_at:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var UX1=o(()=>{HX1();FX1();VX1();qX1();zX1()});var lR6,_40;var BX1=o(()=>{E6();G1();lR6=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.string(),N.unknown()).describe("Redacted tool input"),output:N.record(N.string(),N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),gatewayId:N.string().nullish().describe("Gateway ID if routed through a gateway"),properties:N.record(N.string(),N.string()).nullish().describe("Custom key-value metadata attached to the log")}),_40=B1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),gatewayId:N.string().optional().describe("Filter by gateway ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(100).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination"),properties:N.record(N.string(),N.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:N.array(N.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:N.record(N.string(),N.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:N.object({logs:N.array(lR6).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Q,X)=>{let Y=L6(X),G=Q.properties||Q.propertyKeys||Q.propertyPatterns?{properties:Q.properties,propertyKeys:Q.propertyKeys,propertyPatterns:Q.propertyPatterns}:void 0,W={organizationId:Y.id,connectionId:Q.connectionId,gatewayId:Q.gatewayId,toolName:Q.toolName,isError:Q.isError,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0,limit:Q.limit,offset:Q.offset,propertyFilters:G},Z=await X.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:Q.offset,limit:Q.limit}}})});var y40;var DX1=o(()=>{E6();G1();y40=B1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Q,X)=>{let J={organizationId:L6(X).id,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0},G=await X.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var NX1=o(()=>{BX1();DX1()});var b40;var OX1=o(()=>{G1();E6();b40=B1({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional()}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=lQ(X);if(!Y)throw Error("User ID required to create organization");let J=await X.boundAuth.organization.create({name:Q.name,slug:Q.slug,metadata:Q.description?{description:Q.description}:void 0,userId:Y});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var f40;var LX1=o(()=>{G1();E6();f40=B1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=lQ(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:(await X.boundAuth.organization.list(J)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var h40;var wX1=o(()=>{G1();E6();h40=B1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}}})});var x40;var MX1=o(()=>{G1();E6();x40=B1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y={};if(Q.name)Y.name=Q.name;if(Q.slug)Y.slug=Q.slug;if(Q.description)Y.metadata={description:Q.description};let J=await X.boundAuth.organization.update({organizationId:Q.id,data:Y});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var g40;var PX1=o(()=>{G1();E6();g40=B1({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Q,X)=>{return C1(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var zP;var u40=o(()=>{G1();zP=N.object({title:N.string(),url:N.string(),icon:N.string()})});var m40;var TX1=o(()=>{G1();E6();u40();m40=B1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(zP).nullable().optional(),createdAt:N.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.storage.organizationSettings.get(Y);if(!J)return{organizationId:Y};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var l40;var AX1=o(()=>{G1();E6();u40();l40=B1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(zP).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(zP).nullable().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{if(C1(X),await X.access.check(),X.organization&&X.organization.id!==Q.organizationId)throw Error("Cannot update settings for a different organization");let Y=await X.storage.organizationSettings.upsert(Q.organizationId,{sidebar_items:Q.sidebar_items});return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});var d40;var EX1=o(()=>{G1();E6();d40=B1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.addMember({organizationId:Y,userId:Q.userId,role:Q.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var p40;var jX1=o(()=>{G1();E6();p40=B1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:Y,memberIdOrEmail:Q.memberIdOrEmail}),{success:!0,memberIdOrEmail:Q.memberIdOrEmail}}})});var c40;var CX1=o(()=>{G1();E6();c40=B1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.listMembers({organizationId:Y,limit:Q.limit,offset:Q.offset});return{members:(Array.isArray(J)?J:[]).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var n40;var IX1=o(()=>{G1();E6();n40=B1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.updateMemberRole({organizationId:Y,memberId:Q.memberId,role:Q.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var RX1=o(()=>{OX1();LX1();wX1();MX1();PX1();TX1();AX1();EX1();jX1();CX1();IX1()});var cR6,nR6,i40;var SX1=o(()=>{G1();E6();cR6=N.object({id:N.string().min(1)}),nR6=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),i40=B1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:cR6,outputSchema:nR6,handler:async(Q,X)=>{await X.access.check(),C1(X);let Y=lQ(X);if(!Y)throw Error("Authentication required");let J=await X.storage.users.findById(Q.id,Y);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var vX1=o(()=>{SX1()});var _X1={};$8(_X1,{managementMCP:()=>a40,ALL_TOOLS:()=>kX1});var kX1,a40=(Q)=>{let X=kX1.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return Q.access.setToolName(J.name),await J.execute(G,Q)}}));return nQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var r40=o(()=>{iQ1();$91();n91();o91();ZX1();UX1();NX1();RX1();vX1();kX1=[b40,f40,h40,x40,g40,m40,l40,d40,p40,c40,n40,Q40,V40,q40,B40,D40,N40,C40,R40,S40,v40,k40,r91,_40,y40,o60,t60,e60,s60,O40,L40,w40,M40,P40,T40,A40,i40]});var QF,H80,xy,XF,wP;var gy=o(()=>{QF={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},H80={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},xy={Pending:0,Fulfilled:1,Rejected:2},XF={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},wP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function hU(...Q){B80&&console.log("quickjs-emscripten:",...Q)}function*pY1(Q){return yield Q}function hS6(Q){return pY1(N80(Q))}function kY1(Q,X){return(...Y)=>{let J=X.call(Q,D80,...Y);return N80(J)}}function xS6(Q,X){let Y=X.call(Q,D80);return N80(Y)}function N80(Q){function X(Y){return Y.done?Y.value:Y.value instanceof Promise?Y.value.then((J)=>X(Q.next(J)),(J)=>X(Q.throw(J))):X(Q.next(Y.value))}return X(Q.next())}function F80(Q,X){let Y;try{Q.dispose()}catch(J){Y=J}if(X&&Y)throw Object.assign(X,{message:`${X.message}
|
|
256
|
-
Then, failed to dispose scope: ${Y.message}`,disposeError:Y}),X;if(X||Y)throw X||Y}function cY1(Q){let X=Q?Array.from(Q):[];function Y(){return X.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return X.some((G)=>G.alive)}return Object.defineProperty(X,
|
|
257
|
-
Attempted to suspend at:`);this.suspended=new xY1(`(${this.suspendedCount++})`),hU("asyncify.handleSleep: suspending:",this.suspended),G.then((W)=>{this.suspended=void 0,hU("asyncify.handleSleep: resolved:",W),J(W)},(W)=>{hU("asyncify.handleSleep: rejected:",W),console.error("QuickJS: cannot handle error in suspended function",W),this.suspended=void 0})}catch(G){throw hU("asyncify.handleSleep: error:",G),this.suspended=void 0,G}});let Y=X();if(Y instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return Y}},
|
|
255
|
+
`.execute(Q)).rows[0]?.exists)await t6`CREATE ROLE ${t6.id(Y)} NOLOGIN`.execute(Q);await t6`GRANT ${t6.id(Y)} TO CURRENT_USER`.execute(Q),await t6`GRANT USAGE, CREATE ON SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL TABLES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${t6.id(X)} TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON TABLES TO ${t6.id(Y)}`.execute(Q),await t6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${t6.id(X)} GRANT ALL ON SEQUENCES TO ${t6.id(Y)}`.execute(Q),await t6`REVOKE ALL ON SCHEMA public FROM ${t6.id(Y)}`.execute(Q)}async function TR6(Q,X,Y,J){try{return await Q.transaction().execute(async(G)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(G),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(G),await t6.raw(J).execute(G)})}catch(G){if(MR6(G))return await PR6(Q,X,Y),await Q.transaction().execute(async(W)=>{return await t6`SET LOCAL ROLE ${t6.id(Y)}`.execute(W),await t6`SET LOCAL search_path TO ${t6.id(X)}`.execute(W),await t6.raw(J).execute(W)});throw G}}var DR6,OR6,r91;var o91=o(()=>{G1();E6();DR6=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});OR6=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});r91=B1({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:OR6,outputSchema:N.object({result:N.array(DR6)}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=NR6(Q.sql,Q.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=LR6(X.connectionId),G=wR6(X.connectionId);return{result:[{results:(await TR6(X.db,J,G,Y)).rows,success:!0}]}}})});var s91,ER6,t91;var f7=o(()=>{G1();Ty();s91=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),ER6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),t91=N.object({subscriptions:N.array(ER6).describe("List of subscriptions")})});var O40;var e91=o(()=>{E6();f7();O40=B1({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:QP,outputSchema:XP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await X.eventBus.publish(Y.id,J,{type:Q.type,subject:Q.subject,data:Q.data,deliverAt:Q.deliverAt,cron:Q.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var L40;var QX1=o(()=>{E6();f7();L40=B1({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:YP,outputSchema:JP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await X.eventBus.subscribe(Y.id,{connectionId:J,eventType:Q.eventType,publisher:Q.publisher,filter:Q.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var w40;var XX1=o(()=>{E6();f7();w40=B1({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:ZP,outputSchema:$P,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await X.eventBus.getSubscription(Y.id,Q.subscriptionId);if(!G)throw Error(`Subscription not found: ${Q.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(Y.id,Q.subscriptionId)).success,subscriptionId:Q.subscriptionId}}})});var M40;var YX1=o(()=>{E6();f7();M40=B1({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:KP,outputSchema:HP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(Y.id,Q.eventId))throw Error(`Event not found: ${Q.eventId}`);if(!(await X.eventBus.cancelEvent(Y.id,Q.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Q.eventId}}})});var P40;var JX1=o(()=>{E6();f7();P40=B1({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:FP,outputSchema:VP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(Y.id,Q.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Q.eventId}}})});var T40;var GX1=o(()=>{E6();f7();T40=B1({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:s91,outputSchema:t91,handler:async(Q,X)=>{C1(X);let Y=L6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(Y.id,Q.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var A40;var WX1=o(()=>{E6();f7();A40=B1({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:GP,outputSchema:WP,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await X.eventBus.syncSubscriptions(Y.id,{connectionId:J,subscriptions:Q.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((W)=>({id:W.id,connectionId:W.connectionId,eventType:W.eventType,publisher:W.publisher,filter:W.filter,enabled:W.enabled,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt,updatedAt:W.updatedAt instanceof Date?W.updatedAt.toISOString():W.updatedAt}))}}})});var ZX1=o(()=>{e91();QX1();XX1();YX1();JX1();GX1();WX1();f7()});var E40,CR6,JW,$X1,KX1;var _U=o(()=>{G1();E40=N.enum(["inclusion","exclusion"]).describe("Tool selection mode: 'inclusion' = include selected (default), 'exclusion' = exclude selected"),CR6=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. With 'inclusion' mode: null = all tools included. With 'exclusion' mode: null = entire connection excluded"),selected_resources:N.array(N.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. With 'inclusion' mode: null = all resources included."),selected_prompts:N.array(N.string()).nullable().describe("Selected prompt names. With 'inclusion' mode: null = all prompts included. With 'exclusion' mode: null = entire connection excluded.")}),JW=N.object({id:N.string().describe("Unique identifier for the gateway"),title:N.string().describe("Human-readable name for the gateway"),description:N.string().nullable().describe("Description of the gateway"),icon:N.string().nullable().optional().describe("Icon URL for the gateway"),created_at:N.string().describe("When the gateway was created"),updated_at:N.string().describe("When the gateway was last updated"),created_by:N.string().describe("User ID who created the gateway"),updated_by:N.string().optional().describe("User ID who last updated the gateway"),organization_id:N.string().describe("Organization ID this gateway belongs to"),tool_selection_mode:E40.describe("Tool selection mode: 'inclusion' = include selected, 'exclusion' = exclude selected"),status:N.enum(["active","inactive"]).describe("Current status"),is_default:N.boolean().describe("Whether this is the Organization Agent for the organization"),connections:N.array(CR6).describe("Connections with their selected tools (behavior depends on tool_selection_mode)")}),$X1=N.object({title:N.string().min(1).max(255).describe("Name for the gateway"),description:N.string().nullable().optional().describe("Optional description"),tool_selection_mode:E40.optional().default("inclusion").describe("Tool selection mode (defaults to 'inclusion')"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),is_default:N.boolean().optional().default(!1).describe("Whether this is the Organization Agent for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).describe("Connections to include/exclude (can be empty for exclusion mode)")}),KX1=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),tool_selection_mode:E40.optional().describe("New tool selection mode"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),is_default:N.boolean().optional().describe("Set as Organization Agent for the organization"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools or full exclusion)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts or full exclusion)")})).optional().describe("New connections (replaces existing)")})});var IR6,RR6,j40;var HX1=o(()=>{G1();E6();_U();IR6=N.object({data:$X1.describe("Data for the new gateway")}),RR6=N.object({item:JW.describe("The created gateway entity")}),j40=B1({name:"COLLECTION_GATEWAY_CREATE",description:"Create a new MCP gateway in the organization",inputSchema:IR6,outputSchema:RR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=lQ(X);if(!J)throw Error("User ID required to create gateway");let G={title:Q.data.title,description:Q.data.description??null,toolSelectionMode:Q.data.tool_selection_mode??"inclusion",icon:Q.data.icon??null,status:Q.data.status,isDefault:Q.data.is_default??!1,connections:Q.data.connections.map((Z)=>({connectionId:Z.connection_id,selectedTools:Z.selected_tools??null,selectedResources:Z.selected_resources??null,selectedPrompts:Z.selected_prompts??null}))},W=await X.storage.gateways.create(Y.id,J,G);return{item:{id:W.id,title:W.title,description:W.description,icon:W.icon,organization_id:W.organizationId,tool_selection_mode:W.toolSelectionMode,status:W.status,is_default:W.isDefault,connections:W.connections.map((Z)=>({connection_id:Z.connectionId,selected_tools:Z.selectedTools,selected_resources:Z.selectedResources,selected_prompts:Z.selectedPrompts})),created_at:W.createdAt,updated_at:W.updatedAt,created_by:W.createdBy,updated_by:W.updatedBy??void 0}}}})});function SR6(Q){let X=[],Y=0;while(Y<Q.length){let J=Q[Y];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Y++}return X.join("")}function r$(Q){return typeof Q==="string"||typeof Q==="number"}function C40(Q,X){let Y=X.split("."),J=Q;for(let G of Y){if(J==null||typeof J!=="object")return;J=J[G]}return J}function vR6(Q,X){return Q.connections.some((Y)=>Y.connection_id===X)}function Cy(Q,X){if("conditions"in X){let{operator:$,conditions:K}=X;switch($){case"and":return K.every((H)=>Cy(Q,H));case"or":return K.some((H)=>Cy(Q,H));case"not":return!K.every((H)=>Cy(Q,H));default:return!0}}let{field:Y,operator:J,value:G}=X,W=Y.join(".");if(W==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return vR6(Q,G)}let Z=C40(Q,W);switch(J){case"eq":return Z===G;case"gt":return r$(Z)&&r$(G)&&Z>G;case"gte":return r$(Z)&&r$(G)&&Z>=G;case"lt":return r$(Z)&&r$(G)&&Z<G;case"lte":return r$(Z)&&r$(G)&&Z<=G;case"in":return Array.isArray(G)&&G.includes(Z);case"like":if(typeof Z!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let $=SR6(G);return new RegExp(`^${$}$`,"i").test(Z);case"contains":if(typeof Z!=="string"||typeof G!=="string")return!1;return Z.toLowerCase().includes(G.toLowerCase());default:return!0}}function kR6(Q,X){return[...Q].sort((Y,J)=>{for(let G of X){let W=G.field.join("."),Z=C40(Y,W),$=C40(J,W),K=0;if(Z==null&&$==null)continue;if(Z==null)K=G.nulls==="first"?-1:1;else if($==null)K=G.nulls==="first"?1:-1;else if(typeof Z==="string"&&typeof $==="string")K=Z.localeCompare($);else if(typeof Z==="number"&&typeof $==="number")K=Z-$;else K=String(Z).localeCompare(String($));if(K!==0)return G.direction==="desc"?-K:K}return 0})}var _R6,yR6,I40;var FX1=o(()=>{i$();E6();_U();_R6=tM,yR6=eM(JW),I40=B1({name:"COLLECTION_GATEWAY_LIST",description:"List all MCP gateways in the organization",inputSchema:_R6,outputSchema:yR6,handler:async(Q,X)=>{await X.access.check();let Y=L6(X),J=Q.where&&!("conditions"in Q.where)&&Q.where.field.join(".")==="connection_id"&&Q.where.operator==="eq"&&typeof Q.where.value==="string"?Q.where.value:void 0,W=(J?await X.storage.gateways.listByConnectionId(Y.id,J):await X.storage.gateways.list(Y.id)).map((V)=>({id:V.id,title:V.title,description:V.description,icon:V.icon,is_default:V.isDefault,organization_id:V.organizationId,tool_selection_mode:V.toolSelectionMode,status:V.status,connections:V.connections.map((q)=>({connection_id:q.connectionId,selected_tools:q.selectedTools,selected_resources:q.selectedResources,selected_prompts:q.selectedPrompts})),created_at:V.createdAt,updated_at:V.updatedAt,created_by:V.createdBy,updated_by:V.updatedBy??void 0}));if(Q.where)W=W.filter((V)=>Cy(V,Q.where));if(Q.orderBy&&Q.orderBy.length>0)W=kR6(W,Q.orderBy);let Z=W.length,$=Q.offset??0,K=Q.limit??100,H=W.slice($,$+K),F=$+K<Z;return{items:H,totalCount:Z,hasMore:F}}})});var bR6,fR6,R40;var VX1=o(()=>{G1();E6();_U();bR6=N.object({id:N.string().describe("ID of the gateway to retrieve")}),fR6=N.object({item:JW.nullable().describe("The retrieved gateway, or null if not found")}),R40=B1({name:"COLLECTION_GATEWAY_GET",description:"Get an MCP gateway by ID",inputSchema:bR6,outputSchema:fR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(J&&J.organizationId!==Y.id)return{item:null};if(!J)return{item:null};return{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt,updated_at:J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var hR6,xR6,S40;var qX1=o(()=>{G1();E6();_U();hR6=N.object({id:N.string().describe("ID of the gateway to update"),data:KX1.describe("Partial gateway data to update")}),xR6=N.object({item:JW.describe("The updated gateway entity")}),S40=B1({name:"COLLECTION_GATEWAY_UPDATE",description:"Update an MCP gateway",inputSchema:hR6,outputSchema:xR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=lQ(X);if(!J)throw Error("User ID required to update gateway");let G=await X.storage.gateways.findById(Q.id);if(!G)throw Error(`Gateway not found: ${Q.id}`);if(G.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);let W={};if(Q.data.title!==void 0)W.title=Q.data.title;if(Q.data.description!==void 0)W.description=Q.data.description;if(Q.data.tool_selection_mode!==void 0)W.toolSelectionMode=Q.data.tool_selection_mode;if(Q.data.icon!==void 0)W.icon=Q.data.icon;if(Q.data.status!==void 0)W.status=Q.data.status;if(Q.data.is_default!==void 0)W.isDefault=Q.data.is_default;if(Q.data.connections!==void 0)W.connections=Q.data.connections.map(($)=>({connectionId:$.connection_id,selectedTools:$.selected_tools??null,selectedResources:$.selected_resources??null,selectedPrompts:$.selected_prompts??null}));let Z=await X.storage.gateways.update(Q.id,J,W);return{item:{id:Z.id,title:Z.title,description:Z.description,icon:Z.icon,organization_id:Z.organizationId,tool_selection_mode:Z.toolSelectionMode,status:Z.status,is_default:Z.isDefault,connections:Z.connections.map(($)=>({connection_id:$.connectionId,selected_tools:$.selectedTools,selected_resources:$.selectedResources,selected_prompts:$.selectedPrompts})),created_at:Z.createdAt,updated_at:Z.updatedAt,created_by:Z.createdBy,updated_by:Z.updatedBy??void 0}}}})});var gR6,uR6,v40;var zX1=o(()=>{G1();E6();_U();gR6=N.object({id:N.string().describe("ID of the gateway to delete")}),uR6=N.object({item:JW.describe("The deleted gateway entity")}),v40=B1({name:"COLLECTION_GATEWAY_DELETE",description:"Delete an MCP gateway",inputSchema:gR6,outputSchema:uR6,handler:async(Q,X)=>{C1(X);let Y=L6(X);await X.access.check();let J=await X.storage.gateways.findById(Q.id);if(!J)throw Error(`Gateway not found: ${Q.id}`);if(J.organizationId!==Y.id)throw Error(`Gateway not found: ${Q.id}`);if(J.isDefault)throw Error("Cannot delete the Organization Agent. Set another Agent as the Organization Agent first.");return await X.storage.gateways.delete(Q.id),{item:{id:J.id,title:J.title,description:J.description,icon:J.icon,organization_id:J.organizationId,tool_selection_mode:J.toolSelectionMode,status:J.status,is_default:J.isDefault,connections:J.connections.map((G)=>({connection_id:G.connectionId,selected_tools:G.selectedTools,selected_resources:G.selectedResources,selected_prompts:G.selectedPrompts})),created_at:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updated_at:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt,created_by:J.createdBy,updated_by:J.updatedBy??void 0}}}})});var UX1=o(()=>{HX1();FX1();VX1();qX1();zX1()});var lR6,k40;var BX1=o(()=>{E6();G1();lR6=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.string(),N.unknown()).describe("Redacted tool input"),output:N.record(N.string(),N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),gatewayId:N.string().nullish().describe("Gateway ID if routed through a gateway"),properties:N.record(N.string(),N.string()).nullish().describe("Custom key-value metadata attached to the log")}),k40=B1({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),gatewayId:N.string().optional().describe("Filter by gateway ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(100).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination"),properties:N.record(N.string(),N.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:N.array(N.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:N.record(N.string(),N.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:N.object({logs:N.array(lR6).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Q,X)=>{let Y=L6(X),G=Q.properties||Q.propertyKeys||Q.propertyPatterns?{properties:Q.properties,propertyKeys:Q.propertyKeys,propertyPatterns:Q.propertyPatterns}:void 0,W={organizationId:Y.id,connectionId:Q.connectionId,gatewayId:Q.gatewayId,toolName:Q.toolName,isError:Q.isError,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0,limit:Q.limit,offset:Q.offset,propertyFilters:G},Z=await X.storage.monitoring.query(W);return{logs:Z.logs.map(($)=>({...$,timestamp:$.timestamp instanceof Date?$.timestamp.toISOString():$.timestamp})),total:Z.total,offset:Q.offset,limit:Q.limit}}})});var _40;var DX1=o(()=>{E6();G1();_40=B1({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Q,X)=>{let J={organizationId:L6(X).id,startDate:Q.startDate?new Date(Q.startDate):void 0,endDate:Q.endDate?new Date(Q.endDate):void 0},G=await X.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var NX1=o(()=>{BX1();DX1()});var y40;var OX1=o(()=>{G1();E6();y40=B1({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional()}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=lQ(X);if(!Y)throw Error("User ID required to create organization");let J=await X.boundAuth.organization.create({name:Q.name,slug:Q.slug,metadata:Q.description?{description:Q.description}:void 0,userId:Y});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var b40;var LX1=o(()=>{G1();E6();b40=B1({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=lQ(X),J=Q.userId||Y;if(!J)throw Error("User ID required to list organizations");return{organizations:(await X.boundAuth.organization.list(J)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var f40;var wX1=o(()=>{G1();E6();f40=B1({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=await X.boundAuth.organization.get();if(!Y)throw Error("No active organization found");return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}}})});var h40;var MX1=o(()=>{G1();E6();h40=B1({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y={};if(Q.name)Y.name=Q.name;if(Q.slug)Y.slug=Q.slug;if(Q.description)Y.metadata={description:Q.description};let J=await X.boundAuth.organization.update({organizationId:Q.id,data:Y});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var x40;var PX1=o(()=>{G1();E6();x40=B1({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Q,X)=>{return C1(X),await X.access.check(),await X.boundAuth.organization.delete(Q.id),{success:!0,id:Q.id}}})});var zP;var g40=o(()=>{G1();zP=N.object({title:N.string(),url:N.string(),icon:N.string()})});var u40;var TX1=o(()=>{G1();E6();g40();u40=B1({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(zP).nullable().optional(),createdAt:N.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.storage.organizationSettings.get(Y);if(!J)return{organizationId:Y};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var m40;var AX1=o(()=>{G1();E6();g40();m40=B1({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(zP).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(zP).nullable().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{if(C1(X),await X.access.check(),X.organization&&X.organization.id!==Q.organizationId)throw Error("Cannot update settings for a different organization");let Y=await X.storage.organizationSettings.upsert(Q.organizationId,{sidebar_items:Q.sidebar_items});return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});var l40;var EX1=o(()=>{G1();E6();l40=B1({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.addMember({organizationId:Y,userId:Q.userId,role:Q.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var d40;var jX1=o(()=>{G1();E6();d40=B1({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:Y,memberIdOrEmail:Q.memberIdOrEmail}),{success:!0,memberIdOrEmail:Q.memberIdOrEmail}}})});var p40;var CX1=o(()=>{G1();E6();p40=B1({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.listMembers({organizationId:Y,limit:Q.limit,offset:Q.offset});return{members:(Array.isArray(J)?J:[]).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var c40;var IX1=o(()=>{G1();E6();c40=B1({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Q,X)=>{C1(X),await X.access.check();let Y=Q.organizationId||X.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.updateMemberRole({organizationId:Y,memberId:Q.memberId,role:Q.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var RX1=o(()=>{OX1();LX1();wX1();MX1();PX1();TX1();AX1();EX1();jX1();CX1();IX1()});var cR6,nR6,n40;var SX1=o(()=>{G1();E6();cR6=N.object({id:N.string().min(1)}),nR6=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),n40=B1({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:cR6,outputSchema:nR6,handler:async(Q,X)=>{await X.access.check(),C1(X);let Y=lQ(X);if(!Y)throw Error("Authentication required");let J=await X.storage.users.findById(Q.id,Y);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var vX1=o(()=>{SX1()});var _X1={};$8(_X1,{managementMCP:()=>i40,ALL_TOOLS:()=>kX1});var kX1,i40=(Q)=>{let X=kX1.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,outputSchema:J.outputSchema,handler:async(G)=>{return Q.access.setToolName(J.name),await J.execute(G,Q)}}));return nQ1({name:"mcp-mesh-management",version:"1.0.0"}).withTools(X).build()};var a40=o(()=>{iQ1();$91();n91();o91();ZX1();UX1();NX1();RX1();vX1();kX1=[y40,b40,f40,h40,x40,u40,m40,l40,d40,p40,c40,Q40,V40,q40,B40,D40,N40,j40,I40,R40,S40,v40,r91,k40,_40,o60,t60,e60,s60,O40,L40,w40,M40,P40,T40,A40,n40]});var QF,K80,xy,XF,wP;var gy=o(()=>{QF={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},K80={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},xy={Pending:0,Fulfilled:1,Rejected:2},XF={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},wP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function hU(...Q){U80&&console.log("quickjs-emscripten:",...Q)}function*pY1(Q){return yield Q}function hS6(Q){return pY1(D80(Q))}function kY1(Q,X){return(...Y)=>{let J=X.call(Q,B80,...Y);return D80(J)}}function xS6(Q,X){let Y=X.call(Q,B80);return D80(Y)}function D80(Q){function X(Y){return Y.done?Y.value:Y.value instanceof Promise?Y.value.then((J)=>X(Q.next(J)),(J)=>X(Q.throw(J))):X(Q.next(Y.value))}return X(Q.next())}function H80(Q,X){let Y;try{Q.dispose()}catch(J){Y=J}if(X&&Y)throw Object.assign(X,{message:`${X.message}
|
|
256
|
+
Then, failed to dispose scope: ${Y.message}`,disposeError:Y}),X;if(X||Y)throw X||Y}function cY1(Q){let X=Q?Array.from(Q):[];function Y(){return X.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return X.some((G)=>G.alive)}return Object.defineProperty(X,q80,{configurable:!0,enumerable:!1,value:Y}),Object.defineProperty(X,"dispose",{configurable:!0,enumerable:!1,value:Y}),Object.defineProperty(X,"alive",{configurable:!0,enumerable:!1,get:J}),X}function uy(Q){return!!(Q&&(typeof Q=="object"||typeof Q=="function")&&("alive"in Q)&&typeof Q.alive=="boolean"&&("dispose"in Q)&&typeof Q.dispose=="function")}function gS6(Q){if(!Q)return 0;let X=0;for(let[Y,J]of Object.entries(Q)){if(!(Y in K80))throw new mY1(Y);J&&(X|=K80[Y])}return X}function uS6(Q){if(typeof Q=="number")return Q;if(Q===void 0)return 0;let{type:X,strict:Y,strip:J,compileOnly:G,backtraceBarrier:W}=Q,Z=0;return X==="global"&&(Z|=QF.JS_EVAL_TYPE_GLOBAL),X==="module"&&(Z|=QF.JS_EVAL_TYPE_MODULE),Y&&(Z|=QF.JS_EVAL_FLAG_STRICT),J&&(Z|=QF.JS_EVAL_FLAG_STRIP),G&&(Z|=QF.JS_EVAL_FLAG_COMPILE_ONLY),W&&(Z|=QF.JS_EVAL_FLAG_BACKTRACE_BARRIER),Z}function mS6(Q){if(typeof Q=="number")return Q;if(Q===void 0)return 0;let{strings:X,symbols:Y,quickjsPrivate:J,onlyEnumerable:G,numbers:W,numbersAsStrings:Z}=Q,$=0;return X&&($|=XF.JS_GPN_STRING_MASK),Y&&($|=XF.JS_GPN_SYMBOL_MASK),J&&($|=XF.JS_GPN_PRIVATE_MASK),G&&($|=XF.JS_GPN_ENUM_ONLY),W&&($|=XF.QTS_GPN_NUMBER_MASK),Z&&($|=XF.QTS_STANDARD_COMPLIANT_NUMBER),$}function lS6(...Q){let X=[];for(let Y of Q)Y!==void 0&&(X=X.concat(Y));return X}function w80(Q,X){X.interruptHandler&&Q.setInterruptHandler(X.interruptHandler),X.maxStackSizeBytes!==void 0&&Q.setMaxStackSize(X.maxStackSizeBytes),X.memoryLimitBytes!==void 0&&Q.setMemoryLimit(X.memoryLimitBytes)}function M80(Q,X){X.moduleLoader&&Q.setModuleLoader(X.moduleLoader),X.shouldInterrupt&&Q.setInterruptHandler(X.shouldInterrupt),X.memoryLimitBytes!==void 0&&Q.setMemoryLimit(X.memoryLimitBytes),X.maxStackSizeBytes!==void 0&&Q.setMaxStackSize(X.maxStackSizeBytes)}var bS6,fS6=(Q,X)=>{for(var Y in X)bS6(Q,Y,{get:X[Y],enumerable:!0})},U80=!1,yY1,F80,bY1,V80,fY1,hY1,xY1,gY1,uY1,mY1,lY1,dY1,B80,g7,q80,_Y1,u9,s$,z80,k5,N80,nY1,iY1,YF,aY1,rY1=class{constructor(Q){this.module=Q}toPointerArray(Q){let X=new Int32Array(Q.map((G)=>G.value)),Y=X.length*X.BYTES_PER_ELEMENT,J=this.module._malloc(Y);return new Uint8Array(this.module.HEAPU8.buffer,J,Y).set(new Uint8Array(X.buffer)),new u9(J,void 0,(G)=>this.module._free(G))}newTypedArray(Q,X){let Y=new Q(Array(X).fill(0)),J=Y.length*Y.BYTES_PER_ELEMENT,G=this.module._malloc(J),W=new Q(this.module.HEAPU8.buffer,G,X);return W.set(Y),new u9({typedArray:W,ptr:G},void 0,(Z)=>this.module._free(Z.ptr))}newMutablePointerArray(Q){return this.newTypedArray(Int32Array,Q)}newHeapCharPointer(Q){let X=this.module.lengthBytesUTF8(Q),Y=X+1,J=this.module._malloc(Y);return this.module.stringToUTF8(Q,J,Y),new u9({ptr:J,strlen:X},void 0,(G)=>this.module._free(G.ptr))}newHeapBufferPointer(Q){let X=Q.byteLength,Y=this.module._malloc(X);return this.module.HEAPU8.set(Q,Y),new u9({pointer:Y,numBytes:X},void 0,(J)=>this.module._free(J.pointer))}consumeHeapCharPointer(Q){let X=this.module.UTF8ToString(Q);return this.module._free(Q),X}},rg4,O80,dS6,pS6,oY1,sY1,cS6=class{constructor(Q){this.callFunction=Q.callFunction,this.shouldInterrupt=Q.shouldInterrupt,this.loadModuleSource=Q.loadModuleSource,this.normalizeModule=Q.normalizeModule}},L80=class{constructor(Q){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new cS6({callFunction:(X,Y,J,G,W,Z)=>this.handleAsyncify(X,()=>{try{let $=this.contextCallbacks.get(Y);if(!$)throw Error(`QuickJSContext(ctx = ${Y}) not found for C function call "${Z}"`);return $.callFunction(Y,J,G,W,Z)}catch($){return console.error("[C to host error: returning null]",$),0}}),shouldInterrupt:(X,Y)=>this.handleAsyncify(X,()=>{try{let J=this.runtimeCallbacks.get(Y);if(!J)throw Error(`QuickJSRuntime(rt = ${Y}) not found for C interrupt`);return J.shouldInterrupt(Y)}catch(J){return console.error("[C to host interrupt: returning error]",J),1}}),loadModuleSource:(X,Y,J,G)=>this.handleAsyncify(X,()=>{try{let W=this.runtimeCallbacks.get(Y);if(!W)throw Error(`QuickJSRuntime(rt = ${Y}) not found for C module loader`);let Z=W.loadModuleSource;if(!Z)throw Error(`QuickJSRuntime(rt = ${Y}) does not support module loading`);return Z(Y,J,G)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}}),normalizeModule:(X,Y,J,G,W)=>this.handleAsyncify(X,()=>{try{let Z=this.runtimeCallbacks.get(Y);if(!Z)throw Error(`QuickJSRuntime(rt = ${Y}) not found for C module loader`);let $=Z.normalizeModule;if(!$)throw Error(`QuickJSRuntime(rt = ${Y}) does not support module loading`);return $(Y,J,G,W)}catch(Z){return console.error("[C to host module loader error: returning null]",Z),0}})}),this.module=Q,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(Q,X){this.runtimeCallbacks.set(Q,X)}deleteRuntime(Q){this.runtimeCallbacks.delete(Q)}setContextCallbacks(Q,X){this.contextCallbacks.set(Q,X)}deleteContext(Q){this.contextCallbacks.delete(Q)}handleAsyncify(Q,X){if(Q)return Q.handleSleep((J)=>{try{let G=X();if(!(G instanceof Promise)){hU("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new hY1(`Already suspended at: ${this.suspended.stack}
|
|
257
|
+
Attempted to suspend at:`);this.suspended=new xY1(`(${this.suspendedCount++})`),hU("asyncify.handleSleep: suspending:",this.suspended),G.then((W)=>{this.suspended=void 0,hU("asyncify.handleSleep: resolved:",W),J(W)},(W)=>{hU("asyncify.handleSleep: rejected:",W),console.error("QuickJS: cannot handle error in suspended function",W),this.suspended=void 0})}catch(G){throw hU("asyncify.handleSleep: error:",G),this.suspended=void 0,G}});let Y=X();if(Y instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return Y}},P80=class{constructor(Q,X){this.module=Q,this.ffi=X,this.callbacks=new L80(Q)}newRuntime(Q={}){let X=new u9(this.ffi.QTS_NewRuntime(),void 0,(J)=>{this.callbacks.deleteRuntime(J),this.ffi.QTS_FreeRuntime(J)}),Y=new sY1({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:X});return w80(Y,Q),Q.moduleLoader&&Y.setModuleLoader(Q.moduleLoader),Y}newContext(Q={}){let X=this.newRuntime(),Y=X.newContext({...Q,ownedLifetimes:lS6(X,Q.ownedLifetimes)});return X.context=Y,Y}evalCode(Q,X={}){return k5.withScope((Y)=>{let J=Y.manage(this.newContext());M80(J.runtime,X);let G=J.evalCode(Q,"eval.js");if(X.memoryLimitBytes!==void 0&&J.runtime.setMemoryLimit(-1),G.error)throw J.dump(Y.manage(G.error));return J.dump(Y.manage(G.value))})}getWasmMemory(){let Q=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!Q)throw Error("Variant does not support getting WebAssembly.Memory");return Q}getFFI(){return this.ffi}};var T80=o(()=>{gy();gy();bS6=Object.defineProperty;yY1={};fS6(yY1,{QuickJSAsyncifyError:()=>hY1,QuickJSAsyncifySuspended:()=>xY1,QuickJSEmptyGetOwnPropertyNames:()=>dY1,QuickJSEmscriptenModuleError:()=>uY1,QuickJSMemoryLeakDetected:()=>gY1,QuickJSNotImplemented:()=>fY1,QuickJSPromisePending:()=>lY1,QuickJSUnknownIntrinsic:()=>mY1,QuickJSUnwrapError:()=>F80,QuickJSUseAfterFree:()=>V80,QuickJSWrongOwner:()=>bY1});F80=class extends Error{constructor(Q,X){let Y=typeof Q=="object"&&Q&&"message"in Q?String(Q.message):String(Q);super(Y);this.cause=Q,this.context=X,this.name="QuickJSUnwrapError"}},bY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},V80=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},fY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},hY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},xY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},gY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},uY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},mY1=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},lY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},dY1=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}};B80=pY1;B80.of=hS6;g7=class{[Symbol.dispose](){return this.dispose()}},q80=Symbol.dispose??Symbol.for("Symbol.dispose"),_Y1=g7.prototype;_Y1[q80]||(_Y1[q80]=function(){return this.dispose()});u9=class Q extends g7{constructor(X,Y,J,G){super();this._value=X,this.copier=Y,this.disposer=J,this._owner=G,this._alive=!0,this._constructorStack=U80?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 Q(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(X){this.assertAlive();let Y=X(this);return this.dispose(),Y}map(X){return this.assertAlive(),X(this)}tap(X){return X(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new V80(`Lifetime not alive
|
|
258
258
|
${this._constructorStack}
|
|
259
|
-
Lifetime used`):new q80("Lifetime not alive")}},s$=class extends u9{constructor(Q,X){super(Q,void 0,void 0,X)}get dupable(){return!0}dup(){return this}dispose(){}},U80=class extends u9{constructor(Q,X,Y,J){super(Q,X,Y,J)}dispose(){this._alive=!1}};k5=class Q extends g7{constructor(){super(...arguments);this._disposables=new u9(new Set),this.manage=(X)=>(this._disposables.value.add(X),X)}static withScope(X){let Y=new Q,J;try{return X(Y)}catch(G){throw J=G,G}finally{F80(Y,J)}}static withScopeMaybeAsync(X,Y){return xS6(void 0,function*(J){let G=new Q,W;try{return yield*J.of(Y.call(X,J,G))}catch(Z){throw W=Z,Z}finally{F80(G,W)}})}static async withScopeAsync(X){let Y=new Q,J;try{return await X(Y)}catch(G){throw J=G,G}finally{F80(Y,J)}}get alive(){return this._disposables.alive}dispose(){let X=Array.from(this._disposables.value.values()).reverse();for(let Y of X)Y.alive&&Y.dispose();this._disposables.dispose()}};O80=class Q extends g7{static success(X){return new nY1(X)}static fail(X,Y){return new iY1(X,Y)}static is(X){return X instanceof Q}},nY1=class extends O80{constructor(Q){super();this.value=Q}get alive(){return uy(this.value)?this.value.alive:!0}dispose(){uy(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(Q){return this.value}},iY1=class extends O80{constructor(Q,X){super();this.error=Q,this.onUnwrap=X}get alive(){return uy(this.error)?this.error.alive:!0}dispose(){uy(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(Q){return Q}},YF=O80,aY1=class extends g7{constructor(Q){super();this.resolve=(X)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(X)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=Q.context,this.owner=Q.context.runtime,this.handle=Q.promiseHandle,this.settled=new Promise((X)=>{this.onSettled=X}),this.resolveHandle=Q.resolveHandle,this.rejectHandle=Q.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()}},rg4=Symbol("Unstable"),L80=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});dS6=class extends g7{constructor(Q,X){super();this.handle=Q,this.context=X,this._isDone=!1,this.owner=X.runtime}[Symbol.iterator](){return this}next(Q){if(!this.alive||this._isDone)return{done:!0,value:void 0};let X=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(X,Q)}return(Q){if(!this.alive)return{done:!0,value:void 0};let X=this.context.getProp(this.handle,"return");if(X===this.context.undefined&&Q===void 0)return this.dispose(),{done:!0,value:void 0};let Y=this.callIteratorMethod(X,Q);return X.dispose(),this.dispose(),Y}throw(Q){if(!this.alive)return{done:!0,value:void 0};let X=Q instanceof u9?Q:this.context.newError(Q),Y=this.context.getProp(this.handle,"throw"),J=this.callIteratorMethod(Y,Q);return X.alive&&X.dispose(),Y.dispose(),this.dispose(),J}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Q,X){let Y=X?this.context.callFunction(Q,this.handle,X):this.context.callFunction(Q,this.handle);if(Y.error)return this.dispose(),{value:Y};let J=this.context.getProp(Y.value,"done").consume((W)=>this.context.dump(W));if(J)return Y.value.dispose(),this.dispose(),{done:J,value:void 0};let G=this.context.getProp(Y.value,"value");return Y.value.dispose(),{value:YF.success(G),done:J}}},pS6=class extends rY1{constructor(Q){super(Q.module);this.scope=new k5,this.copyJSValue=(X)=>this.ffi.QTS_DupValuePointer(this.ctx.value,X),this.freeJSValue=(X)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,X)},Q.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.owner=Q.owner,this.module=Q.module,this.ffi=Q.ffi,this.rt=Q.rt,this.ctx=this.scope.manage(Q.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(Q){return this.scope.manage(Q)}consumeJSCharPointer(Q){let X=this.module.UTF8ToString(Q);return this.ffi.QTS_FreeCString(this.ctx.value,Q),X}heapValueHandle(Q){return new u9(Q,this.copyJSValue,this.freeJSValue,this.owner)}staticHeapValueHandle(Q){return this.manage(this.heapValueHandle(Q)),new s$(Q,this.owner)}},oY1=class extends g7{constructor(Q){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.fnNextId=-32768,this.fnMaps=new Map,this.cToHostCallbacks={callFunction:(X,Y,J,G,W)=>{if(X!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let Z=this.getFunction(W);if(!Z)throw Error(`QuickJSContext had no callback with id ${W}`);return k5.withScopeMaybeAsync(this,function*($,K){let H=K.manage(new U80(Y,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),F=Array(J);for(let V=0;V<J;V++){let q=this.ffi.QTS_ArgvGetJSValueConstPointer(G,V);F[V]=K.manage(new U80(q,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let V=yield*$(Z.apply(H,F));if(V){if("error"in V&&V.error)throw this.runtime.debugLog("throw error",V.error),V.error;let q=K.manage(V instanceof u9?V:V.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,q.value)}return 0}catch(V){return this.errorToHandle(V).consume((q)=>this.ffi.QTS_Throw(this.ctx.value,q.value))}})}},this.runtime=Q.runtime,this.module=Q.module,this.ffi=Q.ffi,this.rt=Q.rt,this.ctx=Q.ctx,this.memory=new pS6({...Q,owner:this.runtime}),Q.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 Q=this.ffi.QTS_GetUndefined();return this._undefined=new s$(Q)}get null(){if(this._null)return this._null;let Q=this.ffi.QTS_GetNull();return this._null=new s$(Q)}get true(){if(this._true)return this._true;let Q=this.ffi.QTS_GetTrue();return this._true=new s$(Q)}get false(){if(this._false)return this._false;let Q=this.ffi.QTS_GetFalse();return this._false=new s$(Q)}get global(){if(this._global)return this._global;let Q=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(Q),this._global}newNumber(Q){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,Q))}newString(Q){let X=this.memory.newHeapCharPointer(Q).consume((Y)=>this.ffi.QTS_NewString(this.ctx.value,Y.value.ptr));return this.memory.heapValueHandle(X)}newUniqueSymbol(Q){let X=(typeof Q=="symbol"?Q.description:Q)??"",Y=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,0));return this.memory.heapValueHandle(Y)}newSymbolFor(Q){let X=(typeof Q=="symbol"?Q.description:Q)??"",Y=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,1));return this.memory.heapValueHandle(Y)}getWellKnownSymbol(Q){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,Q)}newBigInt(Q){if(!this._BigInt){let J=this.getProp(this.global,"BigInt");this.memory.manage(J),this._BigInt=new s$(J.value,this.runtime)}let X=this._BigInt,Y=String(Q);return this.newString(Y).consume((J)=>this.unwrapResult(this.callFunction(X,this.undefined,J)))}newObject(Q){Q&&this.runtime.assertOwned(Q);let X=Q?this.ffi.QTS_NewObjectProto(this.ctx.value,Q.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(X)}newArray(){let Q=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(Q)}newArrayBuffer(Q){let X=new Uint8Array(Q),Y=this.memory.newHeapBufferPointer(X),J=this.ffi.QTS_NewArrayBuffer(this.ctx.value,Y.value.pointer,X.length);return this.memory.heapValueHandle(J)}newPromise(Q){let X=k5.withScope((Y)=>{let J=Y.manage(this.memory.newMutablePointerArray(2)),G=this.ffi.QTS_NewPromiseCapability(this.ctx.value,J.value.ptr),W=this.memory.heapValueHandle(G),[Z,$]=Array.from(J.value.typedArray).map((K)=>this.memory.heapValueHandle(K));return new aY1({context:this,promiseHandle:W,resolveHandle:Z,rejectHandle:$})});return Q&&typeof Q=="function"&&(Q=new Promise(Q)),Q&&Promise.resolve(Q).then(X.resolve,(Y)=>Y instanceof u9?X.reject(Y):this.newError(Y).consume(X.reject)),X}newFunction(Q,X){let Y=++this.fnNextId;return this.setFunction(Y,X),this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,Y,Q))}newError(Q){let X=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return Q&&typeof Q=="object"?(Q.name!==void 0&&this.newString(Q.name).consume((Y)=>this.setProp(X,"name",Y)),Q.message!==void 0&&this.newString(Q.message).consume((Y)=>this.setProp(X,"message",Y))):typeof Q=="string"?this.newString(Q).consume((Y)=>this.setProp(X,"message",Y)):Q!==void 0&&this.newString(String(Q)).consume((Y)=>this.setProp(X,"message",Y)),X}typeof(Q){return this.runtime.assertOwned(Q),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,Q.value))}getNumber(Q){return this.runtime.assertOwned(Q),this.ffi.QTS_GetFloat64(this.ctx.value,Q.value)}getString(Q){return this.runtime.assertOwned(Q),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,Q.value))}getSymbol(Q){this.runtime.assertOwned(Q);let X=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,Q.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,Q.value)?Symbol.for(X):Symbol(X)}getBigInt(Q){this.runtime.assertOwned(Q);let X=this.getString(Q);return BigInt(X)}getArrayBuffer(Q){this.runtime.assertOwned(Q);let X=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,Q.value),Y=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Q.value);if(!Y)throw Error("Couldn't allocate memory to get ArrayBuffer");return new u9(this.module.HEAPU8.subarray(Y,Y+X),void 0,()=>this.module._free(Y))}getPromiseState(Q){this.runtime.assertOwned(Q);let X=this.ffi.QTS_PromiseState(this.ctx.value,Q.value);if(X<0)return{type:"fulfilled",value:Q,notAPromise:!0};if(X===xy.Pending)return{type:"pending",get error(){return new lY1("Cannot unwrap a pending promise")}};let Y=this.ffi.QTS_PromiseResult(this.ctx.value,Q.value),J=this.memory.heapValueHandle(Y);if(X===xy.Fulfilled)return{type:"fulfilled",value:J};if(X===xy.Rejected)return{type:"rejected",error:J};throw J.dispose(),Error(`Unknown JSPromiseStateEnum: ${X}`)}resolvePromise(Q){this.runtime.assertOwned(Q);let X=k5.withScope((Y)=>{let J=Y.manage(this.getProp(this.global,"Promise")),G=Y.manage(this.getProp(J,"resolve"));return this.callFunction(G,J,Q)});return X.error?Promise.resolve(X):new Promise((Y)=>{k5.withScope((J)=>{let G=J.manage(this.newFunction("resolve",(K)=>{Y(this.success(K&&K.dup()))})),W=J.manage(this.newFunction("reject",(K)=>{Y(this.fail(K&&K.dup()))})),Z=J.manage(X.value),$=J.manage(this.getProp(Z,"then"));this.callFunction($,Z,G,W).unwrap().dispose()})})}isEqual(Q,X,Y=wP.IsStrictlyEqual){if(Q===X)return!0;this.runtime.assertOwned(Q),this.runtime.assertOwned(X);let J=this.ffi.QTS_IsEqual(this.ctx.value,Q.value,X.value,Y);if(J===-1)throw new fY1("WASM variant does not expose equality");return!!J}eq(Q,X){return this.isEqual(Q,X,wP.IsStrictlyEqual)}sameValue(Q,X){return this.isEqual(Q,X,wP.IsSameValue)}sameValueZero(Q,X){return this.isEqual(Q,X,wP.IsSameValueZero)}getProp(Q,X){this.runtime.assertOwned(Q);let Y;return typeof X=="number"&&X>=0?Y=this.ffi.QTS_GetPropNumber(this.ctx.value,Q.value,X):Y=this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_GetProp(this.ctx.value,Q.value,J.value)),this.memory.heapValueHandle(Y)}getLength(Q){if(this.runtime.assertOwned(Q),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,Q.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(Q,X={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(Q),Q.value;let Y=mS6(X);if(Y===0)throw new dY1("No options set, will return an empty array");return k5.withScope((J)=>{let G=J.manage(this.memory.newMutablePointerArray(1)),W=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,G.value.ptr,this.uint32Out.value.ptr,Q.value,Y);if(W)return this.fail(this.memory.heapValueHandle(W));let Z=this.uint32Out.value.typedArray[0],$=G.value.typedArray[0],K=new Uint32Array(this.module.HEAP8.buffer,$,Z),H=Array.from(K).map((F)=>this.memory.heapValueHandle(F));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,$),this.success(cY1(H))})}getIterator(Q){let X=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return k5.withScope((Y)=>{let J=Y.manage(this.getProp(Q,X)),G=this.callFunction(J,Q);return G.error?G:this.success(new dS6(G.value,this))})}setProp(Q,X,Y){this.runtime.assertOwned(Q),this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_SetProp(this.ctx.value,Q.value,J.value,Y.value))}defineProp(Q,X,Y){this.runtime.assertOwned(Q),k5.withScope((J)=>{let G=J.manage(this.borrowPropertyKey(X)),W=Y.value||this.undefined,Z=!!Y.configurable,$=!!Y.enumerable,K=!!Y.value,H=Y.get?J.manage(this.newFunction(Y.get.name,Y.get)):this.undefined,F=Y.set?J.manage(this.newFunction(Y.set.name,Y.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Q.value,G.value,W.value,H.value,F.value,Z,$,K)})}callFunction(Q,X,...Y){this.runtime.assertOwned(Q);let J,G=Y[0];G===void 0||Array.isArray(G)?J=G??[]:J=Y;let W=this.memory.toPointerArray(J).consume(($)=>this.ffi.QTS_Call(this.ctx.value,Q.value,X.value,J.length,$.value)),Z=this.ffi.QTS_ResolveException(this.ctx.value,W);return Z?(this.ffi.QTS_FreeValuePointer(this.ctx.value,W),this.fail(this.memory.heapValueHandle(Z))):this.success(this.memory.heapValueHandle(W))}callMethod(Q,X,Y=[]){return this.getProp(Q,X).consume((J)=>this.callFunction(J,Q,Y))}evalCode(Q,X="eval.js",Y){let J=Y===void 0?1:0,G=uS6(Y),W=this.memory.newHeapCharPointer(Q).consume(($)=>this.ffi.QTS_Eval(this.ctx.value,$.value.ptr,$.value.strlen,X,J,G)),Z=this.ffi.QTS_ResolveException(this.ctx.value,W);return Z?(this.ffi.QTS_FreeValuePointer(this.ctx.value,W),this.fail(this.memory.heapValueHandle(Z))):this.success(this.memory.heapValueHandle(W))}throw(Q){return this.errorToHandle(Q).consume((X)=>this.ffi.QTS_Throw(this.ctx.value,X.value))}borrowPropertyKey(Q){return typeof Q=="number"?this.newNumber(Q):typeof Q=="string"?this.newString(Q):new s$(Q.value,this.runtime)}getMemory(Q){if(Q===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(Q){this.runtime.assertOwned(Q);let X=this.typeof(Q);if(X==="string")return this.getString(Q);if(X==="number")return this.getNumber(Q);if(X==="bigint")return this.getBigInt(Q);if(X==="undefined")return;if(X==="symbol")return this.getSymbol(Q);let Y=this.getPromiseState(Q);if(Y.type==="fulfilled"&&!Y.notAPromise)return Q.dispose(),{type:Y.type,value:Y.value.consume(this.dump)};if(Y.type==="pending")return Q.dispose(),{type:Y.type};if(Y.type==="rejected")return Q.dispose(),{type:Y.type,error:Y.error.consume(this.dump)};let J=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,Q.value));try{return JSON.parse(J)}catch{return J}}unwrapResult(Q){if(Q.error){let X="context"in Q.error?Q.error.context:this,Y=Q.error.consume((J)=>this.dump(J));if(Y&&typeof Y=="object"&&typeof Y.message=="string"){let{message:J,name:G,stack:W,...Z}=Y,$=new V80(Y,X);typeof G=="string"&&($.name=Y.name),$.message=J;let K=$.stack;throw typeof W=="string"&&($.stack=`${G}: ${J}
|
|
260
|
-
${Y.stack}Host: ${K}`),Object.assign($,Z),$}throw new V80(Y)}return Q.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(Q){let X=Q>>8,Y=this.fnMaps.get(X);if(Y)return Y.get(Q)}setFunction(Q,X){let Y=Q>>8,J=this.fnMaps.get(Y);return J||(J=new Map,this.fnMaps.set(Y,J)),J.set(Q,X)}errorToHandle(Q){return Q instanceof u9?Q:this.newError(Q)}encodeBinaryJSON(Q){let X=this.ffi.QTS_bjson_encode(this.ctx.value,Q.value);return this.memory.heapValueHandle(X)}decodeBinaryJSON(Q){let X=this.ffi.QTS_bjson_decode(this.ctx.value,Q.value);return this.memory.heapValueHandle(X)}success(Q){return YF.success(Q)}fail(Q){return YF.fail(Q,(X)=>this.unwrapResult(X))}},sY1=class extends g7{constructor(Q){super();this.scope=new k5,this.contextMap=new Map,this._debugMode=!1,this.cToHostCallbacks={shouldInterrupt:(X)=>{if(X!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let Y=this.interruptHandler;if(!Y)throw Error("QuickJSContext had no interrupt handler");return Y(this)?1:0},loadModuleSource:kY1(this,function*(X,Y,J,G){let W=this.moduleLoader;if(!W)throw Error("Runtime has no module loader");if(Y!==this.rt.value)throw Error("Runtime pointer mismatch");let Z=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let $=yield*X(W(G,Z));if(typeof $=="object"&&"error"in $&&$.error)throw this.debugLog("cToHostLoadModule: loader returned error",$.error),$.error;let K=typeof $=="string"?$:("value"in $)?$.value:$;return this.memory.newHeapCharPointer(K).value.ptr}catch($){return this.debugLog("cToHostLoadModule: caught error",$),Z.throw($),0}}),normalizeModule:kY1(this,function*(X,Y,J,G,W){let Z=this.moduleNormalizer;if(!Z)throw Error("Runtime has no module normalizer");if(Y!==this.rt.value)throw Error("Runtime pointer mismatch");let $=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let K=yield*X(Z(G,W,$));if(typeof K=="object"&&"error"in K&&K.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",K.error),K.error;let H=typeof K=="string"?K:K.value;return $.getMemory(this.rt.value).newHeapCharPointer(H).value.ptr}catch(K){return this.debugLog("normalizeModule: caught error",K),$.throw(K),0}})},Q.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.module=Q.module,this.memory=new rY1(this.module),this.ffi=Q.ffi,this.rt=Q.rt,this.callbacks=Q.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),B80&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(Q={}){let X=gS6(Q.intrinsics),Y=new u9(Q.contextPointer||this.ffi.QTS_NewContext(this.rt.value,X),void 0,(G)=>{this.contextMap.delete(G),this.callbacks.deleteContext(G),this.ffi.QTS_FreeContext(G)}),J=new oY1({module:this.module,ctx:Y,ffi:this.ffi,rt:this.rt,ownedLifetimes:Q.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(Y.value,J),J}setModuleLoader(Q,X){this.moduleLoader=Q,this.moduleNormalizer=X,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(Q){let X=this.interruptHandler;this.interruptHandler=Q,X||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(Q=-1){let X=this.memory.newMutablePointerArray(1),Y=this.ffi.QTS_ExecutePendingJob(this.rt.value,Q??-1,X.value.ptr),J=X.value.typedArray[0];if(X.dispose(),J===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,Y),YF.success(0);let G=this.contextMap.get(J)??this.newContext({contextPointer:J}),W=G.getMemory(this.rt.value).heapValueHandle(Y);if(G.typeof(W)==="number"){let Z=G.getNumber(W);return W.dispose(),YF.success(Z)}else{let Z=Object.assign(W,{context:G});return YF.fail(Z,($)=>G.unwrapResult($))}}setMemoryLimit(Q){if(Q<0&&Q!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,Q)}computeMemoryUsage(){let Q=this.getSystemContext().getMemory(this.rt.value);return Q.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,Q.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(Q){if(Q<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,Q)}assertOwned(Q){if(Q.owner&&Q.owner.rt!==this.rt)throw new bY1(`Handle is not owned by this runtime: ${Q.owner.rt.value} != ${this.rt.value}`)}setDebugMode(Q){this._debugMode=Q,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,Q?1:0)}isDebugMode(){return this._debugMode}debugLog(...Q){this._debugMode&&console.log("quickjs-emscripten:",...Q)}[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 tY1={};$8(tY1,{applyModuleEvalRuntimeOptions:()=>P80,applyBaseRuntimeOptions:()=>M80,QuickJSWASMModule:()=>T80,QuickJSModuleCallbacks:()=>w80});var eY1=o(()=>{A80()});var XJ1={};$8(XJ1,{QuickJSFFI:()=>nS6});var nS6=class{constructor(Q){this.module=Q,this.DEBUG=!1,this.QTS_Throw=this.module.cwrap("QTS_Throw","number",["number","number"]),this.QTS_NewError=this.module.cwrap("QTS_NewError","number",["number"]),this.QTS_RuntimeSetMemoryLimit=this.module.cwrap("QTS_RuntimeSetMemoryLimit",null,["number","number"]),this.QTS_RuntimeComputeMemoryUsage=this.module.cwrap("QTS_RuntimeComputeMemoryUsage","number",["number","number"]),this.QTS_RuntimeDumpMemoryUsage=this.module.cwrap("QTS_RuntimeDumpMemoryUsage","number",["number"]),this.QTS_RecoverableLeakCheck=this.module.cwrap("QTS_RecoverableLeakCheck","number",[]),this.QTS_BuildIsSanitizeLeak=this.module.cwrap("QTS_BuildIsSanitizeLeak","number",[]),this.QTS_RuntimeSetMaxStackSize=this.module.cwrap("QTS_RuntimeSetMaxStackSize",null,["number","number"]),this.QTS_GetUndefined=this.module.cwrap("QTS_GetUndefined","number",[]),this.QTS_GetNull=this.module.cwrap("QTS_GetNull","number",[]),this.QTS_GetFalse=this.module.cwrap("QTS_GetFalse","number",[]),this.QTS_GetTrue=this.module.cwrap("QTS_GetTrue","number",[]),this.QTS_NewRuntime=this.module.cwrap("QTS_NewRuntime","number",[]),this.QTS_FreeRuntime=this.module.cwrap("QTS_FreeRuntime",null,["number"]),this.QTS_NewContext=this.module.cwrap("QTS_NewContext","number",["number","number"]),this.QTS_FreeContext=this.module.cwrap("QTS_FreeContext",null,["number"]),this.QTS_FreeValuePointer=this.module.cwrap("QTS_FreeValuePointer",null,["number","number"]),this.QTS_FreeValuePointerRuntime=this.module.cwrap("QTS_FreeValuePointerRuntime",null,["number","number"]),this.QTS_FreeVoidPointer=this.module.cwrap("QTS_FreeVoidPointer",null,["number","number"]),this.QTS_FreeCString=this.module.cwrap("QTS_FreeCString",null,["number","number"]),this.QTS_DupValuePointer=this.module.cwrap("QTS_DupValuePointer","number",["number","number"]),this.QTS_NewObject=this.module.cwrap("QTS_NewObject","number",["number"]),this.QTS_NewObjectProto=this.module.cwrap("QTS_NewObjectProto","number",["number","number"]),this.QTS_NewArray=this.module.cwrap("QTS_NewArray","number",["number"]),this.QTS_NewArrayBuffer=this.module.cwrap("QTS_NewArrayBuffer","number",["number","number","number"]),this.QTS_NewFloat64=this.module.cwrap("QTS_NewFloat64","number",["number","number"]),this.QTS_GetFloat64=this.module.cwrap("QTS_GetFloat64","number",["number","number"]),this.QTS_NewString=this.module.cwrap("QTS_NewString","number",["number","number"]),this.QTS_GetString=this.module.cwrap("QTS_GetString","number",["number","number"]),this.QTS_GetArrayBuffer=this.module.cwrap("QTS_GetArrayBuffer","number",["number","number"]),this.QTS_GetArrayBufferLength=this.module.cwrap("QTS_GetArrayBufferLength","number",["number","number"]),this.QTS_NewSymbol=this.module.cwrap("QTS_NewSymbol","number",["number","number","number"]),this.QTS_GetSymbolDescriptionOrKey=this.module.cwrap("QTS_GetSymbolDescriptionOrKey","number",["number","number"]),this.QTS_IsGlobalSymbol=this.module.cwrap("QTS_IsGlobalSymbol","number",["number","number"]),this.QTS_IsJobPending=this.module.cwrap("QTS_IsJobPending","number",["number"]),this.QTS_ExecutePendingJob=this.module.cwrap("QTS_ExecutePendingJob","number",["number","number","number"]),this.QTS_GetProp=this.module.cwrap("QTS_GetProp","number",["number","number","number"]),this.QTS_GetPropNumber=this.module.cwrap("QTS_GetPropNumber","number",["number","number","number"]),this.QTS_SetProp=this.module.cwrap("QTS_SetProp",null,["number","number","number","number"]),this.QTS_DefineProp=this.module.cwrap("QTS_DefineProp",null,["number","number","number","number","number","number","boolean","boolean","boolean"]),this.QTS_GetOwnPropertyNames=this.module.cwrap("QTS_GetOwnPropertyNames","number",["number","number","number","number","number"]),this.QTS_Call=this.module.cwrap("QTS_Call","number",["number","number","number","number","number"]),this.QTS_ResolveException=this.module.cwrap("QTS_ResolveException","number",["number","number"]),this.QTS_Dump=this.module.cwrap("QTS_Dump","number",["number","number"]),this.QTS_Eval=this.module.cwrap("QTS_Eval","number",["number","number","number","string","number","number"]),this.QTS_GetModuleNamespace=this.module.cwrap("QTS_GetModuleNamespace","number",["number","number"]),this.QTS_Typeof=this.module.cwrap("QTS_Typeof","number",["number","number"]),this.QTS_GetLength=this.module.cwrap("QTS_GetLength","number",["number","number","number"]),this.QTS_IsEqual=this.module.cwrap("QTS_IsEqual","number",["number","number","number","number"]),this.QTS_GetGlobalObject=this.module.cwrap("QTS_GetGlobalObject","number",["number"]),this.QTS_NewPromiseCapability=this.module.cwrap("QTS_NewPromiseCapability","number",["number","number"]),this.QTS_PromiseState=this.module.cwrap("QTS_PromiseState","number",["number","number"]),this.QTS_PromiseResult=this.module.cwrap("QTS_PromiseResult","number",["number","number"]),this.QTS_TestStringArg=this.module.cwrap("QTS_TestStringArg",null,["string"]),this.QTS_GetDebugLogEnabled=this.module.cwrap("QTS_GetDebugLogEnabled","number",["number"]),this.QTS_SetDebugLogEnabled=this.module.cwrap("QTS_SetDebugLogEnabled",null,["number","number"]),this.QTS_BuildIsDebug=this.module.cwrap("QTS_BuildIsDebug","number",[]),this.QTS_BuildIsAsyncify=this.module.cwrap("QTS_BuildIsAsyncify","number",[]),this.QTS_NewFunction=this.module.cwrap("QTS_NewFunction","number",["number","number","string"]),this.QTS_ArgvGetJSValueConstPointer=this.module.cwrap("QTS_ArgvGetJSValueConstPointer","number",["number","number"]),this.QTS_RuntimeEnableInterruptHandler=this.module.cwrap("QTS_RuntimeEnableInterruptHandler",null,["number"]),this.QTS_RuntimeDisableInterruptHandler=this.module.cwrap("QTS_RuntimeDisableInterruptHandler",null,["number"]),this.QTS_RuntimeEnableModuleLoader=this.module.cwrap("QTS_RuntimeEnableModuleLoader",null,["number","number"]),this.QTS_RuntimeDisableModuleLoader=this.module.cwrap("QTS_RuntimeDisableModuleLoader",null,["number"]),this.QTS_bjson_encode=this.module.cwrap("QTS_bjson_encode","number",["number","number"]),this.QTS_bjson_decode=this.module.cwrap("QTS_bjson_decode","number",["number","number"])}};var YJ1=()=>{};var JJ1={};$8(JJ1,{default:()=>aS6});var iS6,aS6;var GJ1=o(()=>{iS6=(()=>{var Q=import.meta.url;return async function(X={}){var Y,J=X,G,W,Z=new Promise((w,k)=>{G=w,W=k}),$=typeof window=="object",K=typeof importScripts=="function",H=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(H){let{createRequire:w}=await import("module");var F=w(import.meta.url)}function V(w){w={log:w||function(){}};for(let k of V.Ia)k(w);return J.quickJSEmscriptenExtensions=w}V.Ia=[],J.quickjsEmscriptenInit=V,V.Ia.push((w)=>{w.getWasmMemory=function(){return R}});var q=Object.assign({},J),z="./this.program",B=(w,k)=>{throw k},D="",L,M;if(H){var C=F("fs"),A=F("path");D=F("url").fileURLToPath(new URL("./",import.meta.url)),M=(w)=>{return w=Y1(w)?new URL(w):A.normalize(w),C.readFileSync(w)},L=(w)=>{return w=Y1(w)?new URL(w):A.normalize(w),new Promise((k,c)=>{C.readFile(w,void 0,(t,u)=>{t?c(t):k(u.buffer)})})},!J.thisProgram&&1<process.argv.length&&(z=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),B=(w,k)=>{throw process.exitCode=w,k}}else if($||K)K?D=self.location.href:typeof document<"u"&&document.currentScript&&(D=document.currentScript.src),Q&&(D=Q),D.startsWith("blob:")?D="":D=D.substr(0,D.replace(/[?#].*/,"").lastIndexOf("/")+1),K&&(M=(w)=>{var k=new XMLHttpRequest;return k.open("GET",w,!1),k.responseType="arraybuffer",k.send(null),new Uint8Array(k.response)}),L=(w)=>Y1(w)?new Promise((k,c)=>{var t=new XMLHttpRequest;t.open("GET",w,!0),t.responseType="arraybuffer",t.onload=()=>{t.status==200||t.status==0&&t.response?k(t.response):c(t.status)},t.onerror=c,t.send(null)}):fetch(w,{credentials:"same-origin"}).then((k)=>k.ok?k.arrayBuffer():Promise.reject(Error(k.status+" : "+k.url)));var E=J.print||console.log.bind(console),T=J.printErr||console.error.bind(console);Object.assign(J,q),q=null,J.thisProgram&&(z=J.thisProgram);var j=J.wasmBinary,R,v=!1,y,b,h,a,f;function S(){var w=R.buffer;J.HEAP8=b=new Int8Array(w),J.HEAP16=new Int16Array(w),J.HEAPU8=h=new Uint8Array(w),J.HEAPU16=new Uint16Array(w),J.HEAP32=a=new Int32Array(w),J.HEAPU32=f=new Uint32Array(w),J.HEAPF32=new Float32Array(w),J.HEAPF64=new Float64Array(w)}J.wasmMemory?R=J.wasmMemory:R=new WebAssembly.Memory({initial:(J.INITIAL_MEMORY||16777216)/65536,maximum:32768}),S();var m=[],Q0=[],r=[];function Y0(){var w=J.preRun.shift();m.unshift(w)}var F0=0,Z0=null,B0=null;function T0(w){throw J.onAbort?.(w),w="Aborted("+w+")",T(w),v=!0,y=1,w=new WebAssembly.RuntimeError(w+". Build with -sASSERTIONS for more info."),W(w),w}var b0=(w)=>w.startsWith("data:application/octet-stream;base64,"),Y1=(w)=>w.startsWith("file://"),D0;function G0(w){if(w==D0&&j)return new Uint8Array(j);if(M)return M(w);throw"both async and sync fetching of the wasm failed"}function R0(w){return j?Promise.resolve().then(()=>G0(w)):L(w).then((k)=>new Uint8Array(k),()=>G0(w))}function _1(w,k,c){return R0(w).then((t)=>WebAssembly.instantiate(t,k)).then(c,(t)=>{T(`failed to asynchronously prepare wasm: ${t}`),T0(t)})}function h1(w,k){var c=D0;return j||typeof WebAssembly.instantiateStreaming!="function"||b0(c)||Y1(c)||H||typeof fetch!="function"?_1(c,w,k):fetch(c,{credentials:"same-origin"}).then((t)=>WebAssembly.instantiateStreaming(t,w).then(k,function(u){return T(`wasm streaming compile failed: ${u}`),T("falling back to ArrayBuffer instantiation"),_1(c,w,k)}))}function y0(w){this.name="ExitStatus",this.message=`Program terminated with exit(${w})`,this.status=w}var w0=(w)=>{for(;0<w.length;)w.shift()(J)},$0=J.noExitRuntime||!0,j0=typeof TextDecoder<"u"?new TextDecoder:void 0,H0=(w,k,c)=>{var t=k+c;for(c=k;w[c]&&!(c>=t);)++c;if(16<c-k&&w.buffer&&j0)return j0.decode(w.subarray(k,c));for(t="";k<c;){var u=w[k++];if(u&128){var N0=w[k++]&63;if((u&224)==192)t+=String.fromCharCode((u&31)<<6|N0);else{var r0=w[k++]&63;u=(u&240)==224?(u&15)<<12|N0<<6|r0:(u&7)<<18|N0<<12|r0<<6|w[k++]&63,65536>u?t+=String.fromCharCode(u):(u-=65536,t+=String.fromCharCode(55296|u>>10,56320|u&1023))}}else t+=String.fromCharCode(u)}return t},O0=[0,31,60,91,121,152,182,213,244,274,305,335],t0=[0,31,59,90,120,151,181,212,243,273,304,334],k0={},v0=0,I1=(w)=>{y=w,$0||0<v0||(J.onExit?.(w),v=!0),B(w,new y0(w))},b1=(w)=>{if(!v)try{if(w(),!($0||0<v0))try{y=w=y,I1(w)}catch(k){k instanceof y0||k=="unwind"||B(1,k)}}catch(k){k instanceof y0||k=="unwind"||B(1,k)}},s1;s1=()=>performance.now();var E1=(w,k,c)=>{var t=h;if(!(0<c))return 0;var u=k;c=k+c-1;for(var N0=0;N0<w.length;++N0){var r0=w.charCodeAt(N0);if(55296<=r0&&57343>=r0){var w1=w.charCodeAt(++N0);r0=65536+((r0&1023)<<10)|w1&1023}if(127>=r0){if(k>=c)break;t[k++]=r0}else{if(2047>=r0){if(k+1>=c)break;t[k++]=192|r0>>6}else{if(65535>=r0){if(k+2>=c)break;t[k++]=224|r0>>12}else{if(k+3>=c)break;t[k++]=240|r0>>18,t[k++]=128|r0>>12&63}t[k++]=128|r0>>6&63}t[k++]=128|r0&63}}return t[k]=0,k-u},X1={},C0=()=>{if(!P0){var w={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:z||"./this.program"},k;for(k in X1)X1[k]===void 0?delete w[k]:w[k]=X1[k];var c=[];for(k in w)c.push(`${k}=${w[k]}`);P0=c}return P0},P0,a1=[null,[],[]],M4=(w)=>{for(var k=0,c=0;c<w.length;++c){var t=w.charCodeAt(c);127>=t?k++:2047>=t?k+=2:55296<=t&&57343>=t?(k+=4,++c):k+=3}return k},_8=(w,k,c,t)=>{var u={string:(z1)=>{var H4=0;if(z1!==null&&z1!==void 0&&z1!==0){H4=M4(z1)+1;var DQ=_(H4);E1(z1,DQ,H4),H4=DQ}return H4},array:(z1)=>{var H4=_(z1.length);return b.set(z1,H4),H4}};w=J["_"+w];var N0=[],r0=0;if(t)for(var w1=0;w1<t.length;w1++){var _0=u[c[w1]];_0?(r0===0&&(r0=s()),N0[w1]=_0(t[w1])):N0[w1]=t[w1]}return c=w(...N0),c=function(z1){return r0!==0&&O(r0),k==="string"?z1?H0(h,z1):"":k==="boolean"?!!z1:z1}(c)},g1={b:(w,k,c,t)=>{T0(`Assertion failed: ${w?H0(h,w):""}, at: `+[k?k?H0(h,k):"":"unknown filename",c,t?t?H0(h,t):"":"unknown function"])},q:()=>{T0("")},n:()=>{$0=!1,v0=0},j:function(w,k,c){w=new Date(1000*(k+2097152>>>0<4194305-!!w?(w>>>0)+4294967296*k:NaN)),a[c>>2]=w.getSeconds(),a[c+4>>2]=w.getMinutes(),a[c+8>>2]=w.getHours(),a[c+12>>2]=w.getDate(),a[c+16>>2]=w.getMonth(),a[c+20>>2]=w.getFullYear()-1900,a[c+24>>2]=w.getDay(),k=w.getFullYear(),a[c+28>>2]=(k%4!==0||k%100===0&&k%400!==0?t0:O0)[w.getMonth()]+w.getDate()-1|0,a[c+36>>2]=-(60*w.getTimezoneOffset()),k=new Date(w.getFullYear(),6,1).getTimezoneOffset();var t=new Date(w.getFullYear(),0,1).getTimezoneOffset();a[c+32>>2]=(k!=t&&w.getTimezoneOffset()==Math.min(t,k))|0},l:(w,k)=>{if(k0[w]&&(clearTimeout(k0[w].id),delete k0[w]),!k)return 0;var c=setTimeout(()=>{delete k0[w],b1(()=>GY(w,s1()))},k);return k0[w]={id:c,Na:k},0},o:(w,k,c,t)=>{var u=new Date().getFullYear(),N0=new Date(u,0,1).getTimezoneOffset();u=new Date(u,6,1).getTimezoneOffset(),f[w>>2]=60*Math.max(N0,u),a[k>>2]=Number(N0!=u),k=(r0)=>{var w1=Math.abs(r0);return`UTC${0<=r0?"-":"+"}${String(Math.floor(w1/60)).padStart(2,"0")}${String(w1%60).padStart(2,"0")}`},w=k(N0),k=k(u),u<N0?(E1(w,c,17),E1(k,t,17)):(E1(w,t,17),E1(k,c,17))},p:()=>Date.now(),m:(w)=>{var k=h.length;if(w>>>=0,2147483648<w)return!1;for(var c=1;4>=c;c*=2){var t=k*(1+0.2/c);t=Math.min(t,w+100663296);Q:{t=(Math.min(2147483648,65536*Math.ceil(Math.max(w,t)/65536))-R.buffer.byteLength+65535)/65536;try{R.grow(t),S();var u=1;break Q}catch(N0){}u=void 0}if(u)return!0}return!1},f:(w,k)=>{var c=0;return C0().forEach((t,u)=>{var N0=k+c;u=f[w+4*u>>2]=N0;for(N0=0;N0<t.length;++N0)b[u++]=t.charCodeAt(N0);b[u]=0,c+=t.length+1}),0},g:(w,k)=>{var c=C0();f[w>>2]=c.length;var t=0;return c.forEach((u)=>t+=u.length+1),f[k>>2]=t,0},e:()=>52,k:function(){return 70},d:(w,k,c,t)=>{for(var u=0,N0=0;N0<c;N0++){var r0=f[k>>2],w1=f[k+4>>2];k+=8;for(var _0=0;_0<w1;_0++){var z1=h[r0+_0],H4=a1[w];z1===0||z1===10?((w===1?E:T)(H0(H4,0)),H4.length=0):H4.push(z1)}u+=w1}return f[t>>2]=u,0},a:R,c:I1,s:function(w,k,c,t,u){return J.callbacks.callFunction(void 0,w,k,c,t,u)},r:function(w){return J.callbacks.shouldInterrupt(void 0,w)},i:function(w,k,c){return c=c?H0(h,c):"",J.callbacks.loadModuleSource(void 0,w,k,c)},h:function(w,k,c,t){return c=c?H0(h,c):"",t=t?H0(h,t):"",J.callbacks.normalizeModule(void 0,w,k,c,t)}},I0=function(){function w(c){return I0=c.exports,Q0.unshift(I0.t),F0--,J.monitorRunDependencies?.(F0),F0==0&&(Z0!==null&&(clearInterval(Z0),Z0=null),B0&&(c=B0,B0=null,c())),I0}var k={a:g1};if(F0++,J.monitorRunDependencies?.(F0),J.instantiateWasm)try{return J.instantiateWasm(k,w)}catch(c){T(`Module.instantiateWasm callback failed with error: ${c}`),W(c)}return D0||=J.locateFile?b0("emscripten-module.wasm")?"emscripten-module.wasm":J.locateFile?J.locateFile("emscripten-module.wasm",D):D+"emscripten-module.wasm":new URL("emscripten-module.wasm",import.meta.url).href,h1(k,function(c){w(c.instance)}).catch(W),{}}();J._malloc=(w)=>(J._malloc=I0.u)(w),J._QTS_Throw=(w,k)=>(J._QTS_Throw=I0.v)(w,k),J._QTS_NewError=(w)=>(J._QTS_NewError=I0.w)(w),J._QTS_RuntimeSetMemoryLimit=(w,k)=>(J._QTS_RuntimeSetMemoryLimit=I0.x)(w,k),J._QTS_RuntimeComputeMemoryUsage=(w,k)=>(J._QTS_RuntimeComputeMemoryUsage=I0.y)(w,k),J._QTS_RuntimeDumpMemoryUsage=(w)=>(J._QTS_RuntimeDumpMemoryUsage=I0.z)(w),J._QTS_RecoverableLeakCheck=()=>(J._QTS_RecoverableLeakCheck=I0.A)(),J._QTS_BuildIsSanitizeLeak=()=>(J._QTS_BuildIsSanitizeLeak=I0.B)(),J._QTS_RuntimeSetMaxStackSize=(w,k)=>(J._QTS_RuntimeSetMaxStackSize=I0.C)(w,k),J._QTS_GetUndefined=()=>(J._QTS_GetUndefined=I0.D)(),J._QTS_GetNull=()=>(J._QTS_GetNull=I0.E)(),J._QTS_GetFalse=()=>(J._QTS_GetFalse=I0.F)(),J._QTS_GetTrue=()=>(J._QTS_GetTrue=I0.G)(),J._QTS_NewRuntime=()=>(J._QTS_NewRuntime=I0.H)(),J._QTS_FreeRuntime=(w)=>(J._QTS_FreeRuntime=I0.I)(w),J._free=(w)=>(J._free=I0.J)(w),J._QTS_NewContext=(w,k)=>(J._QTS_NewContext=I0.K)(w,k),J._QTS_FreeContext=(w)=>(J._QTS_FreeContext=I0.L)(w),J._QTS_FreeValuePointer=(w,k)=>(J._QTS_FreeValuePointer=I0.M)(w,k),J._QTS_FreeValuePointerRuntime=(w,k)=>(J._QTS_FreeValuePointerRuntime=I0.N)(w,k),J._QTS_FreeVoidPointer=(w,k)=>(J._QTS_FreeVoidPointer=I0.O)(w,k),J._QTS_FreeCString=(w,k)=>(J._QTS_FreeCString=I0.P)(w,k),J._QTS_DupValuePointer=(w,k)=>(J._QTS_DupValuePointer=I0.Q)(w,k),J._QTS_NewObject=(w)=>(J._QTS_NewObject=I0.R)(w),J._QTS_NewObjectProto=(w,k)=>(J._QTS_NewObjectProto=I0.S)(w,k),J._QTS_NewArray=(w)=>(J._QTS_NewArray=I0.T)(w),J._QTS_NewArrayBuffer=(w,k,c)=>(J._QTS_NewArrayBuffer=I0.U)(w,k,c),J._QTS_NewFloat64=(w,k)=>(J._QTS_NewFloat64=I0.V)(w,k),J._QTS_GetFloat64=(w,k)=>(J._QTS_GetFloat64=I0.W)(w,k),J._QTS_NewString=(w,k)=>(J._QTS_NewString=I0.X)(w,k),J._QTS_GetString=(w,k)=>(J._QTS_GetString=I0.Y)(w,k),J._QTS_GetArrayBuffer=(w,k)=>(J._QTS_GetArrayBuffer=I0.Z)(w,k),J._QTS_GetArrayBufferLength=(w,k)=>(J._QTS_GetArrayBufferLength=I0._)(w,k),J._QTS_NewSymbol=(w,k,c)=>(J._QTS_NewSymbol=I0.$)(w,k,c),J._QTS_GetSymbolDescriptionOrKey=(w,k)=>(J._QTS_GetSymbolDescriptionOrKey=I0.aa)(w,k),J._QTS_IsGlobalSymbol=(w,k)=>(J._QTS_IsGlobalSymbol=I0.ba)(w,k),J._QTS_IsJobPending=(w)=>(J._QTS_IsJobPending=I0.ca)(w),J._QTS_ExecutePendingJob=(w,k,c)=>(J._QTS_ExecutePendingJob=I0.da)(w,k,c),J._QTS_GetProp=(w,k,c)=>(J._QTS_GetProp=I0.ea)(w,k,c),J._QTS_GetPropNumber=(w,k,c)=>(J._QTS_GetPropNumber=I0.fa)(w,k,c),J._QTS_SetProp=(w,k,c,t)=>(J._QTS_SetProp=I0.ga)(w,k,c,t),J._QTS_DefineProp=(w,k,c,t,u,N0,r0,w1,_0)=>(J._QTS_DefineProp=I0.ha)(w,k,c,t,u,N0,r0,w1,_0),J._QTS_GetOwnPropertyNames=(w,k,c,t,u)=>(J._QTS_GetOwnPropertyNames=I0.ia)(w,k,c,t,u),J._QTS_Call=(w,k,c,t,u)=>(J._QTS_Call=I0.ja)(w,k,c,t,u),J._QTS_ResolveException=(w,k)=>(J._QTS_ResolveException=I0.ka)(w,k),J._QTS_Dump=(w,k)=>(J._QTS_Dump=I0.la)(w,k),J._QTS_Eval=(w,k,c,t,u,N0)=>(J._QTS_Eval=I0.ma)(w,k,c,t,u,N0),J._QTS_GetModuleNamespace=(w,k)=>(J._QTS_GetModuleNamespace=I0.na)(w,k),J._QTS_Typeof=(w,k)=>(J._QTS_Typeof=I0.oa)(w,k),J._QTS_GetLength=(w,k,c)=>(J._QTS_GetLength=I0.pa)(w,k,c),J._QTS_IsEqual=(w,k,c,t)=>(J._QTS_IsEqual=I0.qa)(w,k,c,t),J._QTS_GetGlobalObject=(w)=>(J._QTS_GetGlobalObject=I0.ra)(w),J._QTS_NewPromiseCapability=(w,k)=>(J._QTS_NewPromiseCapability=I0.sa)(w,k),J._QTS_PromiseState=(w,k)=>(J._QTS_PromiseState=I0.ta)(w,k),J._QTS_PromiseResult=(w,k)=>(J._QTS_PromiseResult=I0.ua)(w,k),J._QTS_TestStringArg=(w)=>(J._QTS_TestStringArg=I0.va)(w),J._QTS_GetDebugLogEnabled=(w)=>(J._QTS_GetDebugLogEnabled=I0.wa)(w),J._QTS_SetDebugLogEnabled=(w,k)=>(J._QTS_SetDebugLogEnabled=I0.xa)(w,k),J._QTS_BuildIsDebug=()=>(J._QTS_BuildIsDebug=I0.ya)(),J._QTS_BuildIsAsyncify=()=>(J._QTS_BuildIsAsyncify=I0.za)(),J._QTS_NewFunction=(w,k,c)=>(J._QTS_NewFunction=I0.Aa)(w,k,c),J._QTS_ArgvGetJSValueConstPointer=(w,k)=>(J._QTS_ArgvGetJSValueConstPointer=I0.Ba)(w,k),J._QTS_RuntimeEnableInterruptHandler=(w)=>(J._QTS_RuntimeEnableInterruptHandler=I0.Ca)(w),J._QTS_RuntimeDisableInterruptHandler=(w)=>(J._QTS_RuntimeDisableInterruptHandler=I0.Da)(w),J._QTS_RuntimeEnableModuleLoader=(w,k)=>(J._QTS_RuntimeEnableModuleLoader=I0.Ea)(w,k),J._QTS_RuntimeDisableModuleLoader=(w)=>(J._QTS_RuntimeDisableModuleLoader=I0.Fa)(w),J._QTS_bjson_encode=(w,k)=>(J._QTS_bjson_encode=I0.Ga)(w,k),J._QTS_bjson_decode=(w,k)=>(J._QTS_bjson_decode=I0.Ha)(w,k);var GY=(w,k)=>(GY=I0.Ja)(w,k),O=(w)=>(O=I0.Ka)(w),_=(w)=>(_=I0.La)(w),s=()=>(s=I0.Ma)();J.cwrap=(w,k,c,t)=>{var u=!c||c.every((N0)=>N0==="number"||N0==="boolean");return k!=="string"&&u&&!t?J["_"+w]:(...N0)=>_8(w,k,c,N0)},J.UTF8ToString=(w,k)=>w?H0(h,w,k):"",J.stringToUTF8=(w,k,c)=>E1(w,k,c),J.lengthBytesUTF8=M4;var J0;B0=function w(){J0||U(),J0||(B0=w)};function U(){function w(){if(!J0&&(J0=!0,J.calledRun=!0,!v)){if(w0(Q0),G(J),J.onRuntimeInitialized?.(),J.postRun)for(typeof J.postRun=="function"&&(J.postRun=[J.postRun]);J.postRun.length;){var k=J.postRun.shift();r.unshift(k)}w0(r)}}if(!(0<F0)){if(J.preRun)for(typeof J.preRun=="function"&&(J.preRun=[J.preRun]);J.preRun.length;)Y0();w0(m),0<F0||(J.setStatus?(J.setStatus("Running..."),setTimeout(function(){setTimeout(function(){J.setStatus("")},1),w()},1)):w())}}if(J.preInit)for(typeof J.preInit=="function"&&(J.preInit=[J.preInit]);0<J.preInit.length;)J.preInit.pop()();return U(),Y=Z,Y}})(),aS6=iS6});var y80=I((Xl4,o51)=>{var{defineProperty:_80,getOwnPropertyDescriptor:Ck6,getOwnPropertyNames:Ik6}=Object,Rk6=Object.prototype.hasOwnProperty,Sk6=(Q,X)=>{for(var Y in X)_80(Q,Y,{get:X[Y],enumerable:!0})},vk6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of Ik6(X))if(!Rk6.call(Q,G)&&G!==Y)_80(Q,G,{get:()=>X[G],enumerable:!(J=Ck6(X,G))||J.enumerable})}return Q},kk6=(Q)=>vk6(_80({},"__esModule",{value:!0}),Q),a51={};Sk6(a51,{SYMBOL_FOR_REQ_CONTEXT:()=>r51,getContext:()=>_k6});o51.exports=kk6(a51);var r51=Symbol.for("@vercel/request-context");function _k6(){return globalThis[r51]?.get?.()??{}}});var CP=I((Yl4,e51)=>{var{defineProperty:b80,getOwnPropertyDescriptor:yk6,getOwnPropertyNames:bk6}=Object,fk6=Object.prototype.hasOwnProperty,hk6=(Q,X)=>{for(var Y in X)b80(Q,Y,{get:X[Y],enumerable:!0})},xk6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of bk6(X))if(!fk6.call(Q,G)&&G!==Y)b80(Q,G,{get:()=>X[G],enumerable:!(J=yk6(X,G))||J.enumerable})}return Q},gk6=(Q)=>xk6(b80({},"__esModule",{value:!0}),Q),s51={};hk6(s51,{VercelOidcTokenError:()=>t51});e51.exports=gk6(s51);class t51 extends Error{constructor(Q,X){super(Q);this.name="VercelOidcTokenError",this.cause=X}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var JG1=I((Jl4,YG1)=>{var{create:uk6,defineProperty:ay,getOwnPropertyDescriptor:mk6,getOwnPropertyNames:lk6,getPrototypeOf:dk6}=Object,pk6=Object.prototype.hasOwnProperty,ck6=(Q,X)=>{for(var Y in X)ay(Q,Y,{get:X[Y],enumerable:!0})},QG1=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of lk6(X))if(!pk6.call(Q,G)&&G!==Y)ay(Q,G,{get:()=>X[G],enumerable:!(J=mk6(X,G))||J.enumerable})}return Q},h80=(Q,X,Y)=>(Y=Q!=null?uk6(dk6(Q)):{},QG1(X||!Q||!Q.__esModule?ay(Y,"default",{value:Q,enumerable:!0}):Y,Q)),nk6=(Q)=>QG1(ay({},"__esModule",{value:!0}),Q),XG1={};ck6(XG1,{findRootDir:()=>rk6,getUserDataDir:()=>ok6});YG1.exports=nk6(XG1);var IP=h80(U0("path")),ik6=h80(U0("fs")),f80=h80(U0("os")),ak6=CP();function rk6(){try{let Q=process.cwd();while(Q!==IP.default.dirname(Q)){let X=IP.default.join(Q,".vercel");if(ik6.default.existsSync(X))return Q;Q=IP.default.dirname(Q)}}catch(Q){throw new ak6.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function ok6(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(f80.default.platform()){case"darwin":return IP.default.join(f80.default.homedir(),"Library/Application Support");case"linux":return IP.default.join(f80.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var FG1=I((Gl4,HG1)=>{var{create:sk6,defineProperty:ry,getOwnPropertyDescriptor:tk6,getOwnPropertyNames:ek6,getPrototypeOf:Q_6}=Object,X_6=Object.prototype.hasOwnProperty,Y_6=(Q,X)=>{for(var Y in X)ry(Q,Y,{get:X[Y],enumerable:!0})},GG1=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of ek6(X))if(!X_6.call(Q,G)&&G!==Y)ry(Q,G,{get:()=>X[G],enumerable:!(J=tk6(X,G))||J.enumerable})}return Q},WG1=(Q,X,Y)=>(Y=Q!=null?sk6(Q_6(Q)):{},GG1(X||!Q||!Q.__esModule?ry(Y,"default",{value:Q,enumerable:!0}):Y,Q)),J_6=(Q)=>GG1(ry({},"__esModule",{value:!0}),Q),ZG1={};Y_6(ZG1,{isValidAccessToken:()=>$_6,readAuthConfig:()=>W_6,writeAuthConfig:()=>Z_6});HG1.exports=J_6(ZG1);var RP=WG1(U0("fs")),$G1=WG1(U0("path")),G_6=oy();function KG1(){let Q=(0,G_6.getVercelDataDir)();if(!Q)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return $G1.join(Q,"auth.json")}function W_6(){try{let Q=KG1();if(!RP.existsSync(Q))return null;let X=RP.readFileSync(Q,"utf8");if(!X)return null;return JSON.parse(X)}catch(Q){return null}}function Z_6(Q){let X=KG1(),Y=$G1.dirname(X);if(!RP.existsSync(Y))RP.mkdirSync(Y,{mode:504,recursive:!0});RP.writeFileSync(X,JSON.stringify(Q,null,2),{mode:384})}function $_6(Q){if(!Q.token)return!1;if(typeof Q.expiresAt!=="number")return!0;let X=Math.floor(Date.now()/1000);return Q.expiresAt>=X}});var UG1=I((Wl4,zG1)=>{var{defineProperty:u80,getOwnPropertyDescriptor:K_6,getOwnPropertyNames:H_6}=Object,F_6=Object.prototype.hasOwnProperty,V_6=(Q,X)=>{for(var Y in X)u80(Q,Y,{get:X[Y],enumerable:!0})},q_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of H_6(X))if(!F_6.call(Q,G)&&G!==Y)u80(Q,G,{get:()=>X[G],enumerable:!(J=K_6(X,G))||J.enumerable})}return Q},z_6=(Q)=>q_6(u80({},"__esModule",{value:!0}),Q),VG1={};V_6(VG1,{processTokenResponse:()=>O_6,refreshTokenRequest:()=>N_6});zG1.exports=z_6(VG1);var x80=U0("os"),U_6="https://vercel.com",B_6="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",qG1=`@vercel/oidc node-${process.version} ${(0,x80.platform)()} (${(0,x80.arch)()}) ${(0,x80.hostname)()}`,g80=null;async function D_6(){if(g80)return g80;let Q=`${U_6}/.well-known/openid-configuration`,X=await fetch(Q,{headers:{"user-agent":qG1}});if(!X.ok)throw Error("Failed to discover OAuth endpoints");let Y=await X.json();if(!Y||typeof Y.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let J=Y.token_endpoint;return g80=J,J}async function N_6(Q){let X=await D_6();return await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":qG1},body:new URLSearchParams({client_id:B_6,grant_type:"refresh_token",...Q})})}async function O_6(Q){let X=await Q.json();if(!Q.ok){let Y=typeof X==="object"&&X&&"error"in X?String(X.error):"Token refresh failed";return[Error(Y)]}if(typeof X!=="object"||X===null)return[Error("Invalid token response")];if(typeof X.access_token!=="string")return[Error("Missing access_token in response")];if(X.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof X.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,X]}});var oy=I((Zl4,LG1)=>{var{create:L_6,defineProperty:sy,getOwnPropertyDescriptor:w_6,getOwnPropertyNames:M_6,getPrototypeOf:P_6}=Object,T_6=Object.prototype.hasOwnProperty,A_6=(Q,X)=>{for(var Y in X)sy(Q,Y,{get:X[Y],enumerable:!0})},DG1=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of M_6(X))if(!T_6.call(Q,G)&&G!==Y)sy(Q,G,{get:()=>X[G],enumerable:!(J=w_6(X,G))||J.enumerable})}return Q},NG1=(Q,X,Y)=>(Y=Q!=null?L_6(P_6(Q)):{},DG1(X||!Q||!Q.__esModule?sy(Y,"default",{value:Q,enumerable:!0}):Y,Q)),E_6=(Q)=>DG1(sy({},"__esModule",{value:!0}),Q),OG1={};A_6(OG1,{assertVercelOidcTokenResponse:()=>m80,findProjectInfo:()=>R_6,getTokenPayload:()=>k_6,getVercelCliToken:()=>C_6,getVercelDataDir:()=>j_6,getVercelOidcToken:()=>I_6,isExpired:()=>__6,loadToken:()=>v_6,saveToken:()=>S_6});LG1.exports=E_6(OG1);var SP=NG1(U0("path")),HF=NG1(U0("fs")),lU=CP(),ty=JG1(),mU=FG1(),BG1=UG1();function j_6(){let X=(0,ty.getUserDataDir)();if(!X)return null;return SP.join(X,"com.vercel.cli")}async function C_6(){let Q=(0,mU.readAuthConfig)();if(!Q)return null;if((0,mU.isValidAccessToken)(Q))return Q.token||null;if(!Q.refreshToken)return(0,mU.writeAuthConfig)({}),null;try{let X=await(0,BG1.refreshTokenRequest)({refresh_token:Q.refreshToken}),[Y,J]=await(0,BG1.processTokenResponse)(X);if(Y||!J)return(0,mU.writeAuthConfig)({}),null;let G={token:J.access_token,expiresAt:Math.floor(Date.now()/1000)+J.expires_in};if(J.refresh_token)G.refreshToken=J.refresh_token;return(0,mU.writeAuthConfig)(G),G.token??null}catch(X){return(0,mU.writeAuthConfig)({}),null}}async function I_6(Q,X,Y){let J=`https://api.vercel.com/v1/projects/${X}/token?source=vercel-oidc-refresh${Y?`&teamId=${Y}`:""}`,G=await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`}});if(!G.ok)throw new lU.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let W=await G.json();return m80(W),W}function m80(Q){if(!Q||typeof Q!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in Q)||typeof Q.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function R_6(){let Q=(0,ty.findRootDir)();if(!Q)throw new lU.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let X=SP.join(Q,".vercel","project.json");if(!HF.existsSync(X))throw new lU.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let Y=JSON.parse(HF.readFileSync(X,"utf8"));if(typeof Y.projectId!=="string"&&typeof Y.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:Y.projectId,teamId:Y.orgId}}function S_6(Q,X){let Y=(0,ty.getUserDataDir)();if(!Y)throw new lU.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let J=SP.join(Y,"com.vercel.token",`${X}.json`),G=JSON.stringify(Q);HF.mkdirSync(SP.dirname(J),{mode:504,recursive:!0}),HF.writeFileSync(J,G),HF.chmodSync(J,432);return}function v_6(Q){let X=(0,ty.getUserDataDir)();if(!X)throw new lU.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Y=SP.join(X,"com.vercel.token",`${Q}.json`);if(!HF.existsSync(Y))return null;let J=JSON.parse(HF.readFileSync(Y,"utf8"));return m80(J),J}function k_6(Q){let X=Q.split(".");if(X.length!==3)throw new lU.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let Y=X[1].replace(/-/g,"+").replace(/_/g,"/"),J=Y.padEnd(Y.length+(4-Y.length%4)%4,"=");return JSON.parse(Buffer.from(J,"base64").toString("utf8"))}function __6(Q){return Q.exp*1000<Date.now()}});var PG1=I(($l4,MG1)=>{var{defineProperty:d80,getOwnPropertyDescriptor:y_6,getOwnPropertyNames:b_6}=Object,f_6=Object.prototype.hasOwnProperty,h_6=(Q,X)=>{for(var Y in X)d80(Q,Y,{get:X[Y],enumerable:!0})},x_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of b_6(X))if(!f_6.call(Q,G)&&G!==Y)d80(Q,G,{get:()=>X[G],enumerable:!(J=y_6(X,G))||J.enumerable})}return Q},g_6=(Q)=>x_6(d80({},"__esModule",{value:!0}),Q),wG1={};h_6(wG1,{refreshToken:()=>u_6});MG1.exports=g_6(wG1);var l80=CP(),FF=oy();async function u_6(){let{projectId:Q,teamId:X}=(0,FF.findProjectInfo)(),Y=(0,FF.loadToken)(Q);if(!Y||(0,FF.isExpired)((0,FF.getTokenPayload)(Y.token))){let J=await(0,FF.getVercelCliToken)();if(!J)throw new l80.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!Q)throw new l80.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(Y=await(0,FF.getVercelOidcToken)(J,Q,X),!Y)throw new l80.VercelOidcTokenError("Failed to refresh OIDC token");(0,FF.saveToken)(Y,Q)}process.env.VERCEL_OIDC_TOKEN=Y.token;return}});var EG1=I((Kl4,AG1)=>{var{defineProperty:c80,getOwnPropertyDescriptor:m_6,getOwnPropertyNames:l_6}=Object,d_6=Object.prototype.hasOwnProperty,p_6=(Q,X)=>{for(var Y in X)c80(Q,Y,{get:X[Y],enumerable:!0})},c_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of l_6(X))if(!d_6.call(Q,G)&&G!==Y)c80(Q,G,{get:()=>X[G],enumerable:!(J=m_6(X,G))||J.enumerable})}return Q},n_6=(Q)=>c_6(c80({},"__esModule",{value:!0}),Q),TG1={};p_6(TG1,{getVercelOidcToken:()=>r_6,getVercelOidcTokenSync:()=>p80});AG1.exports=n_6(TG1);var i_6=y80(),a_6=CP();async function r_6(){let Q="",X;try{Q=p80()}catch(Y){X=Y}try{let[{getTokenPayload:Y,isExpired:J},{refreshToken:G}]=await Promise.all([await Promise.resolve().then(() => m6(oy())),await Promise.resolve().then(() => m6(PG1()))]);if(!Q||J(Y(Q)))await G(),Q=p80()}catch(Y){let J=X instanceof Error?X.message:"";if(Y instanceof Error)J=`${J}
|
|
261
|
-
${Y.message}`;if(J)throw new a_6.VercelOidcTokenError(J);throw Y}return Q}function p80(){let Q=(0,i_6.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!Q)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return Q}});var i80=I((Hl4,IG1)=>{var{defineProperty:n80,getOwnPropertyDescriptor:o_6,getOwnPropertyNames:s_6}=Object,t_6=Object.prototype.hasOwnProperty,e_6=(Q,X)=>{for(var Y in X)n80(Q,Y,{get:X[Y],enumerable:!0})},Qy6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of s_6(X))if(!t_6.call(Q,G)&&G!==Y)n80(Q,G,{get:()=>X[G],enumerable:!(J=o_6(X,G))||J.enumerable})}return Q},Xy6=(Q)=>Qy6(n80({},"__esModule",{value:!0}),Q),CG1={};e_6(CG1,{getContext:()=>Yy6.getContext,getVercelOidcToken:()=>jG1.getVercelOidcToken,getVercelOidcTokenSync:()=>jG1.getVercelOidcTokenSync});IG1.exports=Xy6(CG1);var jG1=EG1(),Yy6=y80()});var pE=m6(Z1(),1),Nk0=m6(Kk0(),1),Ok0=m6(Dl(),1),Lk0=m6(pm(),1),Nl=new Ok0.PrometheusExporter({preventServerStart:!0}),ji1=new Nk0.NodeSDK({serviceName:"mcp-mesh",traceExporter:new Lk0.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:Nl});ji1.start();var xD=pE.trace.getTracer("mcp-mesh","1.0.0"),cE=pE.metrics.getMeter("mcp-mesh","1.0.0");var Ol=class extends Error{res;status;constructor(Q=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Q}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var wk0=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],Ci1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,Ii1=(Q,X)=>{if(!Q)return{};let Y=new Headers(Q.headers);if(X){let J=Y.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!Ci1.test(Z));if(W.length>0)throw new Ol(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Y.delete(Z)})}}return wk0.forEach((J)=>{Y.delete(J)}),{method:Q.method,body:Q.body,duplex:Q.body?"half":void 0,headers:Y,signal:Q.signal}},Ri1=(Q)=>{if(!Q.headers||Array.isArray(Q.headers)||Q.headers instanceof Headers)return Q;let X=new Headers;for(let[Y,J]of Object.entries(Q.headers))if(J==null)X.delete(Y);else X.set(Y,J);return Q.headers=X,Q},Mk0=async(Q,X)=>{let{raw:Y,customFetch:J,strictConnectionProcessing:G=!1,...W}=X instanceof Request?{raw:X}:X??{},Z=new Request(Q,{...Ii1(Y,G),...Ri1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(wk0.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var Pk0=(Q)=>(X)=>{let Y=new URL(X.req.raw.url),J=new URL(Q);return J.pathname=Y.pathname,J.search=Y.search,Mk0(J,{raw:X.req.raw,headers:{...X.req.raw.headers}})};import{resolve as gD,dirname as Si1}from"path";var vi1="http://localhost:4000",ki1="./dist/client";function _i1(Q,X){let Y=gD(X),J=gD(Q);return J===Y||J.startsWith(Y+"/")}function yi1({requestPath:Q,clientDir:X}){let Y=Q.startsWith("/")?Q.slice(1):Q,J=gD(X,Y);if(!_i1(J,X))return null;return J}function Tk0(Q,X="../client"){let Y=new URL(Q),J=Si1(Y.pathname);return gD(J,X)}function Ak0(Q={}){let{env:X="production",devServerUrl:Y=vi1,clientDir:J=ki1,isServerPath:G=()=>!1}=Q;if(X==="development"){let W=Pk0(Y);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=yi1({requestPath:K,clientDir:J});if(!H)return null;let F=gD(J,"index.html");for(let V of[H,F])try{let q=Bun.file(V);if(await q.exists())return new Response(q)}catch{}return null}}var E71=m6(Dl(),1);var Ll=(Q,X,Y)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(Q[$])F=Q[$][0][0],J.req.routeIndex=$;else F=$===Q.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&X)J.error=V,K=await X(V,J),H=!0;else throw V}else if(J.finalized===!1&&Y)K=await Y(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var Ek0=Symbol();var jk0=async(Q,X=Object.create(null))=>{let{all:Y=!1,dot:J=!1}=X,W=(Q instanceof nE?Q.raw.headers:Q.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return bi1(Q,{all:Y,dot:J});return{}};async function bi1(Q,X){let Y=await Q.formData();if(Y)return fi1(Y,X);return{}}function fi1(Q,X){let Y=Object.create(null);if(Q.forEach((J,G)=>{if(!(X.all||G.endsWith("[]")))Y[G]=J;else hi1(Y,G,J)}),X.dot)Object.entries(Y).forEach(([J,G])=>{if(J.includes("."))xi1(Y,J,G),delete Y[J]});return Y}var hi1=(Q,X,Y)=>{if(Q[X]!==void 0)if(Array.isArray(Q[X]))Q[X].push(Y);else Q[X]=[Q[X],Y];else if(!X.endsWith("[]"))Q[X]=Y;else Q[X]=[Y]},xi1=(Q,X,Y)=>{let J=Q,G=X.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Y;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var Ml=(Q)=>{let X=Q.split("/");if(X[0]==="")X.shift();return X},Ck0=(Q)=>{let{groups:X,path:Y}=gi1(Q),J=Ml(Y);return ui1(J,X)},gi1=(Q)=>{let X=[];return Q=Q.replace(/\{[^}]+\}/g,(Y,J)=>{let G=`@${J}`;return X.push([G,Y]),G}),{groups:X,path:Q}},ui1=(Q,X)=>{for(let Y=X.length-1;Y>=0;Y--){let[J]=X[Y];for(let G=Q.length-1;G>=0;G--)if(Q[G].includes(J)){Q[G]=Q[G].replace(J,X[Y][1]);break}}return Q},iE={},Ik0=(Q,X)=>{if(Q==="*")return"*";let Y=Q.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let J=`${Q}#${X}`;if(!iE[J])if(Y[2])iE[J]=X&&X[0]!==":"&&X[0]!=="*"?[J,Y[1],new RegExp(`^${Y[2]}(?=/${X})`)]:[Q,Y[1],new RegExp(`^${Y[2]}$`)];else iE[J]=[Q,Y[1],!0];return iE[J]}return null},MV=(Q,X)=>{try{return X(Q)}catch{return Q.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return X(Y)}catch{return Y}})}},mi1=(Q)=>MV(Q,decodeURI),Pl=(Q)=>{let X=Q.url,Y=X.indexOf("/",X.indexOf(":")+4),J=Y;for(;J<X.length;J++){let G=X.charCodeAt(J);if(G===37){let W=X.indexOf("?",J),Z=X.slice(Y,W===-1?void 0:W);return mi1(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return X.slice(Y,J)};var Rk0=(Q)=>{let X=Pl(Q);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},tK=(Q,X,...Y)=>{if(Y.length)X=tK(X,...Y);return`${Q?.[0]==="/"?"":"/"}${Q}${X==="/"?"":`${Q?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},aE=(Q)=>{if(Q.charCodeAt(Q.length-1)!==63||!Q.includes(":"))return null;let X=Q.split("/"),Y=[],J="";return X.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Y.length===0&&J==="")Y.push("/");else Y.push(J);let W=G.replace("?","");J+="/"+W,Y.push(J)}else J+="/"+G}),Y.filter((G,W,Z)=>Z.indexOf(G)===W)},wl=(Q)=>{if(!/[%+]/.test(Q))return Q;if(Q.indexOf("+")!==-1)Q=Q.replace(/\+/g," ");return Q.indexOf("%")!==-1?MV(Q,uD):Q},Sk0=(Q,X,Y)=>{let J;if(!Y&&X&&!/[%+]/.test(X)){let Z=Q.indexOf("?",8);if(Z===-1)return;if(!Q.startsWith(X,Z+1))Z=Q.indexOf(`&${X}`,Z+1);while(Z!==-1){let $=Q.charCodeAt(Z+X.length+1);if($===61){let K=Z+X.length+2,H=Q.indexOf("&",K);return wl(Q.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=Q.indexOf(`&${X}`,Z+1)}if(J=/[%+]/.test(Q),!J)return}let G={};J??=/[%+]/.test(Q);let W=Q.indexOf("?",8);while(W!==-1){let Z=Q.indexOf("&",W+1),$=Q.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=Q.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=wl(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=Q.slice($+1,Z===-1?void 0:Z),J)H=wl(H);if(Y){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return X?G[X]:G},vk0=Sk0,kk0=(Q,X)=>{return Sk0(Q,X,!0)},uD=decodeURIComponent;var _k0=(Q)=>MV(Q,uD),nE=class{raw;#Q;#X;routeIndex=0;path;bodyCache={};constructor(Q,X="/",Y=[[]]){this.raw=Q,this.path=X,this.#X=Y,this.#Q={}}param(Q){return Q?this.#Y(Q):this.#J()}#Y(Q){let X=this.#X[0][this.routeIndex][1][Q],Y=this.#W(X);return Y&&/\%/.test(Y)?_k0(Y):Y}#J(){let Q={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let Y of X){let J=this.#W(this.#X[0][this.routeIndex][1][Y]);if(J!==void 0)Q[Y]=/\%/.test(J)?_k0(J):J}return Q}#W(Q){return this.#X[1]?this.#X[1][Q]:Q}query(Q){return vk0(this.url,Q)}queries(Q){return kk0(this.url,Q)}header(Q){if(Q)return this.raw.headers.get(Q)??void 0;let X={};return this.raw.headers.forEach((Y,J)=>{X[J]=Y}),X}async parseBody(Q){return this.bodyCache.parsedBody??=await jk0(this,Q)}#G=(Q)=>{let{bodyCache:X,raw:Y}=this,J=X[Q];if(J)return J;let G=Object.keys(X)[0];if(G)return X[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[Q]()});return X[Q]=Y[Q]()};json(){return this.#G("text").then((Q)=>JSON.parse(Q))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(Q,X){this.#Q[Q]=X}valid(Q){return this.#Q[Q]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ek0](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Q]])=>Q)}get routePath(){return this.#X[0].map(([[,Q]])=>Q)[this.routeIndex].path}};var yk0={Stringify:1,BeforeStream:2,Stream:3},li1=(Q,X)=>{let Y=new String(Q);return Y.isEscaped=!0,Y.callbacks=X,Y};var Tl=async(Q,X,Y,J,G)=>{if(typeof Q==="object"&&!(Q instanceof String)){if(!(Q instanceof Promise))Q=Q.toString();if(Q instanceof Promise)Q=await Q}let W=Q.callbacks;if(!W?.length)return Promise.resolve(Q);if(G)G[0]+=Q;else G=[Q];let Z=Promise.all(W.map(($)=>$({phase:X,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>Tl(K,X,!1,J,G))).then(()=>G[0]));if(Y)return li1(await Z,W);else return Z};var di1="text/plain; charset=UTF-8",Al=(Q,X)=>{return{"Content-Type":Q,...X}},bk0=class{#Q;#X;env={};#Y;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(Q,X){if(this.#Q=Q,X)this.#W=X.executionCtx,this.env=X.env,this.#H=X.notFoundHandler,this.#q=X.path,this.#V=X.matchResult}get req(){return this.#X??=new nE(this.#Q,this.#q,this.#V),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(Q){if(this.#G&&Q){Q=new Response(Q.body,Q);for(let[X,Y]of this.#G.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let J=this.#G.headers.getSetCookie();Q.headers.delete("set-cookie");for(let G of J)Q.headers.append("set-cookie",G)}else Q.headers.set(X,Y)}}this.#G=Q,this.finalized=!0}render=(...Q)=>{return this.#Z??=(X)=>this.html(X),this.#Z(...Q)};setLayout=(Q)=>this.#$=Q;getLayout=()=>this.#$;setRenderer=(Q)=>{this.#Z=Q};header=(Q,X,Y)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(X===void 0)J.delete(Q);else if(Y?.append)J.append(Q,X);else J.set(Q,X)};status=(Q)=>{this.#J=Q};set=(Q,X)=>{this.#Y??=new Map,this.#Y.set(Q,X)};get=(Q)=>{return this.#Y?this.#Y.get(Q):void 0};get var(){if(!this.#Y)return{};return Object.fromEntries(this.#Y)}#F(Q,X,Y){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof X==="object"&&"headers"in X){let W=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Y)for(let[W,Z]of Object.entries(Y))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof X==="number"?X:X?.status??this.#J;return new Response(Q,{status:G,headers:J})}newResponse=(...Q)=>this.#F(...Q);body=(Q,X,Y)=>this.#F(Q,X,Y);text=(Q,X,Y)=>{return!this.#K&&!this.#J&&!X&&!Y&&!this.finalized?new Response(Q):this.#F(Q,X,Al(di1,Y))};json=(Q,X,Y)=>{return this.#F(JSON.stringify(Q),X,Al("application/json",Y))};html=(Q,X,Y)=>{let J=(G)=>this.#F(G,X,Al("text/html; charset=UTF-8",Y));return typeof Q==="object"?Tl(Q,yk0.Stringify,!1,{}).then(J):J(Q)};redirect=(Q,X)=>{let Y=String(Q);return this.header("Location",!/[^\x00-\xFF]/.test(Y)?Y:encodeURI(Y)),this.newResponse(null,X??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var d4="ALL",fk0="all",hk0=["get","post","put","delete","options","patch"],rE="Can not add a route since the matcher is already built.",oE=class extends Error{};var xk0="__COMPOSED_HANDLER";var pi1=(Q)=>{return Q.text("404 Not Found",404)},gk0=(Q,X)=>{if("getResponse"in Q){let Y=Q.getResponse();return X.newResponse(Y.body,Y)}return console.error(Q),X.text("Internal Server Error",500)},uk0=class Q{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Q="/";routes=[];constructor(X={}){[...hk0,fk0].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#Q=Z;else this.#J(W,this.#Q,Z);return $.forEach((K)=>{this.#J(W,this.#Q,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#Q=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#Q,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#Q=W;else this.#Q="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(d4,this.#Q,$)}),this};let{strict:J,...G}=X;Object.assign(this,G),this.getPath=J??!0?X.getPath??Pl:Rk0}#X(){let X=new Q({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#Y=this.#Y,X.routes=this.routes,X}#Y=pi1;errorHandler=gk0;route(X,Y){let J=this.basePath(X);return Y.routes.map((G)=>{let W;if(Y.errorHandler===gk0)W=G.handler;else W=async(Z,$)=>(await Ll([],Y.errorHandler)(Z,()=>G.handler(Z,$))).res,W[xk0]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(X){let Y=this.#X();return Y._basePath=tK(this._basePath,X),Y}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#Y=X,this};mount(X,Y,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=tK(this._basePath,X),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Y(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(d4,tK(X,"*"),$),this}#J(X,Y,J){X=X.toUpperCase(),Y=tK(this._basePath,Y);let G={basePath:this._basePath,path:Y,method:X,handler:J};this.router.add(X,Y,[J,G]),this.routes.push(G)}#W(X,Y){if(X instanceof Error)return this.errorHandler(X,Y);throw X}#G(X,Y,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(X,Y,J,"GET")))();let W=this.getPath(X,{env:J}),Z=this.router.match(G,W),$=new bk0(X,{path:W,matchResult:Z,env:J,executionCtx:Y,notFoundHandler:this.#Y});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Y($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Y($))).catch((F)=>this.#W(F,$)):H??this.#Y($)}let K=Ll(Z[0],this.errorHandler,this.#Y);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(X,...Y)=>{return this.#G(X,Y[1],Y[0],X.method)};request=(X,Y,J,G)=>{if(X instanceof Request)return this.fetch(Y?new Request(X,Y):X,J,G);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${tK("/",X)}`,Y),J,G)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#G(X.request,X,void 0,X.request.method))})}};var mD=[];function sE(Q,X){let Y=this.buildAllMatchers(),J=(G,W)=>{let Z=Y[G]||Y[d4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],mD];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(Q,X)}var tE="[^/]+",lD=".*",dD="(?:|/.*)",eK=Symbol(),ci1=new Set(".\\+*[^]$()");function ni1(Q,X){if(Q.length===1)return X.length===1?Q<X?-1:1:-1;if(X.length===1)return 1;if(Q===lD||Q===dD)return 1;else if(X===lD||X===dD)return-1;if(Q===tE)return 1;else if(X===tE)return-1;return Q.length===X.length?Q<X?-1:1:X.length-Q.length}var mk0=class Q{#Q;#X;#Y=Object.create(null);insert(X,Y,J,G,W){if(X.length===0){if(this.#Q!==void 0)throw eK;if(W)return;this.#Q=Y;return}let[Z,...$]=X,K=Z==="*"?$.length===0?["","",lD]:["","",tE]:Z==="/*"?["","",dD]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||tE;if(F&&K[2]){if(V===".*")throw eK;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw eK}if(H=this.#Y[V],!H){if(Object.keys(this.#Y).some((q)=>q!==lD&&q!==dD))throw eK;if(W)return;if(H=this.#Y[V]=new Q,F!=="")H.#X=G.varIndex++}if(!W&&F!=="")J.push([F,H.#X])}else if(H=this.#Y[Z],!H){if(Object.keys(this.#Y).some((F)=>F.length>1&&F!==lD&&F!==dD))throw eK;if(W)return;H=this.#Y[Z]=new Q}H.insert($,Y,J,G,W)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(ni1).map((J)=>{let G=this.#Y[J];return(typeof G.#X==="number"?`(${J})@${G.#X}`:ci1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#Q==="number")Y.unshift(`#${this.#Q}`);if(Y.length===0)return"";if(Y.length===1)return Y[0];return"(?:"+Y.join("|")+")"}};var lk0=class{#Q={varIndex:0};#X=new mk0;insert(Q,X,Y){let J=[],G=[];for(let Z=0;;){let $=!1;if(Q=Q.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=Q.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#X.insert(W,X,J,this.#Q,Y),J}buildRegExp(){let Q=this.#X.buildRegExpStr();if(Q==="")return[/^$/,[],[]];let X=0,Y=[],J=[];return Q=Q.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Y[++X]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++X,"";return""}),[new RegExp(`^${Q}`),Y,J]}};var ii1=[/^$/,[],Object.create(null)],dk0=Object.create(null);function pk0(Q){return dk0[Q]??=new RegExp(Q==="*"?"":`^${Q.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function ai1(){dk0=Object.create(null)}function ri1(Q){let X=new lk0,Y=[];if(Q.length===0)return ii1;let J=Q.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,z,B]=J[H];if(q)G[z]=[B.map(([L])=>[L,Object.create(null)]),mD];else F++;let D;try{D=X.insert(z,F,q)}catch(L){throw L===eK?new oE(z):L}if(q)continue;Y[F]=B.map(([L,M])=>{let C=Object.create(null);M-=1;for(;M>=0;M--){let[A,E]=D[M];C[A]=E}return[L,C]})}let[W,Z,$]=X.buildRegExp();for(let H=0,F=Y.length;H<F;H++)for(let V=0,q=Y[H].length;V<q;V++){let z=Y[H][V]?.[1];if(!z)continue;let B=Object.keys(z);for(let D=0,L=B.length;D<L;D++)z[B[D]]=$[z[B[D]]]}let K=[];for(let H in Z)K[H]=Y[Z[H]];return[W,K,G]}function PV(Q,X){if(!Q)return;for(let Y of Object.keys(Q).sort((J,G)=>G.length-J.length))if(pk0(Y).test(X))return[...Q[Y]];return}var eE=class{name="RegExpRouter";#Q;#X;constructor(){this.#Q={[d4]:Object.create(null)},this.#X={[d4]:Object.create(null)}}add(Q,X,Y){let J=this.#Q,G=this.#X;if(!J||!G)throw Error(rE);if(!J[Q])[J,G].forEach(($)=>{$[Q]=Object.create(null),Object.keys($[d4]).forEach((K)=>{$[Q][K]=[...$[d4][K]]})});if(X==="/*")X="*";let W=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let $=pk0(X);if(Q===d4)Object.keys(J).forEach((K)=>{J[K][X]||=PV(J[K],X)||PV(J[d4],X)||[]});else J[Q][X]||=PV(J[Q],X)||PV(J[d4],X)||[];Object.keys(J).forEach((K)=>{if(Q===d4||Q===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Y,W])})}),Object.keys(G).forEach((K)=>{if(Q===d4||Q===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Y,W]))});return}let Z=aE(X)||[X];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(Q===d4||Q===F)G[F][H]||=[...PV(J[F],H)||PV(J[d4],H)||[]],G[F][H].push([Y,W-K+$+1])})}}match=sE;buildAllMatchers(){let Q=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Q)).forEach((X)=>{Q[X]||=this.#Y(X)}),this.#Q=this.#X=void 0,ai1(),Q}#Y(Q){let X=[],Y=Q===d4;if([this.#Q,this.#X].forEach((J)=>{let G=J[Q]?Object.keys(J[Q]).map((W)=>[W,J[Q][W]]):[];if(G.length!==0)Y||=!0,X.push(...G);else if(Q!==d4)X.push(...Object.keys(J[d4]).map((W)=>[W,J[d4][W]]))}),!Y)return null;else return ri1(X)}};var oi1=class{name="PreparedRegExpRouter";#Q;#X;constructor(Q,X){this.#Q=Q,this.#X=X}#Y(Q,X){let Y=this.#Q[Q];Y[1].forEach((J)=>J&&J.push(X)),Object.values(Y[2]).forEach((J)=>J[0].push(X))}#J(Q,X,Y,J,G){let W=this.#Q[Q];if(!G)W[2][X][0].push([Y,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Y,G]);else W[2][Z||X][0].push([Y,G])})}add(Q,X,Y){if(!this.#Q[Q]){let G=this.#Q[d4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),mD];this.#Q[Q]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(X==="/*"||X==="*"){let G=[Y,{}];if(Q===d4)for(let W in this.#Q)this.#Y(W,G);else this.#Y(Q,G);return}let J=this.#X[X];if(!J)throw Error(`Path ${X} is not registered`);for(let[G,W]of J)if(Q===d4)for(let Z in this.#Q)this.#J(Z,X,Y,G,W);else this.#J(Q,X,Y,G,W)}buildAllMatchers(){return this.#Q}match=sE};var El=class{name="SmartRouter";#Q=[];#X=[];constructor(Q){this.#Q=Q.routers}add(Q,X,Y){if(!this.#X)throw Error(rE);this.#X.push([Q,X,Y])}match(Q,X){if(!this.#X)throw Error("Fatal error");let Y=this.#Q,J=this.#X,G=Y.length,W=0,Z;for(;W<G;W++){let $=Y[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(Q,X)}catch(K){if(K instanceof oE)continue;throw K}this.match=$.match.bind($),this.#Q=[$],this.#X=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#X||this.#Q.length!==1)throw Error("No active router has been determined yet.");return this.#Q[0]}};var pD=Object.create(null),ck0=class Q{#Q;#X;#Y;#J=0;#W=pD;constructor(X,Y,J){if(this.#X=J||Object.create(null),this.#Q=[],X&&Y){let G=Object.create(null);G[X]={handler:Y,possibleKeys:[],score:0},this.#Q=[G]}this.#Y=[]}insert(X,Y,J){this.#J=++this.#J;let G=this,W=Ck0(Y),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=Ik0(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#X){if(G=G.#X[q],V)Z.push(V[1]);continue}if(G.#X[q]=new Q,V)G.#Y.push(V),Z.push(V[1]);G=G.#X[q]}return G.#Q.push({[X]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(X,Y,J,G){let W=[];for(let Z=0,$=X.#Q.length;Z<$;Z++){let K=X.#Q[Z],H=K[Y]||K[d4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==pD||G&&G!==pD)for(let V=0,q=H.possibleKeys.length;V<q;V++){let z=H.possibleKeys[V],B=F[H.score];H.params[z]=G?.[z]&&!B?G[z]:J[z]??G?.[z],F[H.score]=!0}}}return W}search(X,Y){let J=[];this.#W=pD;let W=[this],Z=Ml(Y),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let z=0,B=W.length;z<B;z++){let D=W[z],L=D.#X[F];if(L)if(L.#W=D.#W,V){if(L.#X["*"])J.push(...this.#G(L.#X["*"],X,D.#W));J.push(...this.#G(L,X,D.#W))}else q.push(L);for(let M=0,C=D.#Y.length;M<C;M++){let A=D.#Y[M],E=D.#W===pD?{}:{...D.#W};if(A==="*"){let b=D.#X["*"];if(b)J.push(...this.#G(b,X,D.#W)),b.#W=E,q.push(b);continue}let[T,j,R]=A;if(!F&&!(R instanceof RegExp))continue;let v=D.#X[T],y=Z.slice(K).join("/");if(R instanceof RegExp){let b=R.exec(y);if(b){if(E[j]=b[0],J.push(...this.#G(v,X,D.#W,E)),Object.keys(v.#X).length){v.#W=E;let h=b[0].match(/\//)?.length??0;($[h]||=[]).push(v)}continue}}if(R===!0||R.test(F))if(E[j]=F,V){if(J.push(...this.#G(v,X,E,D.#W)),v.#X["*"])J.push(...this.#G(v.#X["*"],X,E,D.#W))}else v.#W=E,q.push(v)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var jl=class{name="TrieRouter";#Q;constructor(){this.#Q=new ck0}add(Q,X,Y){let J=aE(X);if(J){for(let G=0,W=J.length;G<W;G++)this.#Q.insert(Q,J[G],Y);return}this.#Q.insert(Q,X,Y)}match(Q,X){return this.#Q.search(Q,X)}};var ZQ=class extends uk0{constructor(Q={}){super(Q);this.router=Q.router??new El({routers:[new eE,new jl]})}};function si1(){let{process:Q,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Q!==void 0?"NO_COLOR"in Q?.env:!1)}async function nk0(){let{navigator:Q}=globalThis,X="cloudflare:workers";return!(Q!==void 0&&Q.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!si1())}var ti1=(Q)=>{let[X,Y]=[",","."];return Q.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(Y)},ei1=(Q)=>{let X=Date.now()-Q;return ti1([X<1000?X+"ms":Math.round(X/1000)+"s"])},Qa1=async(Q)=>{if(await nk0())switch(Q/100|0){case 5:return`\x1B[31m${Q}\x1B[0m`;case 4:return`\x1B[33m${Q}\x1B[0m`;case 3:return`\x1B[36m${Q}\x1B[0m`;case 2:return`\x1B[32m${Q}\x1B[0m`}return`${Q}`};async function ik0(Q,X,Y,J,G=0,W){let Z=X==="<--"?`${X} ${Y} ${J}`:`${X} ${Y} ${J} ${await Qa1(G)} ${W}`;Q(Z)}var ak0=(Q=console.log)=>{return async function(Y,J){let{method:G,url:W}=Y.req,Z=W.slice(W.indexOf("/",8));await ik0(Q,"<--",G,Z);let $=Date.now();await J(),await ik0(Q,"-->",G,Z,Y.res.status,ei1($))}};var rk0=(Q)=>{let Y={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Q},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Y.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Y.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Y.credentials)K("Access-Control-Allow-Credentials","true");if(Y.exposeHeaders?.length)K("Access-Control-Expose-Headers",Y.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Y.origin!=="*")K("Vary","Origin");if(Y.maxAge!=null)K("Access-Control-Max-Age",Y.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Y.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Y.origin!=="*")Z.header("Vary","Origin",{append:!0})}};var ok0=()=>{try{return performance.now()}catch{}return Date.now()},Cl=(Q)=>{let X={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...Q};return async function(J,G){let W=[],Z=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:W,timers:Z}),X.total)TV(J,"total",X.totalDescription);if(await G(),X.total)QH(J,"total");if(X.autoEnd)Z.forEach((K,H)=>QH(J,H));if(typeof X.enabled==="function"?X.enabled(J):X.enabled){J.res.headers.append("Server-Timing",W.join(","));let K=typeof X.crossOrigin==="function"?X.crossOrigin(J):X.crossOrigin;if(K)J.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},sk0=(Q,X,Y,J,G)=>{let W=Q.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Y==="number"){let Z=Y.toFixed(G||1),$=J?`${X};dur=${Z};desc="${J}"`:`${X};dur=${Z}`;W.headers.push($)}else{let Z=Y?`${X};desc="${Y}"`:`${X}`;W.headers.push(Z)}},TV=(Q,X,Y)=>{let J=Q.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(X,{description:Y,start:ok0()})},QH=(Q,X,Y)=>{let J=Q.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(X);if(!G){console.warn(`Timer "${X}" does not exist!`);return}let{description:W,start:Z}=G,$=ok0()-Z;sk0(Q,X,$,W,Y),J.timers.delete(X)};var Xa1=/^[\w!#$%&'*.^`|~+-]+$/,Ya1=/^[ !#-:<-[\]-~]*$/,Il=(Q,X)=>{if(X&&Q.indexOf(X)===-1)return{};let Y=Q.trim().split(";"),J={};for(let G of Y){G=G.trim();let W=G.indexOf("=");if(W===-1)continue;let Z=G.substring(0,W).trim();if(X&&X!==Z||!Xa1.test(Z))continue;let $=G.substring(W+1).trim();if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Ya1.test($)){if(J[Z]=$.indexOf("%")!==-1?MV($,uD):$,X)break}}return J};var tk0=(Q,X,Y)=>{let J=Q.req.raw.headers.get("Cookie");if(typeof X==="string"){if(!J)return;let W=X;if(Y==="secure")W="__Secure-"+X;else if(Y==="host")W="__Host-"+X;return Il(J,W)[W]}if(!J)return{};return Il(J)};var Rl=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_GATEWAY_CREATE",description:"Create gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_LIST",description:"List gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_GET",description:"View gateway details",category:"Gateways"},{name:"COLLECTION_GATEWAY_UPDATE",description:"Update gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_DELETE",description:"Delete gateways",category:"Gateways",dangerous:!0},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"}];function cD(){let Q={Organizations:[],Connections:[],Gateways:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[]};for(let X of Rl)Q[X.category]?.push(X);return Q}var Ja1=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Ga1="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+Ja1+"]*",Wa1=new RegExp("^"+Ga1+"$");function ek0(Q,X){let Y=[],J=X.exec(Q);while(J){let G=[];G.startIndex=X.lastIndex-J[0].length;let W=J.length;for(let Z=0;Z<W;Z++)G.push(J[Z]);Y.push(G),J=X.exec(Q)}return Y}var Sl=function(Q){let X=Wa1.exec(Q);return!(X===null||typeof X>"u")};var Za1={allowBooleanAttributes:!1,unpairedTags:[]};function G_0(Q,X){X=Object.assign({},Za1,X);let Y=[],J=!1,G=!1;if(Q[0]==="\uFEFF")Q=Q.substr(1);for(let W=0;W<Q.length;W++)if(Q[W]==="<"&&Q[W+1]==="?"){if(W+=2,W=X_0(Q,W),W.err)return W}else if(Q[W]==="<"){let Z=W;if(W++,Q[W]==="!"){W=Y_0(Q,W);continue}else{let $=!1;if(Q[W]==="/")$=!0,W++;let K="";for(;W<Q.length&&Q[W]!==">"&&Q[W]!==" "&&Q[W]!=="\t"&&Q[W]!==`
|
|
259
|
+
Lifetime used`):new V80("Lifetime not alive")}},s$=class extends u9{constructor(Q,X){super(Q,void 0,void 0,X)}get dupable(){return!0}dup(){return this}dispose(){}},z80=class extends u9{constructor(Q,X,Y,J){super(Q,X,Y,J)}dispose(){this._alive=!1}};k5=class Q extends g7{constructor(){super(...arguments);this._disposables=new u9(new Set),this.manage=(X)=>(this._disposables.value.add(X),X)}static withScope(X){let Y=new Q,J;try{return X(Y)}catch(G){throw J=G,G}finally{H80(Y,J)}}static withScopeMaybeAsync(X,Y){return xS6(void 0,function*(J){let G=new Q,W;try{return yield*J.of(Y.call(X,J,G))}catch(Z){throw W=Z,Z}finally{H80(G,W)}})}static async withScopeAsync(X){let Y=new Q,J;try{return await X(Y)}catch(G){throw J=G,G}finally{H80(Y,J)}}get alive(){return this._disposables.alive}dispose(){let X=Array.from(this._disposables.value.values()).reverse();for(let Y of X)Y.alive&&Y.dispose();this._disposables.dispose()}};N80=class Q extends g7{static success(X){return new nY1(X)}static fail(X,Y){return new iY1(X,Y)}static is(X){return X instanceof Q}},nY1=class extends N80{constructor(Q){super();this.value=Q}get alive(){return uy(this.value)?this.value.alive:!0}dispose(){uy(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(Q){return this.value}},iY1=class extends N80{constructor(Q,X){super();this.error=Q,this.onUnwrap=X}get alive(){return uy(this.error)?this.error.alive:!0}dispose(){uy(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(Q){return Q}},YF=N80,aY1=class extends g7{constructor(Q){super();this.resolve=(X)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(X)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,X||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=Q.context,this.owner=Q.context.runtime,this.handle=Q.promiseHandle,this.settled=new Promise((X)=>{this.onSettled=X}),this.resolveHandle=Q.resolveHandle,this.rejectHandle=Q.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()}},rg4=Symbol("Unstable"),O80=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});dS6=class extends g7{constructor(Q,X){super();this.handle=Q,this.context=X,this._isDone=!1,this.owner=X.runtime}[Symbol.iterator](){return this}next(Q){if(!this.alive||this._isDone)return{done:!0,value:void 0};let X=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(X,Q)}return(Q){if(!this.alive)return{done:!0,value:void 0};let X=this.context.getProp(this.handle,"return");if(X===this.context.undefined&&Q===void 0)return this.dispose(),{done:!0,value:void 0};let Y=this.callIteratorMethod(X,Q);return X.dispose(),this.dispose(),Y}throw(Q){if(!this.alive)return{done:!0,value:void 0};let X=Q instanceof u9?Q:this.context.newError(Q),Y=this.context.getProp(this.handle,"throw"),J=this.callIteratorMethod(Y,Q);return X.alive&&X.dispose(),Y.dispose(),this.dispose(),J}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Q,X){let Y=X?this.context.callFunction(Q,this.handle,X):this.context.callFunction(Q,this.handle);if(Y.error)return this.dispose(),{value:Y};let J=this.context.getProp(Y.value,"done").consume((W)=>this.context.dump(W));if(J)return Y.value.dispose(),this.dispose(),{done:J,value:void 0};let G=this.context.getProp(Y.value,"value");return Y.value.dispose(),{value:YF.success(G),done:J}}},pS6=class extends rY1{constructor(Q){super(Q.module);this.scope=new k5,this.copyJSValue=(X)=>this.ffi.QTS_DupValuePointer(this.ctx.value,X),this.freeJSValue=(X)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,X)},Q.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.owner=Q.owner,this.module=Q.module,this.ffi=Q.ffi,this.rt=Q.rt,this.ctx=this.scope.manage(Q.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(Q){return this.scope.manage(Q)}consumeJSCharPointer(Q){let X=this.module.UTF8ToString(Q);return this.ffi.QTS_FreeCString(this.ctx.value,Q),X}heapValueHandle(Q){return new u9(Q,this.copyJSValue,this.freeJSValue,this.owner)}staticHeapValueHandle(Q){return this.manage(this.heapValueHandle(Q)),new s$(Q,this.owner)}},oY1=class extends g7{constructor(Q){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.fnNextId=-32768,this.fnMaps=new Map,this.cToHostCallbacks={callFunction:(X,Y,J,G,W)=>{if(X!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let Z=this.getFunction(W);if(!Z)throw Error(`QuickJSContext had no callback with id ${W}`);return k5.withScopeMaybeAsync(this,function*($,K){let H=K.manage(new z80(Y,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),F=Array(J);for(let V=0;V<J;V++){let q=this.ffi.QTS_ArgvGetJSValueConstPointer(G,V);F[V]=K.manage(new z80(q,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let V=yield*$(Z.apply(H,F));if(V){if("error"in V&&V.error)throw this.runtime.debugLog("throw error",V.error),V.error;let q=K.manage(V instanceof u9?V:V.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,q.value)}return 0}catch(V){return this.errorToHandle(V).consume((q)=>this.ffi.QTS_Throw(this.ctx.value,q.value))}})}},this.runtime=Q.runtime,this.module=Q.module,this.ffi=Q.ffi,this.rt=Q.rt,this.ctx=Q.ctx,this.memory=new pS6({...Q,owner:this.runtime}),Q.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 Q=this.ffi.QTS_GetUndefined();return this._undefined=new s$(Q)}get null(){if(this._null)return this._null;let Q=this.ffi.QTS_GetNull();return this._null=new s$(Q)}get true(){if(this._true)return this._true;let Q=this.ffi.QTS_GetTrue();return this._true=new s$(Q)}get false(){if(this._false)return this._false;let Q=this.ffi.QTS_GetFalse();return this._false=new s$(Q)}get global(){if(this._global)return this._global;let Q=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(Q),this._global}newNumber(Q){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,Q))}newString(Q){let X=this.memory.newHeapCharPointer(Q).consume((Y)=>this.ffi.QTS_NewString(this.ctx.value,Y.value.ptr));return this.memory.heapValueHandle(X)}newUniqueSymbol(Q){let X=(typeof Q=="symbol"?Q.description:Q)??"",Y=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,0));return this.memory.heapValueHandle(Y)}newSymbolFor(Q){let X=(typeof Q=="symbol"?Q.description:Q)??"",Y=this.memory.newHeapCharPointer(X).consume((J)=>this.ffi.QTS_NewSymbol(this.ctx.value,J.value.ptr,1));return this.memory.heapValueHandle(Y)}getWellKnownSymbol(Q){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,Q)}newBigInt(Q){if(!this._BigInt){let J=this.getProp(this.global,"BigInt");this.memory.manage(J),this._BigInt=new s$(J.value,this.runtime)}let X=this._BigInt,Y=String(Q);return this.newString(Y).consume((J)=>this.unwrapResult(this.callFunction(X,this.undefined,J)))}newObject(Q){Q&&this.runtime.assertOwned(Q);let X=Q?this.ffi.QTS_NewObjectProto(this.ctx.value,Q.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(X)}newArray(){let Q=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(Q)}newArrayBuffer(Q){let X=new Uint8Array(Q),Y=this.memory.newHeapBufferPointer(X),J=this.ffi.QTS_NewArrayBuffer(this.ctx.value,Y.value.pointer,X.length);return this.memory.heapValueHandle(J)}newPromise(Q){let X=k5.withScope((Y)=>{let J=Y.manage(this.memory.newMutablePointerArray(2)),G=this.ffi.QTS_NewPromiseCapability(this.ctx.value,J.value.ptr),W=this.memory.heapValueHandle(G),[Z,$]=Array.from(J.value.typedArray).map((K)=>this.memory.heapValueHandle(K));return new aY1({context:this,promiseHandle:W,resolveHandle:Z,rejectHandle:$})});return Q&&typeof Q=="function"&&(Q=new Promise(Q)),Q&&Promise.resolve(Q).then(X.resolve,(Y)=>Y instanceof u9?X.reject(Y):this.newError(Y).consume(X.reject)),X}newFunction(Q,X){let Y=++this.fnNextId;return this.setFunction(Y,X),this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,Y,Q))}newError(Q){let X=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return Q&&typeof Q=="object"?(Q.name!==void 0&&this.newString(Q.name).consume((Y)=>this.setProp(X,"name",Y)),Q.message!==void 0&&this.newString(Q.message).consume((Y)=>this.setProp(X,"message",Y))):typeof Q=="string"?this.newString(Q).consume((Y)=>this.setProp(X,"message",Y)):Q!==void 0&&this.newString(String(Q)).consume((Y)=>this.setProp(X,"message",Y)),X}typeof(Q){return this.runtime.assertOwned(Q),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,Q.value))}getNumber(Q){return this.runtime.assertOwned(Q),this.ffi.QTS_GetFloat64(this.ctx.value,Q.value)}getString(Q){return this.runtime.assertOwned(Q),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,Q.value))}getSymbol(Q){this.runtime.assertOwned(Q);let X=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,Q.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,Q.value)?Symbol.for(X):Symbol(X)}getBigInt(Q){this.runtime.assertOwned(Q);let X=this.getString(Q);return BigInt(X)}getArrayBuffer(Q){this.runtime.assertOwned(Q);let X=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,Q.value),Y=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Q.value);if(!Y)throw Error("Couldn't allocate memory to get ArrayBuffer");return new u9(this.module.HEAPU8.subarray(Y,Y+X),void 0,()=>this.module._free(Y))}getPromiseState(Q){this.runtime.assertOwned(Q);let X=this.ffi.QTS_PromiseState(this.ctx.value,Q.value);if(X<0)return{type:"fulfilled",value:Q,notAPromise:!0};if(X===xy.Pending)return{type:"pending",get error(){return new lY1("Cannot unwrap a pending promise")}};let Y=this.ffi.QTS_PromiseResult(this.ctx.value,Q.value),J=this.memory.heapValueHandle(Y);if(X===xy.Fulfilled)return{type:"fulfilled",value:J};if(X===xy.Rejected)return{type:"rejected",error:J};throw J.dispose(),Error(`Unknown JSPromiseStateEnum: ${X}`)}resolvePromise(Q){this.runtime.assertOwned(Q);let X=k5.withScope((Y)=>{let J=Y.manage(this.getProp(this.global,"Promise")),G=Y.manage(this.getProp(J,"resolve"));return this.callFunction(G,J,Q)});return X.error?Promise.resolve(X):new Promise((Y)=>{k5.withScope((J)=>{let G=J.manage(this.newFunction("resolve",(K)=>{Y(this.success(K&&K.dup()))})),W=J.manage(this.newFunction("reject",(K)=>{Y(this.fail(K&&K.dup()))})),Z=J.manage(X.value),$=J.manage(this.getProp(Z,"then"));this.callFunction($,Z,G,W).unwrap().dispose()})})}isEqual(Q,X,Y=wP.IsStrictlyEqual){if(Q===X)return!0;this.runtime.assertOwned(Q),this.runtime.assertOwned(X);let J=this.ffi.QTS_IsEqual(this.ctx.value,Q.value,X.value,Y);if(J===-1)throw new fY1("WASM variant does not expose equality");return!!J}eq(Q,X){return this.isEqual(Q,X,wP.IsStrictlyEqual)}sameValue(Q,X){return this.isEqual(Q,X,wP.IsSameValue)}sameValueZero(Q,X){return this.isEqual(Q,X,wP.IsSameValueZero)}getProp(Q,X){this.runtime.assertOwned(Q);let Y;return typeof X=="number"&&X>=0?Y=this.ffi.QTS_GetPropNumber(this.ctx.value,Q.value,X):Y=this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_GetProp(this.ctx.value,Q.value,J.value)),this.memory.heapValueHandle(Y)}getLength(Q){if(this.runtime.assertOwned(Q),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,Q.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(Q,X={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(Q),Q.value;let Y=mS6(X);if(Y===0)throw new dY1("No options set, will return an empty array");return k5.withScope((J)=>{let G=J.manage(this.memory.newMutablePointerArray(1)),W=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,G.value.ptr,this.uint32Out.value.ptr,Q.value,Y);if(W)return this.fail(this.memory.heapValueHandle(W));let Z=this.uint32Out.value.typedArray[0],$=G.value.typedArray[0],K=new Uint32Array(this.module.HEAP8.buffer,$,Z),H=Array.from(K).map((F)=>this.memory.heapValueHandle(F));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,$),this.success(cY1(H))})}getIterator(Q){let X=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return k5.withScope((Y)=>{let J=Y.manage(this.getProp(Q,X)),G=this.callFunction(J,Q);return G.error?G:this.success(new dS6(G.value,this))})}setProp(Q,X,Y){this.runtime.assertOwned(Q),this.borrowPropertyKey(X).consume((J)=>this.ffi.QTS_SetProp(this.ctx.value,Q.value,J.value,Y.value))}defineProp(Q,X,Y){this.runtime.assertOwned(Q),k5.withScope((J)=>{let G=J.manage(this.borrowPropertyKey(X)),W=Y.value||this.undefined,Z=!!Y.configurable,$=!!Y.enumerable,K=!!Y.value,H=Y.get?J.manage(this.newFunction(Y.get.name,Y.get)):this.undefined,F=Y.set?J.manage(this.newFunction(Y.set.name,Y.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Q.value,G.value,W.value,H.value,F.value,Z,$,K)})}callFunction(Q,X,...Y){this.runtime.assertOwned(Q);let J,G=Y[0];G===void 0||Array.isArray(G)?J=G??[]:J=Y;let W=this.memory.toPointerArray(J).consume(($)=>this.ffi.QTS_Call(this.ctx.value,Q.value,X.value,J.length,$.value)),Z=this.ffi.QTS_ResolveException(this.ctx.value,W);return Z?(this.ffi.QTS_FreeValuePointer(this.ctx.value,W),this.fail(this.memory.heapValueHandle(Z))):this.success(this.memory.heapValueHandle(W))}callMethod(Q,X,Y=[]){return this.getProp(Q,X).consume((J)=>this.callFunction(J,Q,Y))}evalCode(Q,X="eval.js",Y){let J=Y===void 0?1:0,G=uS6(Y),W=this.memory.newHeapCharPointer(Q).consume(($)=>this.ffi.QTS_Eval(this.ctx.value,$.value.ptr,$.value.strlen,X,J,G)),Z=this.ffi.QTS_ResolveException(this.ctx.value,W);return Z?(this.ffi.QTS_FreeValuePointer(this.ctx.value,W),this.fail(this.memory.heapValueHandle(Z))):this.success(this.memory.heapValueHandle(W))}throw(Q){return this.errorToHandle(Q).consume((X)=>this.ffi.QTS_Throw(this.ctx.value,X.value))}borrowPropertyKey(Q){return typeof Q=="number"?this.newNumber(Q):typeof Q=="string"?this.newString(Q):new s$(Q.value,this.runtime)}getMemory(Q){if(Q===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(Q){this.runtime.assertOwned(Q);let X=this.typeof(Q);if(X==="string")return this.getString(Q);if(X==="number")return this.getNumber(Q);if(X==="bigint")return this.getBigInt(Q);if(X==="undefined")return;if(X==="symbol")return this.getSymbol(Q);let Y=this.getPromiseState(Q);if(Y.type==="fulfilled"&&!Y.notAPromise)return Q.dispose(),{type:Y.type,value:Y.value.consume(this.dump)};if(Y.type==="pending")return Q.dispose(),{type:Y.type};if(Y.type==="rejected")return Q.dispose(),{type:Y.type,error:Y.error.consume(this.dump)};let J=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,Q.value));try{return JSON.parse(J)}catch{return J}}unwrapResult(Q){if(Q.error){let X="context"in Q.error?Q.error.context:this,Y=Q.error.consume((J)=>this.dump(J));if(Y&&typeof Y=="object"&&typeof Y.message=="string"){let{message:J,name:G,stack:W,...Z}=Y,$=new F80(Y,X);typeof G=="string"&&($.name=Y.name),$.message=J;let K=$.stack;throw typeof W=="string"&&($.stack=`${G}: ${J}
|
|
260
|
+
${Y.stack}Host: ${K}`),Object.assign($,Z),$}throw new F80(Y)}return Q.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(Q){let X=Q>>8,Y=this.fnMaps.get(X);if(Y)return Y.get(Q)}setFunction(Q,X){let Y=Q>>8,J=this.fnMaps.get(Y);return J||(J=new Map,this.fnMaps.set(Y,J)),J.set(Q,X)}errorToHandle(Q){return Q instanceof u9?Q:this.newError(Q)}encodeBinaryJSON(Q){let X=this.ffi.QTS_bjson_encode(this.ctx.value,Q.value);return this.memory.heapValueHandle(X)}decodeBinaryJSON(Q){let X=this.ffi.QTS_bjson_decode(this.ctx.value,Q.value);return this.memory.heapValueHandle(X)}success(Q){return YF.success(Q)}fail(Q){return YF.fail(Q,(X)=>this.unwrapResult(X))}},sY1=class extends g7{constructor(Q){super();this.scope=new k5,this.contextMap=new Map,this._debugMode=!1,this.cToHostCallbacks={shouldInterrupt:(X)=>{if(X!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let Y=this.interruptHandler;if(!Y)throw Error("QuickJSContext had no interrupt handler");return Y(this)?1:0},loadModuleSource:kY1(this,function*(X,Y,J,G){let W=this.moduleLoader;if(!W)throw Error("Runtime has no module loader");if(Y!==this.rt.value)throw Error("Runtime pointer mismatch");let Z=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let $=yield*X(W(G,Z));if(typeof $=="object"&&"error"in $&&$.error)throw this.debugLog("cToHostLoadModule: loader returned error",$.error),$.error;let K=typeof $=="string"?$:("value"in $)?$.value:$;return this.memory.newHeapCharPointer(K).value.ptr}catch($){return this.debugLog("cToHostLoadModule: caught error",$),Z.throw($),0}}),normalizeModule:kY1(this,function*(X,Y,J,G,W){let Z=this.moduleNormalizer;if(!Z)throw Error("Runtime has no module normalizer");if(Y!==this.rt.value)throw Error("Runtime pointer mismatch");let $=this.contextMap.get(J)??this.newContext({contextPointer:J});try{let K=yield*X(Z(G,W,$));if(typeof K=="object"&&"error"in K&&K.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",K.error),K.error;let H=typeof K=="string"?K:K.value;return $.getMemory(this.rt.value).newHeapCharPointer(H).value.ptr}catch(K){return this.debugLog("normalizeModule: caught error",K),$.throw(K),0}})},Q.ownedLifetimes?.forEach((X)=>this.scope.manage(X)),this.module=Q.module,this.memory=new rY1(this.module),this.ffi=Q.ffi,this.rt=Q.rt,this.callbacks=Q.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),U80&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(Q={}){let X=gS6(Q.intrinsics),Y=new u9(Q.contextPointer||this.ffi.QTS_NewContext(this.rt.value,X),void 0,(G)=>{this.contextMap.delete(G),this.callbacks.deleteContext(G),this.ffi.QTS_FreeContext(G)}),J=new oY1({module:this.module,ctx:Y,ffi:this.ffi,rt:this.rt,ownedLifetimes:Q.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(Y.value,J),J}setModuleLoader(Q,X){this.moduleLoader=Q,this.moduleNormalizer=X,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(Q){let X=this.interruptHandler;this.interruptHandler=Q,X||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(Q=-1){let X=this.memory.newMutablePointerArray(1),Y=this.ffi.QTS_ExecutePendingJob(this.rt.value,Q??-1,X.value.ptr),J=X.value.typedArray[0];if(X.dispose(),J===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,Y),YF.success(0);let G=this.contextMap.get(J)??this.newContext({contextPointer:J}),W=G.getMemory(this.rt.value).heapValueHandle(Y);if(G.typeof(W)==="number"){let Z=G.getNumber(W);return W.dispose(),YF.success(Z)}else{let Z=Object.assign(W,{context:G});return YF.fail(Z,($)=>G.unwrapResult($))}}setMemoryLimit(Q){if(Q<0&&Q!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,Q)}computeMemoryUsage(){let Q=this.getSystemContext().getMemory(this.rt.value);return Q.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,Q.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(Q){if(Q<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,Q)}assertOwned(Q){if(Q.owner&&Q.owner.rt!==this.rt)throw new bY1(`Handle is not owned by this runtime: ${Q.owner.rt.value} != ${this.rt.value}`)}setDebugMode(Q){this._debugMode=Q,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,Q?1:0)}isDebugMode(){return this._debugMode}debugLog(...Q){this._debugMode&&console.log("quickjs-emscripten:",...Q)}[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 tY1={};$8(tY1,{applyModuleEvalRuntimeOptions:()=>M80,applyBaseRuntimeOptions:()=>w80,QuickJSWASMModule:()=>P80,QuickJSModuleCallbacks:()=>L80});var eY1=o(()=>{T80()});var XJ1={};$8(XJ1,{QuickJSFFI:()=>nS6});var nS6=class{constructor(Q){this.module=Q,this.DEBUG=!1,this.QTS_Throw=this.module.cwrap("QTS_Throw","number",["number","number"]),this.QTS_NewError=this.module.cwrap("QTS_NewError","number",["number"]),this.QTS_RuntimeSetMemoryLimit=this.module.cwrap("QTS_RuntimeSetMemoryLimit",null,["number","number"]),this.QTS_RuntimeComputeMemoryUsage=this.module.cwrap("QTS_RuntimeComputeMemoryUsage","number",["number","number"]),this.QTS_RuntimeDumpMemoryUsage=this.module.cwrap("QTS_RuntimeDumpMemoryUsage","number",["number"]),this.QTS_RecoverableLeakCheck=this.module.cwrap("QTS_RecoverableLeakCheck","number",[]),this.QTS_BuildIsSanitizeLeak=this.module.cwrap("QTS_BuildIsSanitizeLeak","number",[]),this.QTS_RuntimeSetMaxStackSize=this.module.cwrap("QTS_RuntimeSetMaxStackSize",null,["number","number"]),this.QTS_GetUndefined=this.module.cwrap("QTS_GetUndefined","number",[]),this.QTS_GetNull=this.module.cwrap("QTS_GetNull","number",[]),this.QTS_GetFalse=this.module.cwrap("QTS_GetFalse","number",[]),this.QTS_GetTrue=this.module.cwrap("QTS_GetTrue","number",[]),this.QTS_NewRuntime=this.module.cwrap("QTS_NewRuntime","number",[]),this.QTS_FreeRuntime=this.module.cwrap("QTS_FreeRuntime",null,["number"]),this.QTS_NewContext=this.module.cwrap("QTS_NewContext","number",["number","number"]),this.QTS_FreeContext=this.module.cwrap("QTS_FreeContext",null,["number"]),this.QTS_FreeValuePointer=this.module.cwrap("QTS_FreeValuePointer",null,["number","number"]),this.QTS_FreeValuePointerRuntime=this.module.cwrap("QTS_FreeValuePointerRuntime",null,["number","number"]),this.QTS_FreeVoidPointer=this.module.cwrap("QTS_FreeVoidPointer",null,["number","number"]),this.QTS_FreeCString=this.module.cwrap("QTS_FreeCString",null,["number","number"]),this.QTS_DupValuePointer=this.module.cwrap("QTS_DupValuePointer","number",["number","number"]),this.QTS_NewObject=this.module.cwrap("QTS_NewObject","number",["number"]),this.QTS_NewObjectProto=this.module.cwrap("QTS_NewObjectProto","number",["number","number"]),this.QTS_NewArray=this.module.cwrap("QTS_NewArray","number",["number"]),this.QTS_NewArrayBuffer=this.module.cwrap("QTS_NewArrayBuffer","number",["number","number","number"]),this.QTS_NewFloat64=this.module.cwrap("QTS_NewFloat64","number",["number","number"]),this.QTS_GetFloat64=this.module.cwrap("QTS_GetFloat64","number",["number","number"]),this.QTS_NewString=this.module.cwrap("QTS_NewString","number",["number","number"]),this.QTS_GetString=this.module.cwrap("QTS_GetString","number",["number","number"]),this.QTS_GetArrayBuffer=this.module.cwrap("QTS_GetArrayBuffer","number",["number","number"]),this.QTS_GetArrayBufferLength=this.module.cwrap("QTS_GetArrayBufferLength","number",["number","number"]),this.QTS_NewSymbol=this.module.cwrap("QTS_NewSymbol","number",["number","number","number"]),this.QTS_GetSymbolDescriptionOrKey=this.module.cwrap("QTS_GetSymbolDescriptionOrKey","number",["number","number"]),this.QTS_IsGlobalSymbol=this.module.cwrap("QTS_IsGlobalSymbol","number",["number","number"]),this.QTS_IsJobPending=this.module.cwrap("QTS_IsJobPending","number",["number"]),this.QTS_ExecutePendingJob=this.module.cwrap("QTS_ExecutePendingJob","number",["number","number","number"]),this.QTS_GetProp=this.module.cwrap("QTS_GetProp","number",["number","number","number"]),this.QTS_GetPropNumber=this.module.cwrap("QTS_GetPropNumber","number",["number","number","number"]),this.QTS_SetProp=this.module.cwrap("QTS_SetProp",null,["number","number","number","number"]),this.QTS_DefineProp=this.module.cwrap("QTS_DefineProp",null,["number","number","number","number","number","number","boolean","boolean","boolean"]),this.QTS_GetOwnPropertyNames=this.module.cwrap("QTS_GetOwnPropertyNames","number",["number","number","number","number","number"]),this.QTS_Call=this.module.cwrap("QTS_Call","number",["number","number","number","number","number"]),this.QTS_ResolveException=this.module.cwrap("QTS_ResolveException","number",["number","number"]),this.QTS_Dump=this.module.cwrap("QTS_Dump","number",["number","number"]),this.QTS_Eval=this.module.cwrap("QTS_Eval","number",["number","number","number","string","number","number"]),this.QTS_GetModuleNamespace=this.module.cwrap("QTS_GetModuleNamespace","number",["number","number"]),this.QTS_Typeof=this.module.cwrap("QTS_Typeof","number",["number","number"]),this.QTS_GetLength=this.module.cwrap("QTS_GetLength","number",["number","number","number"]),this.QTS_IsEqual=this.module.cwrap("QTS_IsEqual","number",["number","number","number","number"]),this.QTS_GetGlobalObject=this.module.cwrap("QTS_GetGlobalObject","number",["number"]),this.QTS_NewPromiseCapability=this.module.cwrap("QTS_NewPromiseCapability","number",["number","number"]),this.QTS_PromiseState=this.module.cwrap("QTS_PromiseState","number",["number","number"]),this.QTS_PromiseResult=this.module.cwrap("QTS_PromiseResult","number",["number","number"]),this.QTS_TestStringArg=this.module.cwrap("QTS_TestStringArg",null,["string"]),this.QTS_GetDebugLogEnabled=this.module.cwrap("QTS_GetDebugLogEnabled","number",["number"]),this.QTS_SetDebugLogEnabled=this.module.cwrap("QTS_SetDebugLogEnabled",null,["number","number"]),this.QTS_BuildIsDebug=this.module.cwrap("QTS_BuildIsDebug","number",[]),this.QTS_BuildIsAsyncify=this.module.cwrap("QTS_BuildIsAsyncify","number",[]),this.QTS_NewFunction=this.module.cwrap("QTS_NewFunction","number",["number","number","string"]),this.QTS_ArgvGetJSValueConstPointer=this.module.cwrap("QTS_ArgvGetJSValueConstPointer","number",["number","number"]),this.QTS_RuntimeEnableInterruptHandler=this.module.cwrap("QTS_RuntimeEnableInterruptHandler",null,["number"]),this.QTS_RuntimeDisableInterruptHandler=this.module.cwrap("QTS_RuntimeDisableInterruptHandler",null,["number"]),this.QTS_RuntimeEnableModuleLoader=this.module.cwrap("QTS_RuntimeEnableModuleLoader",null,["number","number"]),this.QTS_RuntimeDisableModuleLoader=this.module.cwrap("QTS_RuntimeDisableModuleLoader",null,["number"]),this.QTS_bjson_encode=this.module.cwrap("QTS_bjson_encode","number",["number","number"]),this.QTS_bjson_decode=this.module.cwrap("QTS_bjson_decode","number",["number","number"])}};var YJ1=()=>{};var JJ1={};$8(JJ1,{default:()=>aS6});var iS6,aS6;var GJ1=o(()=>{iS6=(()=>{var Q=import.meta.url;return async function(X={}){var Y,J=X,G,W,Z=new Promise((w,k)=>{G=w,W=k}),$=typeof window=="object",K=typeof importScripts=="function",H=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(H){let{createRequire:w}=await import("module");var F=w(import.meta.url)}function V(w){w={log:w||function(){}};for(let k of V.Ia)k(w);return J.quickJSEmscriptenExtensions=w}V.Ia=[],J.quickjsEmscriptenInit=V,V.Ia.push((w)=>{w.getWasmMemory=function(){return R}});var q=Object.assign({},J),z="./this.program",B=(w,k)=>{throw k},D="",L,M;if(H){var C=F("fs"),A=F("path");D=F("url").fileURLToPath(new URL("./",import.meta.url)),M=(w)=>{return w=Y1(w)?new URL(w):A.normalize(w),C.readFileSync(w)},L=(w)=>{return w=Y1(w)?new URL(w):A.normalize(w),new Promise((k,c)=>{C.readFile(w,void 0,(t,u)=>{t?c(t):k(u.buffer)})})},!J.thisProgram&&1<process.argv.length&&(z=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),B=(w,k)=>{throw process.exitCode=w,k}}else if($||K)K?D=self.location.href:typeof document<"u"&&document.currentScript&&(D=document.currentScript.src),Q&&(D=Q),D.startsWith("blob:")?D="":D=D.substr(0,D.replace(/[?#].*/,"").lastIndexOf("/")+1),K&&(M=(w)=>{var k=new XMLHttpRequest;return k.open("GET",w,!1),k.responseType="arraybuffer",k.send(null),new Uint8Array(k.response)}),L=(w)=>Y1(w)?new Promise((k,c)=>{var t=new XMLHttpRequest;t.open("GET",w,!0),t.responseType="arraybuffer",t.onload=()=>{t.status==200||t.status==0&&t.response?k(t.response):c(t.status)},t.onerror=c,t.send(null)}):fetch(w,{credentials:"same-origin"}).then((k)=>k.ok?k.arrayBuffer():Promise.reject(Error(k.status+" : "+k.url)));var E=J.print||console.log.bind(console),T=J.printErr||console.error.bind(console);Object.assign(J,q),q=null,J.thisProgram&&(z=J.thisProgram);var j=J.wasmBinary,R,v=!1,y,b,h,a,f;function S(){var w=R.buffer;J.HEAP8=b=new Int8Array(w),J.HEAP16=new Int16Array(w),J.HEAPU8=h=new Uint8Array(w),J.HEAPU16=new Uint16Array(w),J.HEAP32=a=new Int32Array(w),J.HEAPU32=f=new Uint32Array(w),J.HEAPF32=new Float32Array(w),J.HEAPF64=new Float64Array(w)}J.wasmMemory?R=J.wasmMemory:R=new WebAssembly.Memory({initial:(J.INITIAL_MEMORY||16777216)/65536,maximum:32768}),S();var m=[],Q0=[],r=[];function Y0(){var w=J.preRun.shift();m.unshift(w)}var F0=0,Z0=null,B0=null;function T0(w){throw J.onAbort?.(w),w="Aborted("+w+")",T(w),v=!0,y=1,w=new WebAssembly.RuntimeError(w+". Build with -sASSERTIONS for more info."),W(w),w}var b0=(w)=>w.startsWith("data:application/octet-stream;base64,"),Y1=(w)=>w.startsWith("file://"),D0;function G0(w){if(w==D0&&j)return new Uint8Array(j);if(M)return M(w);throw"both async and sync fetching of the wasm failed"}function R0(w){return j?Promise.resolve().then(()=>G0(w)):L(w).then((k)=>new Uint8Array(k),()=>G0(w))}function _1(w,k,c){return R0(w).then((t)=>WebAssembly.instantiate(t,k)).then(c,(t)=>{T(`failed to asynchronously prepare wasm: ${t}`),T0(t)})}function h1(w,k){var c=D0;return j||typeof WebAssembly.instantiateStreaming!="function"||b0(c)||Y1(c)||H||typeof fetch!="function"?_1(c,w,k):fetch(c,{credentials:"same-origin"}).then((t)=>WebAssembly.instantiateStreaming(t,w).then(k,function(u){return T(`wasm streaming compile failed: ${u}`),T("falling back to ArrayBuffer instantiation"),_1(c,w,k)}))}function y0(w){this.name="ExitStatus",this.message=`Program terminated with exit(${w})`,this.status=w}var w0=(w)=>{for(;0<w.length;)w.shift()(J)},$0=J.noExitRuntime||!0,j0=typeof TextDecoder<"u"?new TextDecoder:void 0,H0=(w,k,c)=>{var t=k+c;for(c=k;w[c]&&!(c>=t);)++c;if(16<c-k&&w.buffer&&j0)return j0.decode(w.subarray(k,c));for(t="";k<c;){var u=w[k++];if(u&128){var N0=w[k++]&63;if((u&224)==192)t+=String.fromCharCode((u&31)<<6|N0);else{var r0=w[k++]&63;u=(u&240)==224?(u&15)<<12|N0<<6|r0:(u&7)<<18|N0<<12|r0<<6|w[k++]&63,65536>u?t+=String.fromCharCode(u):(u-=65536,t+=String.fromCharCode(55296|u>>10,56320|u&1023))}}else t+=String.fromCharCode(u)}return t},O0=[0,31,60,91,121,152,182,213,244,274,305,335],t0=[0,31,59,90,120,151,181,212,243,273,304,334],k0={},v0=0,I1=(w)=>{y=w,$0||0<v0||(J.onExit?.(w),v=!0),B(w,new y0(w))},b1=(w)=>{if(!v)try{if(w(),!($0||0<v0))try{y=w=y,I1(w)}catch(k){k instanceof y0||k=="unwind"||B(1,k)}}catch(k){k instanceof y0||k=="unwind"||B(1,k)}},s1;s1=()=>performance.now();var E1=(w,k,c)=>{var t=h;if(!(0<c))return 0;var u=k;c=k+c-1;for(var N0=0;N0<w.length;++N0){var r0=w.charCodeAt(N0);if(55296<=r0&&57343>=r0){var w1=w.charCodeAt(++N0);r0=65536+((r0&1023)<<10)|w1&1023}if(127>=r0){if(k>=c)break;t[k++]=r0}else{if(2047>=r0){if(k+1>=c)break;t[k++]=192|r0>>6}else{if(65535>=r0){if(k+2>=c)break;t[k++]=224|r0>>12}else{if(k+3>=c)break;t[k++]=240|r0>>18,t[k++]=128|r0>>12&63}t[k++]=128|r0>>6&63}t[k++]=128|r0&63}}return t[k]=0,k-u},X1={},C0=()=>{if(!P0){var w={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:z||"./this.program"},k;for(k in X1)X1[k]===void 0?delete w[k]:w[k]=X1[k];var c=[];for(k in w)c.push(`${k}=${w[k]}`);P0=c}return P0},P0,a1=[null,[],[]],M4=(w)=>{for(var k=0,c=0;c<w.length;++c){var t=w.charCodeAt(c);127>=t?k++:2047>=t?k+=2:55296<=t&&57343>=t?(k+=4,++c):k+=3}return k},_8=(w,k,c,t)=>{var u={string:(z1)=>{var H4=0;if(z1!==null&&z1!==void 0&&z1!==0){H4=M4(z1)+1;var DQ=_(H4);E1(z1,DQ,H4),H4=DQ}return H4},array:(z1)=>{var H4=_(z1.length);return b.set(z1,H4),H4}};w=J["_"+w];var N0=[],r0=0;if(t)for(var w1=0;w1<t.length;w1++){var _0=u[c[w1]];_0?(r0===0&&(r0=s()),N0[w1]=_0(t[w1])):N0[w1]=t[w1]}return c=w(...N0),c=function(z1){return r0!==0&&O(r0),k==="string"?z1?H0(h,z1):"":k==="boolean"?!!z1:z1}(c)},g1={b:(w,k,c,t)=>{T0(`Assertion failed: ${w?H0(h,w):""}, at: `+[k?k?H0(h,k):"":"unknown filename",c,t?t?H0(h,t):"":"unknown function"])},q:()=>{T0("")},n:()=>{$0=!1,v0=0},j:function(w,k,c){w=new Date(1000*(k+2097152>>>0<4194305-!!w?(w>>>0)+4294967296*k:NaN)),a[c>>2]=w.getSeconds(),a[c+4>>2]=w.getMinutes(),a[c+8>>2]=w.getHours(),a[c+12>>2]=w.getDate(),a[c+16>>2]=w.getMonth(),a[c+20>>2]=w.getFullYear()-1900,a[c+24>>2]=w.getDay(),k=w.getFullYear(),a[c+28>>2]=(k%4!==0||k%100===0&&k%400!==0?t0:O0)[w.getMonth()]+w.getDate()-1|0,a[c+36>>2]=-(60*w.getTimezoneOffset()),k=new Date(w.getFullYear(),6,1).getTimezoneOffset();var t=new Date(w.getFullYear(),0,1).getTimezoneOffset();a[c+32>>2]=(k!=t&&w.getTimezoneOffset()==Math.min(t,k))|0},l:(w,k)=>{if(k0[w]&&(clearTimeout(k0[w].id),delete k0[w]),!k)return 0;var c=setTimeout(()=>{delete k0[w],b1(()=>GY(w,s1()))},k);return k0[w]={id:c,Na:k},0},o:(w,k,c,t)=>{var u=new Date().getFullYear(),N0=new Date(u,0,1).getTimezoneOffset();u=new Date(u,6,1).getTimezoneOffset(),f[w>>2]=60*Math.max(N0,u),a[k>>2]=Number(N0!=u),k=(r0)=>{var w1=Math.abs(r0);return`UTC${0<=r0?"-":"+"}${String(Math.floor(w1/60)).padStart(2,"0")}${String(w1%60).padStart(2,"0")}`},w=k(N0),k=k(u),u<N0?(E1(w,c,17),E1(k,t,17)):(E1(w,t,17),E1(k,c,17))},p:()=>Date.now(),m:(w)=>{var k=h.length;if(w>>>=0,2147483648<w)return!1;for(var c=1;4>=c;c*=2){var t=k*(1+0.2/c);t=Math.min(t,w+100663296);Q:{t=(Math.min(2147483648,65536*Math.ceil(Math.max(w,t)/65536))-R.buffer.byteLength+65535)/65536;try{R.grow(t),S();var u=1;break Q}catch(N0){}u=void 0}if(u)return!0}return!1},f:(w,k)=>{var c=0;return C0().forEach((t,u)=>{var N0=k+c;u=f[w+4*u>>2]=N0;for(N0=0;N0<t.length;++N0)b[u++]=t.charCodeAt(N0);b[u]=0,c+=t.length+1}),0},g:(w,k)=>{var c=C0();f[w>>2]=c.length;var t=0;return c.forEach((u)=>t+=u.length+1),f[k>>2]=t,0},e:()=>52,k:function(){return 70},d:(w,k,c,t)=>{for(var u=0,N0=0;N0<c;N0++){var r0=f[k>>2],w1=f[k+4>>2];k+=8;for(var _0=0;_0<w1;_0++){var z1=h[r0+_0],H4=a1[w];z1===0||z1===10?((w===1?E:T)(H0(H4,0)),H4.length=0):H4.push(z1)}u+=w1}return f[t>>2]=u,0},a:R,c:I1,s:function(w,k,c,t,u){return J.callbacks.callFunction(void 0,w,k,c,t,u)},r:function(w){return J.callbacks.shouldInterrupt(void 0,w)},i:function(w,k,c){return c=c?H0(h,c):"",J.callbacks.loadModuleSource(void 0,w,k,c)},h:function(w,k,c,t){return c=c?H0(h,c):"",t=t?H0(h,t):"",J.callbacks.normalizeModule(void 0,w,k,c,t)}},I0=function(){function w(c){return I0=c.exports,Q0.unshift(I0.t),F0--,J.monitorRunDependencies?.(F0),F0==0&&(Z0!==null&&(clearInterval(Z0),Z0=null),B0&&(c=B0,B0=null,c())),I0}var k={a:g1};if(F0++,J.monitorRunDependencies?.(F0),J.instantiateWasm)try{return J.instantiateWasm(k,w)}catch(c){T(`Module.instantiateWasm callback failed with error: ${c}`),W(c)}return D0||=J.locateFile?b0("emscripten-module.wasm")?"emscripten-module.wasm":J.locateFile?J.locateFile("emscripten-module.wasm",D):D+"emscripten-module.wasm":new URL("emscripten-module.wasm",import.meta.url).href,h1(k,function(c){w(c.instance)}).catch(W),{}}();J._malloc=(w)=>(J._malloc=I0.u)(w),J._QTS_Throw=(w,k)=>(J._QTS_Throw=I0.v)(w,k),J._QTS_NewError=(w)=>(J._QTS_NewError=I0.w)(w),J._QTS_RuntimeSetMemoryLimit=(w,k)=>(J._QTS_RuntimeSetMemoryLimit=I0.x)(w,k),J._QTS_RuntimeComputeMemoryUsage=(w,k)=>(J._QTS_RuntimeComputeMemoryUsage=I0.y)(w,k),J._QTS_RuntimeDumpMemoryUsage=(w)=>(J._QTS_RuntimeDumpMemoryUsage=I0.z)(w),J._QTS_RecoverableLeakCheck=()=>(J._QTS_RecoverableLeakCheck=I0.A)(),J._QTS_BuildIsSanitizeLeak=()=>(J._QTS_BuildIsSanitizeLeak=I0.B)(),J._QTS_RuntimeSetMaxStackSize=(w,k)=>(J._QTS_RuntimeSetMaxStackSize=I0.C)(w,k),J._QTS_GetUndefined=()=>(J._QTS_GetUndefined=I0.D)(),J._QTS_GetNull=()=>(J._QTS_GetNull=I0.E)(),J._QTS_GetFalse=()=>(J._QTS_GetFalse=I0.F)(),J._QTS_GetTrue=()=>(J._QTS_GetTrue=I0.G)(),J._QTS_NewRuntime=()=>(J._QTS_NewRuntime=I0.H)(),J._QTS_FreeRuntime=(w)=>(J._QTS_FreeRuntime=I0.I)(w),J._free=(w)=>(J._free=I0.J)(w),J._QTS_NewContext=(w,k)=>(J._QTS_NewContext=I0.K)(w,k),J._QTS_FreeContext=(w)=>(J._QTS_FreeContext=I0.L)(w),J._QTS_FreeValuePointer=(w,k)=>(J._QTS_FreeValuePointer=I0.M)(w,k),J._QTS_FreeValuePointerRuntime=(w,k)=>(J._QTS_FreeValuePointerRuntime=I0.N)(w,k),J._QTS_FreeVoidPointer=(w,k)=>(J._QTS_FreeVoidPointer=I0.O)(w,k),J._QTS_FreeCString=(w,k)=>(J._QTS_FreeCString=I0.P)(w,k),J._QTS_DupValuePointer=(w,k)=>(J._QTS_DupValuePointer=I0.Q)(w,k),J._QTS_NewObject=(w)=>(J._QTS_NewObject=I0.R)(w),J._QTS_NewObjectProto=(w,k)=>(J._QTS_NewObjectProto=I0.S)(w,k),J._QTS_NewArray=(w)=>(J._QTS_NewArray=I0.T)(w),J._QTS_NewArrayBuffer=(w,k,c)=>(J._QTS_NewArrayBuffer=I0.U)(w,k,c),J._QTS_NewFloat64=(w,k)=>(J._QTS_NewFloat64=I0.V)(w,k),J._QTS_GetFloat64=(w,k)=>(J._QTS_GetFloat64=I0.W)(w,k),J._QTS_NewString=(w,k)=>(J._QTS_NewString=I0.X)(w,k),J._QTS_GetString=(w,k)=>(J._QTS_GetString=I0.Y)(w,k),J._QTS_GetArrayBuffer=(w,k)=>(J._QTS_GetArrayBuffer=I0.Z)(w,k),J._QTS_GetArrayBufferLength=(w,k)=>(J._QTS_GetArrayBufferLength=I0._)(w,k),J._QTS_NewSymbol=(w,k,c)=>(J._QTS_NewSymbol=I0.$)(w,k,c),J._QTS_GetSymbolDescriptionOrKey=(w,k)=>(J._QTS_GetSymbolDescriptionOrKey=I0.aa)(w,k),J._QTS_IsGlobalSymbol=(w,k)=>(J._QTS_IsGlobalSymbol=I0.ba)(w,k),J._QTS_IsJobPending=(w)=>(J._QTS_IsJobPending=I0.ca)(w),J._QTS_ExecutePendingJob=(w,k,c)=>(J._QTS_ExecutePendingJob=I0.da)(w,k,c),J._QTS_GetProp=(w,k,c)=>(J._QTS_GetProp=I0.ea)(w,k,c),J._QTS_GetPropNumber=(w,k,c)=>(J._QTS_GetPropNumber=I0.fa)(w,k,c),J._QTS_SetProp=(w,k,c,t)=>(J._QTS_SetProp=I0.ga)(w,k,c,t),J._QTS_DefineProp=(w,k,c,t,u,N0,r0,w1,_0)=>(J._QTS_DefineProp=I0.ha)(w,k,c,t,u,N0,r0,w1,_0),J._QTS_GetOwnPropertyNames=(w,k,c,t,u)=>(J._QTS_GetOwnPropertyNames=I0.ia)(w,k,c,t,u),J._QTS_Call=(w,k,c,t,u)=>(J._QTS_Call=I0.ja)(w,k,c,t,u),J._QTS_ResolveException=(w,k)=>(J._QTS_ResolveException=I0.ka)(w,k),J._QTS_Dump=(w,k)=>(J._QTS_Dump=I0.la)(w,k),J._QTS_Eval=(w,k,c,t,u,N0)=>(J._QTS_Eval=I0.ma)(w,k,c,t,u,N0),J._QTS_GetModuleNamespace=(w,k)=>(J._QTS_GetModuleNamespace=I0.na)(w,k),J._QTS_Typeof=(w,k)=>(J._QTS_Typeof=I0.oa)(w,k),J._QTS_GetLength=(w,k,c)=>(J._QTS_GetLength=I0.pa)(w,k,c),J._QTS_IsEqual=(w,k,c,t)=>(J._QTS_IsEqual=I0.qa)(w,k,c,t),J._QTS_GetGlobalObject=(w)=>(J._QTS_GetGlobalObject=I0.ra)(w),J._QTS_NewPromiseCapability=(w,k)=>(J._QTS_NewPromiseCapability=I0.sa)(w,k),J._QTS_PromiseState=(w,k)=>(J._QTS_PromiseState=I0.ta)(w,k),J._QTS_PromiseResult=(w,k)=>(J._QTS_PromiseResult=I0.ua)(w,k),J._QTS_TestStringArg=(w)=>(J._QTS_TestStringArg=I0.va)(w),J._QTS_GetDebugLogEnabled=(w)=>(J._QTS_GetDebugLogEnabled=I0.wa)(w),J._QTS_SetDebugLogEnabled=(w,k)=>(J._QTS_SetDebugLogEnabled=I0.xa)(w,k),J._QTS_BuildIsDebug=()=>(J._QTS_BuildIsDebug=I0.ya)(),J._QTS_BuildIsAsyncify=()=>(J._QTS_BuildIsAsyncify=I0.za)(),J._QTS_NewFunction=(w,k,c)=>(J._QTS_NewFunction=I0.Aa)(w,k,c),J._QTS_ArgvGetJSValueConstPointer=(w,k)=>(J._QTS_ArgvGetJSValueConstPointer=I0.Ba)(w,k),J._QTS_RuntimeEnableInterruptHandler=(w)=>(J._QTS_RuntimeEnableInterruptHandler=I0.Ca)(w),J._QTS_RuntimeDisableInterruptHandler=(w)=>(J._QTS_RuntimeDisableInterruptHandler=I0.Da)(w),J._QTS_RuntimeEnableModuleLoader=(w,k)=>(J._QTS_RuntimeEnableModuleLoader=I0.Ea)(w,k),J._QTS_RuntimeDisableModuleLoader=(w)=>(J._QTS_RuntimeDisableModuleLoader=I0.Fa)(w),J._QTS_bjson_encode=(w,k)=>(J._QTS_bjson_encode=I0.Ga)(w,k),J._QTS_bjson_decode=(w,k)=>(J._QTS_bjson_decode=I0.Ha)(w,k);var GY=(w,k)=>(GY=I0.Ja)(w,k),O=(w)=>(O=I0.Ka)(w),_=(w)=>(_=I0.La)(w),s=()=>(s=I0.Ma)();J.cwrap=(w,k,c,t)=>{var u=!c||c.every((N0)=>N0==="number"||N0==="boolean");return k!=="string"&&u&&!t?J["_"+w]:(...N0)=>_8(w,k,c,N0)},J.UTF8ToString=(w,k)=>w?H0(h,w,k):"",J.stringToUTF8=(w,k,c)=>E1(w,k,c),J.lengthBytesUTF8=M4;var J0;B0=function w(){J0||U(),J0||(B0=w)};function U(){function w(){if(!J0&&(J0=!0,J.calledRun=!0,!v)){if(w0(Q0),G(J),J.onRuntimeInitialized?.(),J.postRun)for(typeof J.postRun=="function"&&(J.postRun=[J.postRun]);J.postRun.length;){var k=J.postRun.shift();r.unshift(k)}w0(r)}}if(!(0<F0)){if(J.preRun)for(typeof J.preRun=="function"&&(J.preRun=[J.preRun]);J.preRun.length;)Y0();w0(m),0<F0||(J.setStatus?(J.setStatus("Running..."),setTimeout(function(){setTimeout(function(){J.setStatus("")},1),w()},1)):w())}}if(J.preInit)for(typeof J.preInit=="function"&&(J.preInit=[J.preInit]);0<J.preInit.length;)J.preInit.pop()();return U(),Y=Z,Y}})(),aS6=iS6});var y80=I((Yl4,o51)=>{var{defineProperty:_80,getOwnPropertyDescriptor:Ck6,getOwnPropertyNames:Ik6}=Object,Rk6=Object.prototype.hasOwnProperty,Sk6=(Q,X)=>{for(var Y in X)_80(Q,Y,{get:X[Y],enumerable:!0})},vk6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of Ik6(X))if(!Rk6.call(Q,G)&&G!==Y)_80(Q,G,{get:()=>X[G],enumerable:!(J=Ck6(X,G))||J.enumerable})}return Q},kk6=(Q)=>vk6(_80({},"__esModule",{value:!0}),Q),a51={};Sk6(a51,{SYMBOL_FOR_REQ_CONTEXT:()=>r51,getContext:()=>_k6});o51.exports=kk6(a51);var r51=Symbol.for("@vercel/request-context");function _k6(){return globalThis[r51]?.get?.()??{}}});var CP=I((Jl4,e51)=>{var{defineProperty:b80,getOwnPropertyDescriptor:yk6,getOwnPropertyNames:bk6}=Object,fk6=Object.prototype.hasOwnProperty,hk6=(Q,X)=>{for(var Y in X)b80(Q,Y,{get:X[Y],enumerable:!0})},xk6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of bk6(X))if(!fk6.call(Q,G)&&G!==Y)b80(Q,G,{get:()=>X[G],enumerable:!(J=yk6(X,G))||J.enumerable})}return Q},gk6=(Q)=>xk6(b80({},"__esModule",{value:!0}),Q),s51={};hk6(s51,{VercelOidcTokenError:()=>t51});e51.exports=gk6(s51);class t51 extends Error{constructor(Q,X){super(Q);this.name="VercelOidcTokenError",this.cause=X}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var JG1=I((Gl4,YG1)=>{var{create:uk6,defineProperty:ay,getOwnPropertyDescriptor:mk6,getOwnPropertyNames:lk6,getPrototypeOf:dk6}=Object,pk6=Object.prototype.hasOwnProperty,ck6=(Q,X)=>{for(var Y in X)ay(Q,Y,{get:X[Y],enumerable:!0})},QG1=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of lk6(X))if(!pk6.call(Q,G)&&G!==Y)ay(Q,G,{get:()=>X[G],enumerable:!(J=mk6(X,G))||J.enumerable})}return Q},h80=(Q,X,Y)=>(Y=Q!=null?uk6(dk6(Q)):{},QG1(X||!Q||!Q.__esModule?ay(Y,"default",{value:Q,enumerable:!0}):Y,Q)),nk6=(Q)=>QG1(ay({},"__esModule",{value:!0}),Q),XG1={};ck6(XG1,{findRootDir:()=>rk6,getUserDataDir:()=>ok6});YG1.exports=nk6(XG1);var IP=h80(U0("path")),ik6=h80(U0("fs")),f80=h80(U0("os")),ak6=CP();function rk6(){try{let Q=process.cwd();while(Q!==IP.default.dirname(Q)){let X=IP.default.join(Q,".vercel");if(ik6.default.existsSync(X))return Q;Q=IP.default.dirname(Q)}}catch(Q){throw new ak6.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function ok6(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(f80.default.platform()){case"darwin":return IP.default.join(f80.default.homedir(),"Library/Application Support");case"linux":return IP.default.join(f80.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var FG1=I((Wl4,HG1)=>{var{create:sk6,defineProperty:ry,getOwnPropertyDescriptor:tk6,getOwnPropertyNames:ek6,getPrototypeOf:Q_6}=Object,X_6=Object.prototype.hasOwnProperty,Y_6=(Q,X)=>{for(var Y in X)ry(Q,Y,{get:X[Y],enumerable:!0})},GG1=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of ek6(X))if(!X_6.call(Q,G)&&G!==Y)ry(Q,G,{get:()=>X[G],enumerable:!(J=tk6(X,G))||J.enumerable})}return Q},WG1=(Q,X,Y)=>(Y=Q!=null?sk6(Q_6(Q)):{},GG1(X||!Q||!Q.__esModule?ry(Y,"default",{value:Q,enumerable:!0}):Y,Q)),J_6=(Q)=>GG1(ry({},"__esModule",{value:!0}),Q),ZG1={};Y_6(ZG1,{isValidAccessToken:()=>$_6,readAuthConfig:()=>W_6,writeAuthConfig:()=>Z_6});HG1.exports=J_6(ZG1);var RP=WG1(U0("fs")),$G1=WG1(U0("path")),G_6=oy();function KG1(){let Q=(0,G_6.getVercelDataDir)();if(!Q)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return $G1.join(Q,"auth.json")}function W_6(){try{let Q=KG1();if(!RP.existsSync(Q))return null;let X=RP.readFileSync(Q,"utf8");if(!X)return null;return JSON.parse(X)}catch(Q){return null}}function Z_6(Q){let X=KG1(),Y=$G1.dirname(X);if(!RP.existsSync(Y))RP.mkdirSync(Y,{mode:504,recursive:!0});RP.writeFileSync(X,JSON.stringify(Q,null,2),{mode:384})}function $_6(Q){if(!Q.token)return!1;if(typeof Q.expiresAt!=="number")return!0;let X=Math.floor(Date.now()/1000);return Q.expiresAt>=X}});var UG1=I((Zl4,zG1)=>{var{defineProperty:u80,getOwnPropertyDescriptor:K_6,getOwnPropertyNames:H_6}=Object,F_6=Object.prototype.hasOwnProperty,V_6=(Q,X)=>{for(var Y in X)u80(Q,Y,{get:X[Y],enumerable:!0})},q_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of H_6(X))if(!F_6.call(Q,G)&&G!==Y)u80(Q,G,{get:()=>X[G],enumerable:!(J=K_6(X,G))||J.enumerable})}return Q},z_6=(Q)=>q_6(u80({},"__esModule",{value:!0}),Q),VG1={};V_6(VG1,{processTokenResponse:()=>O_6,refreshTokenRequest:()=>N_6});zG1.exports=z_6(VG1);var x80=U0("os"),U_6="https://vercel.com",B_6="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",qG1=`@vercel/oidc node-${process.version} ${(0,x80.platform)()} (${(0,x80.arch)()}) ${(0,x80.hostname)()}`,g80=null;async function D_6(){if(g80)return g80;let Q=`${U_6}/.well-known/openid-configuration`,X=await fetch(Q,{headers:{"user-agent":qG1}});if(!X.ok)throw Error("Failed to discover OAuth endpoints");let Y=await X.json();if(!Y||typeof Y.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let J=Y.token_endpoint;return g80=J,J}async function N_6(Q){let X=await D_6();return await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":qG1},body:new URLSearchParams({client_id:B_6,grant_type:"refresh_token",...Q})})}async function O_6(Q){let X=await Q.json();if(!Q.ok){let Y=typeof X==="object"&&X&&"error"in X?String(X.error):"Token refresh failed";return[Error(Y)]}if(typeof X!=="object"||X===null)return[Error("Invalid token response")];if(typeof X.access_token!=="string")return[Error("Missing access_token in response")];if(X.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof X.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,X]}});var oy=I(($l4,LG1)=>{var{create:L_6,defineProperty:sy,getOwnPropertyDescriptor:w_6,getOwnPropertyNames:M_6,getPrototypeOf:P_6}=Object,T_6=Object.prototype.hasOwnProperty,A_6=(Q,X)=>{for(var Y in X)sy(Q,Y,{get:X[Y],enumerable:!0})},DG1=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of M_6(X))if(!T_6.call(Q,G)&&G!==Y)sy(Q,G,{get:()=>X[G],enumerable:!(J=w_6(X,G))||J.enumerable})}return Q},NG1=(Q,X,Y)=>(Y=Q!=null?L_6(P_6(Q)):{},DG1(X||!Q||!Q.__esModule?sy(Y,"default",{value:Q,enumerable:!0}):Y,Q)),E_6=(Q)=>DG1(sy({},"__esModule",{value:!0}),Q),OG1={};A_6(OG1,{assertVercelOidcTokenResponse:()=>m80,findProjectInfo:()=>R_6,getTokenPayload:()=>k_6,getVercelCliToken:()=>C_6,getVercelDataDir:()=>j_6,getVercelOidcToken:()=>I_6,isExpired:()=>__6,loadToken:()=>v_6,saveToken:()=>S_6});LG1.exports=E_6(OG1);var SP=NG1(U0("path")),HF=NG1(U0("fs")),lU=CP(),ty=JG1(),mU=FG1(),BG1=UG1();function j_6(){let X=(0,ty.getUserDataDir)();if(!X)return null;return SP.join(X,"com.vercel.cli")}async function C_6(){let Q=(0,mU.readAuthConfig)();if(!Q)return null;if((0,mU.isValidAccessToken)(Q))return Q.token||null;if(!Q.refreshToken)return(0,mU.writeAuthConfig)({}),null;try{let X=await(0,BG1.refreshTokenRequest)({refresh_token:Q.refreshToken}),[Y,J]=await(0,BG1.processTokenResponse)(X);if(Y||!J)return(0,mU.writeAuthConfig)({}),null;let G={token:J.access_token,expiresAt:Math.floor(Date.now()/1000)+J.expires_in};if(J.refresh_token)G.refreshToken=J.refresh_token;return(0,mU.writeAuthConfig)(G),G.token??null}catch(X){return(0,mU.writeAuthConfig)({}),null}}async function I_6(Q,X,Y){let J=`https://api.vercel.com/v1/projects/${X}/token?source=vercel-oidc-refresh${Y?`&teamId=${Y}`:""}`,G=await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${Q}`}});if(!G.ok)throw new lU.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let W=await G.json();return m80(W),W}function m80(Q){if(!Q||typeof Q!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in Q)||typeof Q.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function R_6(){let Q=(0,ty.findRootDir)();if(!Q)throw new lU.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let X=SP.join(Q,".vercel","project.json");if(!HF.existsSync(X))throw new lU.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let Y=JSON.parse(HF.readFileSync(X,"utf8"));if(typeof Y.projectId!=="string"&&typeof Y.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:Y.projectId,teamId:Y.orgId}}function S_6(Q,X){let Y=(0,ty.getUserDataDir)();if(!Y)throw new lU.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let J=SP.join(Y,"com.vercel.token",`${X}.json`),G=JSON.stringify(Q);HF.mkdirSync(SP.dirname(J),{mode:504,recursive:!0}),HF.writeFileSync(J,G),HF.chmodSync(J,432);return}function v_6(Q){let X=(0,ty.getUserDataDir)();if(!X)throw new lU.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Y=SP.join(X,"com.vercel.token",`${Q}.json`);if(!HF.existsSync(Y))return null;let J=JSON.parse(HF.readFileSync(Y,"utf8"));return m80(J),J}function k_6(Q){let X=Q.split(".");if(X.length!==3)throw new lU.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let Y=X[1].replace(/-/g,"+").replace(/_/g,"/"),J=Y.padEnd(Y.length+(4-Y.length%4)%4,"=");return JSON.parse(Buffer.from(J,"base64").toString("utf8"))}function __6(Q){return Q.exp*1000<Date.now()}});var PG1=I((Kl4,MG1)=>{var{defineProperty:d80,getOwnPropertyDescriptor:y_6,getOwnPropertyNames:b_6}=Object,f_6=Object.prototype.hasOwnProperty,h_6=(Q,X)=>{for(var Y in X)d80(Q,Y,{get:X[Y],enumerable:!0})},x_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of b_6(X))if(!f_6.call(Q,G)&&G!==Y)d80(Q,G,{get:()=>X[G],enumerable:!(J=y_6(X,G))||J.enumerable})}return Q},g_6=(Q)=>x_6(d80({},"__esModule",{value:!0}),Q),wG1={};h_6(wG1,{refreshToken:()=>u_6});MG1.exports=g_6(wG1);var l80=CP(),FF=oy();async function u_6(){let{projectId:Q,teamId:X}=(0,FF.findProjectInfo)(),Y=(0,FF.loadToken)(Q);if(!Y||(0,FF.isExpired)((0,FF.getTokenPayload)(Y.token))){let J=await(0,FF.getVercelCliToken)();if(!J)throw new l80.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!Q)throw new l80.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(Y=await(0,FF.getVercelOidcToken)(J,Q,X),!Y)throw new l80.VercelOidcTokenError("Failed to refresh OIDC token");(0,FF.saveToken)(Y,Q)}process.env.VERCEL_OIDC_TOKEN=Y.token;return}});var EG1=I((Hl4,AG1)=>{var{defineProperty:c80,getOwnPropertyDescriptor:m_6,getOwnPropertyNames:l_6}=Object,d_6=Object.prototype.hasOwnProperty,p_6=(Q,X)=>{for(var Y in X)c80(Q,Y,{get:X[Y],enumerable:!0})},c_6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of l_6(X))if(!d_6.call(Q,G)&&G!==Y)c80(Q,G,{get:()=>X[G],enumerable:!(J=m_6(X,G))||J.enumerable})}return Q},n_6=(Q)=>c_6(c80({},"__esModule",{value:!0}),Q),TG1={};p_6(TG1,{getVercelOidcToken:()=>r_6,getVercelOidcTokenSync:()=>p80});AG1.exports=n_6(TG1);var i_6=y80(),a_6=CP();async function r_6(){let Q="",X;try{Q=p80()}catch(Y){X=Y}try{let[{getTokenPayload:Y,isExpired:J},{refreshToken:G}]=await Promise.all([await Promise.resolve().then(() => m6(oy())),await Promise.resolve().then(() => m6(PG1()))]);if(!Q||J(Y(Q)))await G(),Q=p80()}catch(Y){let J=X instanceof Error?X.message:"";if(Y instanceof Error)J=`${J}
|
|
261
|
+
${Y.message}`;if(J)throw new a_6.VercelOidcTokenError(J);throw Y}return Q}function p80(){let Q=(0,i_6.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!Q)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return Q}});var i80=I((Fl4,IG1)=>{var{defineProperty:n80,getOwnPropertyDescriptor:o_6,getOwnPropertyNames:s_6}=Object,t_6=Object.prototype.hasOwnProperty,e_6=(Q,X)=>{for(var Y in X)n80(Q,Y,{get:X[Y],enumerable:!0})},Qy6=(Q,X,Y,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of s_6(X))if(!t_6.call(Q,G)&&G!==Y)n80(Q,G,{get:()=>X[G],enumerable:!(J=o_6(X,G))||J.enumerable})}return Q},Xy6=(Q)=>Qy6(n80({},"__esModule",{value:!0}),Q),CG1={};e_6(CG1,{getContext:()=>Yy6.getContext,getVercelOidcToken:()=>jG1.getVercelOidcToken,getVercelOidcTokenSync:()=>jG1.getVercelOidcTokenSync});IG1.exports=Xy6(CG1);var jG1=EG1(),Yy6=y80()});var pE=m6(Z1(),1),Nk0=m6(Kk0(),1),Ok0=m6(Dl(),1),Lk0=m6(pm(),1),Nl=new Ok0.PrometheusExporter({preventServerStart:!0}),ji1=new Nk0.NodeSDK({serviceName:"mcp-mesh",traceExporter:new Lk0.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:Nl});ji1.start();var xD=pE.trace.getTracer("mcp-mesh","1.0.0"),cE=pE.metrics.getMeter("mcp-mesh","1.0.0");var Ol=class extends Error{res;status;constructor(Q=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Q}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var wk0=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],Ci1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,Ii1=(Q,X)=>{if(!Q)return{};let Y=new Headers(Q.headers);if(X){let J=Y.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!Ci1.test(Z));if(W.length>0)throw new Ol(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Y.delete(Z)})}}return wk0.forEach((J)=>{Y.delete(J)}),{method:Q.method,body:Q.body,duplex:Q.body?"half":void 0,headers:Y,signal:Q.signal}},Ri1=(Q)=>{if(!Q.headers||Array.isArray(Q.headers)||Q.headers instanceof Headers)return Q;let X=new Headers;for(let[Y,J]of Object.entries(Q.headers))if(J==null)X.delete(Y);else X.set(Y,J);return Q.headers=X,Q},Mk0=async(Q,X)=>{let{raw:Y,customFetch:J,strictConnectionProcessing:G=!1,...W}=X instanceof Request?{raw:X}:X??{},Z=new Request(Q,{...Ii1(Y,G),...Ri1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(wk0.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var Pk0=(Q)=>(X)=>{let Y=new URL(X.req.raw.url),J=new URL(Q);return J.pathname=Y.pathname,J.search=Y.search,Mk0(J,{raw:X.req.raw,headers:{...X.req.raw.headers}})};import{resolve as gD,dirname as Si1}from"path";var vi1="http://localhost:4000",ki1="./dist/client";function _i1(Q,X){let Y=gD(X),J=gD(Q);return J===Y||J.startsWith(Y+"/")}function yi1({requestPath:Q,clientDir:X}){let Y=Q.startsWith("/")?Q.slice(1):Q,J=gD(X,Y);if(!_i1(J,X))return null;return J}function Tk0(Q,X="../client"){let Y=new URL(Q),J=Si1(Y.pathname);return gD(J,X)}function Ak0(Q={}){let{env:X="production",devServerUrl:Y=vi1,clientDir:J=ki1,isServerPath:G=()=>!1}=Q;if(X==="development"){let W=Pk0(Y);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=yi1({requestPath:K,clientDir:J});if(!H)return null;let F=gD(J,"index.html");for(let V of[H,F])try{let q=Bun.file(V);if(await q.exists())return new Response(q)}catch{}return null}}var E71=m6(Dl(),1);var Ll=(Q,X,Y)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(Q[$])F=Q[$][0][0],J.req.routeIndex=$;else F=$===Q.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&X)J.error=V,K=await X(V,J),H=!0;else throw V}else if(J.finalized===!1&&Y)K=await Y(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var Ek0=Symbol();var jk0=async(Q,X=Object.create(null))=>{let{all:Y=!1,dot:J=!1}=X,W=(Q instanceof nE?Q.raw.headers:Q.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return bi1(Q,{all:Y,dot:J});return{}};async function bi1(Q,X){let Y=await Q.formData();if(Y)return fi1(Y,X);return{}}function fi1(Q,X){let Y=Object.create(null);if(Q.forEach((J,G)=>{if(!(X.all||G.endsWith("[]")))Y[G]=J;else hi1(Y,G,J)}),X.dot)Object.entries(Y).forEach(([J,G])=>{if(J.includes("."))xi1(Y,J,G),delete Y[J]});return Y}var hi1=(Q,X,Y)=>{if(Q[X]!==void 0)if(Array.isArray(Q[X]))Q[X].push(Y);else Q[X]=[Q[X],Y];else if(!X.endsWith("[]"))Q[X]=Y;else Q[X]=[Y]},xi1=(Q,X,Y)=>{let J=Q,G=X.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Y;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var Ml=(Q)=>{let X=Q.split("/");if(X[0]==="")X.shift();return X},Ck0=(Q)=>{let{groups:X,path:Y}=gi1(Q),J=Ml(Y);return ui1(J,X)},gi1=(Q)=>{let X=[];return Q=Q.replace(/\{[^}]+\}/g,(Y,J)=>{let G=`@${J}`;return X.push([G,Y]),G}),{groups:X,path:Q}},ui1=(Q,X)=>{for(let Y=X.length-1;Y>=0;Y--){let[J]=X[Y];for(let G=Q.length-1;G>=0;G--)if(Q[G].includes(J)){Q[G]=Q[G].replace(J,X[Y][1]);break}}return Q},iE={},Ik0=(Q,X)=>{if(Q==="*")return"*";let Y=Q.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Y){let J=`${Q}#${X}`;if(!iE[J])if(Y[2])iE[J]=X&&X[0]!==":"&&X[0]!=="*"?[J,Y[1],new RegExp(`^${Y[2]}(?=/${X})`)]:[Q,Y[1],new RegExp(`^${Y[2]}$`)];else iE[J]=[Q,Y[1],!0];return iE[J]}return null},MV=(Q,X)=>{try{return X(Q)}catch{return Q.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Y)=>{try{return X(Y)}catch{return Y}})}},mi1=(Q)=>MV(Q,decodeURI),Pl=(Q)=>{let X=Q.url,Y=X.indexOf("/",X.indexOf(":")+4),J=Y;for(;J<X.length;J++){let G=X.charCodeAt(J);if(G===37){let W=X.indexOf("?",J),Z=X.slice(Y,W===-1?void 0:W);return mi1(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return X.slice(Y,J)};var Rk0=(Q)=>{let X=Pl(Q);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},tK=(Q,X,...Y)=>{if(Y.length)X=tK(X,...Y);return`${Q?.[0]==="/"?"":"/"}${Q}${X==="/"?"":`${Q?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},aE=(Q)=>{if(Q.charCodeAt(Q.length-1)!==63||!Q.includes(":"))return null;let X=Q.split("/"),Y=[],J="";return X.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Y.length===0&&J==="")Y.push("/");else Y.push(J);let W=G.replace("?","");J+="/"+W,Y.push(J)}else J+="/"+G}),Y.filter((G,W,Z)=>Z.indexOf(G)===W)},wl=(Q)=>{if(!/[%+]/.test(Q))return Q;if(Q.indexOf("+")!==-1)Q=Q.replace(/\+/g," ");return Q.indexOf("%")!==-1?MV(Q,uD):Q},Sk0=(Q,X,Y)=>{let J;if(!Y&&X&&!/[%+]/.test(X)){let Z=Q.indexOf("?",8);if(Z===-1)return;if(!Q.startsWith(X,Z+1))Z=Q.indexOf(`&${X}`,Z+1);while(Z!==-1){let $=Q.charCodeAt(Z+X.length+1);if($===61){let K=Z+X.length+2,H=Q.indexOf("&",K);return wl(Q.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=Q.indexOf(`&${X}`,Z+1)}if(J=/[%+]/.test(Q),!J)return}let G={};J??=/[%+]/.test(Q);let W=Q.indexOf("?",8);while(W!==-1){let Z=Q.indexOf("&",W+1),$=Q.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=Q.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=wl(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=Q.slice($+1,Z===-1?void 0:Z),J)H=wl(H);if(Y){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return X?G[X]:G},vk0=Sk0,kk0=(Q,X)=>{return Sk0(Q,X,!0)},uD=decodeURIComponent;var _k0=(Q)=>MV(Q,uD),nE=class{raw;#Q;#X;routeIndex=0;path;bodyCache={};constructor(Q,X="/",Y=[[]]){this.raw=Q,this.path=X,this.#X=Y,this.#Q={}}param(Q){return Q?this.#Y(Q):this.#J()}#Y(Q){let X=this.#X[0][this.routeIndex][1][Q],Y=this.#W(X);return Y&&/\%/.test(Y)?_k0(Y):Y}#J(){let Q={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let Y of X){let J=this.#W(this.#X[0][this.routeIndex][1][Y]);if(J!==void 0)Q[Y]=/\%/.test(J)?_k0(J):J}return Q}#W(Q){return this.#X[1]?this.#X[1][Q]:Q}query(Q){return vk0(this.url,Q)}queries(Q){return kk0(this.url,Q)}header(Q){if(Q)return this.raw.headers.get(Q)??void 0;let X={};return this.raw.headers.forEach((Y,J)=>{X[J]=Y}),X}async parseBody(Q){return this.bodyCache.parsedBody??=await jk0(this,Q)}#G=(Q)=>{let{bodyCache:X,raw:Y}=this,J=X[Q];if(J)return J;let G=Object.keys(X)[0];if(G)return X[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[Q]()});return X[Q]=Y[Q]()};json(){return this.#G("text").then((Q)=>JSON.parse(Q))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(Q,X){this.#Q[Q]=X}valid(Q){return this.#Q[Q]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ek0](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Q]])=>Q)}get routePath(){return this.#X[0].map(([[,Q]])=>Q)[this.routeIndex].path}};var yk0={Stringify:1,BeforeStream:2,Stream:3},li1=(Q,X)=>{let Y=new String(Q);return Y.isEscaped=!0,Y.callbacks=X,Y};var Tl=async(Q,X,Y,J,G)=>{if(typeof Q==="object"&&!(Q instanceof String)){if(!(Q instanceof Promise))Q=Q.toString();if(Q instanceof Promise)Q=await Q}let W=Q.callbacks;if(!W?.length)return Promise.resolve(Q);if(G)G[0]+=Q;else G=[Q];let Z=Promise.all(W.map(($)=>$({phase:X,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>Tl(K,X,!1,J,G))).then(()=>G[0]));if(Y)return li1(await Z,W);else return Z};var di1="text/plain; charset=UTF-8",Al=(Q,X)=>{return{"Content-Type":Q,...X}},bk0=class{#Q;#X;env={};#Y;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(Q,X){if(this.#Q=Q,X)this.#W=X.executionCtx,this.env=X.env,this.#H=X.notFoundHandler,this.#q=X.path,this.#V=X.matchResult}get req(){return this.#X??=new nE(this.#Q,this.#q,this.#V),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(Q){if(this.#G&&Q){Q=new Response(Q.body,Q);for(let[X,Y]of this.#G.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let J=this.#G.headers.getSetCookie();Q.headers.delete("set-cookie");for(let G of J)Q.headers.append("set-cookie",G)}else Q.headers.set(X,Y)}}this.#G=Q,this.finalized=!0}render=(...Q)=>{return this.#Z??=(X)=>this.html(X),this.#Z(...Q)};setLayout=(Q)=>this.#$=Q;getLayout=()=>this.#$;setRenderer=(Q)=>{this.#Z=Q};header=(Q,X,Y)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(X===void 0)J.delete(Q);else if(Y?.append)J.append(Q,X);else J.set(Q,X)};status=(Q)=>{this.#J=Q};set=(Q,X)=>{this.#Y??=new Map,this.#Y.set(Q,X)};get=(Q)=>{return this.#Y?this.#Y.get(Q):void 0};get var(){if(!this.#Y)return{};return Object.fromEntries(this.#Y)}#F(Q,X,Y){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof X==="object"&&"headers"in X){let W=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Y)for(let[W,Z]of Object.entries(Y))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof X==="number"?X:X?.status??this.#J;return new Response(Q,{status:G,headers:J})}newResponse=(...Q)=>this.#F(...Q);body=(Q,X,Y)=>this.#F(Q,X,Y);text=(Q,X,Y)=>{return!this.#K&&!this.#J&&!X&&!Y&&!this.finalized?new Response(Q):this.#F(Q,X,Al(di1,Y))};json=(Q,X,Y)=>{return this.#F(JSON.stringify(Q),X,Al("application/json",Y))};html=(Q,X,Y)=>{let J=(G)=>this.#F(G,X,Al("text/html; charset=UTF-8",Y));return typeof Q==="object"?Tl(Q,yk0.Stringify,!1,{}).then(J):J(Q)};redirect=(Q,X)=>{let Y=String(Q);return this.header("Location",!/[^\x00-\xFF]/.test(Y)?Y:encodeURI(Y)),this.newResponse(null,X??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var d4="ALL",fk0="all",hk0=["get","post","put","delete","options","patch"],rE="Can not add a route since the matcher is already built.",oE=class extends Error{};var xk0="__COMPOSED_HANDLER";var pi1=(Q)=>{return Q.text("404 Not Found",404)},gk0=(Q,X)=>{if("getResponse"in Q){let Y=Q.getResponse();return X.newResponse(Y.body,Y)}return console.error(Q),X.text("Internal Server Error",500)},uk0=class Q{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Q="/";routes=[];constructor(X={}){[...hk0,fk0].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#Q=Z;else this.#J(W,this.#Q,Z);return $.forEach((K)=>{this.#J(W,this.#Q,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#Q=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#Q,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#Q=W;else this.#Q="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(d4,this.#Q,$)}),this};let{strict:J,...G}=X;Object.assign(this,G),this.getPath=J??!0?X.getPath??Pl:Rk0}#X(){let X=new Q({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#Y=this.#Y,X.routes=this.routes,X}#Y=pi1;errorHandler=gk0;route(X,Y){let J=this.basePath(X);return Y.routes.map((G)=>{let W;if(Y.errorHandler===gk0)W=G.handler;else W=async(Z,$)=>(await Ll([],Y.errorHandler)(Z,()=>G.handler(Z,$))).res,W[xk0]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(X){let Y=this.#X();return Y._basePath=tK(this._basePath,X),Y}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#Y=X,this};mount(X,Y,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=tK(this._basePath,X),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Y(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(d4,tK(X,"*"),$),this}#J(X,Y,J){X=X.toUpperCase(),Y=tK(this._basePath,Y);let G={basePath:this._basePath,path:Y,method:X,handler:J};this.router.add(X,Y,[J,G]),this.routes.push(G)}#W(X,Y){if(X instanceof Error)return this.errorHandler(X,Y);throw X}#G(X,Y,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(X,Y,J,"GET")))();let W=this.getPath(X,{env:J}),Z=this.router.match(G,W),$=new bk0(X,{path:W,matchResult:Z,env:J,executionCtx:Y,notFoundHandler:this.#Y});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Y($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Y($))).catch((F)=>this.#W(F,$)):H??this.#Y($)}let K=Ll(Z[0],this.errorHandler,this.#Y);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(X,...Y)=>{return this.#G(X,Y[1],Y[0],X.method)};request=(X,Y,J,G)=>{if(X instanceof Request)return this.fetch(Y?new Request(X,Y):X,J,G);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${tK("/",X)}`,Y),J,G)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#G(X.request,X,void 0,X.request.method))})}};var mD=[];function sE(Q,X){let Y=this.buildAllMatchers(),J=(G,W)=>{let Z=Y[G]||Y[d4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],mD];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(Q,X)}var tE="[^/]+",lD=".*",dD="(?:|/.*)",eK=Symbol(),ci1=new Set(".\\+*[^]$()");function ni1(Q,X){if(Q.length===1)return X.length===1?Q<X?-1:1:-1;if(X.length===1)return 1;if(Q===lD||Q===dD)return 1;else if(X===lD||X===dD)return-1;if(Q===tE)return 1;else if(X===tE)return-1;return Q.length===X.length?Q<X?-1:1:X.length-Q.length}var mk0=class Q{#Q;#X;#Y=Object.create(null);insert(X,Y,J,G,W){if(X.length===0){if(this.#Q!==void 0)throw eK;if(W)return;this.#Q=Y;return}let[Z,...$]=X,K=Z==="*"?$.length===0?["","",lD]:["","",tE]:Z==="/*"?["","",dD]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||tE;if(F&&K[2]){if(V===".*")throw eK;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw eK}if(H=this.#Y[V],!H){if(Object.keys(this.#Y).some((q)=>q!==lD&&q!==dD))throw eK;if(W)return;if(H=this.#Y[V]=new Q,F!=="")H.#X=G.varIndex++}if(!W&&F!=="")J.push([F,H.#X])}else if(H=this.#Y[Z],!H){if(Object.keys(this.#Y).some((F)=>F.length>1&&F!==lD&&F!==dD))throw eK;if(W)return;H=this.#Y[Z]=new Q}H.insert($,Y,J,G,W)}buildRegExpStr(){let Y=Object.keys(this.#Y).sort(ni1).map((J)=>{let G=this.#Y[J];return(typeof G.#X==="number"?`(${J})@${G.#X}`:ci1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#Q==="number")Y.unshift(`#${this.#Q}`);if(Y.length===0)return"";if(Y.length===1)return Y[0];return"(?:"+Y.join("|")+")"}};var lk0=class{#Q={varIndex:0};#X=new mk0;insert(Q,X,Y){let J=[],G=[];for(let Z=0;;){let $=!1;if(Q=Q.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=Q.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#X.insert(W,X,J,this.#Q,Y),J}buildRegExp(){let Q=this.#X.buildRegExpStr();if(Q==="")return[/^$/,[],[]];let X=0,Y=[],J=[];return Q=Q.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Y[++X]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++X,"";return""}),[new RegExp(`^${Q}`),Y,J]}};var ii1=[/^$/,[],Object.create(null)],dk0=Object.create(null);function pk0(Q){return dk0[Q]??=new RegExp(Q==="*"?"":`^${Q.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,Y)=>Y?`\\${Y}`:"(?:|/.*)")}$`)}function ai1(){dk0=Object.create(null)}function ri1(Q){let X=new lk0,Y=[];if(Q.length===0)return ii1;let J=Q.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,z,B]=J[H];if(q)G[z]=[B.map(([L])=>[L,Object.create(null)]),mD];else F++;let D;try{D=X.insert(z,F,q)}catch(L){throw L===eK?new oE(z):L}if(q)continue;Y[F]=B.map(([L,M])=>{let C=Object.create(null);M-=1;for(;M>=0;M--){let[A,E]=D[M];C[A]=E}return[L,C]})}let[W,Z,$]=X.buildRegExp();for(let H=0,F=Y.length;H<F;H++)for(let V=0,q=Y[H].length;V<q;V++){let z=Y[H][V]?.[1];if(!z)continue;let B=Object.keys(z);for(let D=0,L=B.length;D<L;D++)z[B[D]]=$[z[B[D]]]}let K=[];for(let H in Z)K[H]=Y[Z[H]];return[W,K,G]}function PV(Q,X){if(!Q)return;for(let Y of Object.keys(Q).sort((J,G)=>G.length-J.length))if(pk0(Y).test(X))return[...Q[Y]];return}var eE=class{name="RegExpRouter";#Q;#X;constructor(){this.#Q={[d4]:Object.create(null)},this.#X={[d4]:Object.create(null)}}add(Q,X,Y){let J=this.#Q,G=this.#X;if(!J||!G)throw Error(rE);if(!J[Q])[J,G].forEach(($)=>{$[Q]=Object.create(null),Object.keys($[d4]).forEach((K)=>{$[Q][K]=[...$[d4][K]]})});if(X==="/*")X="*";let W=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let $=pk0(X);if(Q===d4)Object.keys(J).forEach((K)=>{J[K][X]||=PV(J[K],X)||PV(J[d4],X)||[]});else J[Q][X]||=PV(J[Q],X)||PV(J[d4],X)||[];Object.keys(J).forEach((K)=>{if(Q===d4||Q===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Y,W])})}),Object.keys(G).forEach((K)=>{if(Q===d4||Q===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Y,W]))});return}let Z=aE(X)||[X];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(Q===d4||Q===F)G[F][H]||=[...PV(J[F],H)||PV(J[d4],H)||[]],G[F][H].push([Y,W-K+$+1])})}}match=sE;buildAllMatchers(){let Q=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Q)).forEach((X)=>{Q[X]||=this.#Y(X)}),this.#Q=this.#X=void 0,ai1(),Q}#Y(Q){let X=[],Y=Q===d4;if([this.#Q,this.#X].forEach((J)=>{let G=J[Q]?Object.keys(J[Q]).map((W)=>[W,J[Q][W]]):[];if(G.length!==0)Y||=!0,X.push(...G);else if(Q!==d4)X.push(...Object.keys(J[d4]).map((W)=>[W,J[d4][W]]))}),!Y)return null;else return ri1(X)}};var oi1=class{name="PreparedRegExpRouter";#Q;#X;constructor(Q,X){this.#Q=Q,this.#X=X}#Y(Q,X){let Y=this.#Q[Q];Y[1].forEach((J)=>J&&J.push(X)),Object.values(Y[2]).forEach((J)=>J[0].push(X))}#J(Q,X,Y,J,G){let W=this.#Q[Q];if(!G)W[2][X][0].push([Y,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Y,G]);else W[2][Z||X][0].push([Y,G])})}add(Q,X,Y){if(!this.#Q[Q]){let G=this.#Q[d4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),mD];this.#Q[Q]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(X==="/*"||X==="*"){let G=[Y,{}];if(Q===d4)for(let W in this.#Q)this.#Y(W,G);else this.#Y(Q,G);return}let J=this.#X[X];if(!J)throw Error(`Path ${X} is not registered`);for(let[G,W]of J)if(Q===d4)for(let Z in this.#Q)this.#J(Z,X,Y,G,W);else this.#J(Q,X,Y,G,W)}buildAllMatchers(){return this.#Q}match=sE};var El=class{name="SmartRouter";#Q=[];#X=[];constructor(Q){this.#Q=Q.routers}add(Q,X,Y){if(!this.#X)throw Error(rE);this.#X.push([Q,X,Y])}match(Q,X){if(!this.#X)throw Error("Fatal error");let Y=this.#Q,J=this.#X,G=Y.length,W=0,Z;for(;W<G;W++){let $=Y[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(Q,X)}catch(K){if(K instanceof oE)continue;throw K}this.match=$.match.bind($),this.#Q=[$],this.#X=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#X||this.#Q.length!==1)throw Error("No active router has been determined yet.");return this.#Q[0]}};var pD=Object.create(null),ck0=class Q{#Q;#X;#Y;#J=0;#W=pD;constructor(X,Y,J){if(this.#X=J||Object.create(null),this.#Q=[],X&&Y){let G=Object.create(null);G[X]={handler:Y,possibleKeys:[],score:0},this.#Q=[G]}this.#Y=[]}insert(X,Y,J){this.#J=++this.#J;let G=this,W=Ck0(Y),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=Ik0(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#X){if(G=G.#X[q],V)Z.push(V[1]);continue}if(G.#X[q]=new Q,V)G.#Y.push(V),Z.push(V[1]);G=G.#X[q]}return G.#Q.push({[X]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(X,Y,J,G){let W=[];for(let Z=0,$=X.#Q.length;Z<$;Z++){let K=X.#Q[Z],H=K[Y]||K[d4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==pD||G&&G!==pD)for(let V=0,q=H.possibleKeys.length;V<q;V++){let z=H.possibleKeys[V],B=F[H.score];H.params[z]=G?.[z]&&!B?G[z]:J[z]??G?.[z],F[H.score]=!0}}}return W}search(X,Y){let J=[];this.#W=pD;let W=[this],Z=Ml(Y),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let z=0,B=W.length;z<B;z++){let D=W[z],L=D.#X[F];if(L)if(L.#W=D.#W,V){if(L.#X["*"])J.push(...this.#G(L.#X["*"],X,D.#W));J.push(...this.#G(L,X,D.#W))}else q.push(L);for(let M=0,C=D.#Y.length;M<C;M++){let A=D.#Y[M],E=D.#W===pD?{}:{...D.#W};if(A==="*"){let b=D.#X["*"];if(b)J.push(...this.#G(b,X,D.#W)),b.#W=E,q.push(b);continue}let[T,j,R]=A;if(!F&&!(R instanceof RegExp))continue;let v=D.#X[T],y=Z.slice(K).join("/");if(R instanceof RegExp){let b=R.exec(y);if(b){if(E[j]=b[0],J.push(...this.#G(v,X,D.#W,E)),Object.keys(v.#X).length){v.#W=E;let h=b[0].match(/\//)?.length??0;($[h]||=[]).push(v)}continue}}if(R===!0||R.test(F))if(E[j]=F,V){if(J.push(...this.#G(v,X,E,D.#W)),v.#X["*"])J.push(...this.#G(v.#X["*"],X,E,D.#W))}else v.#W=E,q.push(v)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var jl=class{name="TrieRouter";#Q;constructor(){this.#Q=new ck0}add(Q,X,Y){let J=aE(X);if(J){for(let G=0,W=J.length;G<W;G++)this.#Q.insert(Q,J[G],Y);return}this.#Q.insert(Q,X,Y)}match(Q,X){return this.#Q.search(Q,X)}};var ZQ=class extends uk0{constructor(Q={}){super(Q);this.router=Q.router??new El({routers:[new eE,new jl]})}};function si1(){let{process:Q,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Q!==void 0?"NO_COLOR"in Q?.env:!1)}async function nk0(){let{navigator:Q}=globalThis,X="cloudflare:workers";return!(Q!==void 0&&Q.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!si1())}var ti1=(Q)=>{let[X,Y]=[",","."];return Q.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(Y)},ei1=(Q)=>{let X=Date.now()-Q;return ti1([X<1000?X+"ms":Math.round(X/1000)+"s"])},Qa1=async(Q)=>{if(await nk0())switch(Q/100|0){case 5:return`\x1B[31m${Q}\x1B[0m`;case 4:return`\x1B[33m${Q}\x1B[0m`;case 3:return`\x1B[36m${Q}\x1B[0m`;case 2:return`\x1B[32m${Q}\x1B[0m`}return`${Q}`};async function ik0(Q,X,Y,J,G=0,W){let Z=X==="<--"?`${X} ${Y} ${J}`:`${X} ${Y} ${J} ${await Qa1(G)} ${W}`;Q(Z)}var ak0=(Q=console.log)=>{return async function(Y,J){let{method:G,url:W}=Y.req,Z=W.slice(W.indexOf("/",8));await ik0(Q,"<--",G,Z);let $=Date.now();await J(),await ik0(Q,"-->",G,Z,Y.res.status,ei1($))}};var rk0=(Q)=>{let Y={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Q},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Y.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Y.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Y.credentials)K("Access-Control-Allow-Credentials","true");if(Y.exposeHeaders?.length)K("Access-Control-Expose-Headers",Y.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Y.origin!=="*")K("Vary","Origin");if(Y.maxAge!=null)K("Access-Control-Max-Age",Y.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Y.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Y.origin!=="*")Z.header("Vary","Origin",{append:!0})}};var ok0=()=>{try{return performance.now()}catch{}return Date.now()},Cl=(Q)=>{let X={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...Q};return async function(J,G){let W=[],Z=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:W,timers:Z}),X.total)TV(J,"total",X.totalDescription);if(await G(),X.total)QH(J,"total");if(X.autoEnd)Z.forEach((K,H)=>QH(J,H));if(typeof X.enabled==="function"?X.enabled(J):X.enabled){J.res.headers.append("Server-Timing",W.join(","));let K=typeof X.crossOrigin==="function"?X.crossOrigin(J):X.crossOrigin;if(K)J.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},sk0=(Q,X,Y,J,G)=>{let W=Q.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Y==="number"){let Z=Y.toFixed(G||1),$=J?`${X};dur=${Z};desc="${J}"`:`${X};dur=${Z}`;W.headers.push($)}else{let Z=Y?`${X};desc="${Y}"`:`${X}`;W.headers.push(Z)}},TV=(Q,X,Y)=>{let J=Q.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(X,{description:Y,start:ok0()})},QH=(Q,X,Y)=>{let J=Q.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(X);if(!G){console.warn(`Timer "${X}" does not exist!`);return}let{description:W,start:Z}=G,$=ok0()-Z;sk0(Q,X,$,W,Y),J.timers.delete(X)};var Xa1=/^[\w!#$%&'*.^`|~+-]+$/,Ya1=/^[ !#-:<-[\]-~]*$/,Il=(Q,X)=>{if(X&&Q.indexOf(X)===-1)return{};let Y=Q.trim().split(";"),J={};for(let G of Y){G=G.trim();let W=G.indexOf("=");if(W===-1)continue;let Z=G.substring(0,W).trim();if(X&&X!==Z||!Xa1.test(Z))continue;let $=G.substring(W+1).trim();if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Ya1.test($)){if(J[Z]=$.indexOf("%")!==-1?MV($,uD):$,X)break}}return J};var tk0=(Q,X,Y)=>{let J=Q.req.raw.headers.get("Cookie");if(typeof X==="string"){if(!J)return;let W=X;if(Y==="secure")W="__Secure-"+X;else if(Y==="host")W="__Host-"+X;return Il(J,W)[W]}if(!J)return{};return Il(J)};var Rl=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_GATEWAY_CREATE",description:"Create gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_LIST",description:"List gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_GET",description:"View gateway details",category:"Gateways"},{name:"COLLECTION_GATEWAY_UPDATE",description:"Update gateways",category:"Gateways"},{name:"COLLECTION_GATEWAY_DELETE",description:"Delete gateways",category:"Gateways",dangerous:!0},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"}];function cD(){let Q={Organizations:[],Connections:[],Gateways:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[]};for(let X of Rl)Q[X.category]?.push(X);return Q}var Ja1=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Ga1="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+Ja1+"]*",Wa1=new RegExp("^"+Ga1+"$");function ek0(Q,X){let Y=[],J=X.exec(Q);while(J){let G=[];G.startIndex=X.lastIndex-J[0].length;let W=J.length;for(let Z=0;Z<W;Z++)G.push(J[Z]);Y.push(G),J=X.exec(Q)}return Y}var Sl=function(Q){let X=Wa1.exec(Q);return!(X===null||typeof X>"u")};var Za1={allowBooleanAttributes:!1,unpairedTags:[]};function G_0(Q,X){X=Object.assign({},Za1,X);let Y=[],J=!1,G=!1;if(Q[0]==="\uFEFF")Q=Q.substr(1);for(let W=0;W<Q.length;W++)if(Q[W]==="<"&&Q[W+1]==="?"){if(W+=2,W=X_0(Q,W),W.err)return W}else if(Q[W]==="<"){let Z=W;if(W++,Q[W]==="!"){W=Y_0(Q,W);continue}else{let $=!1;if(Q[W]==="/")$=!0,W++;let K="";for(;W<Q.length&&Q[W]!==">"&&Q[W]!==" "&&Q[W]!=="\t"&&Q[W]!==`
|
|
262
262
|
`&&Q[W]!=="\r";W++)K+=Q[W];if(K=K.trim(),K[K.length-1]==="/")K=K.substring(0,K.length-1),W--;if(!Ua1(K)){let V;if(K.trim().length===0)V="Invalid space after '<'.";else V="Tag '"+K+"' is an invalid name.";return u8("InvalidTag",V,n9(Q,W))}let H=Ha1(Q,W);if(H===!1)return u8("InvalidAttr","Attributes for '"+K+"' have open quote.",n9(Q,W));let F=H.value;if(W=H.index,F[F.length-1]==="/"){let V=W-F.length;F=F.substring(0,F.length-1);let q=J_0(F,X);if(q===!0)J=!0;else return u8(q.err.code,q.err.msg,n9(Q,V+q.err.line))}else if($)if(!H.tagClosed)return u8("InvalidTag","Closing tag '"+K+"' doesn't have proper closing.",n9(Q,W));else if(F.trim().length>0)return u8("InvalidTag","Closing tag '"+K+"' can't have attributes or invalid starting.",n9(Q,Z));else if(Y.length===0)return u8("InvalidTag","Closing tag '"+K+"' has not been opened.",n9(Q,Z));else{let V=Y.pop();if(K!==V.tagName){let q=n9(Q,V.tagStartPos);return u8("InvalidTag","Expected closing tag '"+V.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+K+"'.",n9(Q,Z))}if(Y.length==0)G=!0}else{let V=J_0(F,X);if(V!==!0)return u8(V.err.code,V.err.msg,n9(Q,W-F.length+V.err.line));if(G===!0)return u8("InvalidXml","Multiple possible root nodes found.",n9(Q,W));else if(X.unpairedTags.indexOf(K)!==-1);else Y.push({tagName:K,tagStartPos:Z});J=!0}for(W++;W<Q.length;W++)if(Q[W]==="<")if(Q[W+1]==="!"){W++,W=Y_0(Q,W);continue}else if(Q[W+1]==="?"){if(W=X_0(Q,++W),W.err)return W}else break;else if(Q[W]==="&"){let V=qa1(Q,W);if(V==-1)return u8("InvalidChar","char '&' is not expected.",n9(Q,W));W=V}else if(G===!0&&!Q_0(Q[W]))return u8("InvalidXml","Extra text at the end",n9(Q,W));if(Q[W]==="<")W--}}else{if(Q_0(Q[W]))continue;return u8("InvalidChar","char '"+Q[W]+"' is not expected.",n9(Q,W))}if(!J)return u8("InvalidXml","Start tag expected.",1);else if(Y.length==1)return u8("InvalidTag","Unclosed tag '"+Y[0].tagName+"'.",n9(Q,Y[0].tagStartPos));else if(Y.length>0)return u8("InvalidXml","Invalid '"+JSON.stringify(Y.map((W)=>W.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function Q_0(Q){return Q===" "||Q==="\t"||Q===`
|
|
263
263
|
`||Q==="\r"}function X_0(Q,X){let Y=X;for(;X<Q.length;X++)if(Q[X]=="?"||Q[X]==" "){let J=Q.substr(Y,X-Y);if(X>5&&J==="xml")return u8("InvalidXml","XML declaration allowed only at the start of the document.",n9(Q,X));else if(Q[X]=="?"&&Q[X+1]==">"){X++;break}else continue}return X}function Y_0(Q,X){if(Q.length>X+5&&Q[X+1]==="-"&&Q[X+2]==="-"){for(X+=3;X<Q.length;X++)if(Q[X]==="-"&&Q[X+1]==="-"&&Q[X+2]===">"){X+=2;break}}else if(Q.length>X+8&&Q[X+1]==="D"&&Q[X+2]==="O"&&Q[X+3]==="C"&&Q[X+4]==="T"&&Q[X+5]==="Y"&&Q[X+6]==="P"&&Q[X+7]==="E"){let Y=1;for(X+=8;X<Q.length;X++)if(Q[X]==="<")Y++;else if(Q[X]===">"){if(Y--,Y===0)break}}else if(Q.length>X+9&&Q[X+1]==="["&&Q[X+2]==="C"&&Q[X+3]==="D"&&Q[X+4]==="A"&&Q[X+5]==="T"&&Q[X+6]==="A"&&Q[X+7]==="["){for(X+=8;X<Q.length;X++)if(Q[X]==="]"&&Q[X+1]==="]"&&Q[X+2]===">"){X+=2;break}}return X}var $a1='"',Ka1="'";function Ha1(Q,X){let Y="",J="",G=!1;for(;X<Q.length;X++){if(Q[X]===$a1||Q[X]===Ka1)if(J==="")J=Q[X];else if(J!==Q[X]);else J="";else if(Q[X]===">"){if(J===""){G=!0;break}}Y+=Q[X]}if(J!=="")return!1;return{value:Y,index:X,tagClosed:G}}var Fa1=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function J_0(Q,X){let Y=ek0(Q,Fa1),J={};for(let G=0;G<Y.length;G++){if(Y[G][1].length===0)return u8("InvalidAttr","Attribute '"+Y[G][2]+"' has no space in starting.",nD(Y[G]));else if(Y[G][3]!==void 0&&Y[G][4]===void 0)return u8("InvalidAttr","Attribute '"+Y[G][2]+"' is without value.",nD(Y[G]));else if(Y[G][3]===void 0&&!X.allowBooleanAttributes)return u8("InvalidAttr","boolean attribute '"+Y[G][2]+"' is not allowed.",nD(Y[G]));let W=Y[G][2];if(!za1(W))return u8("InvalidAttr","Attribute '"+W+"' is an invalid name.",nD(Y[G]));if(!J.hasOwnProperty(W))J[W]=1;else return u8("InvalidAttr","Attribute '"+W+"' is repeated.",nD(Y[G]))}return!0}function Va1(Q,X){let Y=/\d/;if(Q[X]==="x")X++,Y=/[\da-fA-F]/;for(;X<Q.length;X++){if(Q[X]===";")return X;if(!Q[X].match(Y))break}return-1}function qa1(Q,X){if(X++,Q[X]===";")return-1;if(Q[X]==="#")return X++,Va1(Q,X);let Y=0;for(;X<Q.length;X++,Y++){if(Q[X].match(/\w/)&&Y<20)continue;if(Q[X]===";")break;return-1}return X}function u8(Q,X,Y){return{err:{code:Q,msg:X,line:Y.line||Y,col:Y.col}}}function za1(Q){return Sl(Q)}function Ua1(Q){return Sl(Q)}function n9(Q,X){let Y=Q.substring(0,X).split(/\r?\n/);return{line:Y.length,col:Y[Y.length-1].length+1}}function nD(Q){return Q.startIndex+Q[1].length}var W_0={validate:G_0};var _9=m6(Wl0(),1);mZ();z5();mZ();z5();FX();hQ();var P8=(Q,X="ms")=>{return new Date(Date.now()+(X==="sec"?Q*1000:Q))},Yv=new WeakMap;function bn0(Q,X){let Y=X.fields,J={};for(let G in Q){let W=Y[G];if(!W){J[G]=Q[G];continue}if(W.returned===!1)continue;J[G]=Q[G]}return J}function Jv(Q,X){if(!Yv.has(Q))Yv.set(Q,new Map);let Y=Yv.get(Q);if(Y.has(X))return Y.get(X);let J={...X==="user"?Q.user?.additionalFields:{},...X==="session"?Q.session?.additionalFields:{}};for(let G of Q.plugins||[])if(G.schema&&G.schema[X])J={...J,...G.schema[X].fields};return Yv.get(Q).set(X,J),J}function H9(Q,X){return{...bn0(X,{fields:Jv(Q,"user")}),id:X.id}}function W7(Q,X){return bn0(X,{fields:Jv(Q,"session")})}function fn0(Q,X){let Y=X.action||"create",J=X.fields,G=Object.assign(Object.create(null),null);for(let W in J){if(W in Q){if(J[W].input===!1){if(J[W].defaultValue!==void 0){if(Y!=="update"){G[W]=J[W].defaultValue;continue}}if(Q[W])throw new n("BAD_REQUEST",{message:`${W} is not allowed to be set`});continue}if(J[W].validator?.input&&Q[W]!==void 0){G[W]=J[W].validator.input["~standard"].validate(Q[W]);continue}if(J[W].transform?.input&&Q[W]!==void 0){G[W]=J[W].transform?.input(Q[W]);continue}G[W]=Q[W];continue}if(J[W].defaultValue!==void 0&&Y==="create"){if(typeof J[W].defaultValue==="function"){G[W]=J[W].defaultValue();continue}G[W]=J[W].defaultValue;continue}if(J[W].required&&Y==="create")throw new n("BAD_REQUEST",{message:`${W} is required`})}return G}function zs(Q,X={},Y){return fn0(X,{fields:Jv(Q,"user"),action:Y})}function hn0(Q,X){return fn0(X,{fields:Jv(Q,"session")})}function pX(Q,X){if(!X)return Q;for(let Y in X){let J=X[Y]?.modelName;if(J)Q[Y].modelName=J;for(let G in Q[Y].fields){let W=X[Y]?.fields?.[G];if(!W)continue;Q[Y].fields[G].fieldName=W}}return Q}cX();G1();var wZ6="127.0.0.1";function D$(Q,X){if(X.advanced?.ipAddress?.disableIpTracking)return null;if($7()||wz())return wZ6;let Y="headers"in Q?Q.headers:Q,J=X.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let W="get"in Y?Y.get(G):Y[G];if(typeof W==="string"){let Z=W.split(",")[0].trim();if(MZ6(Z))return Z}}return null}function MZ6(Q){if(K3().safeParse(Q).success)return!0;if(H3().safeParse(Q).success)return!0;return!1}VX();kG();cX();d8();import{sql as xG}from"kysely";async function CZ6(Q,X){let Y;if(!Q.database){let J=OJ(Q),G=Object.keys(J).reduce((Z,$)=>{return Z[$]=[],Z},{}),{memoryAdapter:W}=await Promise.resolve().then(() => (mn0(),un0));Y=W(G)(Q)}else if(typeof Q.database==="function")Y=Q.database(Q);else Y=await X(Q);if(!Y.transaction)d1.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Y.transaction=async(J)=>{return J(Y)};return Y}async function ln0(Q){return CZ6(Q,async(X)=>{let{createKyselyAdapter:Y}=await Promise.resolve().then(() => (Os(),Ns)),{kysely:J,databaseType:G,transaction:W}=await Y(X);if(!J)throw new R1("Failed to initialize database adapter");let{kyselyAdapter:Z}=await Promise.resolve().then(() => (Os(),Ns));return Z(J,{type:G||"sqlite",debugLogs:X.database&&"debugLogs"in X.database?X.database.debugLogs:!1,transaction:W})(X)})}function IZ6(Q,X){let Y=X.hooks;async function J(K,H,F){let V=await TY(),q=K;for(let D of Y||[]){let L=D[H]?.create?.before;if(L){let M=await L(q,V);if(M===!1)return null;if(typeof M==="object"&&"data"in M)q={...q,...M.data}}}let z=F?await F.fn(q):null,B=!F||F.executeMainFn?await(await D4(Q)).create({model:H,data:q,forceAllowId:!0}):z;for(let D of Y||[]){let L=D[H]?.create?.after;if(L)await L(B,V)}return B}async function G(K,H,F,V){let q=await TY(),z=K;for(let L of Y||[]){let M=L[F]?.update?.before;if(M){let C=await M(K,q);if(C===!1)return null;if(typeof C==="object"&&"data"in C)z={...z,...C.data}}}let B=V?await V.fn(z):null,D=!V||V.executeMainFn?await(await D4(Q)).update({model:F,update:z,where:H}):B;for(let L of Y||[]){let M=L[F]?.update?.after;if(M)await M(D,q)}return D}async function W(K,H,F,V){let q=await TY(),z=K;for(let L of Y||[]){let M=L[F]?.update?.before;if(M){let C=await M(K,q);if(C===!1)return null;if(typeof C==="object"&&"data"in C)z={...z,...C.data}}}let B=V?await V.fn(z):null,D=!V||V.executeMainFn?await(await D4(Q)).updateMany({model:F,update:z,where:H}):B;for(let L of Y||[]){let M=L[F]?.update?.after;if(M)await M(D,q)}return D}async function Z(K,H,F){let V=await TY(),q=null;try{q=(await(await D4(Q)).findMany({model:H,where:K,limit:1}))[0]||null}catch(D){}if(q)for(let D of Y||[]){let L=D[H]?.delete?.before;if(L){if(await L(q,V)===!1)return null}}let z=F?await F.fn(K):null,B=!F||F.executeMainFn?await(await D4(Q)).delete({model:H,where:K}):z;if(q)for(let D of Y||[]){let L=D[H]?.delete?.after;if(L)await L(q,V)}return B}async function $(K,H,F){let V=await TY(),q=[];try{q=await(await D4(Q)).findMany({model:H,where:K})}catch(D){}for(let D of q)for(let L of Y||[]){let M=L[H]?.delete?.before;if(M){if(await M(D,V)===!1)return null}}let z=F?await F.fn(K):null,B=!F||F.executeMainFn?await(await D4(Q)).deleteMany({model:H,where:K}):z;for(let D of q)for(let L of Y||[]){let M=L[H]?.delete?.after;if(M)await M(D,V)}return B}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:W,deleteWithHooks:Z,deleteManyWithHooks:$}}var Ls=(Q,X)=>{let{logger:Y,options:J}=X,G=J.secondaryStorage,W=J.session?.expiresIn||604800,{createWithHooks:Z,updateWithHooks:$,updateManyWithHooks:K,deleteWithHooks:H,deleteManyWithHooks:F}=IZ6(Q,X);async function V(q){if(!G)return;let z=await G.get(`active-sessions-${q.id}`);if(!z)return;let B=Date.now(),D=(E4(z)||[]).filter((L)=>L.expiresAt>B);await Promise.all(D.map(async({token:L})=>{let M=await G.get(L);if(!M)return;let C=E4(M);if(!C)return;let A=Math.max(Math.floor(new Date(C.session.expiresAt).getTime()-B)/1000,0);await G.set(L,JSON.stringify({session:C.session,user:q}),Math.floor(A))}))}return{createOAuthUser:async(q,z)=>{return PO(Q,async()=>{let B=await Z({createdAt:new Date,updatedAt:new Date,...q},"user",void 0);return{user:B,account:await Z({...z,userId:B.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q,email:q.email?.toLowerCase()},"user",void 0)},createAccount:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},listSessions:async(q)=>{if(G){let z=await G.get(`active-sessions-${q}`);if(!z)return[];let B=E4(z)||[],D=Date.now(),L=B.filter((C)=>C.expiresAt>D),M=[];for(let C of L){let A=await G.get(C.token);if(A){let E=E4(A);if(!E)return[];let T=W7(X.options,{...E.session,expiresAt:new Date(E.session.expiresAt)});M.push(T)}}return M}return await(await D4(Q)).findMany({model:"session",where:[{field:"userId",value:q}]})},listUsers:async(q,z,B,D)=>{return await(await D4(Q)).findMany({model:"user",limit:q,offset:z,sortBy:B,where:D})},countTotalUsers:async(q)=>{let z=await(await D4(Q)).count({model:"user",where:q});if(typeof z==="string")return parseInt(z);return z},deleteUser:async(q)=>{if(G)await G.delete(`active-sessions-${q}`);if(!G||J.session?.storeSessionInDatabase)await F([{field:"userId",value:q}],"session",void 0);await F([{field:"userId",value:q}],"account",void 0),await H([{field:"id",value:q}],"user",void 0)},createSession:async(q,z,B,D)=>{let L=await TY().catch(()=>null),M=L?.headers||L?.request?.headers,{id:C,...A}=B||{},E=hn0(L?.context.options??J,{}),T={ipAddress:L?.request||L?.headers?D$(L?.request||L?.headers,L?.context.options)||"":"",userAgent:M?.get("user-agent")||"",...A,expiresAt:z?P8(86400,"sec"):P8(W,"sec"),userId:q,token:QQ(32),createdAt:new Date,updatedAt:new Date,...E,...D?A:{}};return await Z(T,"session",G?{fn:async(j)=>{let R=await G.get(`active-sessions-${q}`),v=[],y=Date.now();if(R)v=E4(R)||[],v=v.filter((m)=>m.expiresAt>y);let b=v.sort((m,Q0)=>m.expiresAt-Q0.expiresAt),h=b.at(-1)?.expiresAt;if(b.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!h||h<T.expiresAt.getTime())h=T.expiresAt.getTime();let a=Math.max(Math.floor((h-y)/1000),0);if(a>0)await G.set(`active-sessions-${q}`,JSON.stringify(b),a);let f=await Q.findOne({model:"user",where:[{field:"id",value:q}]}),S=Math.max(Math.floor((T.expiresAt.getTime()-y)/1000),0);if(S>0)await G.set(T.token,JSON.stringify({session:j,user:f}),S);return j},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async(q)=>{if(G){let L=await G.get(q);if(!L&&!J.session?.storeSessionInDatabase)return null;if(L){let M=E4(L);if(!M)return null;return{session:W7(X.options,{...M.session,expiresAt:new Date(M.session.expiresAt),createdAt:new Date(M.session.createdAt),updatedAt:new Date(M.session.updatedAt)}),user:H9(X.options,{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)})}}}let z=await(await D4(Q)).findOne({model:"session",where:[{value:q,field:"token"}],join:{user:!0}});if(!z)return null;let{user:B,...D}=z;if(!B)return null;return{session:W7(X.options,D),user:H9(X.options,B)}},findSessions:async(q)=>{if(G){let B=[];for(let D of q){let L=await G.get(D);if(L){let M=E4(L);if(!M)return[];let C={session:{...M.session,expiresAt:new Date(M.session.expiresAt)},user:{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)}};B.push(C)}}return B}let z=await(await D4(Q)).findMany({model:"session",where:[{field:"token",value:q,operator:"in"}],join:{user:!0}});if(!z.length)return[];if(z.some((B)=>!B.user))return[];return z.map((B)=>{let{user:D,...L}=B;return{session:L,user:D}})},updateSession:async(q,z)=>{return await $(z,[{field:"token",value:q}],"session",G?{async fn(B){let D=await G.get(q),L=null;if(D){let M=E4(D);if(!M)return null;return L={...M.session,...B},L}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async(q)=>{if(G){let z=await G.get(q);if(z){let{session:B}=E4(z)??{};if(!B){Y.error("Session not found in secondary storage");return}let D=B.userId,L=await G.get(`active-sessions-${D}`);if(L){let M=E4(L)||[],C=Date.now(),A=M.filter((T)=>T.expiresAt>C&&T.token!==q),E=A.sort((T,j)=>T.expiresAt-j.expiresAt).at(-1)?.expiresAt;if(A.length>0&&E&&E>Date.now())await G.set(`active-sessions-${D}`,JSON.stringify(A),Math.floor((E-C)/1000));else await G.delete(`active-sessions-${D}`)}else Y.error("Active sessions list not found in secondary storage")}if(await G.delete(q),!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await(await D4(Q)).delete({model:"session",where:[{field:"token",value:q}]})},deleteAccounts:async(q)=>{await F([{field:"userId",value:q}],"account",void 0)},deleteAccount:async(q)=>{await H([{field:"id",value:q}],"account",void 0)},deleteSessions:async(q)=>{if(G){if(typeof q==="string"){let z=await G.get(`active-sessions-${q}`),B=z?E4(z):[];if(!B)return;for(let D of B)await G.delete(D.token)}else for(let z of q)if(await G.get(z))await G.delete(z);if(!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await F([{field:Array.isArray(q)?"token":"userId",value:q,operator:Array.isArray(q)?"in":void 0}],"session",void 0)},findOAuthUser:async(q,z,B)=>{let D=await(await D4(Q)).findMany({model:"account",where:[{value:z,field:"accountId"}],join:{user:!0}}).then((L)=>{return L.find((M)=>M.providerId===B)});if(D)if(D.user)return{user:D.user,accounts:[D]};else{let L=await(await D4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:[D]};return null}else{let L=await(await D4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:await(await D4(Q)).findMany({model:"account",where:[{value:L.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async(q,z)=>{let B=await(await D4(Q)).findOne({model:"user",where:[{value:q.toLowerCase(),field:"email"}],join:{...z?.includeAccounts?{account:!0}:{}}});if(!B)return null;let{account:D,...L}=B;return{user:L,accounts:D??[]}},findUserById:async(q)=>{if(!q)return null;return await(await D4(Q)).findOne({model:"user",where:[{field:"id",value:q}]})},linkAccount:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"account",void 0)},updateUser:async(q,z)=>{let B=await $(z,[{field:"id",value:q}],"user",void 0);return await V(B),await V(B),B},updateUserByEmail:async(q,z)=>{let B=await $(z,[{field:"email",value:q.toLowerCase()}],"user",void 0);return await V(B),await V(B),B},updatePassword:async(q,z)=>{await K({password:z},[{field:"userId",value:q},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async(q)=>{return await(await D4(Q)).findMany({model:"account",where:[{field:"userId",value:q}]})},findAccount:async(q)=>{return await(await D4(Q)).findOne({model:"account",where:[{field:"accountId",value:q}]})},findAccountByProviderId:async(q,z)=>{return await(await D4(Q)).findOne({model:"account",where:[{field:"accountId",value:q},{field:"providerId",value:z}]})},findAccountByUserId:async(q)=>{return await(await D4(Q)).findMany({model:"account",where:[{field:"userId",value:q}]})},updateAccount:async(q,z)=>{return await $(z,[{field:"id",value:q}],"account",void 0)},createVerificationValue:async(q)=>{return await Z({createdAt:new Date,updatedAt:new Date,...q},"verification",void 0)},findVerificationValue:async(q)=>{let z=await(await D4(Q)).findMany({model:"verification",where:[{field:"identifier",value:q}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await D4(Q)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return z[0]},deleteVerificationValue:async(q)=>{await(await D4(Q)).delete({model:"verification",where:[{field:"id",value:q}]})},deleteVerificationByIdentifier:async(q)=>{await(await D4(Q)).delete({model:"verification",where:[{field:"identifier",value:q}]})},updateVerificationValue:async(q,z)=>{return await $(z,[{field:"id",value:q}],"verification",void 0)}}};function RZ6(Q){let X=OJ(Q),Y={};for(let J in X){let G=X[J],W=G.fields,Z={};if(Object.entries(W).forEach(([$,K])=>{if(Z[K.fieldName||$]=K,K.references){let H=X[K.references.model];if(H)Z[K.fieldName||$].references={...K.references,model:H.modelName,field:K.references.field}}}),Y[G.modelName]){Y[G.modelName].fields={...Y[G.modelName].fields,...Z};continue}Y[G.modelName]={fields:Z,order:G.order||1/0}}return Y}var SZ6={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function vZ6(Q,X,Y){function J(W){return W.toLowerCase().split("(")[0].trim()}if(X==="string[]"||X==="number[]")return Q.toLowerCase().includes("json");let G=SZ6[Y];return(Array.isArray(X)?G.string.map((W)=>W.toLowerCase()):G[X].map((W)=>W.toLowerCase())).includes(J(Q))}async function kZ6(Q){try{let X=await xG`SHOW search_path`.execute(Q);if(X.rows[0]?.search_path)return X.rows[0].search_path.split(",").map((Y)=>Y.trim()).map((Y)=>Y.replace(/^["']|["']$/g,"")).filter((Y)=>!Y.startsWith("$"))[0]||"public"}catch(X){}return"public"}async function dn0(Q){let X=RZ6(Q),Y=Pz(Q.logger),{kysely:J,databaseType:G}=await GC(Q);if(!G)Y.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Y.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let W="public";if(G==="postgres"){W=await kZ6(J),Y.debug(`PostgreSQL migration: Using schema '${W}' (from search_path)`);try{if(!(await xG`
|
|
264
264
|
SELECT schema_name
|
|
@@ -1032,22 +1032,22 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
|
|
|
1032
1032
|
</script>
|
|
1033
1033
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" ${J}></script>
|
|
1034
1034
|
</body>
|
|
1035
|
-
</html>`},Ye=(Q)=>{let X=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:f0("/open-api/generate-schema",{method:"GET"},async(Y)=>{let J=await Cr0(Y.context,Y.context.options);return Y.json(J)}),openAPIReference:f0(X,{method:"GET",metadata:{isAction:!1}},async(Y)=>{if(Q?.disableDefaultReference)throw new n("NOT_FOUND");let J=await Cr0(Y.context,Y.context.options);return new Response(nq6(J,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};FX();kG();d8();hQ();G1();var Ow4=a6(async()=>{return{}}),Lw4=a6({use:[X8]},async(Q)=>{return{session:Q.context.session}}),ww4=T4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var Mw4=Number.POSITIVE_INFINITY;var Rr0=P(),aq6=F1(["pending","accepted","rejected","canceled"]).default("pending"),Pw4=d({id:P().default(QQ),name:P(),slug:P(),logo:P().nullish().optional(),metadata:c0(P(),G4()).or(P().transform((Q)=>JSON.parse(Q))).optional(),createdAt:n1()}),Tw4=d({id:P().default(QQ),organizationId:P(),userId:v1.string(),role:Rr0,createdAt:n1().default(()=>new Date)}),Aw4=d({id:P().default(QQ),organizationId:P(),email:P(),role:Rr0,status:aq6,teamId:P().nullish(),inviterId:P(),expiresAt:n1(),createdAt:n1().default(()=>new Date)}),Ew4=d({id:P().default(QQ),name:P().min(1),organizationId:P(),createdAt:n1(),updatedAt:n1().optional()}),jw4=d({id:P().default(QQ),teamId:P(),userId:P(),createdAt:n1().default(()=>new Date)}),Cw4=d({id:P().default(QQ),organizationId:P(),role:P(),permission:c0(P(),M0(P())),createdAt:n1().default(()=>new Date),updatedAt:n1().optional()}),Ir0=["admin","member","owner"],Iw4=o1([F1(Ir0),M0(F1(Ir0))]);q8();d8();hQ();var xw4=T4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});q8();VX();d8();hQ();vQ();c4();var rq6=T4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});d8();hQ();var oq6=T4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var v3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Sr0,readFileSync as vr0}from"fs";var Hk={emailAndPassword:{enabled:!0}},kr0=process.env.CONFIG_PATH||"./config.json",_r0=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function sq6(){if(Sr0(kr0))try{let Q=vr0(kr0,"utf-8"),X=JSON.parse(Q);return{auth:Hk,monitoring:v3,...X}}catch{return{auth:Hk,monitoring:v3}}if(Sr0(_r0))try{let Q=vr0(_r0,"utf-8");return{auth:JSON.parse(Q),monitoring:v3}}catch{return{auth:Hk,monitoring:v3}}return{auth:Hk,monitoring:v3}}var Iw=sq6();function yr0(){return{...v3,...Iw.monitoring}}function br0(){return Iw.theme}import{existsSync as lD6,mkdirSync as dD6}from"fs";import{Kysely as Yt0,PostgresDialect as Jt0,sql as Xt0}from"kysely";import{BunWorkerDialect as Gt0}from"kysely-bun-worker";import*as Wt0 from"path";var SJ=m6(_e(),1),bT4=SJ.default.Client,he=SJ.default.Pool,fT4=SJ.default.Connection,hT4=SJ.default.types,xT4=SJ.default.Query,gT4=SJ.default.DatabaseError,uT4=SJ.default.escapeIdentifier,mT4=SJ.default.escapeLiteral,lT4=SJ.default.Result,dT4=SJ.default.TypeOverrides,pT4=SJ.default.defaults;var pD6=cE.createHistogram("db.query.duration",{description:"Database query execution duration in milliseconds",unit:"ms"}),cD6=1000,Zt0=(Q)=>{let X={"db.statement":Q.query.sql,"db.status":Q.level==="error"?"error":"success"};if(Q.queryDurationMillis>cD6)console.error("Slow query detected:",{durationMs:Q.queryDurationMillis,sql:Q.query.sql,params:Q.query.parameters});if(pD6.record(Q.queryDurationMillis,X),Q.level==="error")console.error("Query failed:",{durationMs:Q.queryDurationMillis,error:Q.error,sql:Q.query.sql})},$t0={keepAlive:!0,keepAliveInitialDelayMillis:1e4,idleTimeoutMillis:300000,connectionTimeoutMillis:30000,allowExitOnIdle:!0};function nD6(Q){let X=new he({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...$t0}),Y=new Jt0({pool:X});return{type:"postgres",db:new Yt0({dialect:Y,log:Zt0}),pool:X}}function Kt0(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function Ht0(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let X=Q.substring(0,Q.lastIndexOf("/"));if(X&&X!=="/"&&!lD6(X))try{dD6(X,{recursive:!0})}catch{return console.warn(`Failed to create directory ${X}, using in-memory database`),":memory:"}}return Q}function iD6(Q){let X=Kt0(Q.connectionString);X=Ht0(X);let Y=new Gt0({url:X||":memory:"}),J=new Yt0({dialect:Y,log:Zt0});if(X!==":memory:"&&Q.options?.enableWAL!==!1)Xt0`PRAGMA journal_mode = WAL;`.execute(J).catch(()=>{});if(X!==":memory:"){let G=Q.options?.busyTimeout||5000;Xt0`PRAGMA busy_timeout = ${G};`.execute(J).catch(()=>{})}return{type:"sqlite",db:J}}function Ft0(Q){let X=Q||"file:./data/mesh.db";if(X===":memory:")return{type:"sqlite",connectionString:":memory:"};X=X.startsWith("/")?`file://${X}`:X;let Y=URL.canParse(X)?new URL(X):null,J=Y?.protocol.replace(":","")??X.split("://")[0];switch(J){case"postgres":case"postgresql":return{type:"postgres",connectionString:X};case"sqlite":case"file":if(!Y?.pathname)throw Error("Invalid database URL: "+X);return{type:"sqlite",connectionString:Y.pathname};default:throw Error(`Unsupported database protocol: ${J}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function ge(){return process.env.DATABASE_URL||`file:${Wt0.join(process.cwd(),"data/mesh.db")}`}function Vt0(Q){let X=Ft0(Q);if(X.type==="postgres")return new Jt0({pool:new he({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...$t0})});let Y=Kt0(X.connectionString);return Y=Ht0(Y),new Gt0({url:Y||":memory:"})}function aD6(Q){let X=Ft0(Q);if(X.type==="postgres")return nD6(X);return iD6(X)}var xe=null;function Mk(){if(!xe)xe=aD6(ge());return xe}class ue{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:X,subject:Y,html:J})});if(!G.ok)throw Error(`Failed to send email: ${G.statusText}`)}}class me{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:X},subject:Y,content:[{type:"text/html",value:J}]})});if(!G.ok){let W=await G.text();throw Error(`Failed to send email via SendGrid: ${G.statusText} - ${W}`)}}}var rD6=(Q)=>{let X=new ue(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},oD6=(Q)=>{let X=new me(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},sD6={resend:rD6,sendgrid:oD6};function Pk(Q){let X=sD6[Q.provider];if(!X)throw Error(`Unknown email provider: ${Q.provider}`);return X(Q)}function Tk(Q,X){return Q.find((Y)=>Y.id===X)}var qt0=(Q,X)=>{let Y=Tk(X,Q.emailProviderId);if(!Y)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let J=Pk(Y);return{sendMagicLink:async({email:G,url:W})=>{await J({to:G,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};y3();import{createCipheriv as tD6,createDecipheriv as eD6,randomBytes as Ot0}from"crypto";var Lt0="aes-256-gcm",gw=16,wt0=16,Mt0=32;class uw{key;constructor(Q){if(Buffer.from(Q,"base64").length===Mt0)this.key=Buffer.from(Q,"base64");else{let X=U0("crypto");this.key=X.createHash("sha256").update(Q).digest()}}async encrypt(Q){let X=Ot0(gw),Y=tD6(Lt0,this.key,X),J=Y.update(Q,"utf8");J=Buffer.concat([J,Y.final()]);let G=Y.getAuthTag();return Buffer.concat([X,G,J]).toString("base64")}async decrypt(Q){let X=Buffer.from(Q,"base64"),Y=X.subarray(0,gw),J=X.subarray(gw,gw+wt0),G=X.subarray(gw+wt0),W=eD6(Lt0,this.key,Y);W.setAuthTag(J);let Z=W.update(G);return Z=Buffer.concat([Z,W.final()]),Z.toString("utf8")}static generateKey(){return Ot0(Mt0).toString("base64")}}O7();mw();var ZN6=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class lw{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async create(Q){let X=Q.id??kJ("conn"),Y=new Date().toISOString(),J=await this.findById(X);if(J){if(J.organization_id!==Q.organization_id)throw Error("Connection ID already exists");return this.update(X,Q)}let G=await this.serializeConnection({...Q,id:Q.id??X,status:"active",created_at:Y,updated_at:Y});await this.db.insertInto("connections").values(G).execute();let W=await this.findById(X);if(!W)throw Error(`Failed to create connection with id: ${X}`);return W}async findById(Q,X){let Y=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(X)Y=Y.where("organization_id","=",X);let J=await Y.executeTakeFirst();return J?this.deserializeConnection(J):null}async list(Q){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(X.map((Y)=>this.deserializeConnection(Y)))}async update(Q,X){if(Object.keys(X).length===0){let G=await this.findById(Q);if(!G)throw Error("Connection not found");return G}let Y=await this.serializeConnection({...X,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(Y).where("id","=",Q).execute();let J=await this.findById(Q);if(!J)throw Error("Connection not found after update");return J}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,X){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");let J=Date.now();if(Y.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-J};if(!Y.connection_url)return{healthy:!1,latencyMs:Date.now()-J};try{let G=Y.connection_headers,W=await fetch(Y.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...Y.connection_token&&{Authorization:`Bearer ${Y.connection_token}`},...G?.headers,...X},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-J}}catch{return{healthy:!1,latencyMs:Date.now()-J}}}async serializeConnection(Q){let X={};for(let[Y,J]of Object.entries(Q)){if(J===void 0)continue;if(Y==="connection_token"&&J)X[Y]=await this.vault.encrypt(J);else if(Y==="configuration_state"&&J){let G=JSON.stringify(J);X[Y]=await this.vault.encrypt(G)}else if(Y==="connection_headers"&&J){let G=J;if(b3(G)&&G.envVars){let W={};for(let[Z,$]of Object.entries(G.envVars))W[Z]=await this.vault.encrypt($);X[Y]=JSON.stringify({...G,envVars:W})}else X[Y]=JSON.stringify(G)}else if(ZN6.includes(Y))X[Y]=J?JSON.stringify(J):null;else X[Y]=J}return X}async deserializeConnection(Q){let X=null;if(Q.connection_token)try{X=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let Y=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);Y=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let J=null;if(Q.connection_headers)try{let W=JSON.parse(Q.connection_headers);if(b3(W)&&W.envVars){let Z={};for(let[$,K]of Object.entries(W.envVars))try{Z[$]=await this.vault.decrypt(K)}catch{Z[$]=K}J={...W,envVars:Z}}else J=W}catch(W){console.error("Failed to parse connection_headers:",W)}let G=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:X,connection_headers:J,oauth_config:G(Q.oauth_config),configuration_state:Y,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}mw();class dw{db;constructor(Q){this.db=Q}async create(Q,X,Y){let J=kJ("gw"),G=new Date().toISOString();if(Y.isDefault)return await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:X}).where("organization_id","=",Q).where("is_default","=",1).execute(),await Z.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_strategy:Y.toolSelectionStrategy??"passthrough",tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:1,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await Z.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:kJ("gwc"),gateway_id:J,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:G}))).execute();let $=await this.findByIdInternal(Z,J);if(!$)throw Error(`Failed to create gateway with id: ${J}`);return $});if(await this.db.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_strategy:Y.toolSelectionStrategy??"passthrough",tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:0,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:kJ("gwc"),gateway_id:J,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create gateway with id: ${J}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,X){let Y=await Q.selectFrom("gateways").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;let J=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X).execute();return this.deserializeGatewayWithConnections(Y,J)}async list(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),Y=X.map((W)=>W.id);if(Y.length===0)return[];let J=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",Y).execute(),G=new Map;for(let W of J){let Z=G.get(W.gateway_id)??[];Z.push(W),G.set(W.gateway_id,Z)}return X.map((W)=>this.deserializeGatewayWithConnections(W,G.get(W.id)??[]))}async listByConnectionId(Q,X){let J=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",X).execute()).map((K)=>K.gateway_id);if(J.length===0)return[];let G=await this.db.selectFrom("gateways").selectAll().where("id","in",J).where("organization_id","=",Q).execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.gateway_id)??[];H.push(K),$.set(K.gateway_id,H)}return G.map((K)=>this.deserializeGatewayWithConnections(K,$.get(K.id)??[]))}async update(Q,X,Y){let J=new Date().toISOString(),G={updated_at:J,updated_by:X};if(Y.title!==void 0)G.title=Y.title;if(Y.description!==void 0)G.description=Y.description;if(Y.toolSelectionStrategy!==void 0)G.tool_selection_strategy=Y.toolSelectionStrategy;if(Y.toolSelectionMode!==void 0)G.tool_selection_mode=Y.toolSelectionMode;if(Y.icon!==void 0)G.icon=Y.icon;if(Y.status!==void 0)G.status=Y.status;if(Y.isDefault===!1)G.is_default=0;if(Y.isDefault===!0)G.is_default=1;if(Y.isDefault===!0){let Z=await this.findById(Q);if(!Z)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Z.organizationId).where("is_default","=",1).execute(),await $.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await $.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await $.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:kJ("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:J}))).execute()}})}else if(await this.db.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:kJ("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:J}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!X)return null;let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X.id).execute();return this.deserializeGatewayWithConnections(X,Y)}async getDefaultByOrgSlug(Q){let X=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!X)return null;return this.getDefaultByOrgId(X.id)}async setDefault(Q,X){let Y=await this.findById(Q);if(!Y)throw Error(`Gateway not found: ${Q}`);let J=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Y.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:J,updated_by:X}).where("id","=",Q).execute()});let G=await this.findById(Q);if(!G)throw Error("Gateway not found after setting default");return G}deserializeGatewayWithConnections(Q,X){return{...this.deserializeGateway(Q),connections:X.map((J)=>({connectionId:J.connection_id,selectedTools:this.parseJson(J.selected_tools),selectedResources:this.parseJson(J.selected_resources),selectedPrompts:this.parseJson(J.selected_prompts)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}By();G1();function aR6(Q){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (r40(),_X1));return X.map((Y)=>{return{name:Y.name,inputSchema:N.toJSONSchema(Y.inputSchema,{unrepresentable:"any"}),outputSchema:Y.outputSchema?N.toJSONSchema(Y.outputSchema,{unrepresentable:"any"}):void 0,description:Y.description}})},data:Nt0(process.env.BASE_URL||"http://localhost:3000")},{data:Dt0()},{data:Bt0(Q)}]}async function yX1(Q,X){try{let Y=Mk(),J=new uw(process.env.ENCRYPTION_KEY||""),G=new lw(Y.db,J),W=new dw(Y.db),Z=aR6(Q),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await h7.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:X,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let F=await K.getTools?.()??await IU({id:"pending",title:K.data.title,connection_type:K.data.connection_type,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),V=K.data.id?K.data.id.startsWith(`${Q}_`)?K.data.id:`${Q}_${K.data.id}`:void 0,q=await G.create({...K.data,id:V,tools:F,organization_id:Q,created_by:X,connection_token:K.data.connection_token??H});$.push(q.id)})),await W.create(Q,X,{title:"Organization Agent",description:"Use all organization connections into a single agent",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:$.map((K)=>({connectionId:K}))})}catch(Y){console.error("Error creating default MCP connections:",Y)}}var o40=["owner","admin","user"],bX1=["owner","admin"];var rR6=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},fX1=(Q)=>{if(Q.providerId==="microsoft")return rR6(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function oR6(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var hX1=["labs","agent","studio","workspace","systems","core","cloud","works"],xX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function sR6(){let Q=Math.floor(Math.random()*xX1.length),X=Math.floor(Math.random()*hX1.length),Y=xX1[Q]??"deco",J=hX1[X]??"studio";return`${Y}-${J}`}var tR6=Object.values(cD()).map((Q)=>Q.map((X)=>X.name)).flat(),eR6={...rv,self:["*",...tR6]},Iy=nG(eR6),QS6=Iy.newRole({self:["*"],...ww.statements}),XS6=Iy.newRole({self:["*"],...ww.statements}),YS6=Iy.newRole({self:["*"],...ww.statements}),gX1=Object.values(cD()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),a8=Iw.auth,uX1=void 0;if(a8.inviteEmailProviderId&&a8.emailProviders&&a8.emailProviders.length>0){let Q=Tk(a8.emailProviders,a8.inviteEmailProviderId);if(Q){let X=Pk(Q);uX1=async(Y)=>{let J=Y.inviter.user?.name||Y.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${Y.invitation.id}`;await X({to:Y.email,subject:`Invitation to join ${Y.organization.name}`,html:`
|
|
1035
|
+
</html>`},Ye=(Q)=>{let X=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:f0("/open-api/generate-schema",{method:"GET"},async(Y)=>{let J=await Cr0(Y.context,Y.context.options);return Y.json(J)}),openAPIReference:f0(X,{method:"GET",metadata:{isAction:!1}},async(Y)=>{if(Q?.disableDefaultReference)throw new n("NOT_FOUND");let J=await Cr0(Y.context,Y.context.options);return new Response(nq6(J,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};FX();kG();d8();hQ();G1();var Ow4=a6(async()=>{return{}}),Lw4=a6({use:[X8]},async(Q)=>{return{session:Q.context.session}}),ww4=T4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var Mw4=Number.POSITIVE_INFINITY;var Rr0=P(),aq6=F1(["pending","accepted","rejected","canceled"]).default("pending"),Pw4=d({id:P().default(QQ),name:P(),slug:P(),logo:P().nullish().optional(),metadata:c0(P(),G4()).or(P().transform((Q)=>JSON.parse(Q))).optional(),createdAt:n1()}),Tw4=d({id:P().default(QQ),organizationId:P(),userId:v1.string(),role:Rr0,createdAt:n1().default(()=>new Date)}),Aw4=d({id:P().default(QQ),organizationId:P(),email:P(),role:Rr0,status:aq6,teamId:P().nullish(),inviterId:P(),expiresAt:n1(),createdAt:n1().default(()=>new Date)}),Ew4=d({id:P().default(QQ),name:P().min(1),organizationId:P(),createdAt:n1(),updatedAt:n1().optional()}),jw4=d({id:P().default(QQ),teamId:P(),userId:P(),createdAt:n1().default(()=>new Date)}),Cw4=d({id:P().default(QQ),organizationId:P(),role:P(),permission:c0(P(),M0(P())),createdAt:n1().default(()=>new Date),updatedAt:n1().optional()}),Ir0=["admin","member","owner"],Iw4=o1([F1(Ir0),M0(F1(Ir0))]);q8();d8();hQ();var xw4=T4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});q8();VX();d8();hQ();vQ();c4();var rq6=T4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});d8();hQ();var oq6=T4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var v3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as Sr0,readFileSync as vr0}from"fs";var Hk={emailAndPassword:{enabled:!0}},kr0=process.env.CONFIG_PATH||"./config.json",_r0=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function sq6(){if(Sr0(kr0))try{let Q=vr0(kr0,"utf-8"),X=JSON.parse(Q);return{auth:Hk,monitoring:v3,...X}}catch{return{auth:Hk,monitoring:v3}}if(Sr0(_r0))try{let Q=vr0(_r0,"utf-8");return{auth:JSON.parse(Q),monitoring:v3}}catch{return{auth:Hk,monitoring:v3}}return{auth:Hk,monitoring:v3}}var Iw=sq6();function yr0(){return{...v3,...Iw.monitoring}}function br0(){return Iw.theme}import{existsSync as lD6,mkdirSync as dD6}from"fs";import{Kysely as Yt0,PostgresDialect as Jt0,sql as Xt0}from"kysely";import{BunWorkerDialect as Gt0}from"kysely-bun-worker";import*as Wt0 from"path";var SJ=m6(_e(),1),bT4=SJ.default.Client,he=SJ.default.Pool,fT4=SJ.default.Connection,hT4=SJ.default.types,xT4=SJ.default.Query,gT4=SJ.default.DatabaseError,uT4=SJ.default.escapeIdentifier,mT4=SJ.default.escapeLiteral,lT4=SJ.default.Result,dT4=SJ.default.TypeOverrides,pT4=SJ.default.defaults;var pD6=cE.createHistogram("db.query.duration",{description:"Database query execution duration in milliseconds",unit:"ms"}),cD6=400,Zt0=(Q)=>{let X={"db.statement":Q.query.sql,"db.status":Q.level==="error"?"error":"success"};if(Q.queryDurationMillis>cD6)console.error("Slow query detected:",{durationMs:Q.queryDurationMillis,sql:Q.query.sql,params:Q.query.parameters});if(pD6.record(Q.queryDurationMillis,X),Q.level==="error")console.error("Query failed:",{durationMs:Q.queryDurationMillis,error:Q.error,sql:Q.query.sql})},$t0={keepAlive:!0,keepAliveInitialDelayMillis:1e4,idleTimeoutMillis:300000,connectionTimeoutMillis:30000,allowExitOnIdle:!0};function nD6(Q){let X=new he({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...$t0}),Y=new Jt0({pool:X});return{type:"postgres",db:new Yt0({dialect:Y,log:Zt0}),pool:X}}function Kt0(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function Ht0(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let X=Q.substring(0,Q.lastIndexOf("/"));if(X&&X!=="/"&&!lD6(X))try{dD6(X,{recursive:!0})}catch{return console.warn(`Failed to create directory ${X}, using in-memory database`),":memory:"}}return Q}function iD6(Q){let X=Kt0(Q.connectionString);X=Ht0(X);let Y=new Gt0({url:X||":memory:"}),J=new Yt0({dialect:Y,log:Zt0});if(X!==":memory:"&&Q.options?.enableWAL!==!1)Xt0`PRAGMA journal_mode = WAL;`.execute(J).catch(()=>{});if(X!==":memory:"){let G=Q.options?.busyTimeout||5000;Xt0`PRAGMA busy_timeout = ${G};`.execute(J).catch(()=>{})}return{type:"sqlite",db:J}}function Ft0(Q){let X=Q||"file:./data/mesh.db";if(X===":memory:")return{type:"sqlite",connectionString:":memory:"};X=X.startsWith("/")?`file://${X}`:X;let Y=URL.canParse(X)?new URL(X):null,J=Y?.protocol.replace(":","")??X.split("://")[0];switch(J){case"postgres":case"postgresql":return{type:"postgres",connectionString:X};case"sqlite":case"file":if(!Y?.pathname)throw Error("Invalid database URL: "+X);return{type:"sqlite",connectionString:Y.pathname};default:throw Error(`Unsupported database protocol: ${J}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function ge(){return process.env.DATABASE_URL||`file:${Wt0.join(process.cwd(),"data/mesh.db")}`}function Vt0(Q){let X=Ft0(Q);if(X.type==="postgres")return new Jt0({pool:new he({connectionString:X.connectionString,max:X.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1,...$t0})});let Y=Kt0(X.connectionString);return Y=Ht0(Y),new Gt0({url:Y||":memory:"})}function aD6(Q){let X=Ft0(Q);if(X.type==="postgres")return nD6(X);return iD6(X)}var xe=null;function Mk(){if(!xe)xe=aD6(ge());return xe}class ue{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:X,subject:Y,html:J})});if(!G.ok)throw Error(`Failed to send email: ${G.statusText}`)}}class me{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:X,subject:Y,html:J}){let G=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:X},subject:Y,content:[{type:"text/html",value:J}]})});if(!G.ok){let W=await G.text();throw Error(`Failed to send email via SendGrid: ${G.statusText} - ${W}`)}}}var rD6=(Q)=>{let X=new ue(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},oD6=(Q)=>{let X=new me(Q.config.apiKey);return async({to:Y,subject:J,html:G})=>{await X.sendEmail({to:Y,from:Q.config.fromEmail,subject:J,html:G})}},sD6={resend:rD6,sendgrid:oD6};function Pk(Q){let X=sD6[Q.provider];if(!X)throw Error(`Unknown email provider: ${Q.provider}`);return X(Q)}function Tk(Q,X){return Q.find((Y)=>Y.id===X)}var qt0=(Q,X)=>{let Y=Tk(X,Q.emailProviderId);if(!Y)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let J=Pk(Y);return{sendMagicLink:async({email:G,url:W})=>{await J({to:G,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};y3();import{createCipheriv as tD6,createDecipheriv as eD6,randomBytes as Ot0}from"crypto";var Lt0="aes-256-gcm",gw=16,wt0=16,Mt0=32;class uw{key;constructor(Q){if(Buffer.from(Q,"base64").length===Mt0)this.key=Buffer.from(Q,"base64");else{let X=U0("crypto");this.key=X.createHash("sha256").update(Q).digest()}}async encrypt(Q){let X=Ot0(gw),Y=tD6(Lt0,this.key,X),J=Y.update(Q,"utf8");J=Buffer.concat([J,Y.final()]);let G=Y.getAuthTag();return Buffer.concat([X,G,J]).toString("base64")}async decrypt(Q){let X=Buffer.from(Q,"base64"),Y=X.subarray(0,gw),J=X.subarray(gw,gw+wt0),G=X.subarray(gw+wt0),W=eD6(Lt0,this.key,Y);W.setAuthTag(J);let Z=W.update(G);return Z=Buffer.concat([Z,W.final()]),Z.toString("utf8")}static generateKey(){return Ot0(Mt0).toString("base64")}}O7();mw();var ZN6=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class lw{db;vault;constructor(Q,X){this.db=Q;this.vault=X}async create(Q){let X=Q.id??kJ("conn"),Y=new Date().toISOString(),J=await this.findById(X);if(J){if(J.organization_id!==Q.organization_id)throw Error("Connection ID already exists");return this.update(X,Q)}let G=await this.serializeConnection({...Q,id:Q.id??X,status:"active",created_at:Y,updated_at:Y});await this.db.insertInto("connections").values(G).execute();let W=await this.findById(X);if(!W)throw Error(`Failed to create connection with id: ${X}`);return W}async findById(Q,X){let Y=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(X)Y=Y.where("organization_id","=",X);let J=await Y.executeTakeFirst();return J?this.deserializeConnection(J):null}async list(Q){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(X.map((Y)=>this.deserializeConnection(Y)))}async update(Q,X){if(Object.keys(X).length===0){let G=await this.findById(Q);if(!G)throw Error("Connection not found");return G}let Y=await this.serializeConnection({...X,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(Y).where("id","=",Q).execute();let J=await this.findById(Q);if(!J)throw Error("Connection not found after update");return J}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,X){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");let J=Date.now();if(Y.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-J};if(!Y.connection_url)return{healthy:!1,latencyMs:Date.now()-J};try{let G=Y.connection_headers,W=await fetch(Y.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...Y.connection_token&&{Authorization:`Bearer ${Y.connection_token}`},...G?.headers,...X},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-J}}catch{return{healthy:!1,latencyMs:Date.now()-J}}}async serializeConnection(Q){let X={};for(let[Y,J]of Object.entries(Q)){if(J===void 0)continue;if(Y==="connection_token"&&J)X[Y]=await this.vault.encrypt(J);else if(Y==="configuration_state"&&J){let G=JSON.stringify(J);X[Y]=await this.vault.encrypt(G)}else if(Y==="connection_headers"&&J){let G=J;if(b3(G)&&G.envVars){let W={};for(let[Z,$]of Object.entries(G.envVars))W[Z]=await this.vault.encrypt($);X[Y]=JSON.stringify({...G,envVars:W})}else X[Y]=JSON.stringify(G)}else if(ZN6.includes(Y))X[Y]=J?JSON.stringify(J):null;else X[Y]=J}return X}async deserializeConnection(Q){let X=null;if(Q.connection_token)try{X=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let Y=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);Y=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let J=null;if(Q.connection_headers)try{let W=JSON.parse(Q.connection_headers);if(b3(W)&&W.envVars){let Z={};for(let[$,K]of Object.entries(W.envVars))try{Z[$]=await this.vault.decrypt(K)}catch{Z[$]=K}J={...W,envVars:Z}}else J=W}catch(W){console.error("Failed to parse connection_headers:",W)}let G=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:X,connection_headers:J,oauth_config:G(Q.oauth_config),configuration_state:Y,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}mw();class dw{db;constructor(Q){this.db=Q}async create(Q,X,Y){let J=kJ("gw"),G=new Date().toISOString();if(Y.isDefault)return await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:X}).where("organization_id","=",Q).where("is_default","=",1).execute(),await Z.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:1,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await Z.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:kJ("gwc"),gateway_id:J,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:G}))).execute();let $=await this.findByIdInternal(Z,J);if(!$)throw Error(`Failed to create gateway with id: ${J}`);return $});if(await this.db.insertInto("gateways").values({id:J,organization_id:Q,title:Y.title,description:Y.description??null,tool_selection_mode:Y.toolSelectionMode??"inclusion",icon:Y.icon??null,status:Y.status??"active",is_default:0,created_at:G,updated_at:G,created_by:X,updated_by:null}).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:kJ("gwc"),gateway_id:J,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create gateway with id: ${J}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,X){let Y=await Q.selectFrom("gateways").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;let J=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X).execute();return this.deserializeGatewayWithConnections(Y,J)}async list(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),Y=X.map((W)=>W.id);if(Y.length===0)return[];let J=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",Y).execute(),G=new Map;for(let W of J){let Z=G.get(W.gateway_id)??[];Z.push(W),G.set(W.gateway_id,Z)}return X.map((W)=>this.deserializeGatewayWithConnections(W,G.get(W.id)??[]))}async listByConnectionId(Q,X){let J=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",X).execute()).map((K)=>K.gateway_id);if(J.length===0)return[];let G=await this.db.selectFrom("gateways").selectAll().where("id","in",J).where("organization_id","=",Q).execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.gateway_id)??[];H.push(K),$.set(K.gateway_id,H)}return G.map((K)=>this.deserializeGatewayWithConnections(K,$.get(K.id)??[]))}async update(Q,X,Y){let J=new Date().toISOString(),G={updated_at:J,updated_by:X};if(Y.title!==void 0)G.title=Y.title;if(Y.description!==void 0)G.description=Y.description;if(Y.toolSelectionMode!==void 0)G.tool_selection_mode=Y.toolSelectionMode;if(Y.icon!==void 0)G.icon=Y.icon;if(Y.status!==void 0)G.status=Y.status;if(Y.isDefault===!1)G.is_default=0;if(Y.isDefault===!0)G.is_default=1;if(Y.isDefault===!0){let Z=await this.findById(Q);if(!Z)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Z.organizationId).where("is_default","=",1).execute(),await $.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await $.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await $.insertInto("gateway_connections").values(Y.connections.map((K)=>({id:kJ("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,selected_resources:K.selectedResources?JSON.stringify(K.selectedResources):null,selected_prompts:K.selectedPrompts?JSON.stringify(K.selectedPrompts):null,created_at:J}))).execute()}})}else if(await this.db.updateTable("gateways").set(G).where("id","=",Q).execute(),Y.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),Y.connections.length>0)await this.db.insertInto("gateway_connections").values(Y.connections.map((Z)=>({id:kJ("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,selected_resources:Z.selectedResources?JSON.stringify(Z.selectedResources):null,selected_prompts:Z.selectedPrompts?JSON.stringify(Z.selectedPrompts):null,created_at:J}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let X=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!X)return null;let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",X.id).execute();return this.deserializeGatewayWithConnections(X,Y)}async getDefaultByOrgSlug(Q){let X=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!X)return null;return this.getDefaultByOrgId(X.id)}async setDefault(Q,X){let Y=await this.findById(Q);if(!Y)throw Error(`Gateway not found: ${Q}`);let J=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:J,updated_by:X}).where("organization_id","=",Y.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:J,updated_by:X}).where("id","=",Q).execute()});let G=await this.findById(Q);if(!G)throw Error("Gateway not found after setting default");return G}deserializeGatewayWithConnections(Q,X){return{...this.deserializeGateway(Q),connections:X.map((J)=>({connectionId:J.connection_id,selectedTools:this.parseJson(J.selected_tools),selectedResources:this.parseJson(J.selected_resources),selectedPrompts:this.parseJson(J.selected_prompts)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}By();G1();function aR6(Q){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (a40(),_X1));return X.map((Y)=>{return{name:Y.name,inputSchema:N.toJSONSchema(Y.inputSchema,{unrepresentable:"any"}),outputSchema:Y.outputSchema?N.toJSONSchema(Y.outputSchema,{unrepresentable:"any"}):void 0,description:Y.description}})},data:Nt0(process.env.BASE_URL||"http://localhost:3000")},{data:Dt0()},{data:Bt0(Q)}]}async function yX1(Q,X){try{let Y=Mk(),J=new uw(process.env.ENCRYPTION_KEY||""),G=new lw(Y.db,J),W=new dw(Y.db),Z=aR6(Q),$=[];await Promise.all(Z.map(async(K)=>{let H=null;if(K.permissions)H=(await h7.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:X,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let F=await K.getTools?.()??await IU({id:"pending",title:K.data.title,connection_type:K.data.connection_type,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),V=K.data.id?K.data.id.startsWith(`${Q}_`)?K.data.id:`${Q}_${K.data.id}`:void 0,q=await G.create({...K.data,id:V,tools:F,organization_id:Q,created_by:X,connection_token:K.data.connection_token??H});$.push(q.id)})),await W.create(Q,X,{title:"Organization Agent",description:"Use all organization connections into a single agent",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:$.map((K)=>({connectionId:K}))})}catch(Y){console.error("Error creating default MCP connections:",Y)}}var r40=["owner","admin","user"],bX1=["owner","admin"];var rR6=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},fX1=(Q)=>{if(Q.providerId==="microsoft")return rR6(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function oR6(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var hX1=["labs","agent","studio","workspace","systems","core","cloud","works"],xX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function sR6(){let Q=Math.floor(Math.random()*xX1.length),X=Math.floor(Math.random()*hX1.length),Y=xX1[Q]??"deco",J=hX1[X]??"studio";return`${Y}-${J}`}var tR6=Object.values(cD()).map((Q)=>Q.map((X)=>X.name)).flat(),eR6={...rv,self:["*",...tR6]},Iy=nG(eR6),QS6=Iy.newRole({self:["*"],...ww.statements}),XS6=Iy.newRole({self:["*"],...ww.statements}),YS6=Iy.newRole({self:["*"],...ww.statements}),gX1=Object.values(cD()).map((Q)=>Q.map((X)=>`self:${X.name}`)).flat(),a8=Iw.auth,uX1=void 0;if(a8.inviteEmailProviderId&&a8.emailProviders&&a8.emailProviders.length>0){let Q=Tk(a8.emailProviders,a8.inviteEmailProviderId);if(Q){let X=Pk(Q);uX1=async(Y)=>{let J=Y.inviter.user?.name||Y.inviter.user?.email,G=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${Y.invitation.id}`;await X({to:Y.email,subject:`Invitation to join ${Y.organization.name}`,html:`
|
|
1036
1036
|
<h2>You've been invited!</h2>
|
|
1037
1037
|
<p>${J} has invited you to join <strong>${Y.organization.name}</strong>.</p>
|
|
1038
1038
|
<p><a href="${G}">Click here to accept the invitation</a></p>
|
|
1039
|
-
`})}}}var JS6=[ht({organizationCreation:{afterCreate:async(Q)=>{await yX1(Q.organization.id,Q.member.userId)}},ac:Iy,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:bX1,resourceNameValidation:(Q)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Q)}}},roles:{user:QS6,admin:XS6,owner:YS6},sendInvitationEmail:uX1}),tt({loginPage:"/login",oidcConfig:{scopes:gX1,metadata:{scopes_supported:gX1},loginPage:"/login"}}),st({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Q)=>{if(Q.headers?.get("X-MCP-Session-Auth")==="true")return null;let Y=Q.headers?.get("Authorization");if(Y?.startsWith("Bearer "))return Y.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),ut({defaultRole:"user",adminRoles:["admin","owner"]}),Ye(),dt({jwt:{expirationTime:"5m"}}),ai0(a8.ssoConfig?fX1(a8.ssoConfig):void 0),...a8.magicLinkConfig&&a8.emailProviders&&a8.emailProviders.length>0?[Xe(qt0(a8.magicLinkConfig,a8.emailProviders))]:[]],GS6=ge(),WS6=Vt0(GS6),h7=as({baseURL:process.env.BASE_URL||"http://localhost:3000",database:WS6,emailAndPassword:{enabled:!0},...a8,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:JS6,databaseHooks:{user:{create:{after:async(Q)=>{if(Iw.autoCreateOrganizationOnSignup===!1)return;let X=Q.name?Q.name.split(" ")[0]:Q.email.split("@")[0],Y=3;for(let J=0;J<Y;J++){let G=`${X} ${sR6()}`,W=oR6(G);try{await h7.api.createOrganization({body:{name:G,slug:W,userId:Q.id}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Y-1){console.error("Failed to create default organization:",Z);return}}}}}}}});PY();import{randomBytes as ZS6}from"crypto";var UP=null;function mX1(){if(UP)return UP;let Q=process.env.MESH_JWT_SECRET??a8.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Q)UP=new TextEncoder().encode(Q);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),UP=new Uint8Array(ZS6(32));return UP}async function lX1(Q,X="5m"){let Y=mX1();return await new gX(Q).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(X).sign(Y)}async function dX1(Q){try{let X=mX1(),{payload:Y}=await W8(Q,X);return Y}catch{return}}import{sql as Ry}from"kysely";class s40{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(Q){return xD.startActiveSpan("redactor.redact",(X)=>{try{if(Q===null||Q===void 0)return Q;if(typeof Q==="string")return X.setAttribute("data.type","string"),this.redactString(Q);if(Array.isArray(Q))return X.setAttribute("data.type","array"),X.setAttribute("data.length",Q.length),Q.map((Y)=>this.redact(Y));if(typeof Q==="object"){X.setAttribute("data.type","object");let Y={};for(let[J,G]of Object.entries(Q)){let W=this.redactString(J);Y[W]=this.redact(G)}return Y}return X.setAttribute("data.type",typeof Q),Q}finally{X.end()}})}redactString(Q){return xD.startActiveSpan("redactor.redactString",(X)=>{try{X.setAttribute("text.length",Q.length);let Y=Q,J=0;for(let G of this.patterns){let W=Q.match(G.regex);if(W)J+=W.length,X.setAttribute(`redaction.${G.type}.count`,W.length);Y=Y.replace(G.regex,`[REDACTED:${G.type}]`)}return X.setAttribute("redaction.total_count",J),Y}finally{X.end()}})}}mw();class t40{db;redactor;databaseType;constructor(Q,X="sqlite"){this.db=Q;this.redactor=new s40,this.databaseType=X}jsonExtract(Q,X){if(this.databaseType==="postgres")return Ry`(${Ry.ref(Q)}::jsonb)->>${X}`;let Y=`$.${X}`;return Ry`json_extract(${Ry.ref(Q)}, ${Y})`}async log(Q){await this.logBatch([Q])}async logBatch(Q){if(Q.length===0)return;let X=Q.map((Y)=>({...Y,input:this.redactor.redact(Y.input),output:this.redactor.redact(Y.output)}));await this.db.transaction().execute(async(Y)=>{await Y.insertInto("monitoring_logs").values(X.map((J)=>this.toDbRow(J))).execute()})}async query(Q){let X=this.db.selectFrom("monitoring_logs").selectAll(),Y=this.db.selectFrom("monitoring_logs").select(($)=>$.fn.count("id").as("count"));if(Q.organizationId)X=X.where("organization_id","=",Q.organizationId),Y=Y.where("organization_id","=",Q.organizationId);if(Q.connectionId)X=X.where("connection_id","=",Q.connectionId),Y=Y.where("connection_id","=",Q.connectionId);if(Q.gatewayId)X=X.where("gateway_id","=",Q.gatewayId),Y=Y.where("gateway_id","=",Q.gatewayId);if(Q.toolName)X=X.where("tool_name","=",Q.toolName),Y=Y.where("tool_name","=",Q.toolName);if(Q.isError!==void 0)X=X.where("is_error","=",Q.isError?1:0),Y=Y.where("is_error","=",Q.isError?1:0);if(Q.startDate)X=X.where("timestamp",">=",Q.startDate.toISOString()),Y=Y.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)X=X.where("timestamp","<=",Q.endDate.toISOString()),Y=Y.where("timestamp","<=",Q.endDate.toISOString());if(Q.propertyFilters){let{properties:$,propertyKeys:K,propertyPatterns:H}=Q.propertyFilters;if($)for(let[F,V]of Object.entries($)){let q=this.jsonExtract("properties",F);X=X.where(q,"=",V),Y=Y.where(q,"=",V)}if(K&&K.length>0)for(let F of K){let V=this.jsonExtract("properties",F);X=X.where(V,"is not",null),Y=Y.where(V,"is not",null)}if(H)for(let[F,V]of Object.entries(H)){let q=this.jsonExtract("properties",F),z=this.databaseType==="postgres"?"ilike":"like";X=X.where(q,z,V),Y=Y.where(q,z,V)}}if(X=X.orderBy("timestamp","desc"),Q.limit)X=X.limit(Q.limit);if(Q.offset)X=X.offset(Q.offset);let[J,G]=await Promise.all([X.execute(),Y.executeTakeFirst()]),W=Number(G?.count||0);return{logs:J.map(($)=>this.fromDbRow($)),total:W}}async getStats(Q){let X=this.db.selectFrom("monitoring_logs").where("organization_id","=",Q.organizationId);if(Q.startDate)X=X.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)X=X.where("timestamp","<=",Q.endDate.toISOString());let Y=await X.select([(Z)=>Z.fn.count("id").as("total_count"),(Z)=>Z.fn.sum(Z.ref("is_error")).as("error_count"),(Z)=>Z.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Y?.total_count||0),G=Number(Y?.error_count||0),W=Number(Y?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:W}}toDbRow(Q){return{id:Q.id||kJ("log"),organization_id:Q.organizationId,connection_id:Q.connectionId,connection_title:Q.connectionTitle,tool_name:Q.toolName,input:JSON.stringify(Q.input),output:JSON.stringify(Q.output),is_error:Q.isError?1:0,error_message:Q.errorMessage||null,duration_ms:Q.durationMs,timestamp:Q.timestamp instanceof Date?Q.timestamp.toISOString():Q.timestamp,user_id:Q.userId||null,request_id:Q.requestId,user_agent:Q.userAgent||null,gateway_id:Q.gatewayId||null,properties:Q.properties?JSON.stringify(Q.properties):null}}fromDbRow(Q){let X=typeof Q.input==="string"?JSON.parse(Q.input):Q.input,Y=typeof Q.output==="string"?JSON.parse(Q.output):Q.output,J=typeof Q.timestamp==="string"?new Date(Q.timestamp):Q.timestamp,G=Q.properties?typeof Q.properties==="string"?JSON.parse(Q.properties):Q.properties:null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,connectionTitle:Q.connection_title,toolName:Q.tool_name,input:X,output:Y,isError:Q.is_error===1,errorMessage:Q.error_message,durationMs:Q.duration_ms,timestamp:J,userId:Q.user_id,requestId:Q.request_id,userAgent:Q.user_agent,gatewayId:Q.gateway_id,properties:G}}}class e40{db;constructor(Q){this.db=Q}async get(Q){let X=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Q).executeTakeFirst();if(!X)return null;return{organizationId:X.organizationId,sidebar_items:X.sidebar_items?typeof X.sidebar_items==="string"?JSON.parse(X.sidebar_items):X.sidebar_items:null,createdAt:X.createdAt,updatedAt:X.updatedAt}}async upsert(Q,X){let Y=new Date().toISOString(),J=X?.sidebar_items?JSON.stringify(X.sidebar_items):null;await this.db.insertInto("organization_settings").values({organizationId:Q,sidebar_items:J,createdAt:Y,updatedAt:Y}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,updatedAt:Y})).execute();let G=await this.get(Q);if(!G)return{organizationId:Q,sidebar_items:X?.sidebar_items??null,createdAt:Y,updatedAt:Y};return G}}class Q80{db;constructor(Q){this.db=Q}async findById(Q,X){let Y=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",Q).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",Q).where("m2.userId","=",X))).executeTakeFirst();if(!Y)return null;return{id:Y.id,name:Y.name,email:Y.email,role:"",createdAt:Y.createdAt,updatedAt:Y.updatedAt,image:Y.image??void 0}}}y3();class pX1 extends Error{constructor(Q){super(Q);this.name="UnauthorizedError"}}class X80 extends Error{constructor(Q){super(Q);this.name="ForbiddenError"}}class yU{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(Q,X,Y,J,G,W=w5.SELF){this.userId=X;this.toolName=Y;this.boundAuth=J;this.role=G;this.connectionId=W}[Symbol.dispose](){this._granted=!1}setToolName(Q){this.toolName=Q}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Q){if(this._granted)return;if(!this.userId&&!this.boundAuth)throw new pX1("Authentication required. Please provide a valid OAuth token or API key.");let X=Q.length>0?Q:this.toolName?[this.toolName]:[];if(X.length===0)throw new X80("No resources specified for access check");for(let Y of X)if(await this.checkResource(Y)){this.grant();return}throw new X80(`Access denied to: ${X.join(", ")}`)}async checkResource(Q){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let X={};if(this.connectionId)X[this.connectionId]=[Q];return this.boundAuth.hasPermission(X)}granted(){return this._granted}}U40();function cX1(Q){let X=null;return()=>{if(X)return X;return X=Q().catch((Y)=>{throw X=null,Y}),X}}class nX1{factory;promise=null;constructor(Q){this.factory=Q}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Q,X){return this.getOrCreatePromise().then(Q,X)}catch(Q){return this.getOrCreatePromise().catch(Q)}finally(Q){return this.getOrCreatePromise().finally(Q)}}function GW(Q){return new nX1(Q)}async function iX1(Q){if(!Q.refreshToken)return{success:!1,error:"No refresh token available"};if(!Q.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Q.clientId)return{success:!1,error:"No client ID available"};try{let X=new URLSearchParams({grant_type:"refresh_token",refresh_token:Q.refreshToken,client_id:Q.clientId});if(Q.clientSecret)X.set("client_secret",Q.clientSecret);if(Q.scope)X.set("scope",Q.scope);let Y=await fetch(Q.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:X.toString()});if(!Y.ok){let G=await Y.text();console.error(`[TokenRefresh] Failed to refresh token: ${Y.status}`,G);try{let W=JSON.parse(G);return{success:!1,error:W.error_description||W.error||`Token refresh failed: ${Y.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Y.status}`}}}let J=await Y.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Q.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(X){return console.error("[TokenRefresh] Error refreshing token:",X),{success:!1,error:X instanceof Error?X.message:"Token refresh failed"}}}zU();m60();function $S6(Q){return new Proxy(Q,{get(Y,J,G){if(J==="close")return async()=>{};if(J==="__actualClient")return Y;return Reflect.get(Y,J,G)}})}var aX1="__mesh_stable_stdio_pool__",e3=globalThis[aX1]??(globalThis[aX1]=new Map);async function oX1(Q){let X=e3.get(Q.id);if(X?.status==="connected"&&X.stableClient)return X.stableClient;if(X?.connectPromise&&(X.status==="connecting"||X.status==="reconnecting"))return X.connectPromise;let Y=X?.status==="failed",J=X??{transport:null,client:null,stableClient:null,config:Q,status:"connecting",connectPromise:null};if(!X)e3.set(Q.id,J);return J.status=Y?"reconnecting":"connecting",J.connectPromise=(async()=>{try{console.log(`[StableStdio] ${Y?"Respawning":"Spawning"}: ${Q.id} (${Q.command} ${Q.args?.join(" ")??""})`);let G=new cM({command:Q.command,args:Q.args,env:Q.env,cwd:Q.cwd,stderr:"pipe"});J.transport=G;let W=new QY({name:`mesh-stdio-${Q.id}`,version:"1.0.0"});J.client=W,J.stableClient=$S6(W),W.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${Q.id}`),J.status="failed",J.connectPromise=null};let Z=Q.name||Q.id,$="\x1B[2m",K="\x1B[0m";G.stderr?.on("data",(V)=>{let q=V.toString().trimEnd();if(q)console.error(`${q} ${$}[${Z}]${K}`)});let H=new AbortController,F=setTimeout(()=>H.abort(),30000);try{await Promise.race([W.connect(G),new Promise((V,q)=>{H.signal.addEventListener("abort",()=>{q(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(F)}return J.status="connected",console.log(`[StableStdio] Connected: ${Q.id}`),J.stableClient}catch(G){console.error(`[StableStdio] Failed to connect ${Q.id}:`,G),J.status="failed",J.connectPromise=null;try{await J.transport?.close()}catch{}throw G}})(),J.connectPromise}async function KS6(Q){let X=e3.get(Q);if(!X)return;console.log(`[StableStdio] Force closing: ${Q}`);try{if(X.client)X.client.onclose=void 0;await X.client?.close()}catch{}e3.delete(Q)}async function HS6(){console.log(`[StableStdio] Closing all connections (${e3.size})`);let Q=Array.from(e3.keys()).map((X)=>KS6(X));await Promise.allSettled(Q),e3.clear()}var rX1="__mesh_stable_stdio_shutdown_registered__";if(!globalThis[rX1]){globalThis[rX1]=!0;let Q=async(X)=>{await HS6(),process.exit(X==="SIGINT"?130:143)};process.on("SIGINT",()=>Q("SIGINT")),process.on("SIGTERM",()=>Q("SIGTERM"))}jy();O7();zU();qy();iM();Dy();Ny();h9();var Sy=new ZQ,Y80=[404,401,406];async function sX1(Q,X){return(await X.storage.connections.findById(Q))?.connection_url??null}function FS6(Q){let X=Q.toLowerCase();return X.includes("resource_metadata=")||X.includes("invalid_token")||X.includes("oauth")}async function tX1(Q,X={}){try{let Y=await fetch(Q,{method:"POST",headers:{...X,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Y.status===401){let J=Y.headers.get("WWW-Authenticate");if(J){if(FS6(J))return J}}return null}catch{return null}}async function vy(Q){let Y=new URL(Q).pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);let J=new URL(Q);J.pathname=`${Y}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!Y80.includes(G.status))return G;let W=new URL(Q);if(W.pathname=`/.well-known/oauth-protected-resource${Y}`,G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),!Y80.includes(G.status))return G;let Z=new URL(Q);return Z.pathname="/.well-known/oauth-protected-resource",G=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function VS6(Q,X){let Y=await sX1(Q,X);if(!Y)return null;let J;try{J=new URL(Y).origin}catch{return null}try{let G=await vy(Y);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function eX1(Q){let X=Q.get("meshContext");if(!X)X=await o$.create(Q.req.raw),Q.set("meshContext",X);return X}async function QY1({error:Q,reqUrl:X,connectionId:Y,connectionUrl:J,headers:G}){let W=Q.message?.toLowerCase()??"";if(!(Q.status===401||Q.code===401||Q.message?.includes("401")||W.includes("unauthorized")||W.includes("invalid_token")||W.includes("api key required")||W.includes("api-key required")))return null;if(Boolean(await tX1(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${X.origin}/mcp/${Y}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}var ky=(Q)=>{if(!(Q.hostname==="localhost"||Q.hostname==="127.0.0.1"))Q.protocol="https:";return Q},XY1=async(Q)=>{let X=Q.req.param("connectionId"),Y=await eX1(Q),J=await sX1(X,Y);if(!J)return Q.json({error:"Connection not found"},404);let G=ky(new URL(Q.req.url)),W=`${G.origin}/mcp/${X}`,Z=`${G.origin}/oauth-proxy/${X}`;try{let $=await vy(J);if(!$.ok&&Y80.includes($.status)){if(await tX1(J))return new Response(JSON.stringify({resource:W,authorization_servers:[Z],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}if(!$.ok)return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}});let H={...await $.json(),resource:W,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}catch($){let K=$;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",K),Q.json({error:"Failed to proxy OAuth metadata",message:K.message},502)}};Sy.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Q)=>XY1(Q));Sy.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Q)=>XY1(Q));async function J80(Q){let Y=new URL(Q).pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);let J=Y!==""&&Y!=="/",G=[];if(J){let Z=new URL(Q);Z.pathname=`/.well-known/oauth-authorization-server${Y}`,G.push(Z);let $=new URL(Q);$.pathname=`/.well-known/openid-configuration${Y}`,G.push($);let K=new URL(Q);K.pathname=`${Y}/.well-known/openid-configuration`,G.push(K)}else{let Z=new URL(Q);Z.pathname="/.well-known/oauth-authorization-server",G.push(Z);let $=new URL(Q);$.pathname="/.well-known/openid-configuration",G.push($)}let W=null;for(let Z of G){if(W=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}Sy.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Q)=>{let X=Q.req.param("connectionId"),Y=await eX1(Q),J=await VS6(X,Y);if(!J)return Q.json({error:"Connection not found or no auth server"},404);try{let G=await J80(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let W=await G.json(),$=`${ky(new URL(Q.req.url)).origin}/oauth-proxy/${X}`,K={...W,authorization_endpoint:W.authorization_endpoint?`${$}/authorize`:void 0,token_endpoint:W.token_endpoint?`${$}/token`:void 0,registration_endpoint:W.registration_endpoint?`${$}/register`:void 0};return new Response(JSON.stringify(K),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let W=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",W),Q.json({error:"Failed to proxy auth server metadata",message:W.message},502)}});var YY1=Sy;function qS6(Q){if(!Q.isError)return;let X=Q.content;if(!Array.isArray(X))return;for(let Y of X)if(Y&&typeof Y==="object"&&"type"in Y&&Y.type==="text"&&"text"in Y&&typeof Y.text==="string")return Y.text;return}function zS6(Q){if(!Q)return;let X=Q._meta;if(!X||typeof X!=="object"||Array.isArray(X))return;let Y=X.properties;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let J={};for(let[G,W]of Object.entries(Y))if(typeof W==="string")J[G]=W;return Object.keys(J).length>0?J:void 0}function US6(Q,X){if(!Q&&!X)return;if(!Q)return X;if(!X)return Q;return{...X,...Q}}function JY1(Q){if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let X=Q,Y=X.structuredContent;if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y;return X}return{value:Q}}async function BS6(Q,X){let Y=Q.body;if(!Y)return{text:"",truncated:!1};let J=Y.getReader(),G=new TextDecoder,W=!1,Z=0,$=[];try{while(!0){let{value:K,done:H}=await J.read();if(H)break;if(K){if(Z+=K.byteLength,Z>X){W=!0;let F=X-(Z-K.byteLength);if(F>0)$.push(G.decode(K.slice(0,F),{stream:!0}));break}$.push(G.decode(K,{stream:!0}))}}}finally{J.releaseLock()}return $.push(G.decode()),{text:$.join(""),truncated:W}}async function BP(Q){let{ctx:X,enabled:Y}=Q,J=Q.organizationId??X.organization?.id;if(!Y||!J)return;let G=zS6(Q.request.params.arguments),W=US6(X.metadata.properties,G);await X.storage.monitoring.log({organizationId:J,connectionId:Q.connectionId,connectionTitle:Q.connectionTitle,toolName:Q.request.params.name,input:Q.request.params.arguments??{},output:Q.output,isError:Q.isError,errorMessage:Q.errorMessage,durationMs:Q.durationMs,timestamp:new Date,userId:X.auth.user?.id||X.auth.apiKey?.userId||null,requestId:X.metadata.requestId,userAgent:X.metadata.userAgent,gatewayId:X.gatewayId,properties:W})}function GY1(Q){let{ctx:X,enabled:Y,connectionId:J,connectionTitle:G}=Q;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=Date.now()-$;return await BP({ctx:X,enabled:Y,connectionId:J,connectionTitle:G,request:W,output:JY1(K),isError:Boolean(K.isError),errorMessage:qS6(K),durationMs:H}),K}catch(K){let H=K,F=Date.now()-$;throw await BP({ctx:X,enabled:Y,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}function WY1(Q){let{ctx:X,enabled:Y,connectionId:J,connectionTitle:G}=Q;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=X.organization?.id;if(Y&&H){let F=K.clone();(async()=>{try{let{text:V,truncated:q}=await BS6(F,262144),z=Date.now()-$,B=F.headers.get("content-type")??"",D=V;if(B.includes("application/json"))try{D=V.length?JSON.parse(V):null}catch{D=V}let L=K.status>=400,M=L&&D&&typeof D==="object"&&"error"in D?D.error:void 0,C=typeof M==="string"&&M?M:L&&typeof D==="string"&&D.trim()?D.slice(0,500):L?`HTTP ${K.status} ${K.statusText}`.trim():q?"Response body truncated to 262144 bytes":void 0;await BP({ctx:X,enabled:Y,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:JY1(D),isError:L,errorMessage:C,durationMs:z})}catch(V){let q=Date.now()-$;await BP({ctx:X,enabled:Y,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${V.message}`,durationMs:q})}})()}return K}catch(K){let H=K,F=Date.now()-$;throw await BP({ctx:X,enabled:Y,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}var ZY1=new ZQ;function DS6(Q,X){return async(Y,J)=>{try{let G=Y.params.name;return await new yU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,G,Q.boundAuth,Q.auth.user?.role,X).check(G),await J()}catch(G){return{content:[{type:"text",text:`Authorization failed: ${G.message}`}],isError:!0}}}}function NS6(Q,X){return async(Y,J)=>{try{let G=Y.params.name;return await new yU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,G,Q.boundAuth,Q.auth.user?.role,X).check(G),await J()}catch(G){return new Response(JSON.stringify({error:`Authorization failed: ${G.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function $Y1(Q,X,{superUser:Y}){let J=typeof Q==="string"?await X.storage.connections.findById(Q,X.organization?.id):Q;if(!J)throw Error("Connection not found");let G=J?.id;if(X.organization&&J.organization_id!==X.organization.id)throw Error("Connection does not belong to the active organization");if(X.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let W,Z=X.auth.user?.connectionId,$=cX1(async()=>{let f=z40(J.configuration_state,J.configuration_scopes),S=X.auth.user?.id??X.auth.apiKey?.userId;if(!S){console.error("User ID required to issue configuration token");return}try{W=await lX1({sub:S,user:{id:S},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??X.baseUrl,connectionId:G,organizationId:X.organization?.id},permissions:f})}catch(m){console.error("Failed to issue configuration token:",m)}}),K=async()=>{await $();let f={...Z?{"x-caller-id":Z}:{}},S=null,m=new b7(X.db,X.vault),Q0=await m.get(G);if(Q0){let r=!!Q0.refreshToken&&!!Q0.tokenEndpoint;if(m.isExpired(Q0,r?300000:0))if(r){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let F0=await iX1(Q0);if(F0.success&&F0.accessToken)await m.upsert({connectionId:G,accessToken:F0.accessToken,refreshToken:F0.refreshToken??Q0.refreshToken,scope:F0.scope??Q0.scope,expiresAt:F0.expiresIn?new Date(Date.now()+F0.expiresIn*1000):null,clientId:Q0.clientId,clientSecret:Q0.clientSecret,tokenEndpoint:Q0.tokenEndpoint}),S=F0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await m.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${F0.error}`)}else await m.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else S=Q0.accessToken}if(!S&&J.connection_token)S=J.connection_token;if(S)f.Authorization=`Bearer ${S}`;if(W)f["x-mesh-token"]=W;return f},H=J.connection_type==="STDIO",F=b3(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{switch(J.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");if(!F)throw Error("STDIO connection missing parameters");return oX1({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd})}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=new QY({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let m=new _7(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(m),f}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=new QY({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let m=new r3(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(m),f}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=Y?async(f,S)=>await S():DS6(X,G),B=Y?async(f,S)=>await S():NS6(X,G),D={enabled:yr0().enabled,connectionId:G,connectionTitle:J.title,ctx:X},L=GY1(D),M=WY1(D),C=rM(L,z),A=rM(M,B),E=async(f)=>{return C(f,async()=>{let S=await q(),m=Date.now(),Q0={...f.params};if(Q0.arguments&&"_meta"in Q0.arguments){let{_meta:r,...Y0}=Q0.arguments;Q0.arguments=Y0}return await X.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":f.params.name}},async(r)=>{try{let Y0=await S.callTool(Q0),F0=Date.now()-m;return X.meter.createHistogram("connection.proxy.duration").record(F0,{"connection.id":G,"tool.name":f.params.name,status:"success"}),X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":f.params.name,status:"success"}),r.end(),Y0}catch(Y0){let F0=Y0,Z0=Date.now()-m;throw X.meter.createHistogram("connection.proxy.duration").record(Z0,{"connection.id":G,"tool.name":f.params.name,status:"error"}),X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":f.params.name,error:F0.message}),r.recordException(F0),r.end(),Y0}finally{S.close().catch(console.error)}})})};return{fetch:async(f)=>{let S=new URL(f.url),m;try{m=await q()}catch(Y0){let F0=J.connection_url?await QY1({error:Y0,reqUrl:S,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(F0)return F0;throw Y0}let Q0=new s3({name:"mcp-mesh",version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),r=new t3({enableJsonResponse:f.headers.get("Accept")?.includes("application/json")??!1});return await Q0.connect(r),Q0.server.setRequestHandler(b$,()=>m.listTools()),Q0.server.setRequestHandler(eG,E),Q0.server.setRequestHandler(S$,()=>m.listResources()),Q0.server.setRequestHandler(k$,(Y0)=>m.readResource(Y0.params)),Q0.server.setRequestHandler(v$,()=>m.listResourceTemplates()),Q0.server.setRequestHandler(_$,()=>m.listPrompts()),Q0.server.setRequestHandler(y$,(Y0)=>m.getPrompt(Y0.params)),await r.handleRequest(f)},client:{callTool:(f)=>{return E({method:"tools/call",params:f})},listTools:async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((S)=>({name:S.name,description:S.description,inputSchema:S.inputSchema,outputSchema:S.outputSchema}))};let f;try{return f=await q(),await f.listTools()}finally{f?.close().catch(console.error)}},listResources:async()=>{let f;try{return f=await q(),await f.listResources()}finally{f?.close().catch(console.error)}},readResource:async(f)=>{let S;try{return S=await q(),await S.readResource(f)}finally{S?.close().catch(console.error)}},listResourceTemplates:async()=>{let f;try{return f=await q(),await f.listResourceTemplates()}finally{f?.close().catch(console.error)}},listPrompts:async()=>{let f;try{return f=await q(),await f.listPrompts()}catch(S){throw console.error("[proxy:listPrompts] Error listing prompts:",S),S}finally{f?.close().catch(console.error)}},getPrompt:async(f)=>{let S;try{return S=await q(),await S.getPrompt(f)}finally{S?.close().catch(console.error)}}},callStreamableTool:async(f,S)=>{if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let m=J.connection_url,Q0={method:"tools/call",params:{name:f,arguments:S}};return A(Q0,async()=>{let r=await K();if(V?.headers)Object.assign(r,V.headers);let Y0=new URL(m);return Y0.pathname=Y0.pathname.replace(/\/$/,"")+`/call-tool/${Q0.params.name}`,await X.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":Q0.params.name}},async(F0)=>{let Z0=Date.now();try{let B0=await fetch(Y0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(Q0.params.arguments),headers:{...r,"Content-Type":"application/json"}}),T0=Date.now()-Z0;return X.meter.createHistogram("connection.proxy.streamable.duration").record(T0,{"connection.id":G,"tool.name":Q0.params.name,status:B0.ok?"success":"error"}),X.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":Q0.params.name,status:B0.ok?"success":"error"}),F0.end(),B0}catch(B0){let T0=B0,b0=Date.now()-Z0;throw X.meter.createHistogram("connection.proxy.streamable.duration").record(b0,{"connection.id":G,"tool.name":Q0.params.name,status:"error"}),X.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":Q0.params.name,error:T0.message}),F0.recordException(T0),F0.end(),B0}})})}}}async function KY1(Q,X){return $Y1(Q,X,{superUser:!1})}async function HY1(Q,X){return $Y1(Q,X,{superUser:!0})}ZY1.all("/:connectionId",async(Q)=>{let X=Q.req.param("connectionId"),Y=Q.get("meshContext");try{return await(await Y.createMCPProxy(X)).fetch(Q.req.raw)}catch(J){let G=J;if(G.message.includes("not found"))return Q.json({error:G.message},404);if(G.message.includes("does not belong to the active organization"))return Q.json({error:"Connection not found"},404);if(G.message.includes("inactive"))return Q.json({error:G.message},503);return Q.json({error:"Internal server error",message:G.message},500)}});var FY1=ZY1;y3();function OS6(Q){if(!Q)return;try{let X=JSON.parse(Q);if(typeof X!=="object"||X===null||Array.isArray(X))return;let Y={};for(let[J,G]of Object.entries(X))if(typeof G==="string")Y[J]=G;return Object.keys(Y).length>0?Y:void 0}catch{return}}function LS6(Q,X){for(let[Y,J]of Object.entries(X)){let G=Q[Y];if(!G||G.length===0){let W=Q["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let Z of J)if(!W.includes(Z))return!1;continue}if(G.includes("*"))continue;for(let W of J)if(!G.includes(W))return!1}return!0}function wS6(Q){let{auth:X,headers:Y,role:J,permissions:G,userId:W}=Q,Z=X.api.hasPermission;return{hasPermission:async($)=>{if(J&&o40.includes(J))return!0;if(G)return LS6(G,$);if(!Z)return console.error("[Auth] hasPermission API not available"),!1;try{if((await Z({headers:Y,body:{permission:$}}))?.success===!0)return!0;let H={};for(let V of Object.keys($))H[V]=["*"];return(await Z({headers:Y,body:{permission:H}}))?.success===!0}catch(K){return console.error("[Auth] Permission check failed:",K),!1}},organization:{create:async($)=>{return X.api.createOrganization({headers:Y,body:$})},update:async($)=>{return X.api.updateOrganization({headers:Y,body:$})},delete:async($)=>{await X.api.deleteOrganization({headers:Y,body:{organizationId:$}})},get:async($)=>{return X.api.getFullOrganization({headers:Y,query:$?{organizationId:$}:void 0})},list:async($)=>{return X.api.listOrganizations({headers:Y,query:$?{userId:$}:void 0})},addMember:async($)=>{return X.api.addMember({headers:Y,body:$})},removeMember:async($)=>{await X.api.removeMember({headers:Y,body:$})},listMembers:async($)=>{return X.api.listMembers({headers:Y,query:$?{organizationId:$.organizationId,limit:$.limit,offset:$.offset}:void 0})},updateMemberRole:async($)=>{return X.api.updateMemberRole({headers:Y,body:$})}},apiKey:{create:async($)=>{return X.api.createApiKey({body:{...$,userId:W}})},list:async()=>{return X.api.listApiKeys({headers:Y})},update:async($)=>{return X.api.updateApiKey({body:{...$,userId:W}})},delete:async($)=>{await X.api.deleteApiKey({headers:Y,body:{keyId:$}})}}}}async function MS6(Q,X,Y){if(o40.includes(Y))return;let J=await Q.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",X).where("role","=",Y).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Y}`);return}}async function PS6(Q,X,Y,J=qY1){let G=Q.headers.get("Authorization");try{let W=new Headers(Q.headers);W.set("X-MCP-Session-Auth","true");let Z=await J.measure("auth_get_mcp_session",()=>X.api.getMcpSession({headers:W}));if(Z){let $=Z.userId,K=await J.measure("auth_query_membership",()=>Y.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",$).executeTakeFirst()),H=K?.role,F=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,V;if(K&&H)V=await J.measure("auth_fetch_role_permissions",()=>MS6(Y,K.organizationId,H));return{user:{id:$,role:H},role:H,permissions:V,organization:F}}}catch(W){console.error("[Auth] OAuth session check failed:",W)}if(G?.startsWith("Bearer ")){let W=G.replace("Bearer ","").trim();try{let Z=await J.measure("auth_verify_mesh_jwt",()=>dX1(W));if(Z){let $,K=Z.metadata?.organizationId;if(Z.sub&&K)$=(await J.measure("auth_query_membership",()=>Y.selectFrom("member").select(["member.role"]).where("member.userId","=",Z.sub).where("member.organizationId","=",K).executeTakeFirst()))?.role;return{user:{id:Z.sub,connectionId:Z.metadata?.connectionId,role:$},role:$,permissions:Z.permissions,organization:Z.metadata?.organizationId?{id:Z.metadata?.organizationId}:void 0}}}catch{}try{let Z=await J.measure("auth_verify_api_key",()=>X.api.verifyApiKey({body:{key:W}}));if(Z?.valid&&Z.key){let $=Z.key.metadata?.organization,K=Z.key.permissions,H,F=Z.key.userId;if(F&&$?.id)H=(await J.measure("auth_query_membership",()=>Y.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",$.id).executeTakeFirst()))?.role;return{apiKeyId:Z.key.id,user:{id:Z.key.userId,role:H},role:H,permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(Z){console.error("[Auth] API key check failed:",Z)}}try{let W=await J.measure("auth_get_session",()=>X.api.getSession({headers:Q.headers}));if(W){let Z,$;if(W.session.activeOrganizationId){let K=await J.measure("auth_get_full_organization",()=>X.api.getFullOrganization({headers:Q.headers}).catch(()=>null));if(K)Z={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((F)=>F.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:$},role:$,organization:Z}}}catch(W){let Z=W;console.error("[Auth] Session check failed:",JSON.stringify({message:Z.message,body:Z.body,stack:Z.stack},null,2))}return{user:void 0}}var VY1,o$={set:(Q)=>{VY1=Q},create:async(Q,X)=>{return await VY1(Q,X)}},qY1={measure:async(Q,X)=>{return await X()}};function zY1(Q){let X=new uw(Q.encryption.key),Y={connections:new lw(Q.db,X),organizationSettings:new e40(Q.db),monitoring:new t40(Q.db,Q.databaseType),gateways:new dw(Q.db),users:new Q80(Q.db)};return async(J,G)=>{let W=G?.timings??qY1,Z=J?.headers.get("x-caller-id")??void 0,$=J?await PS6(J,Q.auth,Q.db,W):{user:void 0},K=wS6({auth:Q.auth,headers:J?.headers??new Headers,role:$.role,permissions:$.permissions,userId:$.user?.id}),H={user:$.user};if($.apiKeyId)H.apiKey={id:$.apiKeyId,name:"",userId:""};let F=$.organization,V=J?new URL(J.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${V.protocol}//${V.host}`,z=new yU(Q.auth,H.user?.id,void 0,K,$.role,w5.SELF),B={timings:W,auth:H,connectionId:Z,organization:F,storage:Y,vault:X,authInstance:Q.auth,boundAuth:K,access:z,db:Q.db,tracer:Q.observability.tracer,meter:Q.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:OS6(J?.headers.get("x-mesh-properties"))},eventBus:Q.eventBus,createMCPProxy:async(D)=>{return await KY1(D,B)}};return B}}var DP={HEALTH:"/health",METRICS:"/metrics"},bU={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known",ORG:"/org/"},TS6=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/;function UY1(Q){return Q===DP.HEALTH||Q===DP.METRICS||Q.startsWith(bU.WELL_KNOWN)}function AS6(Q){return Q.startsWith(bU.API)}function ES6(Q){return Q==="/mcp"||Q.startsWith(bU.MCP)}function jS6(Q){return Q.startsWith(bU.OAUTH_PROXY)}function CS6(Q){return TS6.test(Q)}function IS6(Q){return Q.startsWith(bU.ORG)}function BY1(Q){return AS6(Q)||ES6(Q)||jS6(Q)||IS6(Q)||UY1(Q)}function DY1(Q){return Q==="/"||Q.startsWith(bU.API_AUTH)||UY1(Q)||CS6(Q)}class NY1{db;constructor(Q){this.db=Q}async publishEvent(Q){let X=new Date().toISOString();return await this.db.insertInto("events").values({id:Q.id,organization_id:Q.organizationId,type:Q.type,source:Q.source,specversion:"1.0",subject:Q.subject??null,time:Q.time,datacontenttype:Q.datacontenttype??"application/json",dataschema:Q.dataschema??null,data:Q.data?JSON.stringify(Q.data):null,cron:Q.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:X,updated_at:X}).execute(),{id:Q.id,organizationId:Q.organizationId,type:Q.type,source:Q.source,specversion:"1.0",subject:Q.subject??null,time:Q.time,datacontenttype:Q.datacontenttype??"application/json",dataschema:Q.dataschema??null,data:Q.data??null,cron:Q.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:X,updatedAt:X}}async subscribe(Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("connection_id","=",Q.connectionId).where("event_type","=",Q.eventType);if(Q.publisher)X=X.where("publisher","=",Q.publisher);else X=X.where("publisher","is",null);if(Q.filter)X=X.where("filter","=",Q.filter);else X=X.where("filter","is",null);let Y=await X.executeTakeFirst();if(Y)return{id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,publisher:Y.publisher,eventType:Y.event_type,filter:Y.filter,enabled:Y.enabled===1,createdAt:Y.created_at,updatedAt:Y.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Q.id,organization_id:Q.organizationId,connection_id:Q.connectionId,publisher:Q.publisher??null,event_type:Q.eventType,filter:Q.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Q.id,organizationId:Q.organizationId,connectionId:Q.connectionId,publisher:Q.publisher??null,eventType:Q.eventType,filter:Q.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Q,X){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Q).where("organization_id","=",X).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Q,X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q);if(X)Y=Y.where("connection_id","=",X);return(await Y.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Q,X){let Y=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Q).where("organization_id","=",X).executeTakeFirst();if(!Y)return null;return{id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,publisher:Y.publisher,eventType:Y.event_type,filter:Y.filter,enabled:Y.enabled===1,createdAt:Y.created_at,updatedAt:Y.updated_at}}async getMatchingSubscriptions(Q){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("enabled","=",1).where("event_type","=",Q.type).where((Y)=>Y.or([Y("publisher","is",null),Y("publisher","=",Q.source)])).execute()).map((Y)=>({id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,publisher:Y.publisher,eventType:Y.event_type,filter:Y.filter,enabled:Y.enabled===1,createdAt:Y.created_at,updatedAt:Y.updated_at}))}async createDeliveries(Q,X,Y){if(X.length===0)return;let J=new Date().toISOString(),G=Y??null,W=X.map((Z)=>({id:crypto.randomUUID(),event_id:Q,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(Q){let X=new Date().toISOString(),Y;try{Y=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(W)=>W.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((Z)=>Z.or([Z("d.next_retry_at","is",null),Z("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Q)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Q).execute();if(G.length===0)return[];Y=G.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Y).where("status","=","pending").execute()}if(Y.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Y).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Q){if(Q.length===0)return;let X=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:X}).where("id","in",Q).execute()}async markDeliveriesFailed(Q,X,Y=20,J=1000,G=3600000){if(Q.length===0)return;for(let W of Q){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=Y)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:X,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(J*Math.pow(2,$-1),G),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:X,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(Q){let X=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Q).execute();if(X.length===0)return;let Y=X.every((W)=>W.status==="delivered"),J=X.some((W)=>W.status==="failed"),G=X.some((W)=>W.status==="pending"||W.status==="processing");if(Y)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Q).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Q).execute()}async resetStuckDeliveries(){let Q=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Q.numUpdatedRows??0)}async getEvent(Q,X){let Y=await this.db.selectFrom("events").selectAll().where("id","=",Q).where("organization_id","=",X).executeTakeFirst();if(!Y)return null;return{id:Y.id,organizationId:Y.organization_id,type:Y.type,source:Y.source,specversion:Y.specversion,subject:Y.subject,time:Y.time,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema,data:Y.data?JSON.parse(Y.data):null,cron:Y.cron,status:Y.status,attempts:Y.attempts,lastError:Y.last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.created_at,updatedAt:Y.updated_at}}async findActiveCronEvent(Q,X,Y,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Q).where("type","=",X).where("source","=",Y).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Q,X,Y){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Q).where("organization_id","=",X).where("source","=",Y).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Q).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Q,X){if(Q.length===0)return;let Y=new Date(Date.now()+X).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Y}).where("id","in",Q).execute()}async ackDelivery(Q,X,Y){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Q).where("organization_id","=",X).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Q).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Y).where("event_subscriptions.organization_id","=",X))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(Q);return{success:W}}async syncSubscriptions(Q){let{organizationId:X,connectionId:Y,subscriptions:J}=Q,G=(M,C)=>{return`${M}::${C??""}`},W=await this.listSubscriptions(X,Y),Z=new Map;for(let M of W)Z.set(G(M.eventType,M.publisher),M);let $=new Map;for(let M of J)$.set(G(M.eventType,M.publisher),M);let K=new Date().toISOString(),H=[],F=[],V=[],q=0;for(let[M,C]of $){let A=Z.get(M);if(!A)H.push({id:crypto.randomUUID(),organization_id:X,connection_id:Y,event_type:C.eventType,publisher:C.publisher??null,filter:C.filter??null,enabled:1,created_at:K,updated_at:K});else{let E=A.filter??null,T=C.filter??null;if(E!==T)F.push({id:A.id,filter:T});else q++}}for(let[M,C]of Z)if(!$.has(M))V.push(C.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(F.length>0)await Promise.all(F.map((M)=>this.db.updateTable("event_subscriptions").set({filter:M.filter,updated_at:K}).where("id","=",M.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let z=H.length,B=F.length,D=V.length,L=await this.listSubscriptions(X,Y);return{created:z,updated:B,deleted:D,unchanged:q,subscriptions:L}}}function OY1(Q){return new NY1(Q)}function g9(Q,X,Y,J,G,W,Z,$){return g9.fromTZ(g9.tp(Q,X,Y,J,G,W,Z),$)}g9.fromTZISO=(Q,X,Y)=>g9.fromTZ(RS6(Q,X),Y);g9.fromTZ=function(Q,X){let Y=new Date(Date.UTC(Q.y,Q.m-1,Q.d,Q.h,Q.i,Q.s)),J=G80(Q.tz,Y),G=new Date(Y.getTime()-J),W=G80(Q.tz,G);if(W-J===0)return G;{let Z=new Date(Y.getTime()-W),$=G80(Q.tz,Z);if($-W===0)return Z;if(!X&&$-W>0)return Z;if(X)throw Error("Invalid date passed to fromTZ()");return G}};g9.toTZ=function(Q,X){let Y=Q.toLocaleString("en-US",{timeZone:X}).replace(/[\u202f]/," "),J=new Date(Y);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:X}};g9.tp=(Q,X,Y,J,G,W,Z)=>({y:Q,m:X,d:Y,h:J,i:G,s:W,tz:Z});function G80(Q,X=new Date){let Y=X.toLocaleString("en-US",{timeZone:Q,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=X.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Y}`)}function RS6(Q,X){let Y=new Date(Date.parse(Q));if(isNaN(Y))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Q.substring(9);return Q.includes("Z")||J.includes("-")||J.includes("+")?g9.tp(Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate(),Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),"Etc/UTC"):g9.tp(Y.getFullYear(),Y.getMonth()+1,Y.getDate(),Y.getHours(),Y.getMinutes(),Y.getSeconds(),X)}g9.minitz=g9;var W80=32,OP=31|W80,PY1=[1,2,4,8,16],LY1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Q,X){this.pattern=Q,this.timezone=X,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Q=this.pattern.replace(/\s+/g," ").split(" ");if(Q.length<5||Q.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Q.length===5&&Q.unshift("0"),Q[3].indexOf("L")>=0&&(Q[3]=Q[3].replace("L",""),this.lastDayOfMonth=!0),Q[3]=="*"&&(this.starDOM=!0),Q[4].length>=3&&(Q[4]=this.replaceAlphaMonths(Q[4])),Q[5].length>=3&&(Q[5]=this.replaceAlphaDays(Q[5])),Q[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let X=new xJ(new Date,this.timezone).getDate(!0);Q[0]=Q[0].replace("?",X.getSeconds().toString()),Q[1]=Q[1].replace("?",X.getMinutes().toString()),Q[2]=Q[2].replace("?",X.getHours().toString()),this.starDOM||(Q[3]=Q[3].replace("?",X.getDate().toString())),Q[4]=Q[4].replace("?",(X.getMonth()+1).toString()),this.starDOW||(Q[5]=Q[5].replace("?",X.getDay().toString()))}this.throwAtIllegalCharacters(Q),this.partToArray("second",Q[0],0,1),this.partToArray("minute",Q[1],0,1),this.partToArray("hour",Q[2],0,1),this.partToArray("day",Q[3],-1,1),this.partToArray("month",Q[4],-1,1),this.partToArray("dayOfWeek",Q[5],0,OP),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Q,X,Y,J){let G=this[Q],W=Q==="day"&&this.lastDayOfMonth;if(X===""&&!W)throw TypeError("CronPattern: configuration entry "+Q+" ("+X+") is empty, check for trailing spaces.");if(X==="*")return G.fill(J);let Z=X.split(",");if(Z.length>1)for(let $=0;$<Z.length;$++)this.partToArray(Q,Z[$],Y,J);else X.indexOf("-")!==-1&&X.indexOf("/")!==-1?this.handleRangeWithStepping(X,Q,Y,J):X.indexOf("-")!==-1?this.handleRange(X,Q,Y,J):X.indexOf("/")!==-1?this.handleStepping(X,Q,Y,J):X!==""&&this.handleNumber(X,Q,Y,J)}throwAtIllegalCharacters(Q){for(let X=0;X<Q.length;X++)if((X===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Q[X]))throw TypeError("CronPattern: configuration entry "+X+" ("+Q[X]+") contains illegal characters.")}handleNumber(Q,X,Y,J){let G=this.extractNth(Q,X),W=parseInt(G[0],10)+Y;if(isNaN(W))throw TypeError("CronPattern: "+X+" is not a number: '"+Q+"'");this.setPart(X,W,G[1]||J)}setPart(Q,X,Y){if(!Object.prototype.hasOwnProperty.call(this,Q))throw TypeError("CronPattern: Invalid part specified: "+Q);if(Q==="dayOfWeek"){if(X===7&&(X=0),X<0||X>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+X);this.setNthWeekdayOfMonth(X,Y);return}if(Q==="second"||Q==="minute"){if(X<0||X>=60)throw RangeError("CronPattern: Invalid value for "+Q+": "+X)}else if(Q==="hour"){if(X<0||X>=24)throw RangeError("CronPattern: Invalid value for "+Q+": "+X)}else if(Q==="day"){if(X<0||X>=31)throw RangeError("CronPattern: Invalid value for "+Q+": "+X)}else if(Q==="month"&&(X<0||X>=12))throw RangeError("CronPattern: Invalid value for "+Q+": "+X);this[Q][X]=Y}handleRangeWithStepping(Q,X,Y,J){let G=this.extractNth(Q,X),W=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Q+"'");let[,Z,$,K]=W,H=parseInt(Z,10)+Y,F=parseInt($,10)+Y,V=parseInt(K,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[X].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[X].length+")");if(H>F)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let q=H;q<=F;q+=V)this.setPart(X,q,G[1]||J)}extractNth(Q,X){let Y=Q,J;if(Y.includes("#")){if(X!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Y.split("#")[1],Y=Y.split("#")[0]}return[Y,J]}handleRange(Q,X,Y,J){let G=this.extractNth(Q,X),W=G[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Q+"'");let Z=parseInt(W[0],10)+Y,$=parseInt(W[1],10)+Y;if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Z>$)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let K=Z;K<=$;K++)this.setPart(X,K,G[1]||J)}handleStepping(Q,X,Y,J){let G=this.extractNth(Q,X),W=G[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Q+"'");W[0]===""&&(W[0]="*");let Z=0;W[0]!=="*"&&(Z=parseInt(W[0],10)+Y);let $=parseInt(W[1],10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[X].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[X].length+")");for(let K=Z;K<this[X].length;K+=$)this.setPart(X,K,G[1]||J)}replaceAlphaDays(Q){return Q.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Q){return Q.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Q){let X=Q.trim().toLowerCase();return X==="@yearly"||X==="@annually"?"0 0 1 1 *":X==="@monthly"?"0 0 1 * *":X==="@weekly"?"0 0 * * 0":X==="@daily"?"0 0 * * *":X==="@hourly"?"0 * * * *":Q}setNthWeekdayOfMonth(Q,X){if(typeof X!="number"&&X==="L")this.dayOfWeek[Q]=this.dayOfWeek[Q]|W80;else if(X===OP)this.dayOfWeek[Q]=OP;else if(X<6&&X>0)this.dayOfWeek[Q]=this.dayOfWeek[Q]|PY1[X-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${X}, Type: ${typeof X}`)}},wY1=[31,28,31,30,31,30,31,31,30,31,30,31],x7=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],xJ=class Q{tz;ms;second;minute;hour;day;month;year;constructor(X,Y){if(this.tz=Y,X&&X instanceof Date)if(!isNaN(X))this.fromDate(X);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(X===void 0)this.fromDate(new Date);else if(X&&typeof X=="string")this.fromString(X);else if(X instanceof Q)this.fromCronDate(X);else throw TypeError("CronDate: Invalid type ("+typeof X+") passed to CronDate constructor")}isNthWeekdayOfMonth(X,Y,J,G){let W=new Date(Date.UTC(X,Y,J)).getUTCDay(),Z=0;for(let $=1;$<=J;$++)new Date(Date.UTC(X,Y,$)).getUTCDay()===W&&Z++;if(G&OP&&PY1[Z-1]&G)return!0;if(G&W80){let $=new Date(Date.UTC(X,Y+1,0)).getUTCDate();for(let K=J+1;K<=$;K++)if(new Date(Date.UTC(X,Y,K)).getUTCDay()===W)return!1;return!0}return!1}fromDate(X){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes()+this.tz,this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply();else{let Y=g9.toTZ(X,this.tz);this.ms=X.getMilliseconds(),this.second=Y.s,this.minute=Y.i,this.hour=Y.h,this.day=Y.d,this.month=Y.m-1,this.year=Y.y}else this.ms=X.getMilliseconds(),this.second=X.getSeconds(),this.minute=X.getMinutes(),this.hour=X.getHours(),this.day=X.getDate(),this.month=X.getMonth(),this.year=X.getFullYear()}fromCronDate(X){this.tz=X.tz,this.year=X.year,this.month=X.month,this.day=X.day,this.hour=X.hour,this.minute=X.minute,this.second=X.second,this.ms=X.ms}apply(){if(this.month>11||this.day>wY1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let X=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),!0}else return!1}fromString(X){if(typeof this.tz=="number"){let Y=g9.fromTZISO(X);this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes(),this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),this.apply()}else return this.fromDate(g9.fromTZISO(X,this.tz))}findNext(X,Y,J,G){let W=this[Y],Z;J.lastDayOfMonth&&(this.month!==1?Z=wY1[this.month]:Z=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let $=!J.starDOW&&Y=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let K=this[Y]+G;K<J[Y].length;K++){let H=J[Y][K];if(Y==="day"&&J.lastDayOfMonth&&K-G==Z&&(H=1),Y==="day"&&!J.starDOW){let F=J.dayOfWeek[($+(K-G-1))%7];if(F&&F&OP)F=this.isNthWeekdayOfMonth(this.year,this.month,K-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);X.legacyMode&&!J.starDOM?H=H||F:H=H&&F}if(H)return this[Y]=K-G,W!==this[Y]?2:1}return 3}recurse(X,Y,J){let G=this.findNext(Y,x7[J][0],X,x7[J][2]);if(G>1){let W=J+1;for(;W<x7.length;)this[x7[W][0]]=-x7[W][2],W++;if(G===3)return this[x7[J][1]]++,this[x7[J][0]]=-x7[J][2],this.apply(),this.recurse(X,Y,0);if(this.apply())return this.recurse(X,Y,J-1)}return J+=1,J>=x7.length?this:this.year>=3000?null:this.recurse(X,Y,J)}increment(X,Y,J){return this.second+=Y.interval!==void 0&&Y.interval>1&&J?Y.interval:1,this.ms=0,this.apply(),this.recurse(X,Y,0)}getDate(X){return X||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):g9.fromTZ(g9.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function SS6(Q){if(Q===void 0&&(Q={}),delete Q.name,Q.legacyMode=Q.legacyMode===void 0?!0:Q.legacyMode,Q.paused=Q.paused===void 0?!1:Q.paused,Q.maxRuns=Q.maxRuns===void 0?1/0:Q.maxRuns,Q.catch=Q.catch===void 0?!1:Q.catch,Q.interval=Q.interval===void 0?0:parseInt(Q.interval.toString(),10),Q.utcOffset=Q.utcOffset===void 0?void 0:parseInt(Q.utcOffset.toString(),10),Q.unref=Q.unref===void 0?!1:Q.unref,Q.startAt&&(Q.startAt=new xJ(Q.startAt,Q.timezone)),Q.stopAt&&(Q.stopAt=new xJ(Q.stopAt,Q.timezone)),Q.interval!==null){if(isNaN(Q.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Q.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Q.utcOffset!==void 0){if(isNaN(Q.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Q.utcOffset<-870||Q.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Q.utcOffset!==void 0&&Q.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Q.unref!==!0&&Q.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Q}function NP(Q){return Object.prototype.toString.call(Q)==="[object Function]"||typeof Q=="function"||Q instanceof Function}function vS6(Q){return NP(Q)}function kS6(Q){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Q):Q&&typeof Q.unref<"u"&&Q.unref()}var MY1=30000,_y=[],yy=class{name;options;_states;fn;constructor(Q,X,Y){let J,G;if(NP(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(NP(Y))G=Y;else if(typeof Y=="object")J=Y;else if(Y!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=SS6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new LY1("* * * * *")},Q&&(Q instanceof Date||typeof Q=="string"&&Q.indexOf(":")>0)?this._states.once=new xJ(Q,this.options.timezone||this.options.utcOffset):this._states.pattern=new LY1(Q,this.options.timezone),this.name){if(_y.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");_y.push(this)}return G!==void 0&&vS6(G)&&(this.fn=G,this.schedule()),this}nextRun(Q){let X=this._next(Q);return X?X.getDate(!1):null}nextRuns(Q,X){this._states.maxRuns!==void 0&&Q>this._states.maxRuns&&(Q=this._states.maxRuns);let Y=[],J=X||this._states.currentRun||void 0;for(;Q--&&(J=this.nextRun(J));)Y.push(J);return Y}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Q=this.nextRun(this._states.currentRun),X=!this._states.paused,Y=this.fn!==void 0,J=!this._states.kill;return X&&Y&&J&&Q!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Q){let X=this._next(Q);return X?Q instanceof xJ||Q instanceof Date?X.getTime()-Q.getTime():X.getTime()-new xJ(Q).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Q=_y.indexOf(this);Q>=0&&_y.splice(Q,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Q){if(Q&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Q&&(this.fn=Q);let X=this.msToNext(),Y=this.nextRun(this._states.currentRun);return X==null||isNaN(X)||Y===null?this:(X>MY1&&(X=MY1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Y),X),this._states.currentTimeout&&this.options.unref&&kS6(this._states.currentTimeout),this)}async _trigger(Q){if(this._states.blocking=!0,this._states.currentRun=new xJ(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(X){NP(this.options.catch)&&this.options.catch(X,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new xJ(Q,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Q){let X=new Date,Y=!this._states.paused&&X.getTime()>=Q.getTime(),J=this._states.blocking&&this.options.protect;Y&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Y&&J&&NP(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Q){let X=!!(Q||this._states.currentRun),Y=!1;!Q&&this.options.startAt&&this.options.interval&&([Q,X]=this._calculatePreviousRun(Q,X),Y=!Q),Q=new xJ(Q,this.options.timezone||this.options.utcOffset),this.options.startAt&&Q&&Q.getTime()<this.options.startAt.getTime()&&(Q=this.options.startAt);let J=this._states.once||new xJ(Q,this.options.timezone||this.options.utcOffset);return!Y&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,X)),this._states.once&&this._states.once.getTime()<=Q.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Q,X){let Y=new xJ(void 0,this.options.timezone||this.options.utcOffset),J=Q;if(this.options.startAt.getTime()<=Y.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Y.getTime();)J=new xJ(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;X=!0}return J===null&&(J=void 0),[J,X]}};var by={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Ty();function TY1(){return async(Q,X)=>{try{let Y=await o$.create(),J=await HY1(Q,{...Y,auth:{...Y.auth,user:{id:"notify-worker"}}}),W=await $40.forClient(J).ON_EVENTS({events:X});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(Y){let J=Y instanceof Error?Y.message:String(Y);return console.error(`[EventBus] Failed to notify connection ${Q}:`,J),{success:!1,error:J}}}}function AY1(Q){return{specversion:"1.0",id:Q.id,source:Q.source,type:Q.type,time:Q.time,subject:Q.subject??void 0,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema??void 0,data:Q.data??void 0}}function _S6(Q){let X=new Map;for(let J of Q){let G=J.subscription.connectionId,W=X.get(G);if(W){if(W.deliveryIds.push(J.delivery.id),!W.seenEventIds.has(J.event.id))W.seenEventIds.add(J.event.id),W.events.push(AY1(J.event))}else X.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[AY1(J.event)],seenEventIds:new Set([J.event.id])})}let Y=new Map;for(let[J,G]of X)Y.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Y}class Z80{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Q,X){this.storage=Q;this.notifySubscriber=TY1(),this.config={...by,...X}}async start(){if(this.running)return;let Q=await this.storage.resetStuckDeliveries();if(Q>0)console.log(`[EventBus] Reset ${Q} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(Q){console.error("[EventBus] Error processing events:",Q)}finally{this.processing=!1}}async processEvents(){let Q=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Q.length===0)return;let X=_S6(Q),Y=new Set;for(let[J,G]of X){try{let W=await this.notifySubscriber(G.connectionId,G.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(G,W);else if(W.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let Z=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${J}:`,Z),await this.storage.markDeliveriesFailed(G.deliveryIds,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of Q)if(G.deliveryIds.includes(W.delivery.id))Y.add(W.event.id)}for(let J of Y)try{await this.storage.updateEventStatus(J);let G=Q.find((W)=>W.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Q,X){let Y=[],J=new Map,G=[],W=new Map;for(let Z=0;Z<Q.events.length;Z++){let $=Q.events?.[Z];if(!$)continue;let K=Q.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of Q.events){let $=W.get(Z.id);if(!$)continue;let K=X.results?.[Z.id];if(K)if(K.success)Y.push($);else if(K.retryAfter&&K.retryAfter>0){let H=J.get(K.retryAfter)||[];H.push($),J.set(K.retryAfter,H)}else G.push({deliveryId:$,error:K.error||"Event processing failed"});else if(X.success)Y.push($);else if(X.retryAfter&&X.retryAfter>0){let H=J.get(X.retryAfter)||[];H.push($),J.set(X.retryAfter,H)}else G.push({deliveryId:$,error:X.error||"Batch processing failed"})}if(Y.length>0)await this.storage.markDeliveriesDelivered(Y);for(let[Z,$]of J)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(G.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of G){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Q){if(!Q.cron)return;try{let Y=new yy(Q.cron).nextRun();if(!Y){console.log(`[EventBus] Cron expression for event ${Q.id} has no more runs`);return}let J=Y.toISOString(),G=await this.storage.getMatchingSubscriptions(Q);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Q.id}, skipping next delivery`);return}await this.storage.createDeliveries(Q.id,G.map((W)=>W.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Q.id} at ${J}`)}catch(X){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Q.id}:`,X)}}}class $80{storage;worker;notifyStrategy;running=!1;constructor(Q){this.storage=Q.storage,this.notifyStrategy=Q.notifyStrategy,this.worker=new Z80(this.storage,Q.config)}async publish(Q,X,Y){if(Y.deliverAt&&Y.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Y.cron){try{let F=new yy(Y.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(Q,Y.type,X,Y.cron);if(K)return K}let G=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:G,organizationId:Q,type:Y.type,source:X,subject:Y.subject,time:W,data:Y.data,cron:Y.cron}),$=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=Y.deliverAt??J;if(await this.storage.createDeliveries(G,$.map((H)=>H.id),K),this.notifyStrategy&&!K)await this.notifyStrategy.notify(G).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return Z}async subscribe(Q,X){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Q,connectionId:X.connectionId,publisher:X.publisher,eventType:X.eventType,filter:X.filter})}async unsubscribe(Q,X){return this.storage.unsubscribe(X,Q)}async listSubscriptions(Q,X){return this.storage.listSubscriptions(Q,X)}async getSubscription(Q,X){return this.storage.getSubscription(X,Q)}async getEvent(Q,X){return this.storage.getEvent(X,Q)}async cancelEvent(Q,X,Y){return this.storage.cancelEvent(X,Q,Y)}async ackEvent(Q,X,Y){return this.storage.ackDelivery(X,Q,Y)}async syncSubscriptions(Q,X){return this.storage.syncSubscriptions({organizationId:Q,...X})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Q)=>{console.error("[EventBus] Error processing after notify:",Q)})});await this.worker.processNow().catch((Q)=>{console.error("[EventBus] Error processing pending events on startup:",Q)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Q){console.error("[EventBus] Error stopping notify strategy:",Q)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}function EY1(...Q){return{async start(X){await Promise.all(Q.map((Y)=>Y.start(X)))},async stop(){await Promise.all(Q.map((X)=>X.stop().catch((Y)=>{console.error("[NotifyStrategy] Error stopping strategy:",Y)})))},async notify(X){await Promise.all(Q.map((Y)=>Y.notify(X).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class fy{intervalMs;timer=null;onNotify=null;constructor(Q){this.intervalMs=Q}async start(Q){if(this.timer)return;this.onNotify=Q,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Q){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as yS6}from"kysely";var fU="mesh_events";class K80{db;pool;listenClient=null;onNotify=null;constructor(Q,X){this.db=Q;this.pool=X}async start(Q){if(this.listenClient)return;this.onNotify=Q;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(X)=>{if(X.channel===fU&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(X)=>{console.error("[PostgresNotify] Connection error:",X),this.cleanup()}),await this.listenClient.query(`LISTEN ${fU}`),console.log("[PostgresNotify] Started LISTEN on",fU)}catch(X){console.error("[PostgresNotify] Failed to start LISTEN:",X),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${fU}`),console.log("[PostgresNotify] Stopped LISTEN on",fU)}catch{}this.cleanup()}}async notify(Q){try{await yS6`SELECT pg_notify(${fU}, ${Q})`.execute(this.db)}catch(X){console.warn("[PostgresNotify] Failed to send NOTIFY:",X)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function jY1(Q,X){let Y=OY1(Q.db),J=X?.pollIntervalMs??by.pollIntervalMs,G=Q.type==="postgres"?EY1(new fy(J),new K80(Q.db,Q.pool)):new fy(J);return new $80({storage:Y,config:X,notifyStrategy:G})}var CY1={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var IY1=new ZQ;IY1.get("/config",async(Q)=>{try{let X=Object.keys(a8.socialProviders??{}),Y=X.length>0,J=X.map((Z)=>({name:Z,icon:CY1[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:a8.emailAndPassword?.enabled??!1},magicLink:{enabled:a8.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Y,providers:J},sso:a8.ssoConfig?{enabled:!0,providerId:a8.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Q.json({success:!0,config:W})}catch(X){let Y=X instanceof Error?X.message:"Failed to load auth config";return Q.json({success:!1,error:Y},500)}});var RY1=IY1;jy();var hy=new ZQ;hy.post("/connections/:connectionId/oauth-token",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("connectionId");if(!(X.auth.user?.id??X.auth.apiKey?.userId??null))return Q.json({error:"Unauthorized"},401);if(!await X.storage.connections.findById(Y,X.organization?.id))return Q.json({error:"Connection not found"},404);let W=await Q.req.json();if(!W.accessToken)return Q.json({error:"accessToken is required"},400);if(W.tokenEndpoint){let F;try{F=new URL(W.tokenEndpoint)}catch{return Q.json({error:"tokenEndpoint must be a valid URL"},400)}if(F.protocol!=="http:"&&F.protocol!=="https:")return Q.json({error:"tokenEndpoint must be an http(s) URL"},400)}let Z=W.expiresIn?new Date(Date.now()+W.expiresIn*1000):null,$=new b7(X.db,X.vault),K={connectionId:Y,accessToken:W.accessToken,refreshToken:W.refreshToken??null,scope:W.scope??null,expiresAt:Z,clientId:W.clientId??null,clientSecret:W.clientSecret??null,tokenEndpoint:W.tokenEndpoint??null},H=await $.upsert(K);return Q.json({success:!0,expiresAt:H.expiresAt})});hy.delete("/connections/:connectionId/oauth-token",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("connectionId");if(!(X.auth.user?.id??X.auth.apiKey?.userId??null))return Q.json({error:"Unauthorized"},401);return await new b7(X.db,X.vault).delete(Y),Q.json({success:!0})});hy.get("/connections/:connectionId/oauth-token/status",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("connectionId");if(!(X.auth.user?.id??X.auth.apiKey?.userId??null))return Q.json({error:"Unauthorized"},401);let G=new b7(X.db,X.vault),W=await G.get(Y);if(!W)return Q.json({hasToken:!1,isExpired:!0,canRefresh:!1});let Z=G.isExpired(W),$=!!W.refreshToken&&!!W.tokenEndpoint;return Q.json({hasToken:!0,isExpired:Z,canRefresh:$,expiresAt:W.expiresAt})});var SY1=hy;Dy();Ny();h9();class LP{proxies=new Map;constructor(){}static async create(Q,X){let Y=new LP,J=await Promise.allSettled(Q.map(async({connection:G,selectedTools:W,selectedResources:Z,selectedPrompts:$})=>{try{let K=await X.createMCPProxy(G);return{connection:G,proxy:K,selectedTools:W,selectedResources:Z,selectedPrompts:$}}catch(K){return console.error(`[gateway] Failed to create proxy for connection ${G.id}:`,K),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Y.proxies.set(G.value.connection.id,G.value);return Y}get(Q){return this.proxies.get(Q)}entries(){return this.proxies.entries()}forEach(Q){this.proxies.forEach((X,Y)=>Q(X,Y))}async mapAsync(Q){let X=[];for(let[Y,J]of this.proxies.entries())X.push(Q(J,Y));return await Promise.all(X)}async mapSettled(Q){return Promise.allSettled(Array.from(this.proxies.entries()).map(([X,Y])=>Q(Y,X)))}get size(){return this.proxies.size}}G1();function vY1(Q){let X=[],Y=[],J=(K)=>{let H=Q.newFunction(K,(...F)=>{try{let V=F.map((q)=>Q.dump(q));X.push({type:K??"log",content:V.map(String).join(" ")})}finally{F.forEach((V)=>V.dispose())}return Q.undefined});return Y.push(H),H},G=Q.newObject();Y.push(G);let W=J("log"),Z=J("warn"),$=J("error");return Q.setProp(G,"log",W),Q.setProp(G,"warn",Z),Q.setProp(G,"error",$),Q.setProp(Q.global,"console",G),{logs:X,[Symbol.dispose](){Y.forEach((K)=>K.dispose())}}}A80();gy();async function QJ1(Q){let X=E80(await Q),[Y,J,{QuickJSWASMModule:G}]=await Promise.all([X.importModuleLoader().then(E80),X.importFFI(),Promise.resolve().then(() => (eY1(),tY1)).then(E80)]),W=await Y();W.type="sync";let Z=new J(W);return new G(W,Z)}function E80(Q){return Q&&"default"in Q&&Q.default?Q.default&&"default"in Q.default&&Q.default.default?Q.default.default:Q.default:Q}var rS6={type:"sync",importFFI:()=>Promise.resolve().then(() => (YJ1(),XJ1)).then((Q)=>Q.QuickJSFFI),importModuleLoader:()=>Promise.resolve().then(() => (GJ1(),JJ1)).then((Q)=>Q.default)},WJ1=rS6;var ZJ1;function $J1(){return ZJ1??=QJ1(WJ1),ZJ1}async function KJ1(Q={}){let Y=(await $J1()).newRuntime({maxStackSizeBytes:Q.stackSizeBytes,memoryLimitBytes:Q.memoryLimitBytes});return{newContext:({interruptAfterMs:G,...W}={})=>{let Z=Y.newContext({intrinsics:{...L80,...W}}),$=0,K=(H)=>{$=H?Date.now()+H:0};if(Y.setInterruptHandler(()=>{let H=Date.now(),F=$>0&&H>$;return F}),G)K(G);return Z},dispose:()=>{Y.dispose()},[Symbol.dispose](){Y.dispose()}}}function xU(Q){if(Q===null)return"null";if(Q===void 0)return"undefined";if(Q instanceof Error){let X=Q.message||Q.name||"Error";if(Q.stack&&Q.stack.length<2000)return`${X}
|
|
1039
|
+
`})}}}var JS6=[ht({organizationCreation:{afterCreate:async(Q)=>{await yX1(Q.organization.id,Q.member.userId)}},ac:Iy,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:bX1,resourceNameValidation:(Q)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Q)}}},roles:{user:QS6,admin:XS6,owner:YS6},sendInvitationEmail:uX1}),tt({loginPage:"/login",oidcConfig:{scopes:gX1,metadata:{scopes_supported:gX1},loginPage:"/login"}}),st({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Q)=>{if(Q.headers?.get("X-MCP-Session-Auth")==="true")return null;let Y=Q.headers?.get("Authorization");if(Y?.startsWith("Bearer "))return Y.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),ut({defaultRole:"user",adminRoles:["admin","owner"]}),Ye(),dt({jwt:{expirationTime:"5m"}}),ai0(a8.ssoConfig?fX1(a8.ssoConfig):void 0),...a8.magicLinkConfig&&a8.emailProviders&&a8.emailProviders.length>0?[Xe(qt0(a8.magicLinkConfig,a8.emailProviders))]:[]],GS6=ge(),WS6=Vt0(GS6),h7=as({baseURL:process.env.BASE_URL||"http://localhost:3000",database:WS6,emailAndPassword:{enabled:!0},...a8,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:JS6,databaseHooks:{user:{create:{after:async(Q)=>{if(Iw.autoCreateOrganizationOnSignup===!1)return;let X=Q.name?Q.name.split(" ")[0]:Q.email.split("@")[0],Y=3;for(let J=0;J<Y;J++){let G=`${X} ${sR6()}`,W=oR6(G);try{await h7.api.createOrganization({body:{name:G,slug:W,userId:Q.id}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Y-1){console.error("Failed to create default organization:",Z);return}}}}}}}});PY();import{randomBytes as ZS6}from"crypto";var UP=null;function mX1(){if(UP)return UP;let Q=process.env.MESH_JWT_SECRET??a8.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Q)UP=new TextEncoder().encode(Q);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),UP=new Uint8Array(ZS6(32));return UP}async function lX1(Q,X="5m"){let Y=mX1();return await new gX(Q).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(X).sign(Y)}async function dX1(Q){try{let X=mX1(),{payload:Y}=await W8(Q,X);return Y}catch{return}}import{sql as Ry}from"kysely";class o40{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(Q){return xD.startActiveSpan("redactor.redact",(X)=>{try{if(Q===null||Q===void 0)return Q;if(typeof Q==="string")return X.setAttribute("data.type","string"),this.redactString(Q);if(Array.isArray(Q))return X.setAttribute("data.type","array"),X.setAttribute("data.length",Q.length),Q.map((Y)=>this.redact(Y));if(typeof Q==="object"){X.setAttribute("data.type","object");let Y={};for(let[J,G]of Object.entries(Q)){let W=this.redactString(J);Y[W]=this.redact(G)}return Y}return X.setAttribute("data.type",typeof Q),Q}finally{X.end()}})}redactString(Q){return xD.startActiveSpan("redactor.redactString",(X)=>{try{X.setAttribute("text.length",Q.length);let Y=Q,J=0;for(let G of this.patterns){let W=Q.match(G.regex);if(W)J+=W.length,X.setAttribute(`redaction.${G.type}.count`,W.length);Y=Y.replace(G.regex,`[REDACTED:${G.type}]`)}return X.setAttribute("redaction.total_count",J),Y}finally{X.end()}})}}mw();class s40{db;redactor;databaseType;constructor(Q,X="sqlite"){this.db=Q;this.redactor=new o40,this.databaseType=X}jsonExtract(Q,X){if(this.databaseType==="postgres")return Ry`(${Ry.ref(Q)}::jsonb)->>${X}`;let Y=`$.${X}`;return Ry`json_extract(${Ry.ref(Q)}, ${Y})`}async log(Q){await this.logBatch([Q])}async logBatch(Q){if(Q.length===0)return;let X=Q.map((Y)=>({...Y,input:this.redactor.redact(Y.input),output:this.redactor.redact(Y.output)}));await this.db.transaction().execute(async(Y)=>{await Y.insertInto("monitoring_logs").values(X.map((J)=>this.toDbRow(J))).execute()})}async query(Q){let X=this.db.selectFrom("monitoring_logs").selectAll(),Y=this.db.selectFrom("monitoring_logs").select(($)=>$.fn.count("id").as("count"));if(Q.organizationId)X=X.where("organization_id","=",Q.organizationId),Y=Y.where("organization_id","=",Q.organizationId);if(Q.connectionId)X=X.where("connection_id","=",Q.connectionId),Y=Y.where("connection_id","=",Q.connectionId);if(Q.gatewayId)X=X.where("gateway_id","=",Q.gatewayId),Y=Y.where("gateway_id","=",Q.gatewayId);if(Q.toolName)X=X.where("tool_name","=",Q.toolName),Y=Y.where("tool_name","=",Q.toolName);if(Q.isError!==void 0)X=X.where("is_error","=",Q.isError?1:0),Y=Y.where("is_error","=",Q.isError?1:0);if(Q.startDate)X=X.where("timestamp",">=",Q.startDate.toISOString()),Y=Y.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)X=X.where("timestamp","<=",Q.endDate.toISOString()),Y=Y.where("timestamp","<=",Q.endDate.toISOString());if(Q.propertyFilters){let{properties:$,propertyKeys:K,propertyPatterns:H}=Q.propertyFilters;if($)for(let[F,V]of Object.entries($)){let q=this.jsonExtract("properties",F);X=X.where(q,"=",V),Y=Y.where(q,"=",V)}if(K&&K.length>0)for(let F of K){let V=this.jsonExtract("properties",F);X=X.where(V,"is not",null),Y=Y.where(V,"is not",null)}if(H)for(let[F,V]of Object.entries(H)){let q=this.jsonExtract("properties",F),z=this.databaseType==="postgres"?"ilike":"like";X=X.where(q,z,V),Y=Y.where(q,z,V)}}if(X=X.orderBy("timestamp","desc"),Q.limit)X=X.limit(Q.limit);if(Q.offset)X=X.offset(Q.offset);let[J,G]=await Promise.all([X.execute(),Y.executeTakeFirst()]),W=Number(G?.count||0);return{logs:J.map(($)=>this.fromDbRow($)),total:W}}async getStats(Q){let X=this.db.selectFrom("monitoring_logs").where("organization_id","=",Q.organizationId);if(Q.startDate)X=X.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)X=X.where("timestamp","<=",Q.endDate.toISOString());let Y=await X.select([(Z)=>Z.fn.count("id").as("total_count"),(Z)=>Z.fn.sum(Z.ref("is_error")).as("error_count"),(Z)=>Z.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Y?.total_count||0),G=Number(Y?.error_count||0),W=Number(Y?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:W}}toDbRow(Q){return{id:Q.id||kJ("log"),organization_id:Q.organizationId,connection_id:Q.connectionId,connection_title:Q.connectionTitle,tool_name:Q.toolName,input:JSON.stringify(Q.input),output:JSON.stringify(Q.output),is_error:Q.isError?1:0,error_message:Q.errorMessage||null,duration_ms:Q.durationMs,timestamp:Q.timestamp instanceof Date?Q.timestamp.toISOString():Q.timestamp,user_id:Q.userId||null,request_id:Q.requestId,user_agent:Q.userAgent||null,gateway_id:Q.gatewayId||null,properties:Q.properties?JSON.stringify(Q.properties):null}}fromDbRow(Q){let X=typeof Q.input==="string"?JSON.parse(Q.input):Q.input,Y=typeof Q.output==="string"?JSON.parse(Q.output):Q.output,J=typeof Q.timestamp==="string"?new Date(Q.timestamp):Q.timestamp,G=Q.properties?typeof Q.properties==="string"?JSON.parse(Q.properties):Q.properties:null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,connectionTitle:Q.connection_title,toolName:Q.tool_name,input:X,output:Y,isError:Q.is_error===1,errorMessage:Q.error_message,durationMs:Q.duration_ms,timestamp:J,userId:Q.user_id,requestId:Q.request_id,userAgent:Q.user_agent,gatewayId:Q.gateway_id,properties:G}}}class t40{db;constructor(Q){this.db=Q}async get(Q){let X=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Q).executeTakeFirst();if(!X)return null;return{organizationId:X.organizationId,sidebar_items:X.sidebar_items?typeof X.sidebar_items==="string"?JSON.parse(X.sidebar_items):X.sidebar_items:null,createdAt:X.createdAt,updatedAt:X.updatedAt}}async upsert(Q,X){let Y=new Date().toISOString(),J=X?.sidebar_items?JSON.stringify(X.sidebar_items):null;await this.db.insertInto("organization_settings").values({organizationId:Q,sidebar_items:J,createdAt:Y,updatedAt:Y}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,updatedAt:Y})).execute();let G=await this.get(Q);if(!G)return{organizationId:Q,sidebar_items:X?.sidebar_items??null,createdAt:Y,updatedAt:Y};return G}}class e40{db;constructor(Q){this.db=Q}async findById(Q,X){let Y=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",Q).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",Q).where("m2.userId","=",X))).executeTakeFirst();if(!Y)return null;return{id:Y.id,name:Y.name,email:Y.email,role:"",createdAt:Y.createdAt,updatedAt:Y.updatedAt,image:Y.image??void 0}}}y3();class pX1 extends Error{constructor(Q){super(Q);this.name="UnauthorizedError"}}class Q80 extends Error{constructor(Q){super(Q);this.name="ForbiddenError"}}class yU{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(Q,X,Y,J,G,W=w5.SELF){this.userId=X;this.toolName=Y;this.boundAuth=J;this.role=G;this.connectionId=W}[Symbol.dispose](){this._granted=!1}setToolName(Q){this.toolName=Q}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Q){if(this._granted)return;if(!this.userId&&!this.boundAuth)throw new pX1("Authentication required. Please provide a valid OAuth token or API key.");let X=Q.length>0?Q:this.toolName?[this.toolName]:[];if(X.length===0)throw new Q80("No resources specified for access check");for(let Y of X)if(await this.checkResource(Y)){this.grant();return}throw new Q80(`Access denied to: ${X.join(", ")}`)}async checkResource(Q){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let X={};if(this.connectionId)X[this.connectionId]=[Q];return this.boundAuth.hasPermission(X)}granted(){return this._granted}}U40();function cX1(Q){let X=null;return()=>{if(X)return X;return X=Q().catch((Y)=>{throw X=null,Y}),X}}class nX1{factory;promise=null;constructor(Q){this.factory=Q}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Q,X){return this.getOrCreatePromise().then(Q,X)}catch(Q){return this.getOrCreatePromise().catch(Q)}finally(Q){return this.getOrCreatePromise().finally(Q)}}function GW(Q){return new nX1(Q)}async function iX1(Q){if(!Q.refreshToken)return{success:!1,error:"No refresh token available"};if(!Q.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Q.clientId)return{success:!1,error:"No client ID available"};try{let X=new URLSearchParams({grant_type:"refresh_token",refresh_token:Q.refreshToken,client_id:Q.clientId});if(Q.clientSecret)X.set("client_secret",Q.clientSecret);if(Q.scope)X.set("scope",Q.scope);let Y=await fetch(Q.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:X.toString()});if(!Y.ok){let G=await Y.text();console.error(`[TokenRefresh] Failed to refresh token: ${Y.status}`,G);try{let W=JSON.parse(G);return{success:!1,error:W.error_description||W.error||`Token refresh failed: ${Y.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Y.status}`}}}let J=await Y.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Q.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(X){return console.error("[TokenRefresh] Error refreshing token:",X),{success:!1,error:X instanceof Error?X.message:"Token refresh failed"}}}zU();m60();function $S6(Q){return new Proxy(Q,{get(Y,J,G){if(J==="close")return async()=>{};if(J==="__actualClient")return Y;return Reflect.get(Y,J,G)}})}var aX1="__mesh_stable_stdio_pool__",e3=globalThis[aX1]??(globalThis[aX1]=new Map);async function oX1(Q){let X=e3.get(Q.id);if(X?.status==="connected"&&X.stableClient)return X.stableClient;if(X?.connectPromise&&(X.status==="connecting"||X.status==="reconnecting"))return X.connectPromise;let Y=X?.status==="failed",J=X??{transport:null,client:null,stableClient:null,config:Q,status:"connecting",connectPromise:null};if(!X)e3.set(Q.id,J);return J.status=Y?"reconnecting":"connecting",J.connectPromise=(async()=>{try{console.log(`[StableStdio] ${Y?"Respawning":"Spawning"}: ${Q.id} (${Q.command} ${Q.args?.join(" ")??""})`);let G=new cM({command:Q.command,args:Q.args,env:Q.env,cwd:Q.cwd,stderr:"pipe"});J.transport=G;let W=new QY({name:`mesh-stdio-${Q.id}`,version:"1.0.0"});J.client=W,J.stableClient=$S6(W),W.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${Q.id}`),J.status="failed",J.connectPromise=null};let Z=Q.name||Q.id,$="\x1B[2m",K="\x1B[0m";G.stderr?.on("data",(V)=>{let q=V.toString().trimEnd();if(q)console.error(`${q} ${$}[${Z}]${K}`)});let H=new AbortController,F=setTimeout(()=>H.abort(),30000);try{await Promise.race([W.connect(G),new Promise((V,q)=>{H.signal.addEventListener("abort",()=>{q(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(F)}return J.status="connected",console.log(`[StableStdio] Connected: ${Q.id}`),J.stableClient}catch(G){console.error(`[StableStdio] Failed to connect ${Q.id}:`,G),J.status="failed",J.connectPromise=null;try{await J.transport?.close()}catch{}throw G}})(),J.connectPromise}async function KS6(Q){let X=e3.get(Q);if(!X)return;console.log(`[StableStdio] Force closing: ${Q}`);try{if(X.client)X.client.onclose=void 0;await X.client?.close()}catch{}e3.delete(Q)}async function HS6(){console.log(`[StableStdio] Closing all connections (${e3.size})`);let Q=Array.from(e3.keys()).map((X)=>KS6(X));await Promise.allSettled(Q),e3.clear()}var rX1="__mesh_stable_stdio_shutdown_registered__";if(!globalThis[rX1]){globalThis[rX1]=!0;let Q=async(X)=>{await HS6(),process.exit(X==="SIGINT"?130:143)};process.on("SIGINT",()=>Q("SIGINT")),process.on("SIGTERM",()=>Q("SIGTERM"))}jy();O7();zU();qy();iM();Dy();Ny();h9();var Sy=new ZQ,X80=[404,401,406];async function sX1(Q,X){return(await X.storage.connections.findById(Q))?.connection_url??null}function FS6(Q){let X=Q.toLowerCase();return X.includes("resource_metadata=")||X.includes("invalid_token")||X.includes("oauth")}async function tX1(Q,X={}){try{let Y=await fetch(Q,{method:"POST",headers:{...X,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Y.status===401){let J=Y.headers.get("WWW-Authenticate");if(J){if(FS6(J))return J}}return null}catch{return null}}async function vy(Q){let Y=new URL(Q).pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);let J=new URL(Q);J.pathname=`${Y}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!X80.includes(G.status))return G;let W=new URL(Q);if(W.pathname=`/.well-known/oauth-protected-resource${Y}`,G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),!X80.includes(G.status))return G;let Z=new URL(Q);return Z.pathname="/.well-known/oauth-protected-resource",G=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function VS6(Q,X){let Y=await sX1(Q,X);if(!Y)return null;let J;try{J=new URL(Y).origin}catch{return null}try{let G=await vy(Y);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function eX1(Q){let X=Q.get("meshContext");if(!X)X=await o$.create(Q.req.raw),Q.set("meshContext",X);return X}async function QY1({error:Q,reqUrl:X,connectionId:Y,connectionUrl:J,headers:G}){let W=Q.message?.toLowerCase()??"";if(!(Q.status===401||Q.code===401||Q.message?.includes("401")||W.includes("unauthorized")||W.includes("invalid_token")||W.includes("api key required")||W.includes("api-key required")))return null;if(Boolean(await tX1(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${X.origin}/mcp/${Y}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}var ky=(Q)=>{if(!(Q.hostname==="localhost"||Q.hostname==="127.0.0.1"))Q.protocol="https:";return Q},XY1=async(Q)=>{let X=Q.req.param("connectionId"),Y=await eX1(Q),J=await sX1(X,Y);if(!J)return Q.json({error:"Connection not found"},404);let G=ky(new URL(Q.req.url)),W=`${G.origin}/mcp/${X}`,Z=`${G.origin}/oauth-proxy/${X}`;try{let $=await vy(J);if(!$.ok&&X80.includes($.status)){if(await tX1(J))return new Response(JSON.stringify({resource:W,authorization_servers:[Z],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}if(!$.ok)return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}});let H={...await $.json(),resource:W,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}catch($){let K=$;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",K),Q.json({error:"Failed to proxy OAuth metadata",message:K.message},502)}};Sy.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Q)=>XY1(Q));Sy.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Q)=>XY1(Q));async function Y80(Q){let Y=new URL(Q).pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);let J=Y!==""&&Y!=="/",G=[];if(J){let Z=new URL(Q);Z.pathname=`/.well-known/oauth-authorization-server${Y}`,G.push(Z);let $=new URL(Q);$.pathname=`/.well-known/openid-configuration${Y}`,G.push($);let K=new URL(Q);K.pathname=`${Y}/.well-known/openid-configuration`,G.push(K)}else{let Z=new URL(Q);Z.pathname="/.well-known/oauth-authorization-server",G.push(Z);let $=new URL(Q);$.pathname="/.well-known/openid-configuration",G.push($)}let W=null;for(let Z of G){if(W=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}Sy.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Q)=>{let X=Q.req.param("connectionId"),Y=await eX1(Q),J=await VS6(X,Y);if(!J)return Q.json({error:"Connection not found or no auth server"},404);try{let G=await Y80(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let W=await G.json(),$=`${ky(new URL(Q.req.url)).origin}/oauth-proxy/${X}`,K={...W,authorization_endpoint:W.authorization_endpoint?`${$}/authorize`:void 0,token_endpoint:W.token_endpoint?`${$}/token`:void 0,registration_endpoint:W.registration_endpoint?`${$}/register`:void 0};return new Response(JSON.stringify(K),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let W=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",W),Q.json({error:"Failed to proxy auth server metadata",message:W.message},502)}});var YY1=Sy;function qS6(Q){if(!Q.isError)return;let X=Q.content;if(!Array.isArray(X))return;for(let Y of X)if(Y&&typeof Y==="object"&&"type"in Y&&Y.type==="text"&&"text"in Y&&typeof Y.text==="string")return Y.text;return}function zS6(Q){if(!Q)return;let X=Q._meta;if(!X||typeof X!=="object"||Array.isArray(X))return;let Y=X.properties;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let J={};for(let[G,W]of Object.entries(Y))if(typeof W==="string")J[G]=W;return Object.keys(J).length>0?J:void 0}function US6(Q,X){if(!Q&&!X)return;if(!Q)return X;if(!X)return Q;return{...X,...Q}}function JY1(Q){if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let X=Q,Y=X.structuredContent;if(Y&&typeof Y==="object"&&!Array.isArray(Y))return Y;return X}return{value:Q}}async function BS6(Q,X){let Y=Q.body;if(!Y)return{text:"",truncated:!1};let J=Y.getReader(),G=new TextDecoder,W=!1,Z=0,$=[];try{while(!0){let{value:K,done:H}=await J.read();if(H)break;if(K){if(Z+=K.byteLength,Z>X){W=!0;let F=X-(Z-K.byteLength);if(F>0)$.push(G.decode(K.slice(0,F),{stream:!0}));break}$.push(G.decode(K,{stream:!0}))}}}finally{J.releaseLock()}return $.push(G.decode()),{text:$.join(""),truncated:W}}async function BP(Q){let{ctx:X,enabled:Y}=Q,J=Q.organizationId??X.organization?.id;if(!Y||!J)return;let G=zS6(Q.request.params.arguments),W=US6(X.metadata.properties,G);await X.storage.monitoring.log({organizationId:J,connectionId:Q.connectionId,connectionTitle:Q.connectionTitle,toolName:Q.request.params.name,input:Q.request.params.arguments??{},output:Q.output,isError:Q.isError,errorMessage:Q.errorMessage,durationMs:Q.durationMs,timestamp:new Date,userId:X.auth.user?.id||X.auth.apiKey?.userId||null,requestId:X.metadata.requestId,userAgent:X.metadata.userAgent,gatewayId:X.gatewayId,properties:W})}function GY1(Q){let{ctx:X,enabled:Y,connectionId:J,connectionTitle:G}=Q;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=Date.now()-$;return await BP({ctx:X,enabled:Y,connectionId:J,connectionTitle:G,request:W,output:JY1(K),isError:Boolean(K.isError),errorMessage:qS6(K),durationMs:H}),K}catch(K){let H=K,F=Date.now()-$;throw await BP({ctx:X,enabled:Y,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}function WY1(Q){let{ctx:X,enabled:Y,connectionId:J,connectionTitle:G}=Q;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=X.organization?.id;if(Y&&H){let F=K.clone();(async()=>{try{let{text:V,truncated:q}=await BS6(F,262144),z=Date.now()-$,B=F.headers.get("content-type")??"",D=V;if(B.includes("application/json"))try{D=V.length?JSON.parse(V):null}catch{D=V}let L=K.status>=400,M=L&&D&&typeof D==="object"&&"error"in D?D.error:void 0,C=typeof M==="string"&&M?M:L&&typeof D==="string"&&D.trim()?D.slice(0,500):L?`HTTP ${K.status} ${K.statusText}`.trim():q?"Response body truncated to 262144 bytes":void 0;await BP({ctx:X,enabled:Y,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:JY1(D),isError:L,errorMessage:C,durationMs:z})}catch(V){let q=Date.now()-$;await BP({ctx:X,enabled:Y,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${V.message}`,durationMs:q})}})()}return K}catch(K){let H=K,F=Date.now()-$;throw await BP({ctx:X,enabled:Y,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}var ZY1=new ZQ;function DS6(Q,X){return async(Y,J)=>{try{let G=Y.params.name;return await new yU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,G,Q.boundAuth,Q.auth.user?.role,X).check(G),await J()}catch(G){return{content:[{type:"text",text:`Authorization failed: ${G.message}`}],isError:!0}}}}function NS6(Q,X){return async(Y,J)=>{try{let G=Y.params.name;return await new yU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,G,Q.boundAuth,Q.auth.user?.role,X).check(G),await J()}catch(G){return new Response(JSON.stringify({error:`Authorization failed: ${G.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function $Y1(Q,X,{superUser:Y}){let J=typeof Q==="string"?await X.storage.connections.findById(Q,X.organization?.id):Q;if(!J)throw Error("Connection not found");let G=J?.id;if(X.organization&&J.organization_id!==X.organization.id)throw Error("Connection does not belong to the active organization");if(X.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let W,Z=X.auth.user?.connectionId,$=cX1(async()=>{let f=z40(J.configuration_state,J.configuration_scopes),S=X.auth.user?.id??X.auth.apiKey?.userId;if(!S){console.error("User ID required to issue configuration token");return}try{W=await lX1({sub:S,user:{id:S},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??X.baseUrl,connectionId:G,organizationId:X.organization?.id},permissions:f})}catch(m){console.error("Failed to issue configuration token:",m)}}),K=async()=>{await $();let f={...Z?{"x-caller-id":Z}:{}},S=null,m=new b7(X.db,X.vault),Q0=await m.get(G);if(Q0){let r=!!Q0.refreshToken&&!!Q0.tokenEndpoint;if(m.isExpired(Q0,r?300000:0))if(r){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let F0=await iX1(Q0);if(F0.success&&F0.accessToken)await m.upsert({connectionId:G,accessToken:F0.accessToken,refreshToken:F0.refreshToken??Q0.refreshToken,scope:F0.scope??Q0.scope,expiresAt:F0.expiresIn?new Date(Date.now()+F0.expiresIn*1000):null,clientId:Q0.clientId,clientSecret:Q0.clientSecret,tokenEndpoint:Q0.tokenEndpoint}),S=F0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await m.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${F0.error}`)}else await m.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else S=Q0.accessToken}if(!S&&J.connection_token)S=J.connection_token;if(S)f.Authorization=`Bearer ${S}`;if(W)f["x-mesh-token"]=W;return f},H=J.connection_type==="STDIO",F=b3(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{switch(J.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");if(!F)throw Error("STDIO connection missing parameters");return oX1({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd})}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=new QY({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let m=new _7(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(m),f}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=new QY({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let m=new r3(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(m),f}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=Y?async(f,S)=>await S():DS6(X,G),B=Y?async(f,S)=>await S():NS6(X,G),D={enabled:yr0().enabled,connectionId:G,connectionTitle:J.title,ctx:X},L=GY1(D),M=WY1(D),C=rM(L,z),A=rM(M,B),E=async(f)=>{return C(f,async()=>{let S=await q(),m=Date.now(),Q0={...f.params};if(Q0.arguments&&"_meta"in Q0.arguments){let{_meta:r,...Y0}=Q0.arguments;Q0.arguments=Y0}return await X.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":f.params.name}},async(r)=>{try{let Y0=await S.callTool(Q0),F0=Date.now()-m;return X.meter.createHistogram("connection.proxy.duration").record(F0,{"connection.id":G,"tool.name":f.params.name,status:"success"}),X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":f.params.name,status:"success"}),r.end(),Y0}catch(Y0){let F0=Y0,Z0=Date.now()-m;throw X.meter.createHistogram("connection.proxy.duration").record(Z0,{"connection.id":G,"tool.name":f.params.name,status:"error"}),X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":f.params.name,error:F0.message}),r.recordException(F0),r.end(),Y0}finally{S.close().catch(console.error)}})})};return{fetch:async(f)=>{let S=new URL(f.url),m;try{m=await q()}catch(Y0){let F0=J.connection_url?await QY1({error:Y0,reqUrl:S,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(F0)return F0;throw Y0}let Q0=new s3({name:"mcp-mesh",version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),r=new t3({enableJsonResponse:f.headers.get("Accept")?.includes("application/json")??!1});return await Q0.connect(r),Q0.server.setRequestHandler(b$,()=>m.listTools()),Q0.server.setRequestHandler(eG,E),Q0.server.setRequestHandler(S$,()=>m.listResources()),Q0.server.setRequestHandler(k$,(Y0)=>m.readResource(Y0.params)),Q0.server.setRequestHandler(v$,()=>m.listResourceTemplates()),Q0.server.setRequestHandler(_$,()=>m.listPrompts()),Q0.server.setRequestHandler(y$,(Y0)=>m.getPrompt(Y0.params)),await r.handleRequest(f)},client:{callTool:(f)=>{return E({method:"tools/call",params:f})},listTools:async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((S)=>({name:S.name,description:S.description,inputSchema:S.inputSchema,outputSchema:S.outputSchema}))};let f;try{return f=await q(),await f.listTools()}finally{f?.close().catch(console.error)}},listResources:async()=>{let f;try{return f=await q(),await f.listResources()}finally{f?.close().catch(console.error)}},readResource:async(f)=>{let S;try{return S=await q(),await S.readResource(f)}finally{S?.close().catch(console.error)}},listResourceTemplates:async()=>{let f;try{return f=await q(),await f.listResourceTemplates()}finally{f?.close().catch(console.error)}},listPrompts:async()=>{let f;try{return f=await q(),await f.listPrompts()}catch(S){throw console.error("[proxy:listPrompts] Error listing prompts:",S),S}finally{f?.close().catch(console.error)}},getPrompt:async(f)=>{let S;try{return S=await q(),await S.getPrompt(f)}finally{S?.close().catch(console.error)}}},callStreamableTool:async(f,S)=>{if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let m=J.connection_url,Q0={method:"tools/call",params:{name:f,arguments:S}};return A(Q0,async()=>{let r=await K();if(V?.headers)Object.assign(r,V.headers);let Y0=new URL(m);return Y0.pathname=Y0.pathname.replace(/\/$/,"")+`/call-tool/${Q0.params.name}`,await X.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":Q0.params.name}},async(F0)=>{let Z0=Date.now();try{let B0=await fetch(Y0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(Q0.params.arguments),headers:{...r,"Content-Type":"application/json"}}),T0=Date.now()-Z0;return X.meter.createHistogram("connection.proxy.streamable.duration").record(T0,{"connection.id":G,"tool.name":Q0.params.name,status:B0.ok?"success":"error"}),X.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":Q0.params.name,status:B0.ok?"success":"error"}),F0.end(),B0}catch(B0){let T0=B0,b0=Date.now()-Z0;throw X.meter.createHistogram("connection.proxy.streamable.duration").record(b0,{"connection.id":G,"tool.name":Q0.params.name,status:"error"}),X.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":Q0.params.name,error:T0.message}),F0.recordException(T0),F0.end(),B0}})})}}}async function KY1(Q,X){return $Y1(Q,X,{superUser:!1})}async function HY1(Q,X){return $Y1(Q,X,{superUser:!0})}ZY1.all("/:connectionId",async(Q)=>{let X=Q.req.param("connectionId"),Y=Q.get("meshContext");try{return await(await Y.createMCPProxy(X)).fetch(Q.req.raw)}catch(J){let G=J;if(G.message.includes("not found"))return Q.json({error:G.message},404);if(G.message.includes("does not belong to the active organization"))return Q.json({error:"Connection not found"},404);if(G.message.includes("inactive"))return Q.json({error:G.message},503);return Q.json({error:"Internal server error",message:G.message},500)}});var FY1=ZY1;y3();function OS6(Q){if(!Q)return;try{let X=JSON.parse(Q);if(typeof X!=="object"||X===null||Array.isArray(X))return;let Y={};for(let[J,G]of Object.entries(X))if(typeof G==="string")Y[J]=G;return Object.keys(Y).length>0?Y:void 0}catch{return}}function LS6(Q,X){for(let[Y,J]of Object.entries(X)){let G=Q[Y];if(!G||G.length===0){let W=Q["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let Z of J)if(!W.includes(Z))return!1;continue}if(G.includes("*"))continue;for(let W of J)if(!G.includes(W))return!1}return!0}function wS6(Q){let{auth:X,headers:Y,role:J,permissions:G,userId:W}=Q,Z=X.api.hasPermission;return{hasPermission:async($)=>{if(J&&r40.includes(J))return!0;if(G)return LS6(G,$);if(!Z)return console.error("[Auth] hasPermission API not available"),!1;try{if((await Z({headers:Y,body:{permission:$}}))?.success===!0)return!0;let H={};for(let V of Object.keys($))H[V]=["*"];return(await Z({headers:Y,body:{permission:H}}))?.success===!0}catch(K){return console.error("[Auth] Permission check failed:",K),!1}},organization:{create:async($)=>{return X.api.createOrganization({headers:Y,body:$})},update:async($)=>{return X.api.updateOrganization({headers:Y,body:$})},delete:async($)=>{await X.api.deleteOrganization({headers:Y,body:{organizationId:$}})},get:async($)=>{return X.api.getFullOrganization({headers:Y,query:$?{organizationId:$}:void 0})},list:async($)=>{return X.api.listOrganizations({headers:Y,query:$?{userId:$}:void 0})},addMember:async($)=>{return X.api.addMember({headers:Y,body:$})},removeMember:async($)=>{await X.api.removeMember({headers:Y,body:$})},listMembers:async($)=>{return X.api.listMembers({headers:Y,query:$?{organizationId:$.organizationId,limit:$.limit,offset:$.offset}:void 0})},updateMemberRole:async($)=>{return X.api.updateMemberRole({headers:Y,body:$})}},apiKey:{create:async($)=>{return X.api.createApiKey({body:{...$,userId:W}})},list:async()=>{return X.api.listApiKeys({headers:Y})},update:async($)=>{return X.api.updateApiKey({body:{...$,userId:W}})},delete:async($)=>{await X.api.deleteApiKey({headers:Y,body:{keyId:$}})}}}}async function MS6(Q,X,Y){if(r40.includes(Y))return;let J=await Q.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",X).where("role","=",Y).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Y}`);return}}async function PS6(Q,X,Y,J=qY1){let G=Q.headers.get("Authorization");try{let W=new Headers(Q.headers);W.set("X-MCP-Session-Auth","true");let Z=await J.measure("auth_get_mcp_session",()=>X.api.getMcpSession({headers:W}));if(Z){let $=Z.userId,K=await J.measure("auth_query_membership",()=>Y.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",$).executeTakeFirst()),H=K?.role,F=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,V;if(K&&H)V=await J.measure("auth_fetch_role_permissions",()=>MS6(Y,K.organizationId,H));return{user:{id:$,role:H},role:H,permissions:V,organization:F}}}catch(W){console.error("[Auth] OAuth session check failed:",W)}if(G?.startsWith("Bearer ")){let W=G.replace("Bearer ","").trim();try{let Z=await J.measure("auth_verify_mesh_jwt",()=>dX1(W));if(Z){let $,K=Z.metadata?.organizationId;if(Z.sub&&K)$=(await J.measure("auth_query_membership",()=>Y.selectFrom("member").select(["member.role"]).where("member.userId","=",Z.sub).where("member.organizationId","=",K).executeTakeFirst()))?.role;return{user:{id:Z.sub,connectionId:Z.metadata?.connectionId,role:$},role:$,permissions:Z.permissions,organization:Z.metadata?.organizationId?{id:Z.metadata?.organizationId}:void 0}}}catch{}try{let Z=await J.measure("auth_verify_api_key",()=>X.api.verifyApiKey({body:{key:W}}));if(Z?.valid&&Z.key){let $=Z.key.metadata?.organization,K=Z.key.permissions,H,F=Z.key.userId;if(F&&$?.id)H=(await J.measure("auth_query_membership",()=>Y.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",$.id).executeTakeFirst()))?.role;return{apiKeyId:Z.key.id,user:{id:Z.key.userId,role:H},role:H,permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(Z){console.error("[Auth] API key check failed:",Z)}}try{let W=await J.measure("auth_get_session",()=>X.api.getSession({headers:Q.headers}));if(W){let Z,$;if(W.session.activeOrganizationId){let K=await J.measure("auth_get_full_organization",()=>X.api.getFullOrganization({headers:Q.headers}).catch(()=>null));if(K)Z={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((F)=>F.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:$},role:$,organization:Z}}}catch(W){let Z=W;console.error("[Auth] Session check failed:",JSON.stringify({message:Z.message,body:Z.body,stack:Z.stack},null,2))}return{user:void 0}}var VY1,o$={set:(Q)=>{VY1=Q},create:async(Q,X)=>{return await VY1(Q,X)}},qY1={measure:async(Q,X)=>{return await X()}};function zY1(Q){let X=new uw(Q.encryption.key),Y={connections:new lw(Q.db,X),organizationSettings:new t40(Q.db),monitoring:new s40(Q.db,Q.databaseType),gateways:new dw(Q.db),users:new e40(Q.db)};return async(J,G)=>{let W=G?.timings??qY1,Z=J?.headers.get("x-caller-id")??void 0,$=J?await PS6(J,Q.auth,Q.db,W):{user:void 0},K=wS6({auth:Q.auth,headers:J?.headers??new Headers,role:$.role,permissions:$.permissions,userId:$.user?.id}),H={user:$.user};if($.apiKeyId)H.apiKey={id:$.apiKeyId,name:"",userId:""};let F=$.organization,V=J?new URL(J.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${V.protocol}//${V.host}`,z=new yU(Q.auth,H.user?.id,void 0,K,$.role,w5.SELF),B={timings:W,auth:H,connectionId:Z,organization:F,storage:Y,vault:X,authInstance:Q.auth,boundAuth:K,access:z,db:Q.db,tracer:Q.observability.tracer,meter:Q.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:OS6(J?.headers.get("x-mesh-properties"))},eventBus:Q.eventBus,createMCPProxy:async(D)=>{return await KY1(D,B)}};return B}}var DP={HEALTH:"/health",METRICS:"/metrics"},bU={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known",ORG:"/org/"},TS6=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/;function UY1(Q){return Q===DP.HEALTH||Q===DP.METRICS||Q.startsWith(bU.WELL_KNOWN)}function AS6(Q){return Q.startsWith(bU.API)}function ES6(Q){return Q==="/mcp"||Q.startsWith(bU.MCP)}function jS6(Q){return Q.startsWith(bU.OAUTH_PROXY)}function CS6(Q){return TS6.test(Q)}function IS6(Q){return Q.startsWith(bU.ORG)}function BY1(Q){return AS6(Q)||ES6(Q)||jS6(Q)||IS6(Q)||UY1(Q)}function DY1(Q){return Q==="/"||Q.startsWith(bU.API_AUTH)||UY1(Q)||CS6(Q)}class NY1{db;constructor(Q){this.db=Q}async publishEvent(Q){let X=new Date().toISOString();return await this.db.insertInto("events").values({id:Q.id,organization_id:Q.organizationId,type:Q.type,source:Q.source,specversion:"1.0",subject:Q.subject??null,time:Q.time,datacontenttype:Q.datacontenttype??"application/json",dataschema:Q.dataschema??null,data:Q.data?JSON.stringify(Q.data):null,cron:Q.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:X,updated_at:X}).execute(),{id:Q.id,organizationId:Q.organizationId,type:Q.type,source:Q.source,specversion:"1.0",subject:Q.subject??null,time:Q.time,datacontenttype:Q.datacontenttype??"application/json",dataschema:Q.dataschema??null,data:Q.data??null,cron:Q.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:X,updatedAt:X}}async subscribe(Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("connection_id","=",Q.connectionId).where("event_type","=",Q.eventType);if(Q.publisher)X=X.where("publisher","=",Q.publisher);else X=X.where("publisher","is",null);if(Q.filter)X=X.where("filter","=",Q.filter);else X=X.where("filter","is",null);let Y=await X.executeTakeFirst();if(Y)return{id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,publisher:Y.publisher,eventType:Y.event_type,filter:Y.filter,enabled:Y.enabled===1,createdAt:Y.created_at,updatedAt:Y.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Q.id,organization_id:Q.organizationId,connection_id:Q.connectionId,publisher:Q.publisher??null,event_type:Q.eventType,filter:Q.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Q.id,organizationId:Q.organizationId,connectionId:Q.connectionId,publisher:Q.publisher??null,eventType:Q.eventType,filter:Q.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Q,X){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Q).where("organization_id","=",X).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Q,X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q);if(X)Y=Y.where("connection_id","=",X);return(await Y.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Q,X){let Y=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Q).where("organization_id","=",X).executeTakeFirst();if(!Y)return null;return{id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,publisher:Y.publisher,eventType:Y.event_type,filter:Y.filter,enabled:Y.enabled===1,createdAt:Y.created_at,updatedAt:Y.updated_at}}async getMatchingSubscriptions(Q){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("enabled","=",1).where("event_type","=",Q.type).where((Y)=>Y.or([Y("publisher","is",null),Y("publisher","=",Q.source)])).execute()).map((Y)=>({id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,publisher:Y.publisher,eventType:Y.event_type,filter:Y.filter,enabled:Y.enabled===1,createdAt:Y.created_at,updatedAt:Y.updated_at}))}async createDeliveries(Q,X,Y){if(X.length===0)return;let J=new Date().toISOString(),G=Y??null,W=X.map((Z)=>({id:crypto.randomUUID(),event_id:Q,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(Q){let X=new Date().toISOString(),Y;try{Y=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(W)=>W.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((Z)=>Z.or([Z("d.next_retry_at","is",null),Z("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Q)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Q).execute();if(G.length===0)return[];Y=G.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Y).where("status","=","pending").execute()}if(Y.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Y).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Q){if(Q.length===0)return;let X=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:X}).where("id","in",Q).execute()}async markDeliveriesFailed(Q,X,Y=20,J=1000,G=3600000){if(Q.length===0)return;for(let W of Q){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=Y)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:X,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(J*Math.pow(2,$-1),G),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:X,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(Q){let X=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Q).execute();if(X.length===0)return;let Y=X.every((W)=>W.status==="delivered"),J=X.some((W)=>W.status==="failed"),G=X.some((W)=>W.status==="pending"||W.status==="processing");if(Y)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Q).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Q).execute()}async resetStuckDeliveries(){let Q=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Q.numUpdatedRows??0)}async getEvent(Q,X){let Y=await this.db.selectFrom("events").selectAll().where("id","=",Q).where("organization_id","=",X).executeTakeFirst();if(!Y)return null;return{id:Y.id,organizationId:Y.organization_id,type:Y.type,source:Y.source,specversion:Y.specversion,subject:Y.subject,time:Y.time,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema,data:Y.data?JSON.parse(Y.data):null,cron:Y.cron,status:Y.status,attempts:Y.attempts,lastError:Y.last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.created_at,updatedAt:Y.updated_at}}async findActiveCronEvent(Q,X,Y,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Q).where("type","=",X).where("source","=",Y).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Q,X,Y){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Q).where("organization_id","=",X).where("source","=",Y).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Q).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Q,X){if(Q.length===0)return;let Y=new Date(Date.now()+X).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Y}).where("id","in",Q).execute()}async ackDelivery(Q,X,Y){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Q).where("organization_id","=",X).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Q).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Y).where("event_subscriptions.organization_id","=",X))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(Q);return{success:W}}async syncSubscriptions(Q){let{organizationId:X,connectionId:Y,subscriptions:J}=Q,G=(M,C)=>{return`${M}::${C??""}`},W=await this.listSubscriptions(X,Y),Z=new Map;for(let M of W)Z.set(G(M.eventType,M.publisher),M);let $=new Map;for(let M of J)$.set(G(M.eventType,M.publisher),M);let K=new Date().toISOString(),H=[],F=[],V=[],q=0;for(let[M,C]of $){let A=Z.get(M);if(!A)H.push({id:crypto.randomUUID(),organization_id:X,connection_id:Y,event_type:C.eventType,publisher:C.publisher??null,filter:C.filter??null,enabled:1,created_at:K,updated_at:K});else{let E=A.filter??null,T=C.filter??null;if(E!==T)F.push({id:A.id,filter:T});else q++}}for(let[M,C]of Z)if(!$.has(M))V.push(C.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(F.length>0)await Promise.all(F.map((M)=>this.db.updateTable("event_subscriptions").set({filter:M.filter,updated_at:K}).where("id","=",M.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let z=H.length,B=F.length,D=V.length,L=await this.listSubscriptions(X,Y);return{created:z,updated:B,deleted:D,unchanged:q,subscriptions:L}}}function OY1(Q){return new NY1(Q)}function g9(Q,X,Y,J,G,W,Z,$){return g9.fromTZ(g9.tp(Q,X,Y,J,G,W,Z),$)}g9.fromTZISO=(Q,X,Y)=>g9.fromTZ(RS6(Q,X),Y);g9.fromTZ=function(Q,X){let Y=new Date(Date.UTC(Q.y,Q.m-1,Q.d,Q.h,Q.i,Q.s)),J=J80(Q.tz,Y),G=new Date(Y.getTime()-J),W=J80(Q.tz,G);if(W-J===0)return G;{let Z=new Date(Y.getTime()-W),$=J80(Q.tz,Z);if($-W===0)return Z;if(!X&&$-W>0)return Z;if(X)throw Error("Invalid date passed to fromTZ()");return G}};g9.toTZ=function(Q,X){let Y=Q.toLocaleString("en-US",{timeZone:X}).replace(/[\u202f]/," "),J=new Date(Y);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:X}};g9.tp=(Q,X,Y,J,G,W,Z)=>({y:Q,m:X,d:Y,h:J,i:G,s:W,tz:Z});function J80(Q,X=new Date){let Y=X.toLocaleString("en-US",{timeZone:Q,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=X.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Y}`)}function RS6(Q,X){let Y=new Date(Date.parse(Q));if(isNaN(Y))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Q.substring(9);return Q.includes("Z")||J.includes("-")||J.includes("+")?g9.tp(Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate(),Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),"Etc/UTC"):g9.tp(Y.getFullYear(),Y.getMonth()+1,Y.getDate(),Y.getHours(),Y.getMinutes(),Y.getSeconds(),X)}g9.minitz=g9;var G80=32,OP=31|G80,PY1=[1,2,4,8,16],LY1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Q,X){this.pattern=Q,this.timezone=X,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Q=this.pattern.replace(/\s+/g," ").split(" ");if(Q.length<5||Q.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Q.length===5&&Q.unshift("0"),Q[3].indexOf("L")>=0&&(Q[3]=Q[3].replace("L",""),this.lastDayOfMonth=!0),Q[3]=="*"&&(this.starDOM=!0),Q[4].length>=3&&(Q[4]=this.replaceAlphaMonths(Q[4])),Q[5].length>=3&&(Q[5]=this.replaceAlphaDays(Q[5])),Q[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let X=new xJ(new Date,this.timezone).getDate(!0);Q[0]=Q[0].replace("?",X.getSeconds().toString()),Q[1]=Q[1].replace("?",X.getMinutes().toString()),Q[2]=Q[2].replace("?",X.getHours().toString()),this.starDOM||(Q[3]=Q[3].replace("?",X.getDate().toString())),Q[4]=Q[4].replace("?",(X.getMonth()+1).toString()),this.starDOW||(Q[5]=Q[5].replace("?",X.getDay().toString()))}this.throwAtIllegalCharacters(Q),this.partToArray("second",Q[0],0,1),this.partToArray("minute",Q[1],0,1),this.partToArray("hour",Q[2],0,1),this.partToArray("day",Q[3],-1,1),this.partToArray("month",Q[4],-1,1),this.partToArray("dayOfWeek",Q[5],0,OP),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Q,X,Y,J){let G=this[Q],W=Q==="day"&&this.lastDayOfMonth;if(X===""&&!W)throw TypeError("CronPattern: configuration entry "+Q+" ("+X+") is empty, check for trailing spaces.");if(X==="*")return G.fill(J);let Z=X.split(",");if(Z.length>1)for(let $=0;$<Z.length;$++)this.partToArray(Q,Z[$],Y,J);else X.indexOf("-")!==-1&&X.indexOf("/")!==-1?this.handleRangeWithStepping(X,Q,Y,J):X.indexOf("-")!==-1?this.handleRange(X,Q,Y,J):X.indexOf("/")!==-1?this.handleStepping(X,Q,Y,J):X!==""&&this.handleNumber(X,Q,Y,J)}throwAtIllegalCharacters(Q){for(let X=0;X<Q.length;X++)if((X===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Q[X]))throw TypeError("CronPattern: configuration entry "+X+" ("+Q[X]+") contains illegal characters.")}handleNumber(Q,X,Y,J){let G=this.extractNth(Q,X),W=parseInt(G[0],10)+Y;if(isNaN(W))throw TypeError("CronPattern: "+X+" is not a number: '"+Q+"'");this.setPart(X,W,G[1]||J)}setPart(Q,X,Y){if(!Object.prototype.hasOwnProperty.call(this,Q))throw TypeError("CronPattern: Invalid part specified: "+Q);if(Q==="dayOfWeek"){if(X===7&&(X=0),X<0||X>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+X);this.setNthWeekdayOfMonth(X,Y);return}if(Q==="second"||Q==="minute"){if(X<0||X>=60)throw RangeError("CronPattern: Invalid value for "+Q+": "+X)}else if(Q==="hour"){if(X<0||X>=24)throw RangeError("CronPattern: Invalid value for "+Q+": "+X)}else if(Q==="day"){if(X<0||X>=31)throw RangeError("CronPattern: Invalid value for "+Q+": "+X)}else if(Q==="month"&&(X<0||X>=12))throw RangeError("CronPattern: Invalid value for "+Q+": "+X);this[Q][X]=Y}handleRangeWithStepping(Q,X,Y,J){let G=this.extractNth(Q,X),W=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Q+"'");let[,Z,$,K]=W,H=parseInt(Z,10)+Y,F=parseInt($,10)+Y,V=parseInt(K,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[X].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[X].length+")");if(H>F)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let q=H;q<=F;q+=V)this.setPart(X,q,G[1]||J)}extractNth(Q,X){let Y=Q,J;if(Y.includes("#")){if(X!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Y.split("#")[1],Y=Y.split("#")[0]}return[Y,J]}handleRange(Q,X,Y,J){let G=this.extractNth(Q,X),W=G[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Q+"'");let Z=parseInt(W[0],10)+Y,$=parseInt(W[1],10)+Y;if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Z>$)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let K=Z;K<=$;K++)this.setPart(X,K,G[1]||J)}handleStepping(Q,X,Y,J){let G=this.extractNth(Q,X),W=G[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Q+"'");W[0]===""&&(W[0]="*");let Z=0;W[0]!=="*"&&(Z=parseInt(W[0],10)+Y);let $=parseInt(W[1],10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[X].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[X].length+")");for(let K=Z;K<this[X].length;K+=$)this.setPart(X,K,G[1]||J)}replaceAlphaDays(Q){return Q.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Q){return Q.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Q){let X=Q.trim().toLowerCase();return X==="@yearly"||X==="@annually"?"0 0 1 1 *":X==="@monthly"?"0 0 1 * *":X==="@weekly"?"0 0 * * 0":X==="@daily"?"0 0 * * *":X==="@hourly"?"0 * * * *":Q}setNthWeekdayOfMonth(Q,X){if(typeof X!="number"&&X==="L")this.dayOfWeek[Q]=this.dayOfWeek[Q]|G80;else if(X===OP)this.dayOfWeek[Q]=OP;else if(X<6&&X>0)this.dayOfWeek[Q]=this.dayOfWeek[Q]|PY1[X-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${X}, Type: ${typeof X}`)}},wY1=[31,28,31,30,31,30,31,31,30,31,30,31],x7=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],xJ=class Q{tz;ms;second;minute;hour;day;month;year;constructor(X,Y){if(this.tz=Y,X&&X instanceof Date)if(!isNaN(X))this.fromDate(X);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(X===void 0)this.fromDate(new Date);else if(X&&typeof X=="string")this.fromString(X);else if(X instanceof Q)this.fromCronDate(X);else throw TypeError("CronDate: Invalid type ("+typeof X+") passed to CronDate constructor")}isNthWeekdayOfMonth(X,Y,J,G){let W=new Date(Date.UTC(X,Y,J)).getUTCDay(),Z=0;for(let $=1;$<=J;$++)new Date(Date.UTC(X,Y,$)).getUTCDay()===W&&Z++;if(G&OP&&PY1[Z-1]&G)return!0;if(G&G80){let $=new Date(Date.UTC(X,Y+1,0)).getUTCDate();for(let K=J+1;K<=$;K++)if(new Date(Date.UTC(X,Y,K)).getUTCDay()===W)return!1;return!0}return!1}fromDate(X){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes()+this.tz,this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply();else{let Y=g9.toTZ(X,this.tz);this.ms=X.getMilliseconds(),this.second=Y.s,this.minute=Y.i,this.hour=Y.h,this.day=Y.d,this.month=Y.m-1,this.year=Y.y}else this.ms=X.getMilliseconds(),this.second=X.getSeconds(),this.minute=X.getMinutes(),this.hour=X.getHours(),this.day=X.getDate(),this.month=X.getMonth(),this.year=X.getFullYear()}fromCronDate(X){this.tz=X.tz,this.year=X.year,this.month=X.month,this.day=X.day,this.hour=X.hour,this.minute=X.minute,this.second=X.second,this.ms=X.ms}apply(){if(this.month>11||this.day>wY1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let X=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),!0}else return!1}fromString(X){if(typeof this.tz=="number"){let Y=g9.fromTZISO(X);this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes(),this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),this.apply()}else return this.fromDate(g9.fromTZISO(X,this.tz))}findNext(X,Y,J,G){let W=this[Y],Z;J.lastDayOfMonth&&(this.month!==1?Z=wY1[this.month]:Z=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let $=!J.starDOW&&Y=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let K=this[Y]+G;K<J[Y].length;K++){let H=J[Y][K];if(Y==="day"&&J.lastDayOfMonth&&K-G==Z&&(H=1),Y==="day"&&!J.starDOW){let F=J.dayOfWeek[($+(K-G-1))%7];if(F&&F&OP)F=this.isNthWeekdayOfMonth(this.year,this.month,K-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);X.legacyMode&&!J.starDOM?H=H||F:H=H&&F}if(H)return this[Y]=K-G,W!==this[Y]?2:1}return 3}recurse(X,Y,J){let G=this.findNext(Y,x7[J][0],X,x7[J][2]);if(G>1){let W=J+1;for(;W<x7.length;)this[x7[W][0]]=-x7[W][2],W++;if(G===3)return this[x7[J][1]]++,this[x7[J][0]]=-x7[J][2],this.apply(),this.recurse(X,Y,0);if(this.apply())return this.recurse(X,Y,J-1)}return J+=1,J>=x7.length?this:this.year>=3000?null:this.recurse(X,Y,J)}increment(X,Y,J){return this.second+=Y.interval!==void 0&&Y.interval>1&&J?Y.interval:1,this.ms=0,this.apply(),this.recurse(X,Y,0)}getDate(X){return X||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):g9.fromTZ(g9.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function SS6(Q){if(Q===void 0&&(Q={}),delete Q.name,Q.legacyMode=Q.legacyMode===void 0?!0:Q.legacyMode,Q.paused=Q.paused===void 0?!1:Q.paused,Q.maxRuns=Q.maxRuns===void 0?1/0:Q.maxRuns,Q.catch=Q.catch===void 0?!1:Q.catch,Q.interval=Q.interval===void 0?0:parseInt(Q.interval.toString(),10),Q.utcOffset=Q.utcOffset===void 0?void 0:parseInt(Q.utcOffset.toString(),10),Q.unref=Q.unref===void 0?!1:Q.unref,Q.startAt&&(Q.startAt=new xJ(Q.startAt,Q.timezone)),Q.stopAt&&(Q.stopAt=new xJ(Q.stopAt,Q.timezone)),Q.interval!==null){if(isNaN(Q.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Q.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Q.utcOffset!==void 0){if(isNaN(Q.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Q.utcOffset<-870||Q.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Q.utcOffset!==void 0&&Q.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Q.unref!==!0&&Q.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Q}function NP(Q){return Object.prototype.toString.call(Q)==="[object Function]"||typeof Q=="function"||Q instanceof Function}function vS6(Q){return NP(Q)}function kS6(Q){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Q):Q&&typeof Q.unref<"u"&&Q.unref()}var MY1=30000,_y=[],yy=class{name;options;_states;fn;constructor(Q,X,Y){let J,G;if(NP(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(NP(Y))G=Y;else if(typeof Y=="object")J=Y;else if(Y!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=SS6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new LY1("* * * * *")},Q&&(Q instanceof Date||typeof Q=="string"&&Q.indexOf(":")>0)?this._states.once=new xJ(Q,this.options.timezone||this.options.utcOffset):this._states.pattern=new LY1(Q,this.options.timezone),this.name){if(_y.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");_y.push(this)}return G!==void 0&&vS6(G)&&(this.fn=G,this.schedule()),this}nextRun(Q){let X=this._next(Q);return X?X.getDate(!1):null}nextRuns(Q,X){this._states.maxRuns!==void 0&&Q>this._states.maxRuns&&(Q=this._states.maxRuns);let Y=[],J=X||this._states.currentRun||void 0;for(;Q--&&(J=this.nextRun(J));)Y.push(J);return Y}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Q=this.nextRun(this._states.currentRun),X=!this._states.paused,Y=this.fn!==void 0,J=!this._states.kill;return X&&Y&&J&&Q!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Q){let X=this._next(Q);return X?Q instanceof xJ||Q instanceof Date?X.getTime()-Q.getTime():X.getTime()-new xJ(Q).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Q=_y.indexOf(this);Q>=0&&_y.splice(Q,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Q){if(Q&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Q&&(this.fn=Q);let X=this.msToNext(),Y=this.nextRun(this._states.currentRun);return X==null||isNaN(X)||Y===null?this:(X>MY1&&(X=MY1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Y),X),this._states.currentTimeout&&this.options.unref&&kS6(this._states.currentTimeout),this)}async _trigger(Q){if(this._states.blocking=!0,this._states.currentRun=new xJ(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(X){NP(this.options.catch)&&this.options.catch(X,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new xJ(Q,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Q){let X=new Date,Y=!this._states.paused&&X.getTime()>=Q.getTime(),J=this._states.blocking&&this.options.protect;Y&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Y&&J&&NP(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Q){let X=!!(Q||this._states.currentRun),Y=!1;!Q&&this.options.startAt&&this.options.interval&&([Q,X]=this._calculatePreviousRun(Q,X),Y=!Q),Q=new xJ(Q,this.options.timezone||this.options.utcOffset),this.options.startAt&&Q&&Q.getTime()<this.options.startAt.getTime()&&(Q=this.options.startAt);let J=this._states.once||new xJ(Q,this.options.timezone||this.options.utcOffset);return!Y&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,X)),this._states.once&&this._states.once.getTime()<=Q.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Q,X){let Y=new xJ(void 0,this.options.timezone||this.options.utcOffset),J=Q;if(this.options.startAt.getTime()<=Y.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Y.getTime();)J=new xJ(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;X=!0}return J===null&&(J=void 0),[J,X]}};var by={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Ty();function TY1(){return async(Q,X)=>{try{let Y=await o$.create(),J=await HY1(Q,{...Y,auth:{...Y.auth,user:{id:"notify-worker"}}}),W=await $40.forClient(J).ON_EVENTS({events:X});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(Y){let J=Y instanceof Error?Y.message:String(Y);return console.error(`[EventBus] Failed to notify connection ${Q}:`,J),{success:!1,error:J}}}}function AY1(Q){return{specversion:"1.0",id:Q.id,source:Q.source,type:Q.type,time:Q.time,subject:Q.subject??void 0,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema??void 0,data:Q.data??void 0}}function _S6(Q){let X=new Map;for(let J of Q){let G=J.subscription.connectionId,W=X.get(G);if(W){if(W.deliveryIds.push(J.delivery.id),!W.seenEventIds.has(J.event.id))W.seenEventIds.add(J.event.id),W.events.push(AY1(J.event))}else X.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[AY1(J.event)],seenEventIds:new Set([J.event.id])})}let Y=new Map;for(let[J,G]of X)Y.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Y}class W80{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Q,X){this.storage=Q;this.notifySubscriber=TY1(),this.config={...by,...X}}async start(){if(this.running)return;let Q=await this.storage.resetStuckDeliveries();if(Q>0)console.log(`[EventBus] Reset ${Q} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(Q){console.error("[EventBus] Error processing events:",Q)}finally{this.processing=!1}}async processEvents(){let Q=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Q.length===0)return;let X=_S6(Q),Y=new Set;for(let[J,G]of X){try{let W=await this.notifySubscriber(G.connectionId,G.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(G,W);else if(W.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let Z=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${J}:`,Z),await this.storage.markDeliveriesFailed(G.deliveryIds,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of Q)if(G.deliveryIds.includes(W.delivery.id))Y.add(W.event.id)}for(let J of Y)try{await this.storage.updateEventStatus(J);let G=Q.find((W)=>W.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Q,X){let Y=[],J=new Map,G=[],W=new Map;for(let Z=0;Z<Q.events.length;Z++){let $=Q.events?.[Z];if(!$)continue;let K=Q.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of Q.events){let $=W.get(Z.id);if(!$)continue;let K=X.results?.[Z.id];if(K)if(K.success)Y.push($);else if(K.retryAfter&&K.retryAfter>0){let H=J.get(K.retryAfter)||[];H.push($),J.set(K.retryAfter,H)}else G.push({deliveryId:$,error:K.error||"Event processing failed"});else if(X.success)Y.push($);else if(X.retryAfter&&X.retryAfter>0){let H=J.get(X.retryAfter)||[];H.push($),J.set(X.retryAfter,H)}else G.push({deliveryId:$,error:X.error||"Batch processing failed"})}if(Y.length>0)await this.storage.markDeliveriesDelivered(Y);for(let[Z,$]of J)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(G.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of G){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Q){if(!Q.cron)return;try{let Y=new yy(Q.cron).nextRun();if(!Y){console.log(`[EventBus] Cron expression for event ${Q.id} has no more runs`);return}let J=Y.toISOString(),G=await this.storage.getMatchingSubscriptions(Q);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Q.id}, skipping next delivery`);return}await this.storage.createDeliveries(Q.id,G.map((W)=>W.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Q.id} at ${J}`)}catch(X){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Q.id}:`,X)}}}class Z80{storage;worker;notifyStrategy;running=!1;constructor(Q){this.storage=Q.storage,this.notifyStrategy=Q.notifyStrategy,this.worker=new W80(this.storage,Q.config)}async publish(Q,X,Y){if(Y.deliverAt&&Y.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Y.cron){try{let F=new yy(Y.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(Q,Y.type,X,Y.cron);if(K)return K}let G=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:G,organizationId:Q,type:Y.type,source:X,subject:Y.subject,time:W,data:Y.data,cron:Y.cron}),$=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=Y.deliverAt??J;if(await this.storage.createDeliveries(G,$.map((H)=>H.id),K),this.notifyStrategy&&!K)await this.notifyStrategy.notify(G).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return Z}async subscribe(Q,X){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Q,connectionId:X.connectionId,publisher:X.publisher,eventType:X.eventType,filter:X.filter})}async unsubscribe(Q,X){return this.storage.unsubscribe(X,Q)}async listSubscriptions(Q,X){return this.storage.listSubscriptions(Q,X)}async getSubscription(Q,X){return this.storage.getSubscription(X,Q)}async getEvent(Q,X){return this.storage.getEvent(X,Q)}async cancelEvent(Q,X,Y){return this.storage.cancelEvent(X,Q,Y)}async ackEvent(Q,X,Y){return this.storage.ackDelivery(X,Q,Y)}async syncSubscriptions(Q,X){return this.storage.syncSubscriptions({organizationId:Q,...X})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Q)=>{console.error("[EventBus] Error processing after notify:",Q)})});await this.worker.processNow().catch((Q)=>{console.error("[EventBus] Error processing pending events on startup:",Q)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Q){console.error("[EventBus] Error stopping notify strategy:",Q)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}function EY1(...Q){return{async start(X){await Promise.all(Q.map((Y)=>Y.start(X)))},async stop(){await Promise.all(Q.map((X)=>X.stop().catch((Y)=>{console.error("[NotifyStrategy] Error stopping strategy:",Y)})))},async notify(X){await Promise.all(Q.map((Y)=>Y.notify(X).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class fy{intervalMs;timer=null;onNotify=null;constructor(Q){this.intervalMs=Q}async start(Q){if(this.timer)return;this.onNotify=Q,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Q){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as yS6}from"kysely";var fU="mesh_events";class $80{db;pool;listenClient=null;onNotify=null;constructor(Q,X){this.db=Q;this.pool=X}async start(Q){if(this.listenClient)return;this.onNotify=Q;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(X)=>{if(X.channel===fU&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(X)=>{console.error("[PostgresNotify] Connection error:",X),this.cleanup()}),await this.listenClient.query(`LISTEN ${fU}`),console.log("[PostgresNotify] Started LISTEN on",fU)}catch(X){console.error("[PostgresNotify] Failed to start LISTEN:",X),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${fU}`),console.log("[PostgresNotify] Stopped LISTEN on",fU)}catch{}this.cleanup()}}async notify(Q){try{await yS6`SELECT pg_notify(${fU}, ${Q})`.execute(this.db)}catch(X){console.warn("[PostgresNotify] Failed to send NOTIFY:",X)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function jY1(Q,X){let Y=OY1(Q.db),J=X?.pollIntervalMs??by.pollIntervalMs,G=Q.type==="postgres"?EY1(new fy(J),new $80(Q.db,Q.pool)):new fy(J);return new Z80({storage:Y,config:X,notifyStrategy:G})}var CY1={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var IY1=new ZQ;IY1.get("/config",async(Q)=>{try{let X=Object.keys(a8.socialProviders??{}),Y=X.length>0,J=X.map((Z)=>({name:Z,icon:CY1[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:a8.emailAndPassword?.enabled??!1},magicLink:{enabled:a8.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Y,providers:J},sso:a8.ssoConfig?{enabled:!0,providerId:a8.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Q.json({success:!0,config:W})}catch(X){let Y=X instanceof Error?X.message:"Failed to load auth config";return Q.json({success:!1,error:Y},500)}});var RY1=IY1;jy();var hy=new ZQ;hy.post("/connections/:connectionId/oauth-token",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("connectionId");if(!(X.auth.user?.id??X.auth.apiKey?.userId??null))return Q.json({error:"Unauthorized"},401);if(!await X.storage.connections.findById(Y,X.organization?.id))return Q.json({error:"Connection not found"},404);let W=await Q.req.json();if(!W.accessToken)return Q.json({error:"accessToken is required"},400);if(W.tokenEndpoint){let F;try{F=new URL(W.tokenEndpoint)}catch{return Q.json({error:"tokenEndpoint must be a valid URL"},400)}if(F.protocol!=="http:"&&F.protocol!=="https:")return Q.json({error:"tokenEndpoint must be an http(s) URL"},400)}let Z=W.expiresIn?new Date(Date.now()+W.expiresIn*1000):null,$=new b7(X.db,X.vault),K={connectionId:Y,accessToken:W.accessToken,refreshToken:W.refreshToken??null,scope:W.scope??null,expiresAt:Z,clientId:W.clientId??null,clientSecret:W.clientSecret??null,tokenEndpoint:W.tokenEndpoint??null},H=await $.upsert(K);return Q.json({success:!0,expiresAt:H.expiresAt})});hy.delete("/connections/:connectionId/oauth-token",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("connectionId");if(!(X.auth.user?.id??X.auth.apiKey?.userId??null))return Q.json({error:"Unauthorized"},401);return await new b7(X.db,X.vault).delete(Y),Q.json({success:!0})});hy.get("/connections/:connectionId/oauth-token/status",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("connectionId");if(!(X.auth.user?.id??X.auth.apiKey?.userId??null))return Q.json({error:"Unauthorized"},401);let G=new b7(X.db,X.vault),W=await G.get(Y);if(!W)return Q.json({hasToken:!1,isExpired:!0,canRefresh:!1});let Z=G.isExpired(W),$=!!W.refreshToken&&!!W.tokenEndpoint;return Q.json({hasToken:!0,isExpired:Z,canRefresh:$,expiresAt:W.expiresAt})});var SY1=hy;Dy();Ny();h9();class LP{proxies=new Map;constructor(){}static async create(Q,X){let Y=new LP,J=await Promise.allSettled(Q.map(async({connection:G,selectedTools:W,selectedResources:Z,selectedPrompts:$})=>{try{let K=await X.createMCPProxy(G);return{connection:G,proxy:K,selectedTools:W,selectedResources:Z,selectedPrompts:$}}catch(K){return console.error(`[gateway] Failed to create proxy for connection ${G.id}:`,K),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Y.proxies.set(G.value.connection.id,G.value);return Y}get(Q){return this.proxies.get(Q)}entries(){return this.proxies.entries()}forEach(Q){this.proxies.forEach((X,Y)=>Q(X,Y))}async mapAsync(Q){let X=[];for(let[Y,J]of this.proxies.entries())X.push(Q(J,Y));return await Promise.all(X)}async mapSettled(Q){return Promise.allSettled(Array.from(this.proxies.entries()).map(([X,Y])=>Q(Y,X)))}get size(){return this.proxies.size}}G1();function vY1(Q){let X=[],Y=[],J=(K)=>{let H=Q.newFunction(K,(...F)=>{try{let V=F.map((q)=>Q.dump(q));X.push({type:K??"log",content:V.map(String).join(" ")})}finally{F.forEach((V)=>V.dispose())}return Q.undefined});return Y.push(H),H},G=Q.newObject();Y.push(G);let W=J("log"),Z=J("warn"),$=J("error");return Q.setProp(G,"log",W),Q.setProp(G,"warn",Z),Q.setProp(G,"error",$),Q.setProp(Q.global,"console",G),{logs:X,[Symbol.dispose](){Y.forEach((K)=>K.dispose())}}}T80();gy();async function QJ1(Q){let X=A80(await Q),[Y,J,{QuickJSWASMModule:G}]=await Promise.all([X.importModuleLoader().then(A80),X.importFFI(),Promise.resolve().then(() => (eY1(),tY1)).then(A80)]),W=await Y();W.type="sync";let Z=new J(W);return new G(W,Z)}function A80(Q){return Q&&"default"in Q&&Q.default?Q.default&&"default"in Q.default&&Q.default.default?Q.default.default:Q.default:Q}var rS6={type:"sync",importFFI:()=>Promise.resolve().then(() => (YJ1(),XJ1)).then((Q)=>Q.QuickJSFFI),importModuleLoader:()=>Promise.resolve().then(() => (GJ1(),JJ1)).then((Q)=>Q.default)},WJ1=rS6;var ZJ1;function $J1(){return ZJ1??=QJ1(WJ1),ZJ1}async function KJ1(Q={}){let Y=(await $J1()).newRuntime({maxStackSizeBytes:Q.stackSizeBytes,memoryLimitBytes:Q.memoryLimitBytes});return{newContext:({interruptAfterMs:G,...W}={})=>{let Z=Y.newContext({intrinsics:{...O80,...W}}),$=0,K=(H)=>{$=H?Date.now()+H:0};if(Y.setInterruptHandler(()=>{let H=Date.now(),F=$>0&&H>$;return F}),G)K(G);return Z},dispose:()=>{Y.dispose()},[Symbol.dispose](){Y.dispose()}}}function xU(Q){if(Q===null)return"null";if(Q===void 0)return"undefined";if(Q instanceof Error){let X=Q.message||Q.name||"Error";if(Q.stack&&Q.stack.length<2000)return`${X}
|
|
1040
1040
|
${Q.stack}`;return X}if(typeof Q==="object"&&Q!==null){let X=Q,Y="";if(typeof X.message==="string"&&X.message)Y=X.message;else if(typeof X.error==="string"&&X.error)Y=X.error;else if(typeof X.description==="string"&&X.description)Y=X.description;else if(typeof X.reason==="string"&&X.reason)Y=X.reason;if(Y){if(typeof X.stack==="string"&&X.stack&&X.stack.length<2000)return`${Y}
|
|
1041
1041
|
${X.stack}`;return Y}try{let G=JSON.stringify(X,null,2);if(G!=="{}"&&G.length<1000){if(typeof X.stack==="string"&&X.stack&&X.stack.length<2000)return`${G}
|
|
1042
1042
|
|
|
1043
1043
|
Stack trace:
|
|
1044
|
-
${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Q==="string")return Q;if(typeof Q==="number"||typeof Q==="boolean")return String(Q);if(typeof Q==="function")return`[Function: ${Q.name||"anon"}]`;if(typeof Q==="symbol")return Q.toString();if(typeof Q==="bigint")return Q.toString();try{return String(Q)}catch{return"Unknown value (could not convert to string)"}}function gU(Q,X){switch(typeof X){case"string":return Q.newString(X);case"number":return Q.newNumber(X);case"boolean":return X?Q.true:Q.false;case"undefined":return Q.undefined;case"object":{if(X===null)return Q.null;if(Array.isArray(X)){let J=Q.newArray();return X.forEach((G,W)=>{let Z=gU(Q,G);try{Q.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Y=Q.newObject();for(let[J,G]of Object.entries(X)){let W=gU(Q,G);try{Q.setProp(Y,J,W)}finally{W.dispose?.()}}return Y}case"function":{let Y=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Q.newFunction(Y,(...G)=>{try{let W=G.map(($)=>Q.dump($)),Z=X(...W);if(Z&&typeof Z.then==="function"){let $=Q.newPromise();return Z.then((K)=>{try{let H=gU(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=xU(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=xU(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return gU(Q,Z)}catch(W){let Z=xU(W);return Q.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.dispose())}})}case"bigint":return Q.newString(X.toString());case"symbol":return Q.newString(X.toString());default:try{return Q.newString(String(X))}catch{return Q.undefined}}}var oS6=(Q)=>new Promise((X)=>setTimeout(X,Q));function FJ1(Q){let X=Q.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function HJ1(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){FJ1(Q);let W=await Promise.race([G,oS6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Y)throw Error(`Timed out after ${Y}ms while awaiting a QuickJS promise`)}}async function j80({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await KJ1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Hb(Z,J.newContext({interruptAfterMs:Y}),0);const W=Hb(Z,vY1(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=gU(G,Q);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await HJ1(G,V,Y)):V;if(z!==V)V.dispose();let B=G.getProp(z,"default"),D=G.typeof(B);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(B,G.undefined,q),M=G.unwrapResult(L),C=await HJ1(G,M,Y),A=G.unwrapResult(C);if(G.runtime.hasPendingJob())FJ1(G);return{returnValue:G.dump(A),consoleLogs:W.logs}}catch(F){return console.log(F),{error:xU(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{qQ0(Z,K,H)}}function sS6(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function tS6(Q,X){let Y=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),W=X._meta.connectionTitle.toLowerCase();for(let Z of Q){if(J===Z)Y+=10;else if(J.includes(Z))Y+=3;if(G.includes(Z))Y+=2;if(W.includes(Z))Y+=1}return Y}function eS6(Q,X,Y){let J=sS6(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:tS6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function C80(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function MP(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function VJ1(Q){let X=N.object({query:N.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:N.number().default(10).describe("Maximum results to return (default: 10)")});return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:""} Total tools: ${Q.tools.length}.`,inputSchema:N.toJSONSchema(X)},handler:async(J)=>{let G=X.safeParse(J);if(!G.success)return MP({error:G.error.flatten()});let W=eS6(G.data.query,Q.tools,G.data.limit);return C80({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function qJ1(Q){let X=N.object({tools:N.array(N.string()).min(1).describe("Array of tool names to get detailed schemas for")});return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return MP({error:J.error.flatten()});let G=new Map(Q.tools.map((Z)=>[Z.name,Z])),W=J.data.tools.map((Z)=>G.get(Z)).filter((Z)=>Z!==void 0);return C80({tools:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle,inputSchema:Z.inputSchema,outputSchema:Z.outputSchema})),notFound:J.data.tools.filter((Z)=>!G.has(Z))})}}}function Qv6(Q){let X=Q.tools.map((G)=>G.name),Y=new Map(Q.tools.map((G)=>[G.name,G])),J=N.object({name:N.enum(X).describe("The name of the tool to execute"),arguments:N.record(N.string(),N.unknown()).default({}).describe("Arguments to pass to the tool")});return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:N.toJSONSchema(J)},handler:async(G)=>{let W=J.safeParse(G);if(!W.success)return MP({error:W.error.flatten()});let{name:Z,arguments:$}=W.data;if(!Y.has(Z))return{content:[{type:"text",text:`Tool not found: ${Z}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return Q.callTool(Z,$)}}}function Xv6(Q){let X=N.object({code:N.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:N.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")});return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return MP({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await j80({...J.data,tools:G});if(W.error)return MP(W);return C80(W)}}}function zJ1(Q){let X=new Map(Q.map((J)=>[J.tool.name,J.handler])),Y=Q.map((J)=>J.tool.name);return{tools:Q.map((J)=>J.tool),callTool:async(J,G)=>{let W=X.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Y.join(", ")}`}],isError:!0};return W(G)}}}var Yv6=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),Jv6=(Q)=>zJ1([VJ1(Q),qJ1(Q),Xv6(Q)]),Gv6=(Q)=>zJ1([VJ1(Q),qJ1(Q),Qv6(Q)]);function UJ1(Q){switch(Q){case"smart_tool_selection":return Gv6;case"code_execution":return Jv6;case"passthrough":default:return Yv6}}class my{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){return console.error(`[gateway] Failed to list tools for connection ${H}:`,F),null}}),X=new Set,Y=[],J=new Map,G=new Set;for(let K of Q){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(X.has(q.name))continue;X.add(q.name),Y.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=UJ1(this.options.strategy)({tools:Y,callTool:W,categories:Array.from(G).sort()});return{tools:Y,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(Q){return(await this.cache).strategyResult.callTool(Q.name,Q.arguments??{})}async callStreamable(Q,X){let Y=await this.cache,J=Y.mappings.get(Q);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,X)}let G=await Y.strategyResult.callTool(Q,X);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}function Wv6(Q,X){if(Q===X)return!0;if(!X.includes("*"))return!1;let Y=X.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Y=`^${Y}$`;try{return new RegExp(Y).test(Q)}catch{return!1}}function BJ1(Q,X){return X.some((Y)=>Wv6(Q,Y))}class ly{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!BJ1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>BJ1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){return console.error(`[gateway] Failed to list resources for connection ${W}:`,Z),{connectionId:W,resources:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(X.has($.uri))continue;X.add($.uri),Y.push($),J.set($.uri,W)}}return{resources:Y,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(Q){let Y=(await this.cache).mappings.get(Q.uri);if(!Y)throw Error(`Resource not found: ${Q.uri}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for resource: ${Q.uri}`);return await J.proxy.client.readResource(Q)}}class dy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=GW(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(Y,J)=>{try{let G=await Y.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){return console.error(`[gateway] Failed to list resource templates for connection ${J}:`,G),{connectionId:J,templates:[]}}}),X=[];for(let Y of Q){if(Y.status!=="fulfilled")continue;let{templates:J}=Y.value;for(let G of J)X.push(G)}return{templates:X}}async list(){return{resourceTemplates:(await this.cache).templates}}}class py{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptGateway] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(X.has($.name))continue;X.add($.name),Y.push($),J.set($.name,W)}}return{prompts:Y,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let Y=(await this.cache).mappings.get(Q.name);if(!Y)throw Error(`Prompt not found: ${Q.name}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for prompt: ${Q.name}`);return await J.proxy.client.getPrompt(Q)}}var DJ1=new ZQ;async function Zv6(Q,X){let Y=await LP.create(Q.connections,X),J=new my(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new ly(Y,{selectionMode:Q.toolSelectionMode}),W=new dy(Y),Z=new py(Y,{selectionMode:Q.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function $v6(Q,X){let Y;if(Q.toolSelectionMode==="exclusion"){let W=(await X.storage.connections.list(Q.organizationId)).filter(($)=>$.status==="active"),Z=new Map;for(let $ of Q.connections)Z.set($.connectionId,{selectedTools:$.selectedTools,selectedResources:$.selectedResources,selectedPrompts:$.selectedPrompts});Y=[];for(let $ of W){let K=Z.get($.id);if(K===void 0)Y.push({connection:$,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((K.selectedTools===null||K.selectedTools.length===0)&&(K.selectedResources===null||K.selectedResources.length===0)&&(K.selectedPrompts===null||K.selectedPrompts.length===0));else Y.push({connection:$,selectedTools:K.selectedTools,selectedResources:K.selectedResources,selectedPrompts:K.selectedPrompts})}}else{let G=Q.connections.map((Z)=>Z.connectionId),W=[];for(let Z of G){let $=await X.storage.connections.findById(Z);if($&&$.status==="active")W.push($)}Y=W.map((Z)=>{let $=Q.connections.find((K)=>K.connectionId===Z.id);return{connection:Z,selectedTools:$?.selectedTools??null,selectedResources:$?.selectedResources??null,selectedPrompts:$?.selectedPrompts??null}})}let J={connections:Y,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Q.toolSelectionStrategy};return Zv6(J,X)}DJ1.all("/gateway/:gatewayId?",async(Q)=>{let X=Q.req.param("gatewayId"),Y=Q.get("meshContext");try{let J=null;if(X)J=await Y.storage.gateways.findById(X);else{let K=Q.req.header("x-org-id"),H=Q.req.header("x-org-slug");if(K)J=await Y.storage.gateways.getDefaultByOrgId(K);else if(H)J=await Y.storage.gateways.getDefaultByOrgSlug(H);else return Q.json({error:"Agent ID required, or provide x-org-id or x-org-slug header for Organization Agent"},400)}if(!J){if(X)return Q.json({error:`Agent not found: ${X}`},404);return Q.json({error:"No Organization Agent configured for this organization"},404)}if(Y.gatewayId=J.id,J.status!=="active")return Q.json({error:`Agent is inactive: ${J.id}`},503);let G=await Y.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",J.organizationId).executeTakeFirst();if(G)Y.organization={id:G.id,slug:G.slug,name:G.name};let W=await $v6(J,Y),Z=new s3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),$=new t3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await Z.connect($),Z.server.setRequestHandler(b$,async(K)=>{return W.client.listTools()}),Z.server.setRequestHandler(eG,async(K)=>{return await W.client.callTool(K.params)}),Z.server.setRequestHandler(S$,async()=>{return W.client.listResources()}),Z.server.setRequestHandler(k$,async(K)=>{return W.client.readResource(K.params)}),Z.server.setRequestHandler(v$,async()=>{return W.client.listResourceTemplates()}),Z.server.setRequestHandler(_$,async()=>{return W.client.listPrompts()}),Z.server.setRequestHandler(y$,async(K)=>{return W.client.getPrompt(K.params)}),await $.handleRequest(Q.req.raw)}catch(J){let G=J;return console.error("[gateway] Error handling gateway request:",G),Q.json({error:"Internal server error",message:G.message},500)}});var NJ1=DJ1;r40();var OJ1=new ZQ;OJ1.all("/",async(Q)=>{return a40(Q.get("meshContext")).fetch(Q.req.raw)});var LJ1=OJ1;H40();zU();iM();h9();var aJ1="vercel.ai.error",Kv6=Symbol.for(aJ1),wJ1,MJ1,L1=class Q extends(MJ1=Error,wJ1=Kv6,MJ1){constructor({name:X,message:Y,cause:J}){super(Y);this[wJ1]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,aJ1)}static hasMarker(X,Y){let J=Symbol.for(Y);return X!=null&&typeof X==="object"&&J in X&&typeof X[J]==="boolean"&&X[J]===!0}},rJ1="AI_APICallError",oJ1=`vercel.ai.error.${rJ1}`,Hv6=Symbol.for(oJ1),PJ1,TJ1,r8=class extends(TJ1=L1,PJ1=Hv6,TJ1){constructor({message:Q,url:X,requestBodyValues:Y,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:rJ1,message:Q,cause:Z});this[PJ1]=!0,this.url=X,this.requestBodyValues=Y,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(Q){return L1.hasMarker(Q,oJ1)}},sJ1="AI_EmptyResponseBodyError",tJ1=`vercel.ai.error.${sJ1}`,Fv6=Symbol.for(tJ1),AJ1,EJ1,eJ1=class extends(EJ1=L1,AJ1=Fv6,EJ1){constructor({message:Q="Empty response body"}={}){super({name:sJ1,message:Q});this[AJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,tJ1)}};function _5(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}var Q51="AI_InvalidArgumentError",X51=`vercel.ai.error.${Q51}`,Vv6=Symbol.for(X51),jJ1,CJ1,Y51=class extends(CJ1=L1,jJ1=Vv6,CJ1){constructor({message:Q,cause:X,argument:Y}){super({name:Q51,message:Q,cause:X});this[jJ1]=!0,this.argument=Y}static isInstance(Q){return L1.hasMarker(Q,X51)}},J51="AI_InvalidPromptError",G51=`vercel.ai.error.${J51}`,qv6=Symbol.for(G51),IJ1,RJ1,JF=class extends(RJ1=L1,IJ1=qv6,RJ1){constructor({prompt:Q,message:X,cause:Y}){super({name:J51,message:`Invalid prompt: ${X}`,cause:Y});this[IJ1]=!0,this.prompt=Q}static isInstance(Q){return L1.hasMarker(Q,G51)}},W51="AI_InvalidResponseDataError",Z51=`vercel.ai.error.${W51}`,zv6=Symbol.for(Z51),SJ1,vJ1,Lm4=class extends(vJ1=L1,SJ1=zv6,vJ1){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:W51,message:X});this[SJ1]=!0,this.data=Q}static isInstance(Q){return L1.hasMarker(Q,Z51)}},$51="AI_JSONParseError",K51=`vercel.ai.error.${$51}`,Uv6=Symbol.for(K51),kJ1,_J1,PP=class extends(_J1=L1,kJ1=Uv6,_J1){constructor({text:Q,cause:X}){super({name:$51,message:`JSON parsing failed: Text: ${Q}.
|
|
1045
|
-
Error message: ${_5(X)}`,cause:X});this[
|
|
1046
|
-
Error message: ${_5(Y)}`,cause:Y});this[pJ1]=!0,this.value=X}static isInstance(X){return L1.hasMarker(X,w51)}static wrap({value:X,cause:Y}){return Q.isInstance(Y)&&Y.value===X?Y:new Q({value:X,cause:Y})}},M51="AI_UnsupportedFunctionalityError",P51=`vercel.ai.error.${M51}`,Mv6=Symbol.for(P51),nJ1,iJ1,T51=class extends(iJ1=L1,nJ1=Mv6,iJ1){constructor({functionality:Q,message:X=`'${Q}' functionality not supported.`}){super({name:M51,message:X});this[nJ1]=!0,this.functionality=Q}static isInstance(Q){return L1.hasMarker(Q,P51)}};r6();C$();C$();C$();l60();function WF(...Q){return Q.reduce((X,Y)=>({...X,...Y!=null?Y:{}}),{})}async function S51(Q,X){if(Q==null)return Promise.resolve();let Y=X==null?void 0:X.abortSignal;return new Promise((J,G)=>{if(Y==null?void 0:Y.aborted){G(A51());return}let W=setTimeout(()=>{Z(),J()},Q),Z=()=>{clearTimeout(W),Y==null||Y.removeEventListener("abort",$)},$=()=>{Z(),G(A51())};Y==null||Y.addEventListener("abort",$)})}function A51(){return new DOMException("Delay was aborted","AbortError")}var ZF=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){if(this._promise)return this._promise;return this._promise=new Promise((Q,X)=>{if(this.status.type==="resolved")Q(this.status.value);else if(this.status.type==="rejected")X(this.status.error);this._resolve=Q,this._reject=X}),this._promise}resolve(Q){var X;if(this.status={type:"resolved",value:Q},this._promise)(X=this._resolve)==null||X.call(this,Q)}reject(Q){var X;if(this.status={type:"rejected",error:Q},this._promise)(X=this._reject)==null||X.call(this,Q)}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function TP(Q){return Object.fromEntries([...Q.headers])}var{btoa:Pv6,atob:Tv6}=globalThis;function uU(Q){let X=Q.replace(/-/g,"+").replace(/_/g,"/"),Y=Tv6(X);return Uint8Array.from(Y,(J)=>J.codePointAt(0))}function $F(Q){let X="";for(let Y=0;Y<Q.length;Y++)X+=String.fromCodePoint(Q[Y]);return Pv6(X)}var v51="AI_DownloadError",k51=`vercel.ai.error.${v51}`,Av6=Symbol.for(k51),E51,j51,cy=class extends(j51=L1,E51=Av6,j51){constructor({url:Q,statusCode:X,statusText:Y,cause:J,message:G=J==null?`Failed to download ${Q}: ${X} ${Y}`:`Failed to download ${Q}: ${J}`}){super({name:v51,message:G,cause:J});this[E51]=!0,this.url=Q,this.statusCode=X,this.statusText=Y}static isInstance(Q){return L1.hasMarker(Q,k51)}};var WW=({prefix:Q,size:X=16,alphabet:Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:J="-"}={})=>{let G=()=>{let W=Y.length,Z=Array(X);for(let $=0;$<X;$++)Z[$]=Y[Math.random()*W|0];return Z.join("")};if(Q==null)return G;if(Y.includes(J))throw new Y51({argument:"separator",message:`The separator "${J}" must not be part of the alphabet "${Y}".`});return()=>`${Q}${J}${G()}`},Ev6=WW();function AP(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}function u7(Q){return(Q instanceof Error||Q instanceof DOMException)&&(Q.name==="AbortError"||Q.name==="ResponseAborted"||Q.name==="TimeoutError")}var jv6=["fetch failed","failed to fetch"];function _51({error:Q,url:X,requestBodyValues:Y}){if(u7(Q))return Q;if(Q instanceof TypeError&&jv6.includes(Q.message.toLowerCase())){let J=Q.cause;if(J!=null)return new r8({message:`Cannot connect to API: ${J.message}`,cause:J,url:X,requestBodyValues:Y,isRetryable:!0})}return Q}function ny(Q=globalThis){var X,Y,J;if(Q.window)return"runtime/browser";if((X=Q.navigator)==null?void 0:X.userAgent)return`runtime/${Q.navigator.userAgent.toLowerCase()}`;if((J=(Y=Q.process)==null?void 0:Y.versions)==null?void 0:J.node)return`runtime/node.js/${Q.process.version.substring(0)}`;if(Q.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function Cv6(Q){if(Q==null)return{};let X={};if(Q instanceof Headers)Q.forEach((Y,J)=>{X[J.toLowerCase()]=Y});else{if(!Array.isArray(Q))Q=Object.entries(Q);for(let[Y,J]of Q)if(J!=null)X[Y.toLowerCase()]=J}return X}function t$(Q,...X){let Y=new Headers(Cv6(Q)),J=Y.get("user-agent")||"";return Y.set("user-agent",[J,...X].filter(Boolean).join(" ")),Object.fromEntries(Y.entries())}var y51="4.0.4",Iv6=()=>globalThis.fetch,k80=async({url:Q,headers:X={},successfulResponseHandler:Y,failedResponseHandler:J,abortSignal:G,fetch:W=Iv6()})=>{try{let Z=await W(Q,{method:"GET",headers:t$(X,`ai-sdk/provider-utils/${y51}`,ny()),signal:G}),$=TP(Z);if(!Z.ok){let K;try{K=await J({response:Z,url:Q,requestBodyValues:{}})}catch(H){if(u7(H)||r8.isInstance(H))throw H;throw new r8({message:"Failed to process error response",cause:H,statusCode:Z.status,url:Q,responseHeaders:$,requestBodyValues:{}})}throw K.value}try{return await Y({response:Z,url:Q,requestBodyValues:{}})}catch(K){if(K instanceof Error){if(u7(K)||r8.isInstance(K))throw K}throw new r8({message:"Failed to process successful response",cause:K,statusCode:Z.status,url:Q,responseHeaders:$,requestBodyValues:{}})}}catch(Z){throw _51({error:Z,url:Q,requestBodyValues:{}})}};function b51(Q){return Q!=null}function f51({mediaType:Q,url:X,supportedUrls:Y}){return X=X.toLowerCase(),Q=Q.toLowerCase(),Object.entries(Y).map(([J,G])=>{let W=J.toLowerCase();return W==="*"||W==="*/*"?{mediaTypePrefix:"",regexes:G}:{mediaTypePrefix:W.replace(/\*/,""),regexes:G}}).filter(({mediaTypePrefix:J})=>Q.startsWith(J)).flatMap(({regexes:J})=>J).some((J)=>J.test(X))}function EP({settingValue:Q,environmentVariableName:X}){if(typeof Q==="string")return Q;if(Q!=null||typeof process>"u")return;if(Q=process.env[X],Q==null||typeof Q!=="string")return;return Q}var Rv6=/"__proto__"\s*:/,Sv6=/"constructor"\s*:/;function C51(Q){let X=JSON.parse(Q);if(X===null||typeof X!=="object")return X;if(Rv6.test(Q)===!1&&Sv6.test(Q)===!1)return X;return vv6(X)}function vv6(Q){let X=[Q];while(X.length){let Y=X;X=[];for(let J of Y){if(Object.prototype.hasOwnProperty.call(J,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(J,"constructor")&&Object.prototype.hasOwnProperty.call(J.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let G in J){let W=J[G];if(W&&typeof W==="object")X.push(W)}}}return Q}function h51(Q){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(Y){return C51(Q)}try{return C51(Q)}finally{Error.stackTraceLimit=X}}function x51(Q){if(Q.type==="object"||Array.isArray(Q.type)&&Q.type.includes("object")){Q.additionalProperties=!1;let{properties:Y}=Q;if(Y!=null)for(let J of Object.keys(Y))Y[J]=GF(Y[J])}if(Q.items!=null)Q.items=Array.isArray(Q.items)?Q.items.map(GF):GF(Q.items);if(Q.anyOf!=null)Q.anyOf=Q.anyOf.map(GF);if(Q.allOf!=null)Q.allOf=Q.allOf.map(GF);if(Q.oneOf!=null)Q.oneOf=Q.oneOf.map(GF);let{definitions:X}=Q;if(X!=null)for(let Y of Object.keys(X))X[Y]=GF(X[Y]);return Q}function GF(Q){if(typeof Q==="boolean")return Q;return x51(Q)}var kv6=Symbol("Let zodToJsonSchema decide on which parser to use"),I51={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},_v6=(Q)=>typeof Q==="string"?{...I51,name:Q}:{...I51,...Q};function fY(){return{}}function yv6(Q,X){var Y,J,G;let W={type:"array"};if(((Y=Q.type)==null?void 0:Y._def)&&((G=(J=Q.type)==null?void 0:J._def)==null?void 0:G.typeName)!==E0.ZodAny)W.items=b4(Q.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Q.minLength)W.minItems=Q.minLength.value;if(Q.maxLength)W.maxItems=Q.maxLength.value;if(Q.exactLength)W.minItems=Q.exactLength.value,W.maxItems=Q.exactLength.value;return W}function bv6(Q){let X={type:"integer",format:"int64"};if(!Q.checks)return X;for(let Y of Q.checks)switch(Y.kind){case"min":if(Y.inclusive)X.minimum=Y.value;else X.exclusiveMinimum=Y.value;break;case"max":if(Y.inclusive)X.maximum=Y.value;else X.exclusiveMaximum=Y.value;break;case"multipleOf":X.multipleOf=Y.value;break}return X}function fv6(){return{type:"boolean"}}function g51(Q,X){return b4(Q.type._def,X)}var hv6=(Q,X)=>{return b4(Q.innerType._def,X)};function u51(Q,X,Y){let J=Y!=null?Y:X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>u51(Q,X,G))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xv6(Q)}}var xv6=(Q)=>{let X={type:"integer",format:"unix-time"};for(let Y of Q.checks)switch(Y.kind){case"min":X.minimum=Y.value;break;case"max":X.maximum=Y.value;break}return X};function gv6(Q,X){return{...b4(Q.innerType._def,X),default:Q.defaultValue()}}function uv6(Q,X){return X.effectStrategy==="input"?b4(Q.schema._def,X):fY()}function mv6(Q){return{type:"string",enum:Array.from(Q.values)}}var lv6=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function dv6(Q,X){let Y=[b4(Q.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),b4(Q.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Y.forEach((G)=>{if(lv6(G))J.push(...G.allOf);else{let W=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:Z,...$}=G;W=$}J.push(W)}}),J.length?{allOf:J}:void 0}function pv6(Q){let X=typeof Q.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Q.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Q.value}}var I80=void 0,b5={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(I80===void 0)I80=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return I80},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function m51(Q,X){let Y={type:"string"};if(Q.checks)for(let J of Q.checks)switch(J.kind){case"min":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,J.value):J.value;break;case"max":Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,J.value):J.value;break;case"email":switch(X.emailStrategy){case"format:email":f5(Y,"email",J.message,X);break;case"format:idn-email":f5(Y,"idn-email",J.message,X);break;case"pattern:zod":LX(Y,b5.email,J.message,X);break}break;case"url":f5(Y,"uri",J.message,X);break;case"uuid":f5(Y,"uuid",J.message,X);break;case"regex":LX(Y,J.regex,J.message,X);break;case"cuid":LX(Y,b5.cuid,J.message,X);break;case"cuid2":LX(Y,b5.cuid2,J.message,X);break;case"startsWith":LX(Y,RegExp(`^${R80(J.value,X)}`),J.message,X);break;case"endsWith":LX(Y,RegExp(`${R80(J.value,X)}$`),J.message,X);break;case"datetime":f5(Y,"date-time",J.message,X);break;case"date":f5(Y,"date",J.message,X);break;case"time":f5(Y,"time",J.message,X);break;case"duration":f5(Y,"duration",J.message,X);break;case"length":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,J.value):J.value,Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,J.value):J.value;break;case"includes":{LX(Y,RegExp(R80(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")f5(Y,"ipv4",J.message,X);if(J.version!=="v4")f5(Y,"ipv6",J.message,X);break}case"base64url":LX(Y,b5.base64url,J.message,X);break;case"jwt":LX(Y,b5.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")LX(Y,b5.ipv4Cidr,J.message,X);if(J.version!=="v4")LX(Y,b5.ipv6Cidr,J.message,X);break}case"emoji":LX(Y,b5.emoji(),J.message,X);break;case"ulid":{LX(Y,b5.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{f5(Y,"binary",J.message,X);break}case"contentEncoding:base64":{Y.contentEncoding="base64";break}case"pattern:zod":{LX(Y,b5.base64,J.message,X);break}}break}case"nanoid":LX(Y,b5.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Y}function R80(Q,X){return X.patternStrategy==="escape"?nv6(Q):Q}var cv6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function nv6(Q){let X="";for(let Y=0;Y<Q.length;Y++){if(!cv6.has(Q[Y]))X+="\\";X+=Q[Y]}return X}function f5(Q,X,Y,J){var G;if(Q.format||((G=Q.anyOf)==null?void 0:G.some((W)=>W.format))){if(!Q.anyOf)Q.anyOf=[];if(Q.format)Q.anyOf.push({format:Q.format}),delete Q.format;Q.anyOf.push({format:X,...Y&&J.errorMessages&&{errorMessage:{format:Y}}})}else Q.format=X}function LX(Q,X,Y,J){var G;if(Q.pattern||((G=Q.allOf)==null?void 0:G.some((W)=>W.pattern))){if(!Q.allOf)Q.allOf=[];if(Q.pattern)Q.allOf.push({pattern:Q.pattern}),delete Q.pattern;Q.allOf.push({pattern:R51(X,J),...Y&&J.errorMessages&&{errorMessage:{pattern:Y}}})}else Q.pattern=R51(X,J)}function R51(Q,X){var Y;if(!X.applyRegexFlags||!Q.flags)return Q.source;let J={i:Q.flags.includes("i"),m:Q.flags.includes("m"),s:Q.flags.includes("s")},G=J.i?Q.source.toLowerCase():Q.source,W="",Z=!1,$=!1,K=!1;for(let H=0;H<G.length;H++){if(Z){W+=G[H],Z=!1;continue}if(J.i){if($){if(G[H].match(/[a-z]/)){if(K)W+=G[H],W+=`${G[H-2]}-${G[H]}`.toUpperCase(),K=!1;else if(G[H+1]==="-"&&((Y=G[H+2])==null?void 0:Y.match(/[a-z]/)))W+=G[H],K=!0;else W+=`${G[H]}${G[H].toUpperCase()}`;continue}}else if(G[H].match(/[a-z]/)){W+=`[${G[H]}${G[H].toUpperCase()}]`;continue}}if(J.m){if(G[H]==="^"){W+=`(^|(?<=[\r
|
|
1044
|
+
${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Q==="string")return Q;if(typeof Q==="number"||typeof Q==="boolean")return String(Q);if(typeof Q==="function")return`[Function: ${Q.name||"anon"}]`;if(typeof Q==="symbol")return Q.toString();if(typeof Q==="bigint")return Q.toString();try{return String(Q)}catch{return"Unknown value (could not convert to string)"}}function gU(Q,X){switch(typeof X){case"string":return Q.newString(X);case"number":return Q.newNumber(X);case"boolean":return X?Q.true:Q.false;case"undefined":return Q.undefined;case"object":{if(X===null)return Q.null;if(Array.isArray(X)){let J=Q.newArray();return X.forEach((G,W)=>{let Z=gU(Q,G);try{Q.setProp(J,String(W),Z)}finally{Z.dispose?.()}}),J}let Y=Q.newObject();for(let[J,G]of Object.entries(X)){let W=gU(Q,G);try{Q.setProp(Y,J,W)}finally{W.dispose?.()}}return Y}case"function":{let Y=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Q.newFunction(Y,(...G)=>{try{let W=G.map(($)=>Q.dump($)),Z=X(...W);if(Z&&typeof Z.then==="function"){let $=Q.newPromise();return Z.then((K)=>{try{let H=gU(Q,K);$.resolve(H),H.dispose(),Q.runtime.executePendingJobs()}catch(H){let F=xU(H),V=Q.newString(`Promise resolution error: ${F}`);$.reject(V),V.dispose(),Q.runtime.executePendingJobs()}}).catch((K)=>{let H=xU(K),F=Q.newString(`Promise rejection: ${H}`);$.reject(F),F.dispose(),Q.runtime.executePendingJobs()}),$.handle}return gU(Q,Z)}catch(W){let Z=xU(W);return Q.newString(`HostFunctionError: ${Z}`)}finally{G.forEach((W)=>W.dispose())}})}case"bigint":return Q.newString(X.toString());case"symbol":return Q.newString(X.toString());default:try{return Q.newString(String(X))}catch{return Q.undefined}}}var oS6=(Q)=>new Promise((X)=>setTimeout(X,Q));function FJ1(Q){let X=Q.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function HJ1(Q,X,Y){let J=Date.now(),G=Q.resolvePromise(X);while(!0){FJ1(Q);let W=await Promise.race([G,oS6(0).then(()=>null)]);if(W!==null)return W;if(Date.now()-J>Y)throw Error(`Timed out after ${Y}ms while awaiting a QuickJS promise`)}}async function E80({tools:Q,code:X,timeoutMs:Y}){let Z=[];try{let J=await KJ1({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=Hb(Z,J.newContext({interruptAfterMs:Y}),0);const W=Hb(Z,vY1(G),0);try{let F=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=gU(G,Q);G.setProp(G.global,"tools",q);let z=G.runtime.hasPendingJob()?G.unwrapResult(await HJ1(G,V,Y)):V;if(z!==V)V.dispose();let B=G.getProp(z,"default"),D=G.typeof(B);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:W.logs};let L=G.callFunction(B,G.undefined,q),M=G.unwrapResult(L),C=await HJ1(G,M,Y),A=G.unwrapResult(C);if(G.runtime.hasPendingJob())FJ1(G);return{returnValue:G.dump(A),consoleLogs:W.logs}}catch(F){return console.log(F),{error:xU(F),consoleLogs:W.logs}}}catch($){var K=$,H=1}finally{qQ0(Z,K,H)}}function sS6(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function tS6(Q,X){let Y=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),W=X._meta.connectionTitle.toLowerCase();for(let Z of Q){if(J===Z)Y+=10;else if(J.includes(Z))Y+=3;if(G.includes(Z))Y+=2;if(W.includes(Z))Y+=1}return Y}function eS6(Q,X,Y){let J=sS6(Q);if(J.length===0)return X.slice(0,Y);return X.map((G)=>({tool:G,score:tS6(J,G)})).filter((G)=>G.score>0).sort((G,W)=>W.score-G.score).slice(0,Y).map((G)=>G.tool)}function j80(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}function MP(Q){return{content:[{type:"text",text:JSON.stringify(Q,null,2)}],isError:!0}}function VJ1(Q){let X=N.object({query:N.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:N.number().default(10).describe("Maximum results to return (default: 10)")});return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:""} Total tools: ${Q.tools.length}.`,inputSchema:N.toJSONSchema(X)},handler:async(J)=>{let G=X.safeParse(J);if(!G.success)return MP({error:G.error.flatten()});let W=eS6(G.data.query,Q.tools,G.data.limit);return j80({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Q.tools.length})}}}function qJ1(Q){let X=N.object({tools:N.array(N.string()).min(1).describe("Array of tool names to get detailed schemas for")});return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return MP({error:J.error.flatten()});let G=new Map(Q.tools.map((Z)=>[Z.name,Z])),W=J.data.tools.map((Z)=>G.get(Z)).filter((Z)=>Z!==void 0);return j80({tools:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle,inputSchema:Z.inputSchema,outputSchema:Z.outputSchema})),notFound:J.data.tools.filter((Z)=>!G.has(Z))})}}}function Qv6(Q){let X=Q.tools.map((G)=>G.name),Y=new Map(Q.tools.map((G)=>[G.name,G])),J=N.object({name:N.enum(X).describe("The name of the tool to execute"),arguments:N.record(N.string(),N.unknown()).default({}).describe("Arguments to pass to the tool")});return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:N.toJSONSchema(J)},handler:async(G)=>{let W=J.safeParse(G);if(!W.success)return MP({error:W.error.flatten()});let{name:Z,arguments:$}=W.data;if(!Y.has(Z))return{content:[{type:"text",text:`Tool not found: ${Z}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return Q.callTool(Z,$)}}}function Xv6(Q){let X=N.object({code:N.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:N.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")});return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:N.toJSONSchema(X)},handler:async(Y)=>{let J=X.safeParse(Y);if(!J.success)return MP({error:J.error.flatten()});let G=Object.fromEntries(Q.tools.map((Z)=>[Z.name,async($)=>Q.callTool(Z.name,$??{})])),W=await E80({...J.data,tools:G});if(W.error)return MP(W);return j80(W)}}}function zJ1(Q){let X=new Map(Q.map((J)=>[J.tool.name,J.handler])),Y=Q.map((J)=>J.tool.name);return{tools:Q.map((J)=>J.tool),callTool:async(J,G)=>{let W=X.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Y.join(", ")}`}],isError:!0};return W(G)}}}var Yv6=(Q)=>({tools:Q.tools,callTool:(X,Y)=>Q.callTool(X,Y)}),Jv6=(Q)=>zJ1([VJ1(Q),qJ1(Q),Xv6(Q)]),Gv6=(Q)=>zJ1([VJ1(Q),qJ1(Q),Qv6(Q)]);function UJ1(Q){switch(Q){case"smart_tool_selection":return Gv6;case"code_execution":return Jv6;case"passthrough":default:return Yv6}}function BJ1(Q){switch(Q){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}class my{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){return console.error(`[gateway] Failed to list tools for connection ${H}:`,F),null}}),X=new Set,Y=[],J=new Map,G=new Set;for(let K of Q){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(X.has(q.name))continue;X.add(q.name),Y.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=UJ1(this.options.strategy)({tools:Y,callTool:W,categories:Array.from(G).sort()});return{tools:Y,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(Q){return(await this.cache).strategyResult.callTool(Q.name,Q.arguments??{})}async callStreamable(Q,X){let Y=await this.cache,J=Y.mappings.get(Q);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,X)}let G=await Y.strategyResult.callTool(Q,X);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}function Wv6(Q,X){if(Q===X)return!0;if(!X.includes("*"))return!1;let Y=X.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Y=`^${Y}$`;try{return new RegExp(Y).test(Q)}catch{return!1}}function DJ1(Q,X){return X.some((Y)=>Wv6(Q,Y))}class ly{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!DJ1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>DJ1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){return console.error(`[gateway] Failed to list resources for connection ${W}:`,Z),{connectionId:W,resources:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(X.has($.uri))continue;X.add($.uri),Y.push($),J.set($.uri,W)}}return{resources:Y,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(Q){let Y=(await this.cache).mappings.get(Q.uri);if(!Y)throw Error(`Resource not found: ${Q.uri}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for resource: ${Q.uri}`);return await J.proxy.client.readResource(Q)}}class dy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=GW(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(Y,J)=>{try{let G=await Y.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){return console.error(`[gateway] Failed to list resource templates for connection ${J}:`,G),{connectionId:J,templates:[]}}}),X=[];for(let Y of Q){if(Y.status!=="fulfilled")continue;let{templates:J}=Y.value;for(let G of J)X.push(G)}return{templates:X}}async list(){return{resourceTemplates:(await this.cache).templates}}}class py{proxies;options;cache;constructor(Q,X){this.proxies=Q;this.options=X;this.cache=GW(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptGateway] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),X=new Set,Y=[],J=new Map;for(let G of Q){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(X.has($.name))continue;X.add($.name),Y.push($),J.set($.name,W)}}return{prompts:Y,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let Y=(await this.cache).mappings.get(Q.name);if(!Y)throw Error(`Prompt not found: ${Q.name}`);let J=this.proxies.get(Y);if(!J)throw Error(`Connection not found for prompt: ${Q.name}`);return await J.proxy.client.getPrompt(Q)}}var NJ1=new ZQ;async function Zv6(Q,X){let Y=await LP.create(Q.connections,X),J=new my(Y,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),G=new ly(Y,{selectionMode:Q.toolSelectionMode}),W=new dy(Y),Z=new py(Y,{selectionMode:Q.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function $v6(Q,X,Y){let J;if(Q.toolSelectionMode==="exclusion"){let Z=(await X.storage.connections.list(Q.organizationId)).filter((K)=>K.status==="active"),$=new Map;for(let K of Q.connections)$.set(K.connectionId,{selectedTools:K.selectedTools,selectedResources:K.selectedResources,selectedPrompts:K.selectedPrompts});J=[];for(let K of Z){let H=$.get(K.id);if(H===void 0)J.push({connection:K,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((H.selectedTools===null||H.selectedTools.length===0)&&(H.selectedResources===null||H.selectedResources.length===0)&&(H.selectedPrompts===null||H.selectedPrompts.length===0));else J.push({connection:K,selectedTools:H.selectedTools,selectedResources:H.selectedResources,selectedPrompts:H.selectedPrompts})}}else{let W=Q.connections.map(($)=>$.connectionId),Z=[];for(let $ of W){let K=await X.storage.connections.findById($);if(K&&K.status==="active")Z.push(K)}J=Z.map(($)=>{let K=Q.connections.find((H)=>H.connectionId===$.id);return{connection:$,selectedTools:K?.selectedTools??null,selectedResources:K?.selectedResources??null,selectedPrompts:K?.selectedPrompts??null}})}let G={connections:J,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Y};return Zv6(G,X)}NJ1.all("/gateway/:gatewayId?",async(Q)=>{let X=Q.req.param("gatewayId"),Y=Q.get("meshContext");try{let J=null;if(X)J=await Y.storage.gateways.findById(X);else{let F=Q.req.header("x-org-id"),V=Q.req.header("x-org-slug");if(F)J=await Y.storage.gateways.getDefaultByOrgId(F);else if(V)J=await Y.storage.gateways.getDefaultByOrgSlug(V);else return Q.json({error:"Agent ID required, or provide x-org-id or x-org-slug header for Organization Agent"},400)}if(!J){if(X)return Q.json({error:`Agent not found: ${X}`},404);return Q.json({error:"No Organization Agent configured for this organization"},404)}if(Y.gatewayId=J.id,J.status!=="active")return Q.json({error:`Agent is inactive: ${J.id}`},503);let G=await Y.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",J.organizationId).executeTakeFirst();if(G)Y.organization={id:G.id,slug:G.slug,name:G.name};let W=Q.req.query("mode"),Z=BJ1(W),$=await $v6(J,Y,Z),K=new s3({name:`mcp-gateway-${J.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),H=new t3({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await K.connect(H),K.server.setRequestHandler(b$,async(F)=>{return $.client.listTools()}),K.server.setRequestHandler(eG,async(F)=>{return await $.client.callTool(F.params)}),K.server.setRequestHandler(S$,async()=>{return $.client.listResources()}),K.server.setRequestHandler(k$,async(F)=>{return $.client.readResource(F.params)}),K.server.setRequestHandler(v$,async()=>{return $.client.listResourceTemplates()}),K.server.setRequestHandler(_$,async()=>{return $.client.listPrompts()}),K.server.setRequestHandler(y$,async(F)=>{return $.client.getPrompt(F.params)}),await H.handleRequest(Q.req.raw)}catch(J){let G=J;return console.error("[gateway] Error handling gateway request:",G),Q.json({error:"Internal server error",message:G.message},500)}});var OJ1=NJ1;a40();var LJ1=new ZQ;LJ1.all("/",async(Q)=>{return i40(Q.get("meshContext")).fetch(Q.req.raw)});var wJ1=LJ1;H40();zU();iM();h9();var rJ1="vercel.ai.error",Kv6=Symbol.for(rJ1),MJ1,PJ1,L1=class Q extends(PJ1=Error,MJ1=Kv6,PJ1){constructor({name:X,message:Y,cause:J}){super(Y);this[MJ1]=!0,this.name=X,this.cause=J}static isInstance(X){return Q.hasMarker(X,rJ1)}static hasMarker(X,Y){let J=Symbol.for(Y);return X!=null&&typeof X==="object"&&J in X&&typeof X[J]==="boolean"&&X[J]===!0}},oJ1="AI_APICallError",sJ1=`vercel.ai.error.${oJ1}`,Hv6=Symbol.for(sJ1),TJ1,AJ1,r8=class extends(AJ1=L1,TJ1=Hv6,AJ1){constructor({message:Q,url:X,requestBodyValues:Y,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:oJ1,message:Q,cause:Z});this[TJ1]=!0,this.url=X,this.requestBodyValues=Y,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(Q){return L1.hasMarker(Q,sJ1)}},tJ1="AI_EmptyResponseBodyError",eJ1=`vercel.ai.error.${tJ1}`,Fv6=Symbol.for(eJ1),EJ1,jJ1,Q51=class extends(jJ1=L1,EJ1=Fv6,jJ1){constructor({message:Q="Empty response body"}={}){super({name:tJ1,message:Q});this[EJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,eJ1)}};function _5(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}var X51="AI_InvalidArgumentError",Y51=`vercel.ai.error.${X51}`,Vv6=Symbol.for(Y51),CJ1,IJ1,J51=class extends(IJ1=L1,CJ1=Vv6,IJ1){constructor({message:Q,cause:X,argument:Y}){super({name:X51,message:Q,cause:X});this[CJ1]=!0,this.argument=Y}static isInstance(Q){return L1.hasMarker(Q,Y51)}},G51="AI_InvalidPromptError",W51=`vercel.ai.error.${G51}`,qv6=Symbol.for(W51),RJ1,SJ1,JF=class extends(SJ1=L1,RJ1=qv6,SJ1){constructor({prompt:Q,message:X,cause:Y}){super({name:G51,message:`Invalid prompt: ${X}`,cause:Y});this[RJ1]=!0,this.prompt=Q}static isInstance(Q){return L1.hasMarker(Q,W51)}},Z51="AI_InvalidResponseDataError",$51=`vercel.ai.error.${Z51}`,zv6=Symbol.for($51),vJ1,kJ1,wm4=class extends(kJ1=L1,vJ1=zv6,kJ1){constructor({data:Q,message:X=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:Z51,message:X});this[vJ1]=!0,this.data=Q}static isInstance(Q){return L1.hasMarker(Q,$51)}},K51="AI_JSONParseError",H51=`vercel.ai.error.${K51}`,Uv6=Symbol.for(H51),_J1,yJ1,PP=class extends(yJ1=L1,_J1=Uv6,yJ1){constructor({text:Q,cause:X}){super({name:K51,message:`JSON parsing failed: Text: ${Q}.
|
|
1045
|
+
Error message: ${_5(X)}`,cause:X});this[_J1]=!0,this.text=Q}static isInstance(Q){return L1.hasMarker(Q,H51)}},F51="AI_LoadAPIKeyError",V51=`vercel.ai.error.${F51}`,Bv6=Symbol.for(V51),bJ1,fJ1,Mm4=class extends(fJ1=L1,bJ1=Bv6,fJ1){constructor({message:Q}){super({name:F51,message:Q});this[bJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,V51)}},q51="AI_LoadSettingError",z51=`vercel.ai.error.${q51}`,Dv6=Symbol.for(z51),hJ1,xJ1,Pm4=class extends(xJ1=L1,hJ1=Dv6,xJ1){constructor({message:Q}){super({name:q51,message:Q});this[hJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,z51)}},U51="AI_NoContentGeneratedError",B51=`vercel.ai.error.${U51}`,Nv6=Symbol.for(B51),gJ1,uJ1,Tm4=class extends(uJ1=L1,gJ1=Nv6,uJ1){constructor({message:Q="No content generated."}={}){super({name:U51,message:Q});this[gJ1]=!0}static isInstance(Q){return L1.hasMarker(Q,B51)}},D51="AI_NoSuchModelError",N51=`vercel.ai.error.${D51}`,Ov6=Symbol.for(N51),mJ1,lJ1,Am4=class extends(lJ1=L1,mJ1=Ov6,lJ1){constructor({errorName:Q=D51,modelId:X,modelType:Y,message:J=`No such ${Y}: ${X}`}){super({name:Q,message:J});this[mJ1]=!0,this.modelId=X,this.modelType=Y}static isInstance(Q){return L1.hasMarker(Q,N51)}},O51="AI_TooManyEmbeddingValuesForCallError",L51=`vercel.ai.error.${O51}`,Lv6=Symbol.for(L51),dJ1,pJ1,Em4=class extends(pJ1=L1,dJ1=Lv6,pJ1){constructor(Q){super({name:O51,message:`Too many values for a single embedding call. The ${Q.provider} model "${Q.modelId}" can only embed up to ${Q.maxEmbeddingsPerCall} values per call, but ${Q.values.length} values were provided.`});this[dJ1]=!0,this.provider=Q.provider,this.modelId=Q.modelId,this.maxEmbeddingsPerCall=Q.maxEmbeddingsPerCall,this.values=Q.values}static isInstance(Q){return L1.hasMarker(Q,L51)}},w51="AI_TypeValidationError",M51=`vercel.ai.error.${w51}`,wv6=Symbol.for(M51),cJ1,nJ1,y5=class Q extends(nJ1=L1,cJ1=wv6,nJ1){constructor({value:X,cause:Y}){super({name:w51,message:`Type validation failed: Value: ${JSON.stringify(X)}.
|
|
1046
|
+
Error message: ${_5(Y)}`,cause:Y});this[cJ1]=!0,this.value=X}static isInstance(X){return L1.hasMarker(X,M51)}static wrap({value:X,cause:Y}){return Q.isInstance(Y)&&Y.value===X?Y:new Q({value:X,cause:Y})}},P51="AI_UnsupportedFunctionalityError",T51=`vercel.ai.error.${P51}`,Mv6=Symbol.for(T51),iJ1,aJ1,A51=class extends(aJ1=L1,iJ1=Mv6,aJ1){constructor({functionality:Q,message:X=`'${Q}' functionality not supported.`}){super({name:P51,message:X});this[iJ1]=!0,this.functionality=Q}static isInstance(Q){return L1.hasMarker(Q,T51)}};r6();C$();C$();C$();l60();function WF(...Q){return Q.reduce((X,Y)=>({...X,...Y!=null?Y:{}}),{})}async function v51(Q,X){if(Q==null)return Promise.resolve();let Y=X==null?void 0:X.abortSignal;return new Promise((J,G)=>{if(Y==null?void 0:Y.aborted){G(E51());return}let W=setTimeout(()=>{Z(),J()},Q),Z=()=>{clearTimeout(W),Y==null||Y.removeEventListener("abort",$)},$=()=>{Z(),G(E51())};Y==null||Y.addEventListener("abort",$)})}function E51(){return new DOMException("Delay was aborted","AbortError")}var ZF=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){if(this._promise)return this._promise;return this._promise=new Promise((Q,X)=>{if(this.status.type==="resolved")Q(this.status.value);else if(this.status.type==="rejected")X(this.status.error);this._resolve=Q,this._reject=X}),this._promise}resolve(Q){var X;if(this.status={type:"resolved",value:Q},this._promise)(X=this._resolve)==null||X.call(this,Q)}reject(Q){var X;if(this.status={type:"rejected",error:Q},this._promise)(X=this._reject)==null||X.call(this,Q)}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function TP(Q){return Object.fromEntries([...Q.headers])}var{btoa:Pv6,atob:Tv6}=globalThis;function uU(Q){let X=Q.replace(/-/g,"+").replace(/_/g,"/"),Y=Tv6(X);return Uint8Array.from(Y,(J)=>J.codePointAt(0))}function $F(Q){let X="";for(let Y=0;Y<Q.length;Y++)X+=String.fromCodePoint(Q[Y]);return Pv6(X)}var k51="AI_DownloadError",_51=`vercel.ai.error.${k51}`,Av6=Symbol.for(_51),j51,C51,cy=class extends(C51=L1,j51=Av6,C51){constructor({url:Q,statusCode:X,statusText:Y,cause:J,message:G=J==null?`Failed to download ${Q}: ${X} ${Y}`:`Failed to download ${Q}: ${J}`}){super({name:k51,message:G,cause:J});this[j51]=!0,this.url=Q,this.statusCode=X,this.statusText=Y}static isInstance(Q){return L1.hasMarker(Q,_51)}};var WW=({prefix:Q,size:X=16,alphabet:Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:J="-"}={})=>{let G=()=>{let W=Y.length,Z=Array(X);for(let $=0;$<X;$++)Z[$]=Y[Math.random()*W|0];return Z.join("")};if(Q==null)return G;if(Y.includes(J))throw new J51({argument:"separator",message:`The separator "${J}" must not be part of the alphabet "${Y}".`});return()=>`${Q}${J}${G()}`},Ev6=WW();function AP(Q){if(Q==null)return"unknown error";if(typeof Q==="string")return Q;if(Q instanceof Error)return Q.message;return JSON.stringify(Q)}function u7(Q){return(Q instanceof Error||Q instanceof DOMException)&&(Q.name==="AbortError"||Q.name==="ResponseAborted"||Q.name==="TimeoutError")}var jv6=["fetch failed","failed to fetch"];function y51({error:Q,url:X,requestBodyValues:Y}){if(u7(Q))return Q;if(Q instanceof TypeError&&jv6.includes(Q.message.toLowerCase())){let J=Q.cause;if(J!=null)return new r8({message:`Cannot connect to API: ${J.message}`,cause:J,url:X,requestBodyValues:Y,isRetryable:!0})}return Q}function ny(Q=globalThis){var X,Y,J;if(Q.window)return"runtime/browser";if((X=Q.navigator)==null?void 0:X.userAgent)return`runtime/${Q.navigator.userAgent.toLowerCase()}`;if((J=(Y=Q.process)==null?void 0:Y.versions)==null?void 0:J.node)return`runtime/node.js/${Q.process.version.substring(0)}`;if(Q.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function Cv6(Q){if(Q==null)return{};let X={};if(Q instanceof Headers)Q.forEach((Y,J)=>{X[J.toLowerCase()]=Y});else{if(!Array.isArray(Q))Q=Object.entries(Q);for(let[Y,J]of Q)if(J!=null)X[Y.toLowerCase()]=J}return X}function t$(Q,...X){let Y=new Headers(Cv6(Q)),J=Y.get("user-agent")||"";return Y.set("user-agent",[J,...X].filter(Boolean).join(" ")),Object.fromEntries(Y.entries())}var b51="4.0.5",Iv6=()=>globalThis.fetch,v80=async({url:Q,headers:X={},successfulResponseHandler:Y,failedResponseHandler:J,abortSignal:G,fetch:W=Iv6()})=>{try{let Z=await W(Q,{method:"GET",headers:t$(X,`ai-sdk/provider-utils/${b51}`,ny()),signal:G}),$=TP(Z);if(!Z.ok){let K;try{K=await J({response:Z,url:Q,requestBodyValues:{}})}catch(H){if(u7(H)||r8.isInstance(H))throw H;throw new r8({message:"Failed to process error response",cause:H,statusCode:Z.status,url:Q,responseHeaders:$,requestBodyValues:{}})}throw K.value}try{return await Y({response:Z,url:Q,requestBodyValues:{}})}catch(K){if(K instanceof Error){if(u7(K)||r8.isInstance(K))throw K}throw new r8({message:"Failed to process successful response",cause:K,statusCode:Z.status,url:Q,responseHeaders:$,requestBodyValues:{}})}}catch(Z){throw y51({error:Z,url:Q,requestBodyValues:{}})}};function f51(Q){return Q!=null}function h51({mediaType:Q,url:X,supportedUrls:Y}){return X=X.toLowerCase(),Q=Q.toLowerCase(),Object.entries(Y).map(([J,G])=>{let W=J.toLowerCase();return W==="*"||W==="*/*"?{mediaTypePrefix:"",regexes:G}:{mediaTypePrefix:W.replace(/\*/,""),regexes:G}}).filter(({mediaTypePrefix:J})=>Q.startsWith(J)).flatMap(({regexes:J})=>J).some((J)=>J.test(X))}function EP({settingValue:Q,environmentVariableName:X}){if(typeof Q==="string")return Q;if(Q!=null||typeof process>"u")return;if(Q=process.env[X],Q==null||typeof Q!=="string")return;return Q}var Rv6=/"__proto__"\s*:/,Sv6=/"constructor"\s*:/;function I51(Q){let X=JSON.parse(Q);if(X===null||typeof X!=="object")return X;if(Rv6.test(Q)===!1&&Sv6.test(Q)===!1)return X;return vv6(X)}function vv6(Q){let X=[Q];while(X.length){let Y=X;X=[];for(let J of Y){if(Object.prototype.hasOwnProperty.call(J,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(J,"constructor")&&Object.prototype.hasOwnProperty.call(J.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let G in J){let W=J[G];if(W&&typeof W==="object")X.push(W)}}}return Q}function x51(Q){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(Y){return I51(Q)}try{return I51(Q)}finally{Error.stackTraceLimit=X}}function k80(Q){if(Q.type==="object"||Array.isArray(Q.type)&&Q.type.includes("object")){Q.additionalProperties=!1;let{properties:Y}=Q;if(Y!=null)for(let J of Object.keys(Y))Y[J]=GF(Y[J])}if(Q.items!=null)Q.items=Array.isArray(Q.items)?Q.items.map(GF):GF(Q.items);if(Q.anyOf!=null)Q.anyOf=Q.anyOf.map(GF);if(Q.allOf!=null)Q.allOf=Q.allOf.map(GF);if(Q.oneOf!=null)Q.oneOf=Q.oneOf.map(GF);let{definitions:X}=Q;if(X!=null)for(let Y of Object.keys(X))X[Y]=GF(X[Y]);return Q}function GF(Q){if(typeof Q==="boolean")return Q;return k80(Q)}var kv6=Symbol("Let zodToJsonSchema decide on which parser to use"),R51={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},_v6=(Q)=>typeof Q==="string"?{...R51,name:Q}:{...R51,...Q};function fY(){return{}}function yv6(Q,X){var Y,J,G;let W={type:"array"};if(((Y=Q.type)==null?void 0:Y._def)&&((G=(J=Q.type)==null?void 0:J._def)==null?void 0:G.typeName)!==E0.ZodAny)W.items=b4(Q.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Q.minLength)W.minItems=Q.minLength.value;if(Q.maxLength)W.maxItems=Q.maxLength.value;if(Q.exactLength)W.minItems=Q.exactLength.value,W.maxItems=Q.exactLength.value;return W}function bv6(Q){let X={type:"integer",format:"int64"};if(!Q.checks)return X;for(let Y of Q.checks)switch(Y.kind){case"min":if(Y.inclusive)X.minimum=Y.value;else X.exclusiveMinimum=Y.value;break;case"max":if(Y.inclusive)X.maximum=Y.value;else X.exclusiveMaximum=Y.value;break;case"multipleOf":X.multipleOf=Y.value;break}return X}function fv6(){return{type:"boolean"}}function g51(Q,X){return b4(Q.type._def,X)}var hv6=(Q,X)=>{return b4(Q.innerType._def,X)};function u51(Q,X,Y){let J=Y!=null?Y:X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>u51(Q,X,G))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xv6(Q)}}var xv6=(Q)=>{let X={type:"integer",format:"unix-time"};for(let Y of Q.checks)switch(Y.kind){case"min":X.minimum=Y.value;break;case"max":X.maximum=Y.value;break}return X};function gv6(Q,X){return{...b4(Q.innerType._def,X),default:Q.defaultValue()}}function uv6(Q,X){return X.effectStrategy==="input"?b4(Q.schema._def,X):fY()}function mv6(Q){return{type:"string",enum:Array.from(Q.values)}}var lv6=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function dv6(Q,X){let Y=[b4(Q.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),b4(Q.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Y.forEach((G)=>{if(lv6(G))J.push(...G.allOf);else{let W=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:Z,...$}=G;W=$}J.push(W)}}),J.length?{allOf:J}:void 0}function pv6(Q){let X=typeof Q.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Q.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Q.value}}var C80=void 0,b5={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(C80===void 0)C80=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return C80},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function m51(Q,X){let Y={type:"string"};if(Q.checks)for(let J of Q.checks)switch(J.kind){case"min":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,J.value):J.value;break;case"max":Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,J.value):J.value;break;case"email":switch(X.emailStrategy){case"format:email":f5(Y,"email",J.message,X);break;case"format:idn-email":f5(Y,"idn-email",J.message,X);break;case"pattern:zod":LX(Y,b5.email,J.message,X);break}break;case"url":f5(Y,"uri",J.message,X);break;case"uuid":f5(Y,"uuid",J.message,X);break;case"regex":LX(Y,J.regex,J.message,X);break;case"cuid":LX(Y,b5.cuid,J.message,X);break;case"cuid2":LX(Y,b5.cuid2,J.message,X);break;case"startsWith":LX(Y,RegExp(`^${I80(J.value,X)}`),J.message,X);break;case"endsWith":LX(Y,RegExp(`${I80(J.value,X)}$`),J.message,X);break;case"datetime":f5(Y,"date-time",J.message,X);break;case"date":f5(Y,"date",J.message,X);break;case"time":f5(Y,"time",J.message,X);break;case"duration":f5(Y,"duration",J.message,X);break;case"length":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,J.value):J.value,Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,J.value):J.value;break;case"includes":{LX(Y,RegExp(I80(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")f5(Y,"ipv4",J.message,X);if(J.version!=="v4")f5(Y,"ipv6",J.message,X);break}case"base64url":LX(Y,b5.base64url,J.message,X);break;case"jwt":LX(Y,b5.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")LX(Y,b5.ipv4Cidr,J.message,X);if(J.version!=="v4")LX(Y,b5.ipv6Cidr,J.message,X);break}case"emoji":LX(Y,b5.emoji(),J.message,X);break;case"ulid":{LX(Y,b5.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{f5(Y,"binary",J.message,X);break}case"contentEncoding:base64":{Y.contentEncoding="base64";break}case"pattern:zod":{LX(Y,b5.base64,J.message,X);break}}break}case"nanoid":LX(Y,b5.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Y}function I80(Q,X){return X.patternStrategy==="escape"?nv6(Q):Q}var cv6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function nv6(Q){let X="";for(let Y=0;Y<Q.length;Y++){if(!cv6.has(Q[Y]))X+="\\";X+=Q[Y]}return X}function f5(Q,X,Y,J){var G;if(Q.format||((G=Q.anyOf)==null?void 0:G.some((W)=>W.format))){if(!Q.anyOf)Q.anyOf=[];if(Q.format)Q.anyOf.push({format:Q.format}),delete Q.format;Q.anyOf.push({format:X,...Y&&J.errorMessages&&{errorMessage:{format:Y}}})}else Q.format=X}function LX(Q,X,Y,J){var G;if(Q.pattern||((G=Q.allOf)==null?void 0:G.some((W)=>W.pattern))){if(!Q.allOf)Q.allOf=[];if(Q.pattern)Q.allOf.push({pattern:Q.pattern}),delete Q.pattern;Q.allOf.push({pattern:S51(X,J),...Y&&J.errorMessages&&{errorMessage:{pattern:Y}}})}else Q.pattern=S51(X,J)}function S51(Q,X){var Y;if(!X.applyRegexFlags||!Q.flags)return Q.source;let J={i:Q.flags.includes("i"),m:Q.flags.includes("m"),s:Q.flags.includes("s")},G=J.i?Q.source.toLowerCase():Q.source,W="",Z=!1,$=!1,K=!1;for(let H=0;H<G.length;H++){if(Z){W+=G[H],Z=!1;continue}if(J.i){if($){if(G[H].match(/[a-z]/)){if(K)W+=G[H],W+=`${G[H-2]}-${G[H]}`.toUpperCase(),K=!1;else if(G[H+1]==="-"&&((Y=G[H+2])==null?void 0:Y.match(/[a-z]/)))W+=G[H],K=!0;else W+=`${G[H]}${G[H].toUpperCase()}`;continue}}else if(G[H].match(/[a-z]/)){W+=`[${G[H]}${G[H].toUpperCase()}]`;continue}}if(J.m){if(G[H]==="^"){W+=`(^|(?<=[\r
|
|
1047
1047
|
]))`;continue}else if(G[H]==="$"){W+=`($|(?=[\r
|
|
1048
1048
|
]))`;continue}}if(J.s&&G[H]==="."){W+=$?`${G[H]}\r
|
|
1049
1049
|
`:`[${G[H]}\r
|
|
1050
|
-
]`;continue}if(W+=G[H],G[H]==="\\")Z=!0;else if($&&G[H]==="]")$=!1;else if(!$&&G[H]==="[")$=!0}try{new RegExp(W)}catch(H){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return W}function l51(Q,X){var Y,J,G,W,Z,$;let K={type:"object",additionalProperties:(Y=b4(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?Y:X.allowedAdditionalProperties};if(((J=Q.keyType)==null?void 0:J._def.typeName)===E0.ZodString&&((G=Q.keyType._def.checks)==null?void 0:G.length)){let{type:H,...F}=m51(Q.keyType._def,X);return{...K,propertyNames:F}}else if(((W=Q.keyType)==null?void 0:W._def.typeName)===E0.ZodEnum)return{...K,propertyNames:{enum:Q.keyType._def.values}};else if(((Z=Q.keyType)==null?void 0:Z._def.typeName)===E0.ZodBranded&&Q.keyType._def.type._def.typeName===E0.ZodString&&(($=Q.keyType._def.type._def.checks)==null?void 0:$.length)){let{type:H,...F}=g51(Q.keyType._def,X);return{...K,propertyNames:F}}return K}function iv6(Q,X){if(X.mapStrategy==="record")return l51(Q,X);let Y=b4(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||fY(),J=b4(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||fY();return{type:"array",maxItems:125,items:{type:"array",items:[Y,J],minItems:2,maxItems:2}}}function av6(Q){let X=Q.values,J=Object.keys(Q.values).filter((W)=>{return typeof X[X[W]]!=="number"}).map((W)=>X[W]),G=Array.from(new Set(J.map((W)=>typeof W)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:J}}function rv6(){return{not:fY()}}function ov6(){return{type:"null"}}var S80={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sv6(Q,X){let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every((J)=>(J._def.typeName in S80)&&(!J._def.checks||!J._def.checks.length))){let J=Y.reduce((G,W)=>{let Z=S80[W._def.typeName];return Z&&!G.includes(Z)?[...G,Z]:G},[]);return{type:J.length>1?J:J[0]}}else if(Y.every((J)=>J._def.typeName==="ZodLiteral"&&!J.description)){let J=Y.reduce((G,W)=>{let Z=typeof W._def.value;switch(Z){case"string":case"number":case"boolean":return[...G,Z];case"bigint":return[...G,"integer"];case"object":if(W._def.value===null)return[...G,"null"];case"symbol":case"undefined":case"function":default:return G}},[]);if(J.length===Y.length){let G=J.filter((W,Z,$)=>$.indexOf(W)===Z);return{type:G.length>1?G:G[0],enum:Y.reduce((W,Z)=>{return W.includes(Z._def.value)?W:[...W,Z._def.value]},[])}}}else if(Y.every((J)=>J._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((J,G)=>[...J,...G._def.values.filter((W)=>!J.includes(W))],[])};return tv6(Q,X)}var tv6=(Q,X)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((J,G)=>b4(J._def,{...X,currentPath:[...X.currentPath,"anyOf",`${G}`]})).filter((J)=>!!J&&(!X.strictUnions||typeof J==="object"&&Object.keys(J).length>0));return Y.length?{anyOf:Y}:void 0};function ev6(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length))return{type:[S80[Q.innerType._def.typeName],"null"]};let Y=b4(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function Qk6(Q){let X={type:"number"};if(!Q.checks)return X;for(let Y of Q.checks)switch(Y.kind){case"int":X.type="integer";break;case"min":if(Y.inclusive)X.minimum=Y.value;else X.exclusiveMinimum=Y.value;break;case"max":if(Y.inclusive)X.maximum=Y.value;else X.exclusiveMaximum=Y.value;break;case"multipleOf":X.multipleOf=Y.value;break}return X}function Xk6(Q,X){let Y={type:"object",properties:{}},J=[],G=Q.shape();for(let Z in G){let $=G[Z];if($===void 0||$._def===void 0)continue;let K=Jk6($),H=b4($._def,{...X,currentPath:[...X.currentPath,"properties",Z],propertyPath:[...X.currentPath,"properties",Z]});if(H===void 0)continue;if(Y.properties[Z]=H,!K)J.push(Z)}if(J.length)Y.required=J;let W=Yk6(Q,X);if(W!==void 0)Y.additionalProperties=W;return Y}function Yk6(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return b4(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function Jk6(Q){try{return Q.isOptional()}catch(X){return!0}}var Gk6=(Q,X)=>{var Y;if(X.currentPath.toString()===((Y=X.propertyPath)==null?void 0:Y.toString()))return b4(Q.innerType._def,X);let J=b4(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return J?{anyOf:[{not:fY()},J]}:fY()},Wk6=(Q,X)=>{if(X.pipeStrategy==="input")return b4(Q.in._def,X);else if(X.pipeStrategy==="output")return b4(Q.out._def,X);let Y=b4(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),J=b4(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,J].filter((G)=>G!==void 0)}};function Zk6(Q,X){return b4(Q.type._def,X)}function $k6(Q,X){let J={type:"array",uniqueItems:!0,items:b4(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)J.minItems=Q.minSize.value;if(Q.maxSize)J.maxItems=Q.maxSize.value;return J}function Kk6(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,J)=>b4(Y._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce((Y,J)=>J===void 0?Y:[...Y,J],[]),additionalItems:b4(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,J)=>b4(Y._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce((Y,J)=>J===void 0?Y:[...Y,J],[])}}function Hk6(){return{not:fY()}}function Fk6(){return fY()}var Vk6=(Q,X)=>{return b4(Q.innerType._def,X)},qk6=(Q,X,Y)=>{switch(X){case E0.ZodString:return m51(Q,Y);case E0.ZodNumber:return Qk6(Q);case E0.ZodObject:return Xk6(Q,Y);case E0.ZodBigInt:return bv6(Q);case E0.ZodBoolean:return fv6();case E0.ZodDate:return u51(Q,Y);case E0.ZodUndefined:return Hk6();case E0.ZodNull:return ov6();case E0.ZodArray:return yv6(Q,Y);case E0.ZodUnion:case E0.ZodDiscriminatedUnion:return sv6(Q,Y);case E0.ZodIntersection:return dv6(Q,Y);case E0.ZodTuple:return Kk6(Q,Y);case E0.ZodRecord:return l51(Q,Y);case E0.ZodLiteral:return pv6(Q);case E0.ZodEnum:return mv6(Q);case E0.ZodNativeEnum:return av6(Q);case E0.ZodNullable:return ev6(Q,Y);case E0.ZodOptional:return Gk6(Q,Y);case E0.ZodMap:return iv6(Q,Y);case E0.ZodSet:return $k6(Q,Y);case E0.ZodLazy:return()=>Q.getter()._def;case E0.ZodPromise:return Zk6(Q,Y);case E0.ZodNaN:case E0.ZodNever:return rv6();case E0.ZodEffects:return uv6(Q,Y);case E0.ZodAny:return fY();case E0.ZodUnknown:return Fk6();case E0.ZodDefault:return gv6(Q,Y);case E0.ZodBranded:return g51(Q,Y);case E0.ZodReadonly:return Vk6(Q,Y);case E0.ZodCatch:return hv6(Q,Y);case E0.ZodPipeline:return Wk6(Q,Y);case E0.ZodFunction:case E0.ZodVoid:case E0.ZodSymbol:return;default:return((J)=>{return})(X)}},zk6=(Q,X)=>{let Y=0;for(;Y<Q.length&&Y<X.length;Y++)if(Q[Y]!==X[Y])break;return[(Q.length-Y).toString(),...X.slice(Y)].join("/")};function b4(Q,X,Y=!1){var J;let G=X.seen.get(Q);if(X.override){let K=(J=X.override)==null?void 0:J.call(X,Q,X,G,Y);if(K!==kv6)return K}if(G&&!Y){let K=Uk6(G,X);if(K!==void 0)return K}let W={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,W);let Z=qk6(Q,Q.typeName,X),$=typeof Z==="function"?b4(Z(),X):Z;if($)Bk6(Q,X,$);if(X.postProcess){let K=X.postProcess($,Q,X);return W.jsonSchema=$,K}return W.jsonSchema=$,$}var Uk6=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:zk6(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every((Y,J)=>X.currentPath[J]===Y))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),fY();return X.$refStrategy==="seen"?fY():void 0}}},Bk6=(Q,X,Y)=>{if(Q.description)Y.description=Q.description;return Y},Dk6=(Q)=>{let X=_v6(Q),Y=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:Y,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([J,G])=>[G._def,{def:G._def,path:[...X.basePath,X.definitionPath,J],jsonSchema:void 0}]))}},Nk6=(Q,X)=>{var Y;let J=Dk6(X),G=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[F,V])=>{var q;return{...H,[F]:(q=b4(V._def,{...J,currentPath:[...J.basePath,J.definitionPath,F]},!0))!=null?q:fY()}},{}):void 0,W=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,Z=(Y=b4(Q._def,W===void 0?J:{...J,currentPath:[...J.basePath,J.definitionPath,W]},!1))!=null?Y:fY(),$=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if($!==void 0)Z.title=$;let K=W===void 0?G?{...Z,[J.definitionPath]:G}:Z:{$ref:[...J.$refStrategy==="relative"?[]:J.basePath,J.definitionPath,W].join("/"),[J.definitionPath]:{...G,[W]:Z}};return K.$schema="http://json-schema.org/draft-07/schema#",K},v80=Symbol.for("vercel.ai.schema");function dQ(Q){let X;return()=>{if(X==null)X=Q();return X}}function e$(Q,{validate:X}={}){return{[v80]:!0,_type:void 0,get jsonSchema(){if(typeof Q==="function")Q=Q();return Q},validate:X}}function Ok6(Q){return typeof Q==="object"&&Q!==null&&v80 in Q&&Q[v80]===!0&&"jsonSchema"in Q&&"validate"in Q}function ZW(Q){return Q==null?e$({properties:{},additionalProperties:!1}):Ok6(Q)?Q:("~standard"in Q)?Q["~standard"].vendor==="zod"?JQ(Q):Lk6(Q):Q()}function Lk6(Q){return e$(()=>Q["~standard"].jsonSchema.input({target:"draft-07"}),{validate:async(X)=>{let Y=await Q["~standard"].validate(X);return"value"in Y?{success:!0,value:Y.value}:{success:!1,error:new y5({value:X,cause:Y.issues})}}})}function wk6(Q,X){var Y;let J=(Y=X==null?void 0:X.useReferences)!=null?Y:!1;return e$(()=>Nk6(Q,{$refStrategy:J?"root":"none"}),{validate:async(G)=>{let W=await Q.safeParseAsync(G);return W.success?{success:!0,value:W.data}:{success:!1,error:W.error}}})}function Mk6(Q,X){var Y;let J=(Y=X==null?void 0:X.useReferences)!=null?Y:!1;return e$(()=>x51(bG(Q,{target:"draft-7",io:"input",reused:J?"ref":"inline"})),{validate:async(G)=>{let W=await Kz(Q,G);return W.success?{success:!0,value:W.data}:{success:!1,error:W.error}}})}function Pk6(Q){return"_zod"in Q}function JQ(Q,X){if(Pk6(Q))return Mk6(Q,X);else return wk6(Q,X)}async function jP({value:Q,schema:X}){let Y=await wX({value:Q,schema:X});if(!Y.success)throw y5.wrap({value:Q,cause:Y.error});return Y.value}async function wX({value:Q,schema:X}){let Y=ZW(X);try{if(Y.validate==null)return{success:!0,value:Q,rawValue:Q};let J=await Y.validate(Q);if(J.success)return{success:!0,value:J.value,rawValue:Q};return{success:!1,error:y5.wrap({value:Q,cause:J.error}),rawValue:Q}}catch(J){return{success:!1,error:y5.wrap({value:Q,cause:J}),rawValue:Q}}}async function Tk6({text:Q,schema:X}){try{let Y=h51(Q);if(X==null)return Y;return jP({value:Y,schema:X})}catch(Y){if(PP.isInstance(Y)||y5.isInstance(Y))throw Y;throw new PP({text:Q,cause:Y})}}async function JY({text:Q,schema:X}){try{let Y=h51(Q);if(X==null)return{success:!0,value:Y,rawValue:Y};return await wX({value:Y,schema:X})}catch(Y){return{success:!1,error:PP.isInstance(Y)?Y:new PP({text:Q,cause:Y}),rawValue:void 0}}}function d51({stream:Q,schema:X}){return Q.pipeThrough(new TextDecoderStream).pipeThrough(new nM).pipeThrough(new TransformStream({async transform({data:Y},J){if(Y==="[DONE]")return;J.enqueue(await JY({text:Y,schema:X}))}}))}var Ak6=()=>globalThis.fetch,KF=async({url:Q,headers:X,body:Y,failedResponseHandler:J,successfulResponseHandler:G,abortSignal:W,fetch:Z})=>Ek6({url:Q,headers:{"Content-Type":"application/json",...X},body:{content:JSON.stringify(Y),values:Y},failedResponseHandler:J,successfulResponseHandler:G,abortSignal:W,fetch:Z});var Ek6=async({url:Q,headers:X={},body:Y,successfulResponseHandler:J,failedResponseHandler:G,abortSignal:W,fetch:Z=Ak6()})=>{try{let $=await Z(Q,{method:"POST",headers:t$(X,`ai-sdk/provider-utils/${y51}`,ny()),body:Y.content,signal:W}),K=TP($);if(!$.ok){let H;try{H=await G({response:$,url:Q,requestBodyValues:Y.values})}catch(F){if(u7(F)||r8.isInstance(F))throw F;throw new r8({message:"Failed to process error response",cause:F,statusCode:$.status,url:Q,responseHeaders:K,requestBodyValues:Y.values})}throw H.value}try{return await J({response:$,url:Q,requestBodyValues:Y.values})}catch(H){if(H instanceof Error){if(u7(H)||r8.isInstance(H))throw H}throw new r8({message:"Failed to process successful response",cause:H,statusCode:$.status,url:Q,responseHeaders:K,requestBodyValues:Y.values})}}catch($){throw _51({error:$,url:Q,requestBodyValues:Y.values})}};function iy(Q){return Q}function p51({id:Q,inputSchema:X,outputSchema:Y,supportsDeferredResults:J}){return({execute:G,needsApproval:W,toModelOutput:Z,onInputStart:$,onInputDelta:K,onInputAvailable:H,...F})=>iy({type:"provider",id:Q,args:F,inputSchema:X,outputSchema:Y,execute:G,needsApproval:W,toModelOutput:Z,onInputStart:$,onInputDelta:K,onInputAvailable:H,supportsDeferredResults:J})}async function N9(Q){if(typeof Q==="function")Q=Q();return Promise.resolve(Q)}var $W=({errorSchema:Q,errorToMessage:X,isRetryable:Y})=>async({response:J,url:G,requestBodyValues:W})=>{let Z=await J.text(),$=TP(J);if(Z.trim()==="")return{responseHeaders:$,value:new r8({message:J.statusText,url:G,requestBodyValues:W,statusCode:J.status,responseHeaders:$,responseBody:Z,isRetryable:Y==null?void 0:Y(J)})};try{let K=await Tk6({text:Z,schema:Q});return{responseHeaders:$,value:new r8({message:X(K),url:G,requestBodyValues:W,statusCode:J.status,responseHeaders:$,responseBody:Z,data:K,isRetryable:Y==null?void 0:Y(J,K)})}}catch(K){return{responseHeaders:$,value:new r8({message:J.statusText,url:G,requestBodyValues:W,statusCode:J.status,responseHeaders:$,responseBody:Z,isRetryable:Y==null?void 0:Y(J)})}}},c51=(Q)=>async({response:X})=>{let Y=TP(X);if(X.body==null)throw new eJ1({});return{responseHeaders:Y,value:d51({stream:X.body,schema:Q})}},m7=(Q)=>async({response:X,url:Y,requestBodyValues:J})=>{let G=await X.text(),W=await JY({text:G,schema:Q}),Z=TP(X);if(!W.success)throw new r8({message:"Invalid JSON response",cause:W.error,statusCode:X.status,responseHeaders:Z,responseBody:G,url:Y,requestBodyValues:J});return{responseHeaders:Z,value:W.value,rawValue:W.rawValue}};function n51(Q){return Q==null?void 0:Q.replace(/\/$/,"")}function jk6(Q){return Q!=null&&typeof Q[Symbol.asyncIterator]==="function"}async function*i51({execute:Q,input:X,options:Y}){let J=Q(X,Y);if(jk6(J)){let G;for await(let W of J)G=W,yield{type:"preliminary",output:W};yield{type:"final",output:G}}else yield{type:"final",output:await J}}r6();r6();r6();r6();r6();r6();r6();G1();var ZW1=m6(i80(),1),$W1=m6(i80(),1);var Jy6="vercel.ai.gateway.error",a80=Symbol.for(Jy6),RG1,SG1,hY=class Q extends(SG1=Error,RG1=a80,SG1){constructor({message:X,statusCode:Y=500,cause:J}){super(X);this[RG1]=!0,this.statusCode=Y,this.cause=J}static isInstance(X){return Q.hasMarker(X)}static hasMarker(X){return typeof X==="object"&&X!==null&&a80 in X&&X[a80]===!0}},eG1="GatewayAuthenticationError",Gy6=`vercel.ai.gateway.error.${eG1}`,vG1=Symbol.for(Gy6),kG1,_G1,ey=class Q extends(_G1=hY,kG1=vG1,_G1){constructor({message:X="Authentication failed",statusCode:Y=401,cause:J}={}){super({message:X,statusCode:Y,cause:J});this[kG1]=!0,this.name=eG1,this.type="authentication_error"}static isInstance(X){return hY.hasMarker(X)&&vG1 in X}static createContextualError({apiKeyProvided:X,oidcTokenProvided:Y,message:J="Authentication failed",statusCode:G=401,cause:W}){let Z;if(X)Z=`AI Gateway authentication failed: Invalid API key.
|
|
1050
|
+
]`;continue}if(W+=G[H],G[H]==="\\")Z=!0;else if($&&G[H]==="]")$=!1;else if(!$&&G[H]==="[")$=!0}try{new RegExp(W)}catch(H){return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return W}function l51(Q,X){var Y,J,G,W,Z,$;let K={type:"object",additionalProperties:(Y=b4(Q.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]}))!=null?Y:X.allowedAdditionalProperties};if(((J=Q.keyType)==null?void 0:J._def.typeName)===E0.ZodString&&((G=Q.keyType._def.checks)==null?void 0:G.length)){let{type:H,...F}=m51(Q.keyType._def,X);return{...K,propertyNames:F}}else if(((W=Q.keyType)==null?void 0:W._def.typeName)===E0.ZodEnum)return{...K,propertyNames:{enum:Q.keyType._def.values}};else if(((Z=Q.keyType)==null?void 0:Z._def.typeName)===E0.ZodBranded&&Q.keyType._def.type._def.typeName===E0.ZodString&&(($=Q.keyType._def.type._def.checks)==null?void 0:$.length)){let{type:H,...F}=g51(Q.keyType._def,X);return{...K,propertyNames:F}}return K}function iv6(Q,X){if(X.mapStrategy==="record")return l51(Q,X);let Y=b4(Q.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||fY(),J=b4(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||fY();return{type:"array",maxItems:125,items:{type:"array",items:[Y,J],minItems:2,maxItems:2}}}function av6(Q){let X=Q.values,J=Object.keys(Q.values).filter((W)=>{return typeof X[X[W]]!=="number"}).map((W)=>X[W]),G=Array.from(new Set(J.map((W)=>typeof W)));return{type:G.length===1?G[0]==="string"?"string":"number":["string","number"],enum:J}}function rv6(){return{not:fY()}}function ov6(){return{type:"null"}}var R80={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sv6(Q,X){let Y=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(Y.every((J)=>(J._def.typeName in R80)&&(!J._def.checks||!J._def.checks.length))){let J=Y.reduce((G,W)=>{let Z=R80[W._def.typeName];return Z&&!G.includes(Z)?[...G,Z]:G},[]);return{type:J.length>1?J:J[0]}}else if(Y.every((J)=>J._def.typeName==="ZodLiteral"&&!J.description)){let J=Y.reduce((G,W)=>{let Z=typeof W._def.value;switch(Z){case"string":case"number":case"boolean":return[...G,Z];case"bigint":return[...G,"integer"];case"object":if(W._def.value===null)return[...G,"null"];case"symbol":case"undefined":case"function":default:return G}},[]);if(J.length===Y.length){let G=J.filter((W,Z,$)=>$.indexOf(W)===Z);return{type:G.length>1?G:G[0],enum:Y.reduce((W,Z)=>{return W.includes(Z._def.value)?W:[...W,Z._def.value]},[])}}}else if(Y.every((J)=>J._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((J,G)=>[...J,...G._def.values.filter((W)=>!J.includes(W))],[])};return tv6(Q,X)}var tv6=(Q,X)=>{let Y=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((J,G)=>b4(J._def,{...X,currentPath:[...X.currentPath,"anyOf",`${G}`]})).filter((J)=>!!J&&(!X.strictUnions||typeof J==="object"&&Object.keys(J).length>0));return Y.length?{anyOf:Y}:void 0};function ev6(Q,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length))return{type:[R80[Q.innerType._def.typeName],"null"]};let Y=b4(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function Qk6(Q){let X={type:"number"};if(!Q.checks)return X;for(let Y of Q.checks)switch(Y.kind){case"int":X.type="integer";break;case"min":if(Y.inclusive)X.minimum=Y.value;else X.exclusiveMinimum=Y.value;break;case"max":if(Y.inclusive)X.maximum=Y.value;else X.exclusiveMaximum=Y.value;break;case"multipleOf":X.multipleOf=Y.value;break}return X}function Xk6(Q,X){let Y={type:"object",properties:{}},J=[],G=Q.shape();for(let Z in G){let $=G[Z];if($===void 0||$._def===void 0)continue;let K=Jk6($),H=b4($._def,{...X,currentPath:[...X.currentPath,"properties",Z],propertyPath:[...X.currentPath,"properties",Z]});if(H===void 0)continue;if(Y.properties[Z]=H,!K)J.push(Z)}if(J.length)Y.required=J;let W=Yk6(Q,X);if(W!==void 0)Y.additionalProperties=W;return Y}function Yk6(Q,X){if(Q.catchall._def.typeName!=="ZodNever")return b4(Q.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function Jk6(Q){try{return Q.isOptional()}catch(X){return!0}}var Gk6=(Q,X)=>{var Y;if(X.currentPath.toString()===((Y=X.propertyPath)==null?void 0:Y.toString()))return b4(Q.innerType._def,X);let J=b4(Q.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return J?{anyOf:[{not:fY()},J]}:fY()},Wk6=(Q,X)=>{if(X.pipeStrategy==="input")return b4(Q.in._def,X);else if(X.pipeStrategy==="output")return b4(Q.out._def,X);let Y=b4(Q.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),J=b4(Q.out._def,{...X,currentPath:[...X.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,J].filter((G)=>G!==void 0)}};function Zk6(Q,X){return b4(Q.type._def,X)}function $k6(Q,X){let J={type:"array",uniqueItems:!0,items:b4(Q.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if(Q.minSize)J.minItems=Q.minSize.value;if(Q.maxSize)J.maxItems=Q.maxSize.value;return J}function Kk6(Q,X){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((Y,J)=>b4(Y._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce((Y,J)=>J===void 0?Y:[...Y,J],[]),additionalItems:b4(Q.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((Y,J)=>b4(Y._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce((Y,J)=>J===void 0?Y:[...Y,J],[])}}function Hk6(){return{not:fY()}}function Fk6(){return fY()}var Vk6=(Q,X)=>{return b4(Q.innerType._def,X)},qk6=(Q,X,Y)=>{switch(X){case E0.ZodString:return m51(Q,Y);case E0.ZodNumber:return Qk6(Q);case E0.ZodObject:return Xk6(Q,Y);case E0.ZodBigInt:return bv6(Q);case E0.ZodBoolean:return fv6();case E0.ZodDate:return u51(Q,Y);case E0.ZodUndefined:return Hk6();case E0.ZodNull:return ov6();case E0.ZodArray:return yv6(Q,Y);case E0.ZodUnion:case E0.ZodDiscriminatedUnion:return sv6(Q,Y);case E0.ZodIntersection:return dv6(Q,Y);case E0.ZodTuple:return Kk6(Q,Y);case E0.ZodRecord:return l51(Q,Y);case E0.ZodLiteral:return pv6(Q);case E0.ZodEnum:return mv6(Q);case E0.ZodNativeEnum:return av6(Q);case E0.ZodNullable:return ev6(Q,Y);case E0.ZodOptional:return Gk6(Q,Y);case E0.ZodMap:return iv6(Q,Y);case E0.ZodSet:return $k6(Q,Y);case E0.ZodLazy:return()=>Q.getter()._def;case E0.ZodPromise:return Zk6(Q,Y);case E0.ZodNaN:case E0.ZodNever:return rv6();case E0.ZodEffects:return uv6(Q,Y);case E0.ZodAny:return fY();case E0.ZodUnknown:return Fk6();case E0.ZodDefault:return gv6(Q,Y);case E0.ZodBranded:return g51(Q,Y);case E0.ZodReadonly:return Vk6(Q,Y);case E0.ZodCatch:return hv6(Q,Y);case E0.ZodPipeline:return Wk6(Q,Y);case E0.ZodFunction:case E0.ZodVoid:case E0.ZodSymbol:return;default:return((J)=>{return})(X)}},zk6=(Q,X)=>{let Y=0;for(;Y<Q.length&&Y<X.length;Y++)if(Q[Y]!==X[Y])break;return[(Q.length-Y).toString(),...X.slice(Y)].join("/")};function b4(Q,X,Y=!1){var J;let G=X.seen.get(Q);if(X.override){let K=(J=X.override)==null?void 0:J.call(X,Q,X,G,Y);if(K!==kv6)return K}if(G&&!Y){let K=Uk6(G,X);if(K!==void 0)return K}let W={def:Q,path:X.currentPath,jsonSchema:void 0};X.seen.set(Q,W);let Z=qk6(Q,Q.typeName,X),$=typeof Z==="function"?b4(Z(),X):Z;if($)Bk6(Q,X,$);if(X.postProcess){let K=X.postProcess($,Q,X);return W.jsonSchema=$,K}return W.jsonSchema=$,$}var Uk6=(Q,X)=>{switch(X.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:zk6(X.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<X.currentPath.length&&Q.path.every((Y,J)=>X.currentPath[J]===Y))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),fY();return X.$refStrategy==="seen"?fY():void 0}}},Bk6=(Q,X,Y)=>{if(Q.description)Y.description=Q.description;return Y},Dk6=(Q)=>{let X=_v6(Q),Y=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:Y,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([J,G])=>[G._def,{def:G._def,path:[...X.basePath,X.definitionPath,J],jsonSchema:void 0}]))}},Nk6=(Q,X)=>{var Y;let J=Dk6(X),G=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((H,[F,V])=>{var q;return{...H,[F]:(q=b4(V._def,{...J,currentPath:[...J.basePath,J.definitionPath,F]},!0))!=null?q:fY()}},{}):void 0,W=typeof X==="string"?X:(X==null?void 0:X.nameStrategy)==="title"?void 0:X==null?void 0:X.name,Z=(Y=b4(Q._def,W===void 0?J:{...J,currentPath:[...J.basePath,J.definitionPath,W]},!1))!=null?Y:fY(),$=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if($!==void 0)Z.title=$;let K=W===void 0?G?{...Z,[J.definitionPath]:G}:Z:{$ref:[...J.$refStrategy==="relative"?[]:J.basePath,J.definitionPath,W].join("/"),[J.definitionPath]:{...G,[W]:Z}};return K.$schema="http://json-schema.org/draft-07/schema#",K},S80=Symbol.for("vercel.ai.schema");function dQ(Q){let X;return()=>{if(X==null)X=Q();return X}}function e$(Q,{validate:X}={}){return{[S80]:!0,_type:void 0,get jsonSchema(){if(typeof Q==="function")Q=Q();return Q},validate:X}}function Ok6(Q){return typeof Q==="object"&&Q!==null&&S80 in Q&&Q[S80]===!0&&"jsonSchema"in Q&&"validate"in Q}function ZW(Q){return Q==null?e$({properties:{},additionalProperties:!1}):Ok6(Q)?Q:("~standard"in Q)?Q["~standard"].vendor==="zod"?JQ(Q):Lk6(Q):Q()}function Lk6(Q){return e$(()=>k80(Q["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async(X)=>{let Y=await Q["~standard"].validate(X);return"value"in Y?{success:!0,value:Y.value}:{success:!1,error:new y5({value:X,cause:Y.issues})}}})}function wk6(Q,X){var Y;let J=(Y=X==null?void 0:X.useReferences)!=null?Y:!1;return e$(()=>Nk6(Q,{$refStrategy:J?"root":"none"}),{validate:async(G)=>{let W=await Q.safeParseAsync(G);return W.success?{success:!0,value:W.data}:{success:!1,error:W.error}}})}function Mk6(Q,X){var Y;let J=(Y=X==null?void 0:X.useReferences)!=null?Y:!1;return e$(()=>k80(bG(Q,{target:"draft-7",io:"input",reused:J?"ref":"inline"})),{validate:async(G)=>{let W=await Kz(Q,G);return W.success?{success:!0,value:W.data}:{success:!1,error:W.error}}})}function Pk6(Q){return"_zod"in Q}function JQ(Q,X){if(Pk6(Q))return Mk6(Q,X);else return wk6(Q,X)}async function jP({value:Q,schema:X}){let Y=await wX({value:Q,schema:X});if(!Y.success)throw y5.wrap({value:Q,cause:Y.error});return Y.value}async function wX({value:Q,schema:X}){let Y=ZW(X);try{if(Y.validate==null)return{success:!0,value:Q,rawValue:Q};let J=await Y.validate(Q);if(J.success)return{success:!0,value:J.value,rawValue:Q};return{success:!1,error:y5.wrap({value:Q,cause:J.error}),rawValue:Q}}catch(J){return{success:!1,error:y5.wrap({value:Q,cause:J}),rawValue:Q}}}async function Tk6({text:Q,schema:X}){try{let Y=x51(Q);if(X==null)return Y;return jP({value:Y,schema:X})}catch(Y){if(PP.isInstance(Y)||y5.isInstance(Y))throw Y;throw new PP({text:Q,cause:Y})}}async function JY({text:Q,schema:X}){try{let Y=x51(Q);if(X==null)return{success:!0,value:Y,rawValue:Y};return await wX({value:Y,schema:X})}catch(Y){return{success:!1,error:PP.isInstance(Y)?Y:new PP({text:Q,cause:Y}),rawValue:void 0}}}function d51({stream:Q,schema:X}){return Q.pipeThrough(new TextDecoderStream).pipeThrough(new nM).pipeThrough(new TransformStream({async transform({data:Y},J){if(Y==="[DONE]")return;J.enqueue(await JY({text:Y,schema:X}))}}))}var Ak6=()=>globalThis.fetch,KF=async({url:Q,headers:X,body:Y,failedResponseHandler:J,successfulResponseHandler:G,abortSignal:W,fetch:Z})=>Ek6({url:Q,headers:{"Content-Type":"application/json",...X},body:{content:JSON.stringify(Y),values:Y},failedResponseHandler:J,successfulResponseHandler:G,abortSignal:W,fetch:Z});var Ek6=async({url:Q,headers:X={},body:Y,successfulResponseHandler:J,failedResponseHandler:G,abortSignal:W,fetch:Z=Ak6()})=>{try{let $=await Z(Q,{method:"POST",headers:t$(X,`ai-sdk/provider-utils/${b51}`,ny()),body:Y.content,signal:W}),K=TP($);if(!$.ok){let H;try{H=await G({response:$,url:Q,requestBodyValues:Y.values})}catch(F){if(u7(F)||r8.isInstance(F))throw F;throw new r8({message:"Failed to process error response",cause:F,statusCode:$.status,url:Q,responseHeaders:K,requestBodyValues:Y.values})}throw H.value}try{return await J({response:$,url:Q,requestBodyValues:Y.values})}catch(H){if(H instanceof Error){if(u7(H)||r8.isInstance(H))throw H}throw new r8({message:"Failed to process successful response",cause:H,statusCode:$.status,url:Q,responseHeaders:K,requestBodyValues:Y.values})}}catch($){throw y51({error:$,url:Q,requestBodyValues:Y.values})}};function iy(Q){return Q}function p51({id:Q,inputSchema:X,outputSchema:Y,supportsDeferredResults:J}){return({execute:G,needsApproval:W,toModelOutput:Z,onInputStart:$,onInputDelta:K,onInputAvailable:H,...F})=>iy({type:"provider",id:Q,args:F,inputSchema:X,outputSchema:Y,execute:G,needsApproval:W,toModelOutput:Z,onInputStart:$,onInputDelta:K,onInputAvailable:H,supportsDeferredResults:J})}async function N9(Q){if(typeof Q==="function")Q=Q();return Promise.resolve(Q)}var $W=({errorSchema:Q,errorToMessage:X,isRetryable:Y})=>async({response:J,url:G,requestBodyValues:W})=>{let Z=await J.text(),$=TP(J);if(Z.trim()==="")return{responseHeaders:$,value:new r8({message:J.statusText,url:G,requestBodyValues:W,statusCode:J.status,responseHeaders:$,responseBody:Z,isRetryable:Y==null?void 0:Y(J)})};try{let K=await Tk6({text:Z,schema:Q});return{responseHeaders:$,value:new r8({message:X(K),url:G,requestBodyValues:W,statusCode:J.status,responseHeaders:$,responseBody:Z,data:K,isRetryable:Y==null?void 0:Y(J,K)})}}catch(K){return{responseHeaders:$,value:new r8({message:J.statusText,url:G,requestBodyValues:W,statusCode:J.status,responseHeaders:$,responseBody:Z,isRetryable:Y==null?void 0:Y(J)})}}},c51=(Q)=>async({response:X})=>{let Y=TP(X);if(X.body==null)throw new Q51({});return{responseHeaders:Y,value:d51({stream:X.body,schema:Q})}},m7=(Q)=>async({response:X,url:Y,requestBodyValues:J})=>{let G=await X.text(),W=await JY({text:G,schema:Q}),Z=TP(X);if(!W.success)throw new r8({message:"Invalid JSON response",cause:W.error,statusCode:X.status,responseHeaders:Z,responseBody:G,url:Y,requestBodyValues:J});return{responseHeaders:Z,value:W.value,rawValue:W.rawValue}};function n51(Q){return Q==null?void 0:Q.replace(/\/$/,"")}function jk6(Q){return Q!=null&&typeof Q[Symbol.asyncIterator]==="function"}async function*i51({execute:Q,input:X,options:Y}){let J=Q(X,Y);if(jk6(J)){let G;for await(let W of J)G=W,yield{type:"preliminary",output:W};yield{type:"final",output:G}}else yield{type:"final",output:await J}}r6();r6();r6();r6();r6();r6();r6();G1();var ZW1=m6(i80(),1),$W1=m6(i80(),1);var Jy6="vercel.ai.gateway.error",a80=Symbol.for(Jy6),RG1,SG1,hY=class Q extends(SG1=Error,RG1=a80,SG1){constructor({message:X,statusCode:Y=500,cause:J}){super(X);this[RG1]=!0,this.statusCode=Y,this.cause=J}static isInstance(X){return Q.hasMarker(X)}static hasMarker(X){return typeof X==="object"&&X!==null&&a80 in X&&X[a80]===!0}},eG1="GatewayAuthenticationError",Gy6=`vercel.ai.gateway.error.${eG1}`,vG1=Symbol.for(Gy6),kG1,_G1,ey=class Q extends(_G1=hY,kG1=vG1,_G1){constructor({message:X="Authentication failed",statusCode:Y=401,cause:J}={}){super({message:X,statusCode:Y,cause:J});this[kG1]=!0,this.name=eG1,this.type="authentication_error"}static isInstance(X){return hY.hasMarker(X)&&vG1 in X}static createContextualError({apiKeyProvided:X,oidcTokenProvided:Y,message:J="Authentication failed",statusCode:G=401,cause:W}){let Z;if(X)Z=`AI Gateway authentication failed: Invalid API key.
|
|
1051
1051
|
|
|
1052
1052
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
1053
1053
|
|
|
@@ -1062,7 +1062,7 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
|
1062
1062
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
1063
1063
|
|
|
1064
1064
|
Option 2 - OIDC token:
|
|
1065
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new Q({message:Z,statusCode:G,cause:W})}},QW1="GatewayInvalidRequestError",Wy6=`vercel.ai.gateway.error.${QW1}`,yG1=Symbol.for(Wy6),bG1,fG1,Zy6=class extends(fG1=hY,bG1=yG1,fG1){constructor({message:Q="Invalid request",statusCode:X=400,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[bG1]=!0,this.name=QW1,this.type="invalid_request_error"}static isInstance(Q){return hY.hasMarker(Q)&&yG1 in Q}},XW1="GatewayRateLimitError",$y6=`vercel.ai.gateway.error.${XW1}`,hG1=Symbol.for($y6),xG1,gG1,Ky6=class extends(gG1=hY,xG1=hG1,gG1){constructor({message:Q="Rate limit exceeded",statusCode:X=429,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[xG1]=!0,this.name=XW1,this.type="rate_limit_exceeded"}static isInstance(Q){return hY.hasMarker(Q)&&hG1 in Q}},YW1="GatewayModelNotFoundError",Hy6=`vercel.ai.gateway.error.${YW1}`,uG1=Symbol.for(Hy6),Fy6=dQ(()=>JQ(N.object({modelId:N.string()}))),mG1,lG1,Vy6=class extends(lG1=hY,mG1=uG1,lG1){constructor({message:Q="Model not found",statusCode:X=404,modelId:Y,cause:J}={}){super({message:Q,statusCode:X,cause:J});this[mG1]=!0,this.name=YW1,this.type="model_not_found",this.modelId=Y}static isInstance(Q){return hY.hasMarker(Q)&&uG1 in Q}},JW1="GatewayInternalServerError",qy6=`vercel.ai.gateway.error.${JW1}`,dG1=Symbol.for(qy6),pG1,cG1,nG1=class extends(cG1=hY,pG1=dG1,cG1){constructor({message:Q="Internal server error",statusCode:X=500,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[pG1]=!0,this.name=JW1,this.type="internal_server_error"}static isInstance(Q){return hY.hasMarker(Q)&&dG1 in Q}},GW1="GatewayResponseError",zy6=`vercel.ai.gateway.error.${GW1}`,iG1=Symbol.for(zy6),aG1,rG1,Uy6=class extends(rG1=hY,aG1=iG1,rG1){constructor({message:Q="Invalid response from Gateway",statusCode:X=502,response:Y,validationError:J,cause:G}={}){super({message:Q,statusCode:X,cause:G});this[aG1]=!0,this.name=GW1,this.type="response_error",this.response=Y,this.validationError=J}static isInstance(Q){return hY.hasMarker(Q)&&iG1 in Q}};async function oG1({response:Q,statusCode:X,defaultMessage:Y="Gateway request failed",cause:J,authMethod:G}){let W=await wX({value:Q,schema:By6});if(!W.success)return new Uy6({message:`Invalid error response format: ${Y}`,statusCode:X,response:Q,validationError:W.error,cause:J});let Z=W.value,$=Z.error.type,K=Z.error.message;switch($){case"authentication_error":return ey.createContextualError({apiKeyProvided:G==="api-key",oidcTokenProvided:G==="oidc",statusCode:X,cause:J});case"invalid_request_error":return new Zy6({message:K,statusCode:X,cause:J});case"rate_limit_exceeded":return new Ky6({message:K,statusCode:X,cause:J});case"model_not_found":{let H=await wX({value:Z.error.param,schema:Fy6});return new Vy6({message:K,statusCode:X,modelId:H.success?H.value.modelId:void 0,cause:J})}case"internal_server_error":return new nG1({message:K,statusCode:X,cause:J});default:return new nG1({message:K,statusCode:X,cause:J})}}var By6=dQ(()=>JQ(N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.unknown().nullish(),code:N.union([N.string(),N.number()]).nullish()})})));function QK(Q,X){var Y;if(hY.isInstance(Q))return Q;if(r8.isInstance(Q))return oG1({response:Dy6(Q),statusCode:(Y=Q.statusCode)!=null?Y:500,defaultMessage:"Gateway request failed",cause:Q,authMethod:X});return oG1({response:{},statusCode:500,defaultMessage:Q instanceof Error?`Gateway request failed: ${Q.message}`:"Unknown Gateway error",cause:Q,authMethod:X})}function Dy6(Q){if(Q.data!==void 0)return Q.data;if(Q.responseBody!=null)try{return JSON.parse(Q.responseBody)}catch(X){return Q.responseBody}return{}}var WW1="ai-gateway-auth-method";async function dU(Q){let X=await wX({value:Q[WW1],schema:Ny6});return X.success?X.value:void 0}var Ny6=dQ(()=>JQ(N.union([N.literal("api-key"),N.literal("oidc")]))),sG1=class{constructor(Q){this.config=Q}async getAvailableModels(){try{let{value:Q}=await k80({url:`${this.config.baseURL}/config`,headers:await N9(this.config.headers()),successfulResponseHandler:m7(Oy6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(X)=>X}),fetch:this.config.fetch});return Q}catch(Q){throw await QK(Q)}}async getCredits(){try{let Q=new URL(this.config.baseURL),{value:X}=await k80({url:`${Q.origin}/v1/credits`,headers:await N9(this.config.headers()),successfulResponseHandler:m7(Ly6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(Y)=>Y}),fetch:this.config.fetch});return X}catch(Q){throw await QK(Q)}}},Oy6=dQ(()=>JQ(N.object({models:N.array(N.object({id:N.string(),name:N.string(),description:N.string().nullish(),pricing:N.object({input:N.string(),output:N.string(),input_cache_read:N.string().nullish(),input_cache_write:N.string().nullish()}).transform(({input:Q,output:X,input_cache_read:Y,input_cache_write:J})=>({input:Q,output:X,...Y?{cachedInputTokens:Y}:{},...J?{cacheCreationInputTokens:J}:{}})).nullish(),specification:N.object({specificationVersion:N.literal("v3"),provider:N.string(),modelId:N.string()}),modelType:N.enum(["language","embedding","image"]).nullish()}))}))),Ly6=dQ(()=>JQ(N.object({balance:N.string(),total_used:N.string()}).transform(({balance:Q,total_used:X})=>({balance:Q,totalUsed:X})))),wy6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(Q){let{abortSignal:X,...Y}=Q;return{args:this.maybeEncodeFileParts(Y),warnings:[]}}async doGenerate(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await N9(this.config.headers());try{let{responseHeaders:W,value:Z,rawValue:$}=await KF({url:this.getUrl(),headers:WF(G,Q.headers,this.getModelConfigHeaders(this.modelId,!1),await N9(this.config.o11yHeaders)),body:X,successfulResponseHandler:m7(N.any()),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(K)=>K}),...J&&{abortSignal:J},fetch:this.config.fetch});return{...Z,request:{body:X},response:{headers:W,body:$},warnings:Y}}catch(W){throw await QK(W,await dU(G))}}async doStream(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await N9(this.config.headers());try{let{value:W,responseHeaders:Z}=await KF({url:this.getUrl(),headers:WF(G,Q.headers,this.getModelConfigHeaders(this.modelId,!0),await N9(this.config.o11yHeaders)),body:X,successfulResponseHandler:c51(N.any()),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:($)=>$}),...J&&{abortSignal:J},fetch:this.config.fetch});return{stream:W.pipeThrough(new TransformStream({start($){if(Y.length>0)$.enqueue({type:"stream-start",warnings:Y})},transform($,K){if($.success){let H=$.value;if(H.type==="raw"&&!Q.includeRawChunks)return;if(H.type==="response-metadata"&&H.timestamp&&typeof H.timestamp==="string")H.timestamp=new Date(H.timestamp);K.enqueue(H)}else K.error($.error)}})),request:{body:X},response:{headers:Z}}}catch(W){throw await QK(W,await dU(G))}}isFilePart(Q){return Q&&typeof Q==="object"&&"type"in Q&&Q.type==="file"}maybeEncodeFileParts(Q){for(let X of Q.prompt)for(let Y of X.content)if(this.isFilePart(Y)){let J=Y;if(J.data instanceof Uint8Array){let G=Uint8Array.from(J.data),W=Buffer.from(G).toString("base64");J.data=new URL(`data:${J.mediaType||"application/octet-stream"};base64,${W}`)}}return Q}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(Q,X){return{"ai-language-model-specification-version":"3","ai-language-model-id":Q,"ai-language-model-streaming":String(X)}}},My6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:Q,headers:X,abortSignal:Y,providerOptions:J}){var G;let W=await N9(this.config.headers());try{let{responseHeaders:Z,value:$,rawValue:K}=await KF({url:this.getUrl(),headers:WF(W,X!=null?X:{},this.getModelConfigHeaders(),await N9(this.config.o11yHeaders)),body:{values:Q,...J?{providerOptions:J}:{}},successfulResponseHandler:m7(Py6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(H)=>H}),...Y&&{abortSignal:Y},fetch:this.config.fetch});return{embeddings:$.embeddings,usage:(G=$.usage)!=null?G:void 0,providerMetadata:$.providerMetadata,response:{headers:Z,body:K},warnings:[]}}catch(Z){throw await QK(Z,await dU(W))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},Py6=dQ(()=>JQ(N.object({embeddings:N.array(N.array(N.number())),usage:N.object({tokens:N.number()}).nullish(),providerMetadata:N.record(N.string(),N.record(N.string(),N.unknown())).optional()}))),Ty6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:X,size:Y,aspectRatio:J,seed:G,files:W,mask:Z,providerOptions:$,headers:K,abortSignal:H}){var F;let V=await N9(this.config.headers());try{let{responseHeaders:q,value:z,rawValue:B}=await KF({url:this.getUrl(),headers:WF(V,K!=null?K:{},this.getModelConfigHeaders(),await N9(this.config.o11yHeaders)),body:{prompt:Q,n:X,...Y&&{size:Y},...J&&{aspectRatio:J},...G&&{seed:G},...$&&{providerOptions:$},...W&&{files:W.map((D)=>tG1(D))},...Z&&{mask:tG1(Z)}},successfulResponseHandler:m7(Ey6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(D)=>D}),...H&&{abortSignal:H},fetch:this.config.fetch});return{images:z.images,warnings:(F=z.warnings)!=null?F:[],providerMetadata:z.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:q}}}catch(q){throw QK(q,await dU(V))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function tG1(Q){if(Q.type==="file"&&Q.data instanceof Uint8Array)return{...Q,data:$F(Q.data)};return Q}var Ay6=N.object({images:N.array(N.unknown()).optional()}).catchall(N.unknown()),Ey6=N.object({images:N.array(N.string()),warnings:N.array(N.object({type:N.literal("other"),message:N.string()})).optional(),providerMetadata:N.record(N.string(),Ay6).optional()}),jy6=dQ(()=>JQ(N.object({query:N.union([N.string(),N.array(N.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:N.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:N.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 1024)"),country:N.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:N.array(N.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:N.array(N.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:N.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:N.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:N.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),Cy6=dQ(()=>JQ(N.union([N.object({results:N.array(N.object({title:N.string(),url:N.string(),snippet:N.string(),date:N.string().optional(),lastUpdated:N.string().optional()})),id:N.string()}),N.object({error:N.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:N.number().optional(),message:N.string()})]))),Iy6=p51({id:"gateway.perplexity_search",inputSchema:jy6,outputSchema:Cy6}),Ry6=(Q={})=>Iy6(Q),Sy6={perplexitySearch:Ry6};async function vy6(){var Q;return(Q=ZW1.getContext().headers)==null?void 0:Q["x-vercel-id"]}var ky6="3.0.11",_y6="0.0.1";function yy6(Q={}){var X,Y;let J=null,G=null,W=(X=Q.metadataCacheRefreshMillis)!=null?X:300000,Z=0,$=(Y=n51(Q.baseURL))!=null?Y:"https://ai-gateway.vercel.sh/v3/ai",K=async()=>{try{let D=await by6(Q);return t$({Authorization:`Bearer ${D.token}`,"ai-gateway-protocol-version":_y6,[WW1]:D.authMethod,...Q.headers},`ai-sdk/gateway/${ky6}`)}catch(D){throw ey.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:D})}},H=()=>{let D=EP({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),L=EP({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),M=EP({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let C=await vy6();return{...D&&{"ai-o11y-deployment-id":D},...L&&{"ai-o11y-environment":L},...M&&{"ai-o11y-region":M},...C&&{"ai-o11y-request-id":C}}}},F=(D)=>{return new wy6(D,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},V=async()=>{var D,L,M;let C=(M=(L=(D=Q._internal)==null?void 0:D.currentDate)==null?void 0:L.call(D).getTime())!=null?M:Date.now();if(!J||C-Z>W)Z=C,J=new sG1({baseURL:$,headers:K,fetch:Q.fetch}).getAvailableModels().then((A)=>{return G=A,A}).catch(async(A)=>{throw await QK(A,await dU(await K()))});return G?Promise.resolve(G):J},q=async()=>{return new sG1({baseURL:$,headers:K,fetch:Q.fetch}).getCredits().catch(async(D)=>{throw await QK(D,await dU(await K()))})},z=function(D){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return F(D)};z.specificationVersion="v3",z.getAvailableModels=V,z.getCredits=q,z.imageModel=(D)=>{return new Ty6(D,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},z.languageModel=F;let B=(D)=>{return new My6(D,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})};return z.embeddingModel=B,z.textEmbeddingModel=B,z.tools=Sy6,z}var KW1=yy6();async function by6(Q){let X=EP({settingValue:Q.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(X)return{token:X,authMethod:"api-key"};return{token:await $W1.getVercelOidcToken(),authMethod:"oidc"}}r6();r6();r6();r6();r6();r6();var $71=m6(Z1(),1),YQ0=m6(Z1(),1);r6();r6();var fy6=Object.defineProperty,hy6=(Q,X)=>{for(var Y in X)fy6(Q,Y,{get:X[Y],enumerable:!0})},NW1="AI_InvalidArgumentError",OW1=`vercel.ai.error.${NW1}`,xy6=Symbol.for(OW1),LW1,KW=class extends L1{constructor({parameter:Q,value:X,message:Y}){super({name:NW1,message:`Invalid argument for parameter ${Q}: ${Y}`});this[LW1]=!0,this.parameter=Q,this.value=X}static isInstance(Q){return L1.hasMarker(Q,OW1)}};LW1=xy6;var gy6="AI_InvalidStreamPartError",uy6=`vercel.ai.error.${gy6}`,my6=Symbol.for(uy6),ly6;ly6=my6;var wW1="AI_InvalidToolApprovalError",MW1=`vercel.ai.error.${wW1}`,dy6=Symbol.for(MW1),PW1,py6=class extends L1{constructor({approvalId:Q}){super({name:wW1,message:`Tool approval response references unknown approvalId: "${Q}". No matching tool-approval-request found in message history.`});this[PW1]=!0,this.approvalId=Q}static isInstance(Q){return L1.hasMarker(Q,MW1)}};PW1=dy6;var TW1="AI_InvalidToolInputError",AW1=`vercel.ai.error.${TW1}`,cy6=Symbol.for(AW1),EW1,$Q0=class extends L1{constructor({toolInput:Q,toolName:X,cause:Y,message:J=`Invalid input for tool ${X}: ${_5(Y)}`}){super({name:TW1,message:J,cause:Y});this[EW1]=!0,this.toolInput=Q,this.toolName=X}static isInstance(Q){return L1.hasMarker(Q,AW1)}};EW1=cy6;var jW1="AI_ToolCallNotFoundForApprovalError",CW1=`vercel.ai.error.${jW1}`,ny6=Symbol.for(CW1),IW1,RW1=class extends L1{constructor({toolCallId:Q,approvalId:X}){super({name:jW1,message:`Tool call "${Q}" not found for approval request "${X}".`});this[IW1]=!0,this.toolCallId=Q,this.approvalId=X}static isInstance(Q){return L1.hasMarker(Q,CW1)}};IW1=ny6;var iy6="AI_NoImageGeneratedError",ay6=`vercel.ai.error.${iy6}`,ry6=Symbol.for(ay6),oy6;oy6=ry6;var SW1="AI_NoObjectGeneratedError",vW1=`vercel.ai.error.${SW1}`,sy6=Symbol.for(vW1),kW1,XK=class extends L1{constructor({message:Q="No object generated.",cause:X,text:Y,response:J,usage:G,finishReason:W}){super({name:SW1,message:Q,cause:X});this[kW1]=!0,this.text=Y,this.response=J,this.usage=G,this.finishReason=W}static isInstance(Q){return L1.hasMarker(Q,vW1)}};kW1=sy6;var _W1="AI_NoOutputGeneratedError",yW1=`vercel.ai.error.${_W1}`,ty6=Symbol.for(yW1),bW1,ey6=class extends L1{constructor({message:Q="No output generated.",cause:X}={}){super({name:_W1,message:Q,cause:X});this[bW1]=!0}static isInstance(Q){return L1.hasMarker(Q,yW1)}};bW1=ty6;var fW1="AI_NoSuchToolError",hW1=`vercel.ai.error.${fW1}`,Qb6=Symbol.for(hW1),xW1,QQ0=class extends L1{constructor({toolName:Q,availableTools:X=void 0,message:Y=`Model tried to call unavailable tool '${Q}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:fW1,message:Y});this[xW1]=!0,this.toolName=Q,this.availableTools=X}static isInstance(Q){return L1.hasMarker(Q,hW1)}};xW1=Qb6;var gW1="AI_ToolCallRepairError",uW1=`vercel.ai.error.${gW1}`,Xb6=Symbol.for(uW1),mW1,Yb6=class extends L1{constructor({cause:Q,originalError:X,message:Y=`Error repairing tool call: ${_5(Q)}`}){super({name:gW1,message:Y,cause:Q});this[mW1]=!0,this.originalError=X}static isInstance(Q){return L1.hasMarker(Q,uW1)}};mW1=Xb6;var Jb6=class extends L1{constructor(Q){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${Q.version} for provider "${Q.provider}" and model "${Q.modelId}". AI SDK 5 only supports models that implement specification version "v2".`});this.version=Q.version,this.provider=Q.provider,this.modelId=Q.modelId}},Gb6="AI_InvalidDataContentError",Wb6=`vercel.ai.error.${Gb6}`,Zb6=Symbol.for(Wb6),$b6;$b6=Zb6;var lW1="AI_InvalidMessageRoleError",dW1=`vercel.ai.error.${lW1}`,Kb6=Symbol.for(dW1),pW1,Hb6=class extends L1{constructor({role:Q,message:X=`Invalid message role: '${Q}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:lW1,message:X});this[pW1]=!0,this.role=Q}static isInstance(Q){return L1.hasMarker(Q,dW1)}};pW1=Kb6;var cW1="AI_MessageConversionError",nW1=`vercel.ai.error.${cW1}`,Fb6=Symbol.for(nW1),iW1,Vb6=class extends L1{constructor({originalMessage:Q,message:X}){super({name:cW1,message:X});this[iW1]=!0,this.originalMessage=Q}static isInstance(Q){return L1.hasMarker(Q,nW1)}};iW1=Fb6;var aW1="AI_RetryError",rW1=`vercel.ai.error.${aW1}`,qb6=Symbol.for(rW1),oW1,HW1=class extends L1{constructor({message:Q,reason:X,errors:Y}){super({name:aW1,message:Q});this[oW1]=!0,this.reason=X,this.errors=Y,this.lastError=Y[Y.length-1]}static isInstance(Q){return L1.hasMarker(Q,rW1)}};oW1=qb6;function zb6({warning:Q,provider:X,model:Y}){let J=`AI SDK Warning (${X} / ${Y}):`;switch(Q.type){case"unsupported":{let G=`${J} The feature "${Q.feature}" is not supported.`;if(Q.details)G+=` ${Q.details}`;return G}case"compatibility":{let G=`${J} The feature "${Q.feature}" is used in a compatibility mode.`;if(Q.details)G+=` ${Q.details}`;return G}case"other":return`${J} ${Q.message}`;default:return`${J} ${JSON.stringify(Q,null,2)}`}}var Ub6="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",FW1=!1,sW1=(Q)=>{if(Q.warnings.length===0)return;let X=globalThis.AI_SDK_LOG_WARNINGS;if(X===!1)return;if(typeof X==="function"){X(Q);return}if(!FW1)FW1=!0,console.info(Ub6);for(let Y of Q.warnings)console.warn(zb6({warning:Y,provider:Q.provider,model:Q.model}))};function Bb6({provider:Q,modelId:X}){sW1({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:Q,model:X})}function Db6(Q){if(Q.specificationVersion==="v3")return Q;return Bb6({provider:Q.provider,modelId:Q.modelId}),new Proxy(Q,{get(X,Y){switch(Y){case"specificationVersion":return"v3";case"doGenerate":return async(...J)=>{let G=await X.doGenerate(...J);return{...G,finishReason:tW1(G.finishReason),usage:eW1(G.usage)}};case"doStream":return async(...J)=>{let G=await X.doStream(...J);return{...G,stream:Nb6(G.stream)}};default:return X[Y]}}})}function Nb6(Q){return Q.pipeThrough(new TransformStream({transform(X,Y){switch(X.type){case"finish":Y.enqueue({...X,finishReason:tW1(X.finishReason),usage:eW1(X.usage)});break;default:Y.enqueue(X);break}}}))}function tW1(Q){return{unified:Q==="unknown"?"other":Q,raw:void 0}}function eW1(Q){return{inputTokens:{total:Q.inputTokens,noCache:void 0,cacheRead:Q.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:Q.outputTokens,text:void 0,reasoning:Q.reasoningTokens}}}function Q71(Q){if(typeof Q!=="string"){if(Q.specificationVersion!=="v3"&&Q.specificationVersion!=="v2"){let X=Q;throw new Jb6({version:X.specificationVersion,provider:X.provider,modelId:X.modelId})}return Db6(Q)}return Ob6().languageModel(Q)}function Ob6(){var Q;return(Q=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?Q:KW1}function X71(Q){if(Q==null)return;if(typeof Q==="number")return Q;return Q.totalMs}function Lb6(Q){if(Q==null||typeof Q==="number")return;return Q.stepMs}function wb6(Q){if(Q==null||typeof Q==="number")return;return Q.chunkMs}var Mb6=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var Pb6=(Q)=>{let X=typeof Q==="string"?uU(Q):Q,Y=(X[6]&127)<<21|(X[7]&127)<<14|(X[8]&127)<<7|X[9]&127;return X.slice(Y+10)};function Tb6(Q){return typeof Q==="string"&&Q.startsWith("SUQz")||typeof Q!=="string"&&Q.length>10&&Q[0]===73&&Q[1]===68&&Q[2]===51?Pb6(Q):Q}function Ab6({data:Q,signatures:X}){let Y=Tb6(Q),J=typeof Y==="string"?uU(Y.substring(0,Math.min(Y.length,24))):Y;for(let G of X)if(J.length>=G.bytesPrefix.length&&G.bytesPrefix.every((W,Z)=>W===null||J[Z]===W))return G.mediaType;return}var Eb6="6.0.28",jb6=async({url:Q})=>{var X;let Y=Q.toString();try{let J=await fetch(Y,{headers:t$({},`ai-sdk/${Eb6}`,ny())});if(!J.ok)throw new cy({url:Y,statusCode:J.status,statusText:J.statusText});return{data:new Uint8Array(await J.arrayBuffer()),mediaType:(X=J.headers.get("content-type"))!=null?X:void 0}}catch(J){if(cy.isInstance(J))throw J;throw new cy({url:Y,cause:J})}},Cb6=(Q=jb6)=>(X)=>Promise.all(X.map(async(Y)=>Y.isUrlSupportedByModel?null:Q(Y)));function Ib6(Q){try{let[X,Y]=Q.split(",");return{mediaType:X.split(";")[0].split(":")[1],base64Content:Y}}catch(X){return{mediaType:void 0,base64Content:void 0}}}var Y71=N.union([N.string(),N.instanceof(Uint8Array),N.instanceof(ArrayBuffer),N.custom((Q)=>{var X,Y;return(Y=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Q))!=null?Y:!1},{message:"Must be a Buffer"})]);function J71(Q){if(Q instanceof Uint8Array)return{data:Q,mediaType:void 0};if(Q instanceof ArrayBuffer)return{data:new Uint8Array(Q),mediaType:void 0};if(typeof Q==="string")try{Q=new URL(Q)}catch(X){}if(Q instanceof URL&&Q.protocol==="data:"){let{mediaType:X,base64Content:Y}=Ib6(Q.toString());if(X==null||Y==null)throw new L1({name:"InvalidDataContentError",message:`Invalid data URL format in content ${Q.toString()}`});return{data:Y,mediaType:X}}return{data:Q,mediaType:void 0}}function Rb6(Q){if(typeof Q==="string")return Q;if(Q instanceof ArrayBuffer)return $F(new Uint8Array(Q));return $F(Q)}function Xb(Q){return Q===void 0?[]:Array.isArray(Q)?Q:[Q]}async function Sb6({prompt:Q,supportedUrls:X,download:Y=Cb6()}){let J=await kb6(Q.messages,Y,X),G=[...Q.system!=null?typeof Q.system==="string"?[{role:"system",content:Q.system}]:Xb(Q.system).map((Z)=>({role:"system",content:Z.content,providerOptions:Z.providerOptions})):[],...Q.messages.map((Z)=>vb6({message:Z,downloadedAssets:J}))],W=[];for(let Z of G){if(Z.role!=="tool"){W.push(Z);continue}let $=W.at(-1);if(($==null?void 0:$.role)==="tool")$.content.push(...Z.content);else W.push(Z)}return W}function vb6({message:Q,downloadedAssets:X}){let Y=Q.role;switch(Y){case"system":return{role:"system",content:Q.content,providerOptions:Q.providerOptions};case"user":{if(typeof Q.content==="string")return{role:"user",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"user",content:Q.content.map((J)=>_b6(J,X)).filter((J)=>J.type!=="text"||J.text!==""),providerOptions:Q.providerOptions}}case"assistant":{if(typeof Q.content==="string")return{role:"assistant",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"assistant",content:Q.content.filter((J)=>J.type!=="text"||J.text!==""||J.providerOptions!=null).filter((J)=>J.type!=="tool-approval-request").map((J)=>{let G=J.providerOptions;switch(J.type){case"file":{let{data:W,mediaType:Z}=J71(J.data);return{type:"file",data:W,filename:J.filename,mediaType:Z!=null?Z:J.mediaType,providerOptions:G}}case"reasoning":return{type:"reasoning",text:J.text,providerOptions:G};case"text":return{type:"text",text:J.text,providerOptions:G};case"tool-call":return{type:"tool-call",toolCallId:J.toolCallId,toolName:J.toolName,input:J.input,providerExecuted:J.providerExecuted,providerOptions:G};case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:VW1(J.output),providerOptions:G}}}),providerOptions:Q.providerOptions}}case"tool":return{role:"tool",content:Q.content.filter((J)=>J.type!=="tool-approval-response"||J.providerExecuted).map((J)=>{switch(J.type){case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:VW1(J.output),providerOptions:J.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:J.approvalId,approved:J.approved,reason:J.reason}}}),providerOptions:Q.providerOptions};default:throw new Hb6({role:Y})}}async function kb6(Q,X,Y){let J=Q.filter((W)=>W.role==="user").map((W)=>W.content).filter((W)=>Array.isArray(W)).flat().filter((W)=>W.type==="image"||W.type==="file").map((W)=>{var Z;let $=(Z=W.mediaType)!=null?Z:W.type==="image"?"image/*":void 0,K=W.type==="image"?W.image:W.data;if(typeof K==="string")try{K=new URL(K)}catch(H){}return{mediaType:$,data:K}}).filter((W)=>W.data instanceof URL).map((W)=>({url:W.data,isUrlSupportedByModel:W.mediaType!=null&&f51({url:W.data.toString(),mediaType:W.mediaType,supportedUrls:Y})})),G=await X(J);return Object.fromEntries(G.map((W,Z)=>W==null?null:[J[Z].url.toString(),{data:W.data,mediaType:W.mediaType}]).filter((W)=>W!=null))}function _b6(Q,X){var Y;if(Q.type==="text")return{type:"text",text:Q.text,providerOptions:Q.providerOptions};let J,G=Q.type;switch(G){case"image":J=Q.image;break;case"file":J=Q.data;break;default:throw Error(`Unsupported part type: ${G}`)}let{data:W,mediaType:Z}=J71(J),$=Z!=null?Z:Q.mediaType,K=W;if(K instanceof URL){let H=X[K.toString()];if(H)K=H.data,$!=null||($=H.mediaType)}switch(G){case"image":{if(K instanceof Uint8Array||typeof K==="string")$=(Y=Ab6({data:K,signatures:Mb6}))!=null?Y:$;return{type:"file",mediaType:$!=null?$:"image/*",filename:void 0,data:K,providerOptions:Q.providerOptions}}case"file":{if($==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:$,filename:Q.filename,data:K,providerOptions:Q.providerOptions}}}}function VW1(Q){if(Q.type!=="content")return Q;return{type:"content",value:Q.value.map((X)=>{if(X.type!=="media")return X;if(X.mediaType.startsWith("image/"))return{type:"image-data",data:X.data,mediaType:X.mediaType};return{type:"file-data",data:X.data,mediaType:X.mediaType}})}}async function cU({toolCallId:Q,input:X,output:Y,tool:J,errorMode:G}){if(G==="text")return{type:"error-text",value:_5(Y)};else if(G==="json")return{type:"error-json",value:qW1(Y)};if(J==null?void 0:J.toModelOutput)return await J.toModelOutput({toolCallId:Q,input:X,output:Y});return typeof Y==="string"?{type:"text",value:Y}:{type:"json",value:qW1(Y)}}function qW1(Q){return Q===void 0?null:Q}function yb6({maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,seed:Z,stopSequences:$}){if(Q!=null){if(!Number.isInteger(Q))throw new KW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be an integer"});if(Q<1)throw new KW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be >= 1"})}if(X!=null){if(typeof X!=="number")throw new KW({parameter:"temperature",value:X,message:"temperature must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new KW({parameter:"topP",value:Y,message:"topP must be a number"})}if(J!=null){if(typeof J!=="number")throw new KW({parameter:"topK",value:J,message:"topK must be a number"})}if(G!=null){if(typeof G!=="number")throw new KW({parameter:"presencePenalty",value:G,message:"presencePenalty must be a number"})}if(W!=null){if(typeof W!=="number")throw new KW({parameter:"frequencyPenalty",value:W,message:"frequencyPenalty must be a number"})}if(Z!=null){if(!Number.isInteger(Z))throw new KW({parameter:"seed",value:Z,message:"seed must be an integer"})}return{maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,stopSequences:$,seed:Z}}function bb6(Q){return Q!=null&&Object.keys(Q).length>0}async function fb6({tools:Q,toolChoice:X,activeTools:Y}){if(!bb6(Q))return{tools:void 0,toolChoice:void 0};let J=Y!=null?Object.entries(Q).filter(([W])=>Y.includes(W)):Object.entries(Q),G=[];for(let[W,Z]of J){let $=Z.type;switch($){case void 0:case"dynamic":case"function":G.push({type:"function",name:W,description:Z.description,inputSchema:await ZW(Z.inputSchema).jsonSchema,...Z.inputExamples!=null?{inputExamples:Z.inputExamples}:{},providerOptions:Z.providerOptions,...Z.strict!=null?{strict:Z.strict}:{}});break;case"provider":G.push({type:"provider",name:W,id:Z.id,args:Z.args});break;default:throw Error(`Unsupported tool type: ${$}`)}}return{tools:G,toolChoice:X==null?{type:"auto"}:typeof X==="string"?{type:X}:{type:"tool",toolName:X.toolName}}}var _P=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),_P.optional()),N.array(_P)])),i1=N.record(N.string(),N.record(N.string(),_P.optional())),G71=N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),hb6=N.object({type:N.literal("image"),image:N.union([Y71,N.instanceof(URL)]),mediaType:N.string().optional(),providerOptions:i1.optional()}),W71=N.object({type:N.literal("file"),data:N.union([Y71,N.instanceof(URL)]),filename:N.string().optional(),mediaType:N.string(),providerOptions:i1.optional()}),xb6=N.object({type:N.literal("reasoning"),text:N.string(),providerOptions:i1.optional()}),gb6=N.object({type:N.literal("tool-call"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerOptions:i1.optional(),providerExecuted:N.boolean().optional()}),ub6=N.discriminatedUnion("type",[N.object({type:N.literal("text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("json"),value:_P,providerOptions:i1.optional()}),N.object({type:N.literal("execution-denied"),reason:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("error-text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("error-json"),value:_P,providerOptions:i1.optional()}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("media"),data:N.string(),mediaType:N.string()}),N.object({type:N.literal("file-data"),data:N.string(),mediaType:N.string(),filename:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("file-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("image-data"),data:N.string(),mediaType:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("custom"),providerOptions:i1.optional()})]))})]),Z71=N.object({type:N.literal("tool-result"),toolCallId:N.string(),toolName:N.string(),output:ub6,providerOptions:i1.optional()}),mb6=N.object({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),lb6=N.object({type:N.literal("tool-approval-response"),approvalId:N.string(),approved:N.boolean(),reason:N.string().optional()}),db6=N.object({role:N.literal("system"),content:N.string(),providerOptions:i1.optional()}),pb6=N.object({role:N.literal("user"),content:N.union([N.string(),N.array(N.union([G71,hb6,W71]))]),providerOptions:i1.optional()}),cb6=N.object({role:N.literal("assistant"),content:N.union([N.string(),N.array(N.union([G71,W71,xb6,gb6,Z71,mb6]))]),providerOptions:i1.optional()}),nb6=N.object({role:N.literal("tool"),content:N.array(N.union([Z71,lb6])),providerOptions:i1.optional()}),ib6=N.union([db6,pb6,cb6,nb6]);async function ab6(Q){if(Q.prompt==null&&Q.messages==null)throw new JF({prompt:Q,message:"prompt or messages must be defined"});if(Q.prompt!=null&&Q.messages!=null)throw new JF({prompt:Q,message:"prompt and messages cannot be defined at the same time"});if(Q.system!=null&&typeof Q.system!=="string"&&!Xb(Q.system).every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&J.role==="system"))throw new JF({prompt:Q,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let X;if(Q.prompt!=null&&typeof Q.prompt==="string")X=[{role:"user",content:Q.prompt}];else if(Q.prompt!=null&&Array.isArray(Q.prompt))X=Q.prompt;else if(Q.messages!=null)X=Q.messages;else throw new JF({prompt:Q,message:"prompt or messages must be defined"});if(X.length===0)throw new JF({prompt:Q,message:"messages must not be empty"});let Y=await wX({value:X,schema:N.array(ib6)});if(!Y.success)throw new JF({prompt:Q,message:"The messages do not match the ModelMessage[] schema.",cause:Y.error});return{messages:X,system:Q.system}}function rb6(Q){if(!ey.isInstance(Q))return Q;let X=(process==null?void 0:"production")==="production",Y="https://ai-sdk.dev/unauthenticated-ai-gateway";if(X)return new L1({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${Y}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
1065
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;return new Q({message:Z,statusCode:G,cause:W})}},QW1="GatewayInvalidRequestError",Wy6=`vercel.ai.gateway.error.${QW1}`,yG1=Symbol.for(Wy6),bG1,fG1,Zy6=class extends(fG1=hY,bG1=yG1,fG1){constructor({message:Q="Invalid request",statusCode:X=400,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[bG1]=!0,this.name=QW1,this.type="invalid_request_error"}static isInstance(Q){return hY.hasMarker(Q)&&yG1 in Q}},XW1="GatewayRateLimitError",$y6=`vercel.ai.gateway.error.${XW1}`,hG1=Symbol.for($y6),xG1,gG1,Ky6=class extends(gG1=hY,xG1=hG1,gG1){constructor({message:Q="Rate limit exceeded",statusCode:X=429,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[xG1]=!0,this.name=XW1,this.type="rate_limit_exceeded"}static isInstance(Q){return hY.hasMarker(Q)&&hG1 in Q}},YW1="GatewayModelNotFoundError",Hy6=`vercel.ai.gateway.error.${YW1}`,uG1=Symbol.for(Hy6),Fy6=dQ(()=>JQ(N.object({modelId:N.string()}))),mG1,lG1,Vy6=class extends(lG1=hY,mG1=uG1,lG1){constructor({message:Q="Model not found",statusCode:X=404,modelId:Y,cause:J}={}){super({message:Q,statusCode:X,cause:J});this[mG1]=!0,this.name=YW1,this.type="model_not_found",this.modelId=Y}static isInstance(Q){return hY.hasMarker(Q)&&uG1 in Q}},JW1="GatewayInternalServerError",qy6=`vercel.ai.gateway.error.${JW1}`,dG1=Symbol.for(qy6),pG1,cG1,nG1=class extends(cG1=hY,pG1=dG1,cG1){constructor({message:Q="Internal server error",statusCode:X=500,cause:Y}={}){super({message:Q,statusCode:X,cause:Y});this[pG1]=!0,this.name=JW1,this.type="internal_server_error"}static isInstance(Q){return hY.hasMarker(Q)&&dG1 in Q}},GW1="GatewayResponseError",zy6=`vercel.ai.gateway.error.${GW1}`,iG1=Symbol.for(zy6),aG1,rG1,Uy6=class extends(rG1=hY,aG1=iG1,rG1){constructor({message:Q="Invalid response from Gateway",statusCode:X=502,response:Y,validationError:J,cause:G}={}){super({message:Q,statusCode:X,cause:G});this[aG1]=!0,this.name=GW1,this.type="response_error",this.response=Y,this.validationError=J}static isInstance(Q){return hY.hasMarker(Q)&&iG1 in Q}};async function oG1({response:Q,statusCode:X,defaultMessage:Y="Gateway request failed",cause:J,authMethod:G}){let W=await wX({value:Q,schema:By6});if(!W.success)return new Uy6({message:`Invalid error response format: ${Y}`,statusCode:X,response:Q,validationError:W.error,cause:J});let Z=W.value,$=Z.error.type,K=Z.error.message;switch($){case"authentication_error":return ey.createContextualError({apiKeyProvided:G==="api-key",oidcTokenProvided:G==="oidc",statusCode:X,cause:J});case"invalid_request_error":return new Zy6({message:K,statusCode:X,cause:J});case"rate_limit_exceeded":return new Ky6({message:K,statusCode:X,cause:J});case"model_not_found":{let H=await wX({value:Z.error.param,schema:Fy6});return new Vy6({message:K,statusCode:X,modelId:H.success?H.value.modelId:void 0,cause:J})}case"internal_server_error":return new nG1({message:K,statusCode:X,cause:J});default:return new nG1({message:K,statusCode:X,cause:J})}}var By6=dQ(()=>JQ(N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.unknown().nullish(),code:N.union([N.string(),N.number()]).nullish()})})));function QK(Q,X){var Y;if(hY.isInstance(Q))return Q;if(r8.isInstance(Q))return oG1({response:Dy6(Q),statusCode:(Y=Q.statusCode)!=null?Y:500,defaultMessage:"Gateway request failed",cause:Q,authMethod:X});return oG1({response:{},statusCode:500,defaultMessage:Q instanceof Error?`Gateway request failed: ${Q.message}`:"Unknown Gateway error",cause:Q,authMethod:X})}function Dy6(Q){if(Q.data!==void 0)return Q.data;if(Q.responseBody!=null)try{return JSON.parse(Q.responseBody)}catch(X){return Q.responseBody}return{}}var WW1="ai-gateway-auth-method";async function dU(Q){let X=await wX({value:Q[WW1],schema:Ny6});return X.success?X.value:void 0}var Ny6=dQ(()=>JQ(N.union([N.literal("api-key"),N.literal("oidc")]))),sG1=class{constructor(Q){this.config=Q}async getAvailableModels(){try{let{value:Q}=await v80({url:`${this.config.baseURL}/config`,headers:await N9(this.config.headers()),successfulResponseHandler:m7(Oy6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(X)=>X}),fetch:this.config.fetch});return Q}catch(Q){throw await QK(Q)}}async getCredits(){try{let Q=new URL(this.config.baseURL),{value:X}=await v80({url:`${Q.origin}/v1/credits`,headers:await N9(this.config.headers()),successfulResponseHandler:m7(Ly6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(Y)=>Y}),fetch:this.config.fetch});return X}catch(Q){throw await QK(Q)}}},Oy6=dQ(()=>JQ(N.object({models:N.array(N.object({id:N.string(),name:N.string(),description:N.string().nullish(),pricing:N.object({input:N.string(),output:N.string(),input_cache_read:N.string().nullish(),input_cache_write:N.string().nullish()}).transform(({input:Q,output:X,input_cache_read:Y,input_cache_write:J})=>({input:Q,output:X,...Y?{cachedInputTokens:Y}:{},...J?{cacheCreationInputTokens:J}:{}})).nullish(),specification:N.object({specificationVersion:N.literal("v3"),provider:N.string(),modelId:N.string()}),modelType:N.enum(["language","embedding","image"]).nullish()}))}))),Ly6=dQ(()=>JQ(N.object({balance:N.string(),total_used:N.string()}).transform(({balance:Q,total_used:X})=>({balance:Q,totalUsed:X})))),wy6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(Q){let{abortSignal:X,...Y}=Q;return{args:this.maybeEncodeFileParts(Y),warnings:[]}}async doGenerate(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await N9(this.config.headers());try{let{responseHeaders:W,value:Z,rawValue:$}=await KF({url:this.getUrl(),headers:WF(G,Q.headers,this.getModelConfigHeaders(this.modelId,!1),await N9(this.config.o11yHeaders)),body:X,successfulResponseHandler:m7(N.any()),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(K)=>K}),...J&&{abortSignal:J},fetch:this.config.fetch});return{...Z,request:{body:X},response:{headers:W,body:$},warnings:Y}}catch(W){throw await QK(W,await dU(G))}}async doStream(Q){let{args:X,warnings:Y}=await this.getArgs(Q),{abortSignal:J}=Q,G=await N9(this.config.headers());try{let{value:W,responseHeaders:Z}=await KF({url:this.getUrl(),headers:WF(G,Q.headers,this.getModelConfigHeaders(this.modelId,!0),await N9(this.config.o11yHeaders)),body:X,successfulResponseHandler:c51(N.any()),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:($)=>$}),...J&&{abortSignal:J},fetch:this.config.fetch});return{stream:W.pipeThrough(new TransformStream({start($){if(Y.length>0)$.enqueue({type:"stream-start",warnings:Y})},transform($,K){if($.success){let H=$.value;if(H.type==="raw"&&!Q.includeRawChunks)return;if(H.type==="response-metadata"&&H.timestamp&&typeof H.timestamp==="string")H.timestamp=new Date(H.timestamp);K.enqueue(H)}else K.error($.error)}})),request:{body:X},response:{headers:Z}}}catch(W){throw await QK(W,await dU(G))}}isFilePart(Q){return Q&&typeof Q==="object"&&"type"in Q&&Q.type==="file"}maybeEncodeFileParts(Q){for(let X of Q.prompt)for(let Y of X.content)if(this.isFilePart(Y)){let J=Y;if(J.data instanceof Uint8Array){let G=Uint8Array.from(J.data),W=Buffer.from(G).toString("base64");J.data=new URL(`data:${J.mediaType||"application/octet-stream"};base64,${W}`)}}return Q}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(Q,X){return{"ai-language-model-specification-version":"3","ai-language-model-id":Q,"ai-language-model-streaming":String(X)}}},My6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:Q,headers:X,abortSignal:Y,providerOptions:J}){var G;let W=await N9(this.config.headers());try{let{responseHeaders:Z,value:$,rawValue:K}=await KF({url:this.getUrl(),headers:WF(W,X!=null?X:{},this.getModelConfigHeaders(),await N9(this.config.o11yHeaders)),body:{values:Q,...J?{providerOptions:J}:{}},successfulResponseHandler:m7(Py6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(H)=>H}),...Y&&{abortSignal:Y},fetch:this.config.fetch});return{embeddings:$.embeddings,usage:(G=$.usage)!=null?G:void 0,providerMetadata:$.providerMetadata,response:{headers:Z,body:K},warnings:[]}}catch(Z){throw await QK(Z,await dU(W))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},Py6=dQ(()=>JQ(N.object({embeddings:N.array(N.array(N.number())),usage:N.object({tokens:N.number()}).nullish(),providerMetadata:N.record(N.string(),N.record(N.string(),N.unknown())).optional()}))),Ty6=class{constructor(Q,X){this.modelId=Q,this.config=X,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:Q,n:X,size:Y,aspectRatio:J,seed:G,files:W,mask:Z,providerOptions:$,headers:K,abortSignal:H}){var F;let V=await N9(this.config.headers());try{let{responseHeaders:q,value:z,rawValue:B}=await KF({url:this.getUrl(),headers:WF(V,K!=null?K:{},this.getModelConfigHeaders(),await N9(this.config.o11yHeaders)),body:{prompt:Q,n:X,...Y&&{size:Y},...J&&{aspectRatio:J},...G&&{seed:G},...$&&{providerOptions:$},...W&&{files:W.map((D)=>tG1(D))},...Z&&{mask:tG1(Z)}},successfulResponseHandler:m7(Ey6),failedResponseHandler:$W({errorSchema:N.any(),errorToMessage:(D)=>D}),...H&&{abortSignal:H},fetch:this.config.fetch});return{images:z.images,warnings:(F=z.warnings)!=null?F:[],providerMetadata:z.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:q}}}catch(q){throw QK(q,await dU(V))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function tG1(Q){if(Q.type==="file"&&Q.data instanceof Uint8Array)return{...Q,data:$F(Q.data)};return Q}var Ay6=N.object({images:N.array(N.unknown()).optional()}).catchall(N.unknown()),Ey6=N.object({images:N.array(N.string()),warnings:N.array(N.object({type:N.literal("other"),message:N.string()})).optional(),providerMetadata:N.record(N.string(),Ay6).optional()}),jy6=dQ(()=>JQ(N.object({query:N.union([N.string(),N.array(N.string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:N.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:N.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 1024)"),country:N.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:N.array(N.string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:N.array(N.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:N.string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:N.string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:N.enum(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),Cy6=dQ(()=>JQ(N.union([N.object({results:N.array(N.object({title:N.string(),url:N.string(),snippet:N.string(),date:N.string().optional(),lastUpdated:N.string().optional()})),id:N.string()}),N.object({error:N.enum(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:N.number().optional(),message:N.string()})]))),Iy6=p51({id:"gateway.perplexity_search",inputSchema:jy6,outputSchema:Cy6}),Ry6=(Q={})=>Iy6(Q),Sy6={perplexitySearch:Ry6};async function vy6(){var Q;return(Q=ZW1.getContext().headers)==null?void 0:Q["x-vercel-id"]}var ky6="3.0.12",_y6="0.0.1";function yy6(Q={}){var X,Y;let J=null,G=null,W=(X=Q.metadataCacheRefreshMillis)!=null?X:300000,Z=0,$=(Y=n51(Q.baseURL))!=null?Y:"https://ai-gateway.vercel.sh/v3/ai",K=async()=>{try{let D=await by6(Q);return t$({Authorization:`Bearer ${D.token}`,"ai-gateway-protocol-version":_y6,[WW1]:D.authMethod,...Q.headers},`ai-sdk/gateway/${ky6}`)}catch(D){throw ey.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:D})}},H=()=>{let D=EP({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),L=EP({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),M=EP({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{let C=await vy6();return{...D&&{"ai-o11y-deployment-id":D},...L&&{"ai-o11y-environment":L},...M&&{"ai-o11y-region":M},...C&&{"ai-o11y-request-id":C}}}},F=(D)=>{return new wy6(D,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},V=async()=>{var D,L,M;let C=(M=(L=(D=Q._internal)==null?void 0:D.currentDate)==null?void 0:L.call(D).getTime())!=null?M:Date.now();if(!J||C-Z>W)Z=C,J=new sG1({baseURL:$,headers:K,fetch:Q.fetch}).getAvailableModels().then((A)=>{return G=A,A}).catch(async(A)=>{throw await QK(A,await dU(await K()))});return G?Promise.resolve(G):J},q=async()=>{return new sG1({baseURL:$,headers:K,fetch:Q.fetch}).getCredits().catch(async(D)=>{throw await QK(D,await dU(await K()))})},z=function(D){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return F(D)};z.specificationVersion="v3",z.getAvailableModels=V,z.getCredits=q,z.imageModel=(D)=>{return new Ty6(D,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})},z.languageModel=F;let B=(D)=>{return new My6(D,{provider:"gateway",baseURL:$,headers:K,fetch:Q.fetch,o11yHeaders:H()})};return z.embeddingModel=B,z.textEmbeddingModel=B,z.tools=Sy6,z}var KW1=yy6();async function by6(Q){let X=EP({settingValue:Q.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(X)return{token:X,authMethod:"api-key"};return{token:await $W1.getVercelOidcToken(),authMethod:"oidc"}}r6();r6();r6();r6();r6();r6();var $71=m6(Z1(),1),YQ0=m6(Z1(),1);r6();r6();var fy6=Object.defineProperty,hy6=(Q,X)=>{for(var Y in X)fy6(Q,Y,{get:X[Y],enumerable:!0})},NW1="AI_InvalidArgumentError",OW1=`vercel.ai.error.${NW1}`,xy6=Symbol.for(OW1),LW1,KW=class extends L1{constructor({parameter:Q,value:X,message:Y}){super({name:NW1,message:`Invalid argument for parameter ${Q}: ${Y}`});this[LW1]=!0,this.parameter=Q,this.value=X}static isInstance(Q){return L1.hasMarker(Q,OW1)}};LW1=xy6;var gy6="AI_InvalidStreamPartError",uy6=`vercel.ai.error.${gy6}`,my6=Symbol.for(uy6),ly6;ly6=my6;var wW1="AI_InvalidToolApprovalError",MW1=`vercel.ai.error.${wW1}`,dy6=Symbol.for(MW1),PW1,py6=class extends L1{constructor({approvalId:Q}){super({name:wW1,message:`Tool approval response references unknown approvalId: "${Q}". No matching tool-approval-request found in message history.`});this[PW1]=!0,this.approvalId=Q}static isInstance(Q){return L1.hasMarker(Q,MW1)}};PW1=dy6;var TW1="AI_InvalidToolInputError",AW1=`vercel.ai.error.${TW1}`,cy6=Symbol.for(AW1),EW1,$Q0=class extends L1{constructor({toolInput:Q,toolName:X,cause:Y,message:J=`Invalid input for tool ${X}: ${_5(Y)}`}){super({name:TW1,message:J,cause:Y});this[EW1]=!0,this.toolInput=Q,this.toolName=X}static isInstance(Q){return L1.hasMarker(Q,AW1)}};EW1=cy6;var jW1="AI_ToolCallNotFoundForApprovalError",CW1=`vercel.ai.error.${jW1}`,ny6=Symbol.for(CW1),IW1,RW1=class extends L1{constructor({toolCallId:Q,approvalId:X}){super({name:jW1,message:`Tool call "${Q}" not found for approval request "${X}".`});this[IW1]=!0,this.toolCallId=Q,this.approvalId=X}static isInstance(Q){return L1.hasMarker(Q,CW1)}};IW1=ny6;var iy6="AI_NoImageGeneratedError",ay6=`vercel.ai.error.${iy6}`,ry6=Symbol.for(ay6),oy6;oy6=ry6;var SW1="AI_NoObjectGeneratedError",vW1=`vercel.ai.error.${SW1}`,sy6=Symbol.for(vW1),kW1,XK=class extends L1{constructor({message:Q="No object generated.",cause:X,text:Y,response:J,usage:G,finishReason:W}){super({name:SW1,message:Q,cause:X});this[kW1]=!0,this.text=Y,this.response=J,this.usage=G,this.finishReason=W}static isInstance(Q){return L1.hasMarker(Q,vW1)}};kW1=sy6;var _W1="AI_NoOutputGeneratedError",yW1=`vercel.ai.error.${_W1}`,ty6=Symbol.for(yW1),bW1,ey6=class extends L1{constructor({message:Q="No output generated.",cause:X}={}){super({name:_W1,message:Q,cause:X});this[bW1]=!0}static isInstance(Q){return L1.hasMarker(Q,yW1)}};bW1=ty6;var fW1="AI_NoSuchToolError",hW1=`vercel.ai.error.${fW1}`,Qb6=Symbol.for(hW1),xW1,QQ0=class extends L1{constructor({toolName:Q,availableTools:X=void 0,message:Y=`Model tried to call unavailable tool '${Q}'. ${X===void 0?"No tools are available.":`Available tools: ${X.join(", ")}.`}`}){super({name:fW1,message:Y});this[xW1]=!0,this.toolName=Q,this.availableTools=X}static isInstance(Q){return L1.hasMarker(Q,hW1)}};xW1=Qb6;var gW1="AI_ToolCallRepairError",uW1=`vercel.ai.error.${gW1}`,Xb6=Symbol.for(uW1),mW1,Yb6=class extends L1{constructor({cause:Q,originalError:X,message:Y=`Error repairing tool call: ${_5(Q)}`}){super({name:gW1,message:Y,cause:Q});this[mW1]=!0,this.originalError=X}static isInstance(Q){return L1.hasMarker(Q,uW1)}};mW1=Xb6;var Jb6=class extends L1{constructor(Q){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${Q.version} for provider "${Q.provider}" and model "${Q.modelId}". AI SDK 5 only supports models that implement specification version "v2".`});this.version=Q.version,this.provider=Q.provider,this.modelId=Q.modelId}},Gb6="AI_InvalidDataContentError",Wb6=`vercel.ai.error.${Gb6}`,Zb6=Symbol.for(Wb6),$b6;$b6=Zb6;var lW1="AI_InvalidMessageRoleError",dW1=`vercel.ai.error.${lW1}`,Kb6=Symbol.for(dW1),pW1,Hb6=class extends L1{constructor({role:Q,message:X=`Invalid message role: '${Q}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:lW1,message:X});this[pW1]=!0,this.role=Q}static isInstance(Q){return L1.hasMarker(Q,dW1)}};pW1=Kb6;var cW1="AI_MessageConversionError",nW1=`vercel.ai.error.${cW1}`,Fb6=Symbol.for(nW1),iW1,Vb6=class extends L1{constructor({originalMessage:Q,message:X}){super({name:cW1,message:X});this[iW1]=!0,this.originalMessage=Q}static isInstance(Q){return L1.hasMarker(Q,nW1)}};iW1=Fb6;var aW1="AI_RetryError",rW1=`vercel.ai.error.${aW1}`,qb6=Symbol.for(rW1),oW1,HW1=class extends L1{constructor({message:Q,reason:X,errors:Y}){super({name:aW1,message:Q});this[oW1]=!0,this.reason=X,this.errors=Y,this.lastError=Y[Y.length-1]}static isInstance(Q){return L1.hasMarker(Q,rW1)}};oW1=qb6;function zb6({warning:Q,provider:X,model:Y}){let J=`AI SDK Warning (${X} / ${Y}):`;switch(Q.type){case"unsupported":{let G=`${J} The feature "${Q.feature}" is not supported.`;if(Q.details)G+=` ${Q.details}`;return G}case"compatibility":{let G=`${J} The feature "${Q.feature}" is used in a compatibility mode.`;if(Q.details)G+=` ${Q.details}`;return G}case"other":return`${J} ${Q.message}`;default:return`${J} ${JSON.stringify(Q,null,2)}`}}var Ub6="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",FW1=!1,sW1=(Q)=>{if(Q.warnings.length===0)return;let X=globalThis.AI_SDK_LOG_WARNINGS;if(X===!1)return;if(typeof X==="function"){X(Q);return}if(!FW1)FW1=!0,console.info(Ub6);for(let Y of Q.warnings)console.warn(zb6({warning:Y,provider:Q.provider,model:Q.model}))};function Bb6({provider:Q,modelId:X}){sW1({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:Q,model:X})}function Db6(Q){if(Q.specificationVersion==="v3")return Q;return Bb6({provider:Q.provider,modelId:Q.modelId}),new Proxy(Q,{get(X,Y){switch(Y){case"specificationVersion":return"v3";case"doGenerate":return async(...J)=>{let G=await X.doGenerate(...J);return{...G,finishReason:tW1(G.finishReason),usage:eW1(G.usage)}};case"doStream":return async(...J)=>{let G=await X.doStream(...J);return{...G,stream:Nb6(G.stream)}};default:return X[Y]}}})}function Nb6(Q){return Q.pipeThrough(new TransformStream({transform(X,Y){switch(X.type){case"finish":Y.enqueue({...X,finishReason:tW1(X.finishReason),usage:eW1(X.usage)});break;default:Y.enqueue(X);break}}}))}function tW1(Q){return{unified:Q==="unknown"?"other":Q,raw:void 0}}function eW1(Q){return{inputTokens:{total:Q.inputTokens,noCache:void 0,cacheRead:Q.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:Q.outputTokens,text:void 0,reasoning:Q.reasoningTokens}}}function Q71(Q){if(typeof Q!=="string"){if(Q.specificationVersion!=="v3"&&Q.specificationVersion!=="v2"){let X=Q;throw new Jb6({version:X.specificationVersion,provider:X.provider,modelId:X.modelId})}return Db6(Q)}return Ob6().languageModel(Q)}function Ob6(){var Q;return(Q=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?Q:KW1}function X71(Q){if(Q==null)return;if(typeof Q==="number")return Q;return Q.totalMs}function Lb6(Q){if(Q==null||typeof Q==="number")return;return Q.stepMs}function wb6(Q){if(Q==null||typeof Q==="number")return;return Q.chunkMs}var Mb6=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var Pb6=(Q)=>{let X=typeof Q==="string"?uU(Q):Q,Y=(X[6]&127)<<21|(X[7]&127)<<14|(X[8]&127)<<7|X[9]&127;return X.slice(Y+10)};function Tb6(Q){return typeof Q==="string"&&Q.startsWith("SUQz")||typeof Q!=="string"&&Q.length>10&&Q[0]===73&&Q[1]===68&&Q[2]===51?Pb6(Q):Q}function Ab6({data:Q,signatures:X}){let Y=Tb6(Q),J=typeof Y==="string"?uU(Y.substring(0,Math.min(Y.length,24))):Y;for(let G of X)if(J.length>=G.bytesPrefix.length&&G.bytesPrefix.every((W,Z)=>W===null||J[Z]===W))return G.mediaType;return}var Eb6="6.0.30",jb6=async({url:Q})=>{var X;let Y=Q.toString();try{let J=await fetch(Y,{headers:t$({},`ai-sdk/${Eb6}`,ny())});if(!J.ok)throw new cy({url:Y,statusCode:J.status,statusText:J.statusText});return{data:new Uint8Array(await J.arrayBuffer()),mediaType:(X=J.headers.get("content-type"))!=null?X:void 0}}catch(J){if(cy.isInstance(J))throw J;throw new cy({url:Y,cause:J})}},Cb6=(Q=jb6)=>(X)=>Promise.all(X.map(async(Y)=>Y.isUrlSupportedByModel?null:Q(Y)));function Ib6(Q){try{let[X,Y]=Q.split(",");return{mediaType:X.split(";")[0].split(":")[1],base64Content:Y}}catch(X){return{mediaType:void 0,base64Content:void 0}}}var Y71=N.union([N.string(),N.instanceof(Uint8Array),N.instanceof(ArrayBuffer),N.custom((Q)=>{var X,Y;return(Y=(X=globalThis.Buffer)==null?void 0:X.isBuffer(Q))!=null?Y:!1},{message:"Must be a Buffer"})]);function J71(Q){if(Q instanceof Uint8Array)return{data:Q,mediaType:void 0};if(Q instanceof ArrayBuffer)return{data:new Uint8Array(Q),mediaType:void 0};if(typeof Q==="string")try{Q=new URL(Q)}catch(X){}if(Q instanceof URL&&Q.protocol==="data:"){let{mediaType:X,base64Content:Y}=Ib6(Q.toString());if(X==null||Y==null)throw new L1({name:"InvalidDataContentError",message:`Invalid data URL format in content ${Q.toString()}`});return{data:Y,mediaType:X}}return{data:Q,mediaType:void 0}}function Rb6(Q){if(typeof Q==="string")return Q;if(Q instanceof ArrayBuffer)return $F(new Uint8Array(Q));return $F(Q)}function Xb(Q){return Q===void 0?[]:Array.isArray(Q)?Q:[Q]}async function Sb6({prompt:Q,supportedUrls:X,download:Y=Cb6()}){let J=await kb6(Q.messages,Y,X),G=[...Q.system!=null?typeof Q.system==="string"?[{role:"system",content:Q.system}]:Xb(Q.system).map((Z)=>({role:"system",content:Z.content,providerOptions:Z.providerOptions})):[],...Q.messages.map((Z)=>vb6({message:Z,downloadedAssets:J}))],W=[];for(let Z of G){if(Z.role!=="tool"){W.push(Z);continue}let $=W.at(-1);if(($==null?void 0:$.role)==="tool")$.content.push(...Z.content);else W.push(Z)}return W}function vb6({message:Q,downloadedAssets:X}){let Y=Q.role;switch(Y){case"system":return{role:"system",content:Q.content,providerOptions:Q.providerOptions};case"user":{if(typeof Q.content==="string")return{role:"user",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"user",content:Q.content.map((J)=>_b6(J,X)).filter((J)=>J.type!=="text"||J.text!==""),providerOptions:Q.providerOptions}}case"assistant":{if(typeof Q.content==="string")return{role:"assistant",content:[{type:"text",text:Q.content}],providerOptions:Q.providerOptions};return{role:"assistant",content:Q.content.filter((J)=>J.type!=="text"||J.text!==""||J.providerOptions!=null).filter((J)=>J.type!=="tool-approval-request").map((J)=>{let G=J.providerOptions;switch(J.type){case"file":{let{data:W,mediaType:Z}=J71(J.data);return{type:"file",data:W,filename:J.filename,mediaType:Z!=null?Z:J.mediaType,providerOptions:G}}case"reasoning":return{type:"reasoning",text:J.text,providerOptions:G};case"text":return{type:"text",text:J.text,providerOptions:G};case"tool-call":return{type:"tool-call",toolCallId:J.toolCallId,toolName:J.toolName,input:J.input,providerExecuted:J.providerExecuted,providerOptions:G};case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:VW1(J.output),providerOptions:G}}}),providerOptions:Q.providerOptions}}case"tool":return{role:"tool",content:Q.content.filter((J)=>J.type!=="tool-approval-response"||J.providerExecuted).map((J)=>{switch(J.type){case"tool-result":return{type:"tool-result",toolCallId:J.toolCallId,toolName:J.toolName,output:VW1(J.output),providerOptions:J.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:J.approvalId,approved:J.approved,reason:J.reason}}}),providerOptions:Q.providerOptions};default:throw new Hb6({role:Y})}}async function kb6(Q,X,Y){let J=Q.filter((W)=>W.role==="user").map((W)=>W.content).filter((W)=>Array.isArray(W)).flat().filter((W)=>W.type==="image"||W.type==="file").map((W)=>{var Z;let $=(Z=W.mediaType)!=null?Z:W.type==="image"?"image/*":void 0,K=W.type==="image"?W.image:W.data;if(typeof K==="string")try{K=new URL(K)}catch(H){}return{mediaType:$,data:K}}).filter((W)=>W.data instanceof URL).map((W)=>({url:W.data,isUrlSupportedByModel:W.mediaType!=null&&h51({url:W.data.toString(),mediaType:W.mediaType,supportedUrls:Y})})),G=await X(J);return Object.fromEntries(G.map((W,Z)=>W==null?null:[J[Z].url.toString(),{data:W.data,mediaType:W.mediaType}]).filter((W)=>W!=null))}function _b6(Q,X){var Y;if(Q.type==="text")return{type:"text",text:Q.text,providerOptions:Q.providerOptions};let J,G=Q.type;switch(G){case"image":J=Q.image;break;case"file":J=Q.data;break;default:throw Error(`Unsupported part type: ${G}`)}let{data:W,mediaType:Z}=J71(J),$=Z!=null?Z:Q.mediaType,K=W;if(K instanceof URL){let H=X[K.toString()];if(H)K=H.data,$!=null||($=H.mediaType)}switch(G){case"image":{if(K instanceof Uint8Array||typeof K==="string")$=(Y=Ab6({data:K,signatures:Mb6}))!=null?Y:$;return{type:"file",mediaType:$!=null?$:"image/*",filename:void 0,data:K,providerOptions:Q.providerOptions}}case"file":{if($==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:$,filename:Q.filename,data:K,providerOptions:Q.providerOptions}}}}function VW1(Q){if(Q.type!=="content")return Q;return{type:"content",value:Q.value.map((X)=>{if(X.type!=="media")return X;if(X.mediaType.startsWith("image/"))return{type:"image-data",data:X.data,mediaType:X.mediaType};return{type:"file-data",data:X.data,mediaType:X.mediaType}})}}async function cU({toolCallId:Q,input:X,output:Y,tool:J,errorMode:G}){if(G==="text")return{type:"error-text",value:_5(Y)};else if(G==="json")return{type:"error-json",value:qW1(Y)};if(J==null?void 0:J.toModelOutput)return await J.toModelOutput({toolCallId:Q,input:X,output:Y});return typeof Y==="string"?{type:"text",value:Y}:{type:"json",value:qW1(Y)}}function qW1(Q){return Q===void 0?null:Q}function yb6({maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,seed:Z,stopSequences:$}){if(Q!=null){if(!Number.isInteger(Q))throw new KW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be an integer"});if(Q<1)throw new KW({parameter:"maxOutputTokens",value:Q,message:"maxOutputTokens must be >= 1"})}if(X!=null){if(typeof X!=="number")throw new KW({parameter:"temperature",value:X,message:"temperature must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new KW({parameter:"topP",value:Y,message:"topP must be a number"})}if(J!=null){if(typeof J!=="number")throw new KW({parameter:"topK",value:J,message:"topK must be a number"})}if(G!=null){if(typeof G!=="number")throw new KW({parameter:"presencePenalty",value:G,message:"presencePenalty must be a number"})}if(W!=null){if(typeof W!=="number")throw new KW({parameter:"frequencyPenalty",value:W,message:"frequencyPenalty must be a number"})}if(Z!=null){if(!Number.isInteger(Z))throw new KW({parameter:"seed",value:Z,message:"seed must be an integer"})}return{maxOutputTokens:Q,temperature:X,topP:Y,topK:J,presencePenalty:G,frequencyPenalty:W,stopSequences:$,seed:Z}}function bb6(Q){return Q!=null&&Object.keys(Q).length>0}async function fb6({tools:Q,toolChoice:X,activeTools:Y}){if(!bb6(Q))return{tools:void 0,toolChoice:void 0};let J=Y!=null?Object.entries(Q).filter(([W])=>Y.includes(W)):Object.entries(Q),G=[];for(let[W,Z]of J){let $=Z.type;switch($){case void 0:case"dynamic":case"function":G.push({type:"function",name:W,description:Z.description,inputSchema:await ZW(Z.inputSchema).jsonSchema,...Z.inputExamples!=null?{inputExamples:Z.inputExamples}:{},providerOptions:Z.providerOptions,...Z.strict!=null?{strict:Z.strict}:{}});break;case"provider":G.push({type:"provider",name:W,id:Z.id,args:Z.args});break;default:throw Error(`Unsupported tool type: ${$}`)}}return{tools:G,toolChoice:X==null?{type:"auto"}:typeof X==="string"?{type:X}:{type:"tool",toolName:X.toolName}}}var _P=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),_P.optional()),N.array(_P)])),i1=N.record(N.string(),N.record(N.string(),_P.optional())),G71=N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),hb6=N.object({type:N.literal("image"),image:N.union([Y71,N.instanceof(URL)]),mediaType:N.string().optional(),providerOptions:i1.optional()}),W71=N.object({type:N.literal("file"),data:N.union([Y71,N.instanceof(URL)]),filename:N.string().optional(),mediaType:N.string(),providerOptions:i1.optional()}),xb6=N.object({type:N.literal("reasoning"),text:N.string(),providerOptions:i1.optional()}),gb6=N.object({type:N.literal("tool-call"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerOptions:i1.optional(),providerExecuted:N.boolean().optional()}),ub6=N.discriminatedUnion("type",[N.object({type:N.literal("text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("json"),value:_P,providerOptions:i1.optional()}),N.object({type:N.literal("execution-denied"),reason:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("error-text"),value:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("error-json"),value:_P,providerOptions:i1.optional()}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("media"),data:N.string(),mediaType:N.string()}),N.object({type:N.literal("file-data"),data:N.string(),mediaType:N.string(),filename:N.string().optional(),providerOptions:i1.optional()}),N.object({type:N.literal("file-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("image-data"),data:N.string(),mediaType:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-url"),url:N.string(),providerOptions:i1.optional()}),N.object({type:N.literal("image-file-id"),fileId:N.union([N.string(),N.record(N.string(),N.string())]),providerOptions:i1.optional()}),N.object({type:N.literal("custom"),providerOptions:i1.optional()})]))})]),Z71=N.object({type:N.literal("tool-result"),toolCallId:N.string(),toolName:N.string(),output:ub6,providerOptions:i1.optional()}),mb6=N.object({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),lb6=N.object({type:N.literal("tool-approval-response"),approvalId:N.string(),approved:N.boolean(),reason:N.string().optional()}),db6=N.object({role:N.literal("system"),content:N.string(),providerOptions:i1.optional()}),pb6=N.object({role:N.literal("user"),content:N.union([N.string(),N.array(N.union([G71,hb6,W71]))]),providerOptions:i1.optional()}),cb6=N.object({role:N.literal("assistant"),content:N.union([N.string(),N.array(N.union([G71,W71,xb6,gb6,Z71,mb6]))]),providerOptions:i1.optional()}),nb6=N.object({role:N.literal("tool"),content:N.array(N.union([Z71,lb6])),providerOptions:i1.optional()}),ib6=N.union([db6,pb6,cb6,nb6]);async function ab6(Q){if(Q.prompt==null&&Q.messages==null)throw new JF({prompt:Q,message:"prompt or messages must be defined"});if(Q.prompt!=null&&Q.messages!=null)throw new JF({prompt:Q,message:"prompt and messages cannot be defined at the same time"});if(Q.system!=null&&typeof Q.system!=="string"&&!Xb(Q.system).every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&J.role==="system"))throw new JF({prompt:Q,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let X;if(Q.prompt!=null&&typeof Q.prompt==="string")X=[{role:"user",content:Q.prompt}];else if(Q.prompt!=null&&Array.isArray(Q.prompt))X=Q.prompt;else if(Q.messages!=null)X=Q.messages;else throw new JF({prompt:Q,message:"prompt or messages must be defined"});if(X.length===0)throw new JF({prompt:Q,message:"messages must not be empty"});let Y=await wX({value:X,schema:N.array(ib6)});if(!Y.success)throw new JF({prompt:Q,message:"The messages do not match the ModelMessage[] schema.",cause:Y.error});return{messages:X,system:Q.system}}function rb6(Q){if(!ey.isInstance(Q))return Q;let X=(process==null?void 0:"production")==="production",Y="https://ai-sdk.dev/unauthenticated-ai-gateway";if(X)return new L1({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${Y}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
1066
1066
|
|
|
1067
1067
|
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
1068
1068
|
|
|
@@ -1070,11 +1070,11 @@ Alternatively, you can use a provider module instead of the AI Gateway.
|
|
|
1070
1070
|
|
|
1071
1071
|
Learn more: \x1B[34m${Y}\x1B[0m
|
|
1072
1072
|
|
|
1073
|
-
`),{name:"GatewayAuthenticationError"})}function XQ0({operationId:Q,telemetry:X}){return{"operation.name":`${Q}${(X==null?void 0:X.functionId)!=null?` ${X.functionId}`:""}`,"resource.name":X==null?void 0:X.functionId,"ai.operationId":Q,"ai.telemetry.functionId":X==null?void 0:X.functionId}}function ob6({model:Q,settings:X,telemetry:Y,headers:J}){var G;return{"ai.model.provider":Q.provider,"ai.model.id":Q.modelId,...Object.entries(X).reduce((W,[Z,$])=>{if(Z==="timeout"){let K=X71($);if(K!=null)W[`ai.settings.${Z}`]=K}else W[`ai.settings.${Z}`]=$;return W},{}),...Object.entries((G=Y==null?void 0:Y.metadata)!=null?G:{}).reduce((W,[Z,$])=>{return W[`ai.telemetry.metadata.${Z}`]=$,W},{}),...Object.entries(J!=null?J:{}).reduce((W,[Z,$])=>{if($!==void 0)W[`ai.request.headers.${Z}`]=$;return W},{})}}var sb6={startSpan(){return Qb},startActiveSpan(Q,X,Y,J){if(typeof X==="function")return X(Qb);if(typeof Y==="function")return Y(Qb);if(typeof J==="function")return J(Qb)}},Qb={spanContext(){return tb6},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},tb6={traceId:"",spanId:"",traceFlags:0};function eb6({isEnabled:Q=!1,tracer:X}={}){if(!Q)return sb6;if(X)return X;return $71.trace.getTracer("ai")}async function JQ0({name:Q,tracer:X,attributes:Y,fn:J,endWhenDone:G=!0}){return X.startActiveSpan(Q,{attributes:await Y},async(W)=>{try{let Z=await J(W);if(G)W.end();return Z}catch(Z){try{K71(W,Z)}finally{W.end()}throw Z}})}function K71(Q,X){if(X instanceof Error)Q.recordException({name:X.name,message:X.message,stack:X.stack}),Q.setStatus({code:YQ0.SpanStatusCode.ERROR,message:X.message});else Q.setStatus({code:YQ0.SpanStatusCode.ERROR})}async function pU({telemetry:Q,attributes:X}){if((Q==null?void 0:Q.isEnabled)!==!0)return{};let Y={};for(let[J,G]of Object.entries(X)){if(G==null)continue;if(typeof G==="object"&&"input"in G&&typeof G.input==="function"){if((Q==null?void 0:Q.recordInputs)===!1)continue;let W=await G.input();if(W!=null)Y[J]=W;continue}if(typeof G==="object"&&"output"in G&&typeof G.output==="function"){if((Q==null?void 0:Q.recordOutputs)===!1)continue;let W=await G.output();if(W!=null)Y[J]=W;continue}Y[J]=G}return Y}function Qf6(Q){return JSON.stringify(Q.map((X)=>({...X,content:typeof X.content==="string"?X.content:X.content.map((Y)=>Y.type==="file"?{...Y,data:Y.data instanceof Uint8Array?Rb6(Y.data):Y.data}:Y)})))}function Xf6(Q){return{inputTokens:Q.inputTokens.total,inputTokenDetails:{noCacheTokens:Q.inputTokens.noCache,cacheReadTokens:Q.inputTokens.cacheRead,cacheWriteTokens:Q.inputTokens.cacheWrite},outputTokens:Q.outputTokens.total,outputTokenDetails:{textTokens:Q.outputTokens.text,reasoningTokens:Q.outputTokens.reasoning},totalTokens:h5(Q.inputTokens.total,Q.outputTokens.total),raw:Q.raw,reasoningTokens:Q.outputTokens.reasoning,cachedInputTokens:Q.inputTokens.cacheRead}}function r80(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function Yf6(Q,X){var Y,J,G,W,Z,$,K,H,F,V;return{inputTokens:h5(Q.inputTokens,X.inputTokens),inputTokenDetails:{noCacheTokens:h5((Y=Q.inputTokenDetails)==null?void 0:Y.noCacheTokens,(J=X.inputTokenDetails)==null?void 0:J.noCacheTokens),cacheReadTokens:h5((G=Q.inputTokenDetails)==null?void 0:G.cacheReadTokens,(W=X.inputTokenDetails)==null?void 0:W.cacheReadTokens),cacheWriteTokens:h5((Z=Q.inputTokenDetails)==null?void 0:Z.cacheWriteTokens,($=X.inputTokenDetails)==null?void 0:$.cacheWriteTokens)},outputTokens:h5(Q.outputTokens,X.outputTokens),outputTokenDetails:{textTokens:h5((K=Q.outputTokenDetails)==null?void 0:K.textTokens,(H=X.outputTokenDetails)==null?void 0:H.textTokens),reasoningTokens:h5((F=Q.outputTokenDetails)==null?void 0:F.reasoningTokens,(V=X.outputTokenDetails)==null?void 0:V.reasoningTokens)},totalTokens:h5(Q.totalTokens,X.totalTokens),reasoningTokens:h5(Q.reasoningTokens,X.reasoningTokens),cachedInputTokens:h5(Q.cachedInputTokens,X.cachedInputTokens)}}function h5(Q,X){return Q==null&&X==null?void 0:(Q!=null?Q:0)+(X!=null?X:0)}function KQ0(Q,X){if(Q===void 0&&X===void 0)return;if(Q===void 0)return X;if(X===void 0)return Q;let Y={...Q};for(let J in X)if(Object.prototype.hasOwnProperty.call(X,J)){let G=X[J];if(G===void 0)continue;let W=J in Q?Q[J]:void 0,Z=G!==null&&typeof G==="object"&&!Array.isArray(G)&&!(G instanceof Date)&&!(G instanceof RegExp),$=W!==null&&W!==void 0&&typeof W==="object"&&!Array.isArray(W)&&!(W instanceof Date)&&!(W instanceof RegExp);if(Z&&$)Y[J]=KQ0(W,G);else Y[J]=G}return Y}function Jf6({error:Q,exponentialBackoffDelay:X}){let Y=Q.responseHeaders;if(!Y)return X;let J,G=Y["retry-after-ms"];if(G){let Z=parseFloat(G);if(!Number.isNaN(Z))J=Z}let W=Y["retry-after"];if(W&&J===void 0){let Z=parseFloat(W);if(!Number.isNaN(Z))J=Z*1000;else J=Date.parse(W)-Date.now()}if(J!=null&&!Number.isNaN(J)&&0<=J&&(J<60000||J<X))return J;return X}var Gf6=({maxRetries:Q=2,initialDelayInMs:X=2000,backoffFactor:Y=2,abortSignal:J}={})=>async(G)=>H71(G,{maxRetries:Q,delayInMs:X,backoffFactor:Y,abortSignal:J});async function H71(Q,{maxRetries:X,delayInMs:Y,backoffFactor:J,abortSignal:G},W=[]){try{return await Q()}catch(Z){if(u7(Z))throw Z;if(X===0)throw Z;let $=AP(Z),K=[...W,Z],H=K.length;if(H>X)throw new HW1({message:`Failed after ${H} attempts. Last error: ${$}`,reason:"maxRetriesExceeded",errors:K});if(Z instanceof Error&&r8.isInstance(Z)&&Z.isRetryable===!0&&H<=X)return await S51(Jf6({error:Z,exponentialBackoffDelay:Y}),{abortSignal:G}),H71(Q,{maxRetries:X,delayInMs:J*Y,backoffFactor:J,abortSignal:G},K);if(H===1)throw Z;throw new HW1({message:`Failed after ${H} attempts with non-retryable error: '${$}'`,reason:"errorNotRetryable",errors:K})}}function Wf6({maxRetries:Q,abortSignal:X}){if(Q!=null){if(!Number.isInteger(Q))throw new KW({parameter:"maxRetries",value:Q,message:"maxRetries must be an integer"});if(Q<0)throw new KW({parameter:"maxRetries",value:Q,message:"maxRetries must be >= 0"})}let Y=Q!=null?Q:2;return{maxRetries:Y,retry:Gf6({maxRetries:Y,abortSignal:X})}}function Zf6({messages:Q}){let X=Q.at(-1);if((X==null?void 0:X.role)!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let Y={};for(let K of Q)if(K.role==="assistant"&&typeof K.content!=="string"){let H=K.content;for(let F of H)if(F.type==="tool-call")Y[F.toolCallId]=F}let J={};for(let K of Q)if(K.role==="assistant"&&typeof K.content!=="string"){let H=K.content;for(let F of H)if(F.type==="tool-approval-request")J[F.approvalId]=F}let G={};for(let K of X.content)if(K.type==="tool-result")G[K.toolCallId]=K;let W=[],Z=[],$=X.content.filter((K)=>K.type==="tool-approval-response");for(let K of $){let H=J[K.approvalId];if(H==null)throw new py6({approvalId:K.approvalId});if(G[H.toolCallId]!=null)continue;let F=Y[H.toolCallId];if(F==null)throw new RW1({toolCallId:H.toolCallId,approvalId:H.approvalId});let V={approvalRequest:H,approvalResponse:K,toolCall:F};if(K.approved)W.push(V);else Z.push(V)}return{approvedToolApprovals:W,deniedToolApprovals:Z}}async function F71({toolCall:Q,tools:X,tracer:Y,telemetry:J,messages:G,abortSignal:W,experimental_context:Z,onPreliminaryToolResult:$}){let{toolName:K,toolCallId:H,input:F}=Q,V=X==null?void 0:X[K];if((V==null?void 0:V.execute)==null)return;return JQ0({name:"ai.toolCall",attributes:pU({telemetry:J,attributes:{...XQ0({operationId:"ai.toolCall",telemetry:J}),"ai.toolCall.name":K,"ai.toolCall.id":H,"ai.toolCall.args":{output:()=>JSON.stringify(F)}}}),tracer:Y,fn:async(q)=>{let z;try{let B=i51({execute:V.execute.bind(V),input:F,options:{toolCallId:H,messages:G,abortSignal:W,experimental_context:Z}});for await(let D of B)if(D.type==="preliminary")$==null||$({...Q,type:"tool-result",output:D.output,preliminary:!0});else z=D.output}catch(B){return K71(q,B),{type:"tool-error",toolCallId:H,toolName:K,input:F,error:B,dynamic:V.type==="dynamic",...Q.providerMetadata!=null?{providerMetadata:Q.providerMetadata}:{}}}try{q.setAttributes(await pU({telemetry:J,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(z)}}}))}catch(B){}return{type:"tool-result",toolCallId:H,toolName:K,input:F,output:z,dynamic:V.type==="dynamic",...Q.providerMetadata!=null?{providerMetadata:Q.providerMetadata}:{}}}})}var $f6=class{constructor({data:Q,mediaType:X}){let Y=Q instanceof Uint8Array;this.base64Data=Y?void 0:Q,this.uint8ArrayData=Y?Q:void 0,this.mediaType=X}get base64(){if(this.base64Data==null)this.base64Data=$F(this.uint8ArrayData);return this.base64Data}get uint8Array(){if(this.uint8ArrayData==null)this.uint8ArrayData=uU(this.base64Data);return this.uint8ArrayData}},Kf6=class extends $f6{constructor(Q){super(Q);this.type="file"}};async function Hf6({tool:Q,toolCall:X,messages:Y,experimental_context:J}){if(Q.needsApproval==null)return!1;if(typeof Q.needsApproval==="boolean")return Q.needsApproval;return await Q.needsApproval(X.input,{toolCallId:X.toolCallId,messages:Y,experimental_context:J})}var Ff6={};hy6(Ff6,{array:()=>zf6,choice:()=>Uf6,json:()=>Bf6,object:()=>qf6,text:()=>GQ0});function Vf6(Q){let X=["ROOT"],Y=-1,J=null;function G(K,H,F){switch(K){case'"':{Y=H,X.pop(),X.push(F),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{Y=H,J=H,X.pop(),X.push(F),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(F),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{Y=H,X.pop(),X.push(F),X.push("INSIDE_NUMBER");break}case"{":{Y=H,X.pop(),X.push(F),X.push("INSIDE_OBJECT_START");break}case"[":{Y=H,X.pop(),X.push(F),X.push("INSIDE_ARRAY_START");break}}}function W(K,H){switch(K){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{Y=H,X.pop();break}}}function Z(K,H){switch(K){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{Y=H,X.pop();break}}}for(let K=0;K<Q.length;K++){let H=Q[K];switch(X[X.length-1]){case"ROOT":G(H,K,"FINISH");break;case"INSIDE_OBJECT_START":{switch(H){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{Y=K,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(H){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(H){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(H){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{G(H,K,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{W(H,K);break}case"INSIDE_STRING":{switch(H){case'"':{X.pop(),Y=K;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:Y=K}break}case"INSIDE_ARRAY_START":{switch(H){case"]":{Y=K,X.pop();break}default:{Y=K,G(H,K,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(H){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{Y=K,X.pop();break}default:{Y=K;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{G(H,K,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{X.pop(),Y=K;break}case"INSIDE_NUMBER":{switch(H){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{Y=K;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(H,K);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")W(H,K);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")W(H,K);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(H,K);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Q.substring(J,K+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")W(H,K);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(H,K)}else Y=K;break}}}let $=Q.slice(0,Y+1);for(let K=X.length-1;K>=0;K--)switch(X[K]){case"INSIDE_STRING":{$+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{$+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{$+="]";break}case"INSIDE_LITERAL":{let F=Q.substring(J,Q.length);if("true".startsWith(F))$+="true".slice(F.length);else if("false".startsWith(F))$+="false".slice(F.length);else if("null".startsWith(F))$+="null".slice(F.length)}}return $}async function yP(Q){if(Q===void 0)return{value:void 0,state:"undefined-input"};let X=await JY({text:Q});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await JY({text:Vf6(Q)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var GQ0=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Q}){return Q},async parsePartialOutput({text:Q}){return{partial:Q}},createElementStreamTransform(){return}}),qf6=({schema:Q,name:X,description:Y})=>{let J=ZW(Q);return{name:"object",responseFormat:N9(J.jsonSchema).then((G)=>({type:"json",schema:G,...X!=null&&{name:X},...Y!=null&&{description:Y}})),async parseCompleteOutput({text:G},W){let Z=await JY({text:G});if(!Z.success)throw new XK({message:"No object generated: could not parse the response.",cause:Z.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});let $=await wX({value:Z.value,schema:J});if(!$.success)throw new XK({message:"No object generated: response did not match schema.",cause:$.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});return $.value},async parsePartialOutput({text:G}){let W=await yP(G);switch(W.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:W.value}}},createElementStreamTransform(){return}}},zf6=({element:Q,name:X,description:Y})=>{let J=ZW(Q);return{name:"array",responseFormat:N9(J.jsonSchema).then((G)=>{let{$schema:W,...Z}=G;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:Z}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...Y!=null&&{description:Y}}}),async parseCompleteOutput({text:G},W){let Z=await JY({text:G});if(!Z.success)throw new XK({message:"No object generated: could not parse the response.",cause:Z.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});let $=Z.value;if($==null||typeof $!=="object"||!("elements"in $)||!Array.isArray($.elements))throw new XK({message:"No object generated: response did not match schema.",cause:new y5({value:$,cause:"response must be an object with an elements array"}),text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});for(let K of $.elements){let H=await wX({value:K,schema:J});if(!H.success)throw new XK({message:"No object generated: response did not match schema.",cause:H.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason})}return $.elements},async parsePartialOutput({text:G}){let W=await yP(G);switch(W.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let Z=W.value;if(Z==null||typeof Z!=="object"||!("elements"in Z)||!Array.isArray(Z.elements))return;let $=W.state==="repaired-parse"&&Z.elements.length>0?Z.elements.slice(0,-1):Z.elements,K=[];for(let H of $){let F=await wX({value:H,schema:J});if(F.success)K.push(F.value)}return{partial:K}}}},createElementStreamTransform(){let G=0;return new TransformStream({transform({partialOutput:W},Z){if(W!=null)for(;G<W.length;G++)Z.enqueue(W[G])}})}}},Uf6=({options:Q,name:X,description:Y})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Q}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...Y!=null&&{description:Y}}),async parseCompleteOutput({text:J},G){let W=await JY({text:J});if(!W.success)throw new XK({message:"No object generated: could not parse the response.",cause:W.error,text:J,response:G.response,usage:G.usage,finishReason:G.finishReason});let Z=W.value;if(Z==null||typeof Z!=="object"||!("result"in Z)||typeof Z.result!=="string"||!Q.includes(Z.result))throw new XK({message:"No object generated: response did not match schema.",cause:new y5({value:Z,cause:"response must be an object that contains a choice value."}),text:J,response:G.response,usage:G.usage,finishReason:G.finishReason});return Z.result},async parsePartialOutput({text:J}){let G=await yP(J);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string")return;let Z=Q.filter(($)=>$.startsWith(W.result));if(G.state==="successful-parse")return Z.includes(W.result)?{partial:W.result}:void 0;else return Z.length===1?{partial:Z[0]}:void 0}}},createElementStreamTransform(){return}}},Bf6=({name:Q,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Q!=null&&{name:Q},...X!=null&&{description:X}}),async parseCompleteOutput({text:Y},J){let G=await JY({text:Y});if(!G.success)throw new XK({message:"No object generated: could not parse the response.",cause:G.error,text:Y,response:J.response,usage:J.usage,finishReason:J.finishReason});return G.value},async parsePartialOutput({text:Y}){let J=await yP(Y);switch(J.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return J.value===void 0?void 0:{partial:J.value}}},createElementStreamTransform(){return}}};async function Df6({toolCall:Q,tools:X,repairToolCall:Y,system:J,messages:G}){var W;try{if(X==null){if(Q.providerExecuted&&Q.dynamic)return await V71(Q);throw new QQ0({toolName:Q.toolName})}try{return await zW1({toolCall:Q,tools:X})}catch(Z){if(Y==null||!(QQ0.isInstance(Z)||$Q0.isInstance(Z)))throw Z;let $=null;try{$=await Y({toolCall:Q,tools:X,inputSchema:async({toolName:K})=>{let{inputSchema:H}=X[K];return await ZW(H).jsonSchema},system:J,messages:G,error:Z})}catch(K){throw new Yb6({cause:K,originalError:Z})}if($==null)throw Z;return await zW1({toolCall:$,tools:X})}}catch(Z){let $=await JY({text:Q.input}),K=$.success?$.value:Q.input;return{type:"tool-call",toolCallId:Q.toolCallId,toolName:Q.toolName,input:K,dynamic:!0,invalid:!0,error:Z,title:(W=X==null?void 0:X[Q.toolName])==null?void 0:W.title,providerExecuted:Q.providerExecuted,providerMetadata:Q.providerMetadata}}}async function V71(Q){let X=Q.input.trim()===""?{success:!0,value:{}}:await JY({text:Q.input});if(X.success===!1)throw new $Q0({toolName:Q.toolName,toolInput:Q.input,cause:X.error});return{type:"tool-call",toolCallId:Q.toolCallId,toolName:Q.toolName,input:X.value,providerExecuted:!0,dynamic:!0,providerMetadata:Q.providerMetadata}}async function zW1({toolCall:Q,tools:X}){let Y=Q.toolName,J=X[Y];if(J==null){if(Q.providerExecuted&&Q.dynamic)return await V71(Q);throw new QQ0({toolName:Q.toolName,availableTools:Object.keys(X)})}let G=ZW(J.inputSchema),W=Q.input.trim()===""?await wX({value:{},schema:G}):await JY({text:Q.input,schema:G});if(W.success===!1)throw new $Q0({toolName:Y,toolInput:Q.input,cause:W.error});return J.type==="dynamic"?{type:"tool-call",toolCallId:Q.toolCallId,toolName:Q.toolName,input:W.value,providerExecuted:Q.providerExecuted,providerMetadata:Q.providerMetadata,dynamic:!0,title:J.title}:{type:"tool-call",toolCallId:Q.toolCallId,toolName:Y,input:W.value,providerExecuted:Q.providerExecuted,providerMetadata:Q.providerMetadata,title:J.title}}var Nf6=class{constructor({content:Q,finishReason:X,rawFinishReason:Y,usage:J,warnings:G,request:W,response:Z,providerMetadata:$}){this.content=Q,this.finishReason=X,this.rawFinishReason=Y,this.usage=J,this.warnings=G,this.request=W,this.response=Z,this.providerMetadata=$}get text(){return this.content.filter((Q)=>Q.type==="text").map((Q)=>Q.text).join("")}get reasoning(){return this.content.filter((Q)=>Q.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map((Q)=>Q.text).join("")}get files(){return this.content.filter((Q)=>Q.type==="file").map((Q)=>Q.file)}get sources(){return this.content.filter((Q)=>Q.type==="source")}get toolCalls(){return this.content.filter((Q)=>Q.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter((Q)=>Q.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter((Q)=>Q.dynamic===!0)}get toolResults(){return this.content.filter((Q)=>Q.type==="tool-result")}get staticToolResults(){return this.toolResults.filter((Q)=>Q.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter((Q)=>Q.dynamic===!0)}};function HQ0(Q){return({steps:X})=>X.length===Q}async function Of6({stopConditions:Q,steps:X}){return(await Promise.all(Q.map((Y)=>Y({steps:X})))).some((Y)=>Y)}async function UW1({content:Q,tools:X}){let Y=[],J=[];for(let W of Q){if(W.type==="source")continue;if((W.type==="tool-result"||W.type==="tool-error")&&!W.providerExecuted)continue;if(W.type==="text"&&W.text.length===0)continue;switch(W.type){case"text":J.push({type:"text",text:W.text,providerOptions:W.providerMetadata});break;case"reasoning":J.push({type:"reasoning",text:W.text,providerOptions:W.providerMetadata});break;case"file":J.push({type:"file",data:W.file.base64,mediaType:W.file.mediaType,providerOptions:W.providerMetadata});break;case"tool-call":J.push({type:"tool-call",toolCallId:W.toolCallId,toolName:W.toolName,input:W.input,providerExecuted:W.providerExecuted,providerOptions:W.providerMetadata});break;case"tool-result":{let Z=await cU({toolCallId:W.toolCallId,input:W.input,tool:X==null?void 0:X[W.toolName],output:W.output,errorMode:"none"});J.push({type:"tool-result",toolCallId:W.toolCallId,toolName:W.toolName,output:Z,providerOptions:W.providerMetadata});break}case"tool-error":{let Z=await cU({toolCallId:W.toolCallId,input:W.input,tool:X==null?void 0:X[W.toolName],output:W.error,errorMode:"json"});J.push({type:"tool-result",toolCallId:W.toolCallId,toolName:W.toolName,output:Z,providerOptions:W.providerMetadata});break}case"tool-approval-request":J.push({type:"tool-approval-request",approvalId:W.approvalId,toolCallId:W.toolCall.toolCallId});break}}if(J.length>0)Y.push({role:"assistant",content:J});let G=[];for(let W of Q){if(!(W.type==="tool-result"||W.type==="tool-error")||W.providerExecuted)continue;let Z=await cU({toolCallId:W.toolCallId,input:W.input,tool:X==null?void 0:X[W.toolName],output:W.type==="tool-result"?W.output:W.error,errorMode:W.type==="tool-error"?"text":"none"});G.push({type:"tool-result",toolCallId:W.toolCallId,toolName:W.toolName,output:Z,...W.providerMetadata!=null?{providerOptions:W.providerMetadata}:{}})}if(G.length>0)Y.push({role:"tool",content:G});return Y}function Lf6(...Q){let X=Q.filter((J)=>J!=null);if(X.length===0)return;if(X.length===1)return X[0];let Y=new AbortController;for(let J of X){if(J.aborted)return Y.abort(J.reason),Y.signal;J.addEventListener("abort",()=>{Y.abort(J.reason)},{once:!0})}return Y.signal}var Cd4=WW({prefix:"aitxt",size:24});function Yb(Q,X){let Y=new Headers(Q!=null?Q:{});for(let[J,G]of Object.entries(X))if(!Y.has(J))Y.set(J,G);return Y}function wf6({status:Q,statusText:X,headers:Y,textStream:J}){return new Response(J.pipeThrough(new TextEncoderStream),{status:Q!=null?Q:200,statusText:X,headers:Yb(Y,{"content-type":"text/plain; charset=utf-8"})})}function q71({response:Q,status:X,statusText:Y,headers:J,stream:G}){let W=X!=null?X:200;if(Y!==void 0)Q.writeHead(W,Y,J);else Q.writeHead(W,J);let Z=G.getReader();(async()=>{try{while(!0){let{done:K,value:H}=await Z.read();if(K)break;if(!Q.write(H))await new Promise((V)=>{Q.once("drain",V)})}}catch(K){throw K}finally{Q.end()}})()}function Mf6({response:Q,status:X,statusText:Y,headers:J,textStream:G}){q71({response:Q,status:X,statusText:Y,headers:Object.fromEntries(Yb(J,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:G.pipeThrough(new TextEncoderStream)})}var z71=class extends TransformStream{constructor(){super({transform(Q,X){X.enqueue(`data: ${JSON.stringify(Q)}
|
|
1073
|
+
`),{name:"GatewayAuthenticationError"})}function XQ0({operationId:Q,telemetry:X}){return{"operation.name":`${Q}${(X==null?void 0:X.functionId)!=null?` ${X.functionId}`:""}`,"resource.name":X==null?void 0:X.functionId,"ai.operationId":Q,"ai.telemetry.functionId":X==null?void 0:X.functionId}}function ob6({model:Q,settings:X,telemetry:Y,headers:J}){var G;return{"ai.model.provider":Q.provider,"ai.model.id":Q.modelId,...Object.entries(X).reduce((W,[Z,$])=>{if(Z==="timeout"){let K=X71($);if(K!=null)W[`ai.settings.${Z}`]=K}else W[`ai.settings.${Z}`]=$;return W},{}),...Object.entries((G=Y==null?void 0:Y.metadata)!=null?G:{}).reduce((W,[Z,$])=>{return W[`ai.telemetry.metadata.${Z}`]=$,W},{}),...Object.entries(J!=null?J:{}).reduce((W,[Z,$])=>{if($!==void 0)W[`ai.request.headers.${Z}`]=$;return W},{})}}var sb6={startSpan(){return Qb},startActiveSpan(Q,X,Y,J){if(typeof X==="function")return X(Qb);if(typeof Y==="function")return Y(Qb);if(typeof J==="function")return J(Qb)}},Qb={spanContext(){return tb6},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},tb6={traceId:"",spanId:"",traceFlags:0};function eb6({isEnabled:Q=!1,tracer:X}={}){if(!Q)return sb6;if(X)return X;return $71.trace.getTracer("ai")}async function JQ0({name:Q,tracer:X,attributes:Y,fn:J,endWhenDone:G=!0}){return X.startActiveSpan(Q,{attributes:await Y},async(W)=>{try{let Z=await J(W);if(G)W.end();return Z}catch(Z){try{K71(W,Z)}finally{W.end()}throw Z}})}function K71(Q,X){if(X instanceof Error)Q.recordException({name:X.name,message:X.message,stack:X.stack}),Q.setStatus({code:YQ0.SpanStatusCode.ERROR,message:X.message});else Q.setStatus({code:YQ0.SpanStatusCode.ERROR})}async function pU({telemetry:Q,attributes:X}){if((Q==null?void 0:Q.isEnabled)!==!0)return{};let Y={};for(let[J,G]of Object.entries(X)){if(G==null)continue;if(typeof G==="object"&&"input"in G&&typeof G.input==="function"){if((Q==null?void 0:Q.recordInputs)===!1)continue;let W=await G.input();if(W!=null)Y[J]=W;continue}if(typeof G==="object"&&"output"in G&&typeof G.output==="function"){if((Q==null?void 0:Q.recordOutputs)===!1)continue;let W=await G.output();if(W!=null)Y[J]=W;continue}Y[J]=G}return Y}function Qf6(Q){return JSON.stringify(Q.map((X)=>({...X,content:typeof X.content==="string"?X.content:X.content.map((Y)=>Y.type==="file"?{...Y,data:Y.data instanceof Uint8Array?Rb6(Y.data):Y.data}:Y)})))}function Xf6(Q){return{inputTokens:Q.inputTokens.total,inputTokenDetails:{noCacheTokens:Q.inputTokens.noCache,cacheReadTokens:Q.inputTokens.cacheRead,cacheWriteTokens:Q.inputTokens.cacheWrite},outputTokens:Q.outputTokens.total,outputTokenDetails:{textTokens:Q.outputTokens.text,reasoningTokens:Q.outputTokens.reasoning},totalTokens:h5(Q.inputTokens.total,Q.outputTokens.total),raw:Q.raw,reasoningTokens:Q.outputTokens.reasoning,cachedInputTokens:Q.inputTokens.cacheRead}}function r80(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function Yf6(Q,X){var Y,J,G,W,Z,$,K,H,F,V;return{inputTokens:h5(Q.inputTokens,X.inputTokens),inputTokenDetails:{noCacheTokens:h5((Y=Q.inputTokenDetails)==null?void 0:Y.noCacheTokens,(J=X.inputTokenDetails)==null?void 0:J.noCacheTokens),cacheReadTokens:h5((G=Q.inputTokenDetails)==null?void 0:G.cacheReadTokens,(W=X.inputTokenDetails)==null?void 0:W.cacheReadTokens),cacheWriteTokens:h5((Z=Q.inputTokenDetails)==null?void 0:Z.cacheWriteTokens,($=X.inputTokenDetails)==null?void 0:$.cacheWriteTokens)},outputTokens:h5(Q.outputTokens,X.outputTokens),outputTokenDetails:{textTokens:h5((K=Q.outputTokenDetails)==null?void 0:K.textTokens,(H=X.outputTokenDetails)==null?void 0:H.textTokens),reasoningTokens:h5((F=Q.outputTokenDetails)==null?void 0:F.reasoningTokens,(V=X.outputTokenDetails)==null?void 0:V.reasoningTokens)},totalTokens:h5(Q.totalTokens,X.totalTokens),reasoningTokens:h5(Q.reasoningTokens,X.reasoningTokens),cachedInputTokens:h5(Q.cachedInputTokens,X.cachedInputTokens)}}function h5(Q,X){return Q==null&&X==null?void 0:(Q!=null?Q:0)+(X!=null?X:0)}function KQ0(Q,X){if(Q===void 0&&X===void 0)return;if(Q===void 0)return X;if(X===void 0)return Q;let Y={...Q};for(let J in X)if(Object.prototype.hasOwnProperty.call(X,J)){let G=X[J];if(G===void 0)continue;let W=J in Q?Q[J]:void 0,Z=G!==null&&typeof G==="object"&&!Array.isArray(G)&&!(G instanceof Date)&&!(G instanceof RegExp),$=W!==null&&W!==void 0&&typeof W==="object"&&!Array.isArray(W)&&!(W instanceof Date)&&!(W instanceof RegExp);if(Z&&$)Y[J]=KQ0(W,G);else Y[J]=G}return Y}function Jf6({error:Q,exponentialBackoffDelay:X}){let Y=Q.responseHeaders;if(!Y)return X;let J,G=Y["retry-after-ms"];if(G){let Z=parseFloat(G);if(!Number.isNaN(Z))J=Z}let W=Y["retry-after"];if(W&&J===void 0){let Z=parseFloat(W);if(!Number.isNaN(Z))J=Z*1000;else J=Date.parse(W)-Date.now()}if(J!=null&&!Number.isNaN(J)&&0<=J&&(J<60000||J<X))return J;return X}var Gf6=({maxRetries:Q=2,initialDelayInMs:X=2000,backoffFactor:Y=2,abortSignal:J}={})=>async(G)=>H71(G,{maxRetries:Q,delayInMs:X,backoffFactor:Y,abortSignal:J});async function H71(Q,{maxRetries:X,delayInMs:Y,backoffFactor:J,abortSignal:G},W=[]){try{return await Q()}catch(Z){if(u7(Z))throw Z;if(X===0)throw Z;let $=AP(Z),K=[...W,Z],H=K.length;if(H>X)throw new HW1({message:`Failed after ${H} attempts. Last error: ${$}`,reason:"maxRetriesExceeded",errors:K});if(Z instanceof Error&&r8.isInstance(Z)&&Z.isRetryable===!0&&H<=X)return await v51(Jf6({error:Z,exponentialBackoffDelay:Y}),{abortSignal:G}),H71(Q,{maxRetries:X,delayInMs:J*Y,backoffFactor:J,abortSignal:G},K);if(H===1)throw Z;throw new HW1({message:`Failed after ${H} attempts with non-retryable error: '${$}'`,reason:"errorNotRetryable",errors:K})}}function Wf6({maxRetries:Q,abortSignal:X}){if(Q!=null){if(!Number.isInteger(Q))throw new KW({parameter:"maxRetries",value:Q,message:"maxRetries must be an integer"});if(Q<0)throw new KW({parameter:"maxRetries",value:Q,message:"maxRetries must be >= 0"})}let Y=Q!=null?Q:2;return{maxRetries:Y,retry:Gf6({maxRetries:Y,abortSignal:X})}}function Zf6({messages:Q}){let X=Q.at(-1);if((X==null?void 0:X.role)!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let Y={};for(let K of Q)if(K.role==="assistant"&&typeof K.content!=="string"){let H=K.content;for(let F of H)if(F.type==="tool-call")Y[F.toolCallId]=F}let J={};for(let K of Q)if(K.role==="assistant"&&typeof K.content!=="string"){let H=K.content;for(let F of H)if(F.type==="tool-approval-request")J[F.approvalId]=F}let G={};for(let K of X.content)if(K.type==="tool-result")G[K.toolCallId]=K;let W=[],Z=[],$=X.content.filter((K)=>K.type==="tool-approval-response");for(let K of $){let H=J[K.approvalId];if(H==null)throw new py6({approvalId:K.approvalId});if(G[H.toolCallId]!=null)continue;let F=Y[H.toolCallId];if(F==null)throw new RW1({toolCallId:H.toolCallId,approvalId:H.approvalId});let V={approvalRequest:H,approvalResponse:K,toolCall:F};if(K.approved)W.push(V);else Z.push(V)}return{approvedToolApprovals:W,deniedToolApprovals:Z}}async function F71({toolCall:Q,tools:X,tracer:Y,telemetry:J,messages:G,abortSignal:W,experimental_context:Z,onPreliminaryToolResult:$}){let{toolName:K,toolCallId:H,input:F}=Q,V=X==null?void 0:X[K];if((V==null?void 0:V.execute)==null)return;return JQ0({name:"ai.toolCall",attributes:pU({telemetry:J,attributes:{...XQ0({operationId:"ai.toolCall",telemetry:J}),"ai.toolCall.name":K,"ai.toolCall.id":H,"ai.toolCall.args":{output:()=>JSON.stringify(F)}}}),tracer:Y,fn:async(q)=>{let z;try{let B=i51({execute:V.execute.bind(V),input:F,options:{toolCallId:H,messages:G,abortSignal:W,experimental_context:Z}});for await(let D of B)if(D.type==="preliminary")$==null||$({...Q,type:"tool-result",output:D.output,preliminary:!0});else z=D.output}catch(B){return K71(q,B),{type:"tool-error",toolCallId:H,toolName:K,input:F,error:B,dynamic:V.type==="dynamic",...Q.providerMetadata!=null?{providerMetadata:Q.providerMetadata}:{}}}try{q.setAttributes(await pU({telemetry:J,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(z)}}}))}catch(B){}return{type:"tool-result",toolCallId:H,toolName:K,input:F,output:z,dynamic:V.type==="dynamic",...Q.providerMetadata!=null?{providerMetadata:Q.providerMetadata}:{}}}})}var $f6=class{constructor({data:Q,mediaType:X}){let Y=Q instanceof Uint8Array;this.base64Data=Y?void 0:Q,this.uint8ArrayData=Y?Q:void 0,this.mediaType=X}get base64(){if(this.base64Data==null)this.base64Data=$F(this.uint8ArrayData);return this.base64Data}get uint8Array(){if(this.uint8ArrayData==null)this.uint8ArrayData=uU(this.base64Data);return this.uint8ArrayData}},Kf6=class extends $f6{constructor(Q){super(Q);this.type="file"}};async function Hf6({tool:Q,toolCall:X,messages:Y,experimental_context:J}){if(Q.needsApproval==null)return!1;if(typeof Q.needsApproval==="boolean")return Q.needsApproval;return await Q.needsApproval(X.input,{toolCallId:X.toolCallId,messages:Y,experimental_context:J})}var Ff6={};hy6(Ff6,{array:()=>zf6,choice:()=>Uf6,json:()=>Bf6,object:()=>qf6,text:()=>GQ0});function Vf6(Q){let X=["ROOT"],Y=-1,J=null;function G(K,H,F){switch(K){case'"':{Y=H,X.pop(),X.push(F),X.push("INSIDE_STRING");break}case"f":case"t":case"n":{Y=H,J=H,X.pop(),X.push(F),X.push("INSIDE_LITERAL");break}case"-":{X.pop(),X.push(F),X.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{Y=H,X.pop(),X.push(F),X.push("INSIDE_NUMBER");break}case"{":{Y=H,X.pop(),X.push(F),X.push("INSIDE_OBJECT_START");break}case"[":{Y=H,X.pop(),X.push(F),X.push("INSIDE_ARRAY_START");break}}}function W(K,H){switch(K){case",":{X.pop(),X.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{Y=H,X.pop();break}}}function Z(K,H){switch(K){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{Y=H,X.pop();break}}}for(let K=0;K<Q.length;K++){let H=Q[K];switch(X[X.length-1]){case"ROOT":G(H,K,"FINISH");break;case"INSIDE_OBJECT_START":{switch(H){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}case"}":{Y=K,X.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(H){case'"':{X.pop(),X.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(H){case'"':{X.pop(),X.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(H){case":":{X.pop(),X.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{G(H,K,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{W(H,K);break}case"INSIDE_STRING":{switch(H){case'"':{X.pop(),Y=K;break}case"\\":{X.push("INSIDE_STRING_ESCAPE");break}default:Y=K}break}case"INSIDE_ARRAY_START":{switch(H){case"]":{Y=K,X.pop();break}default:{Y=K,G(H,K,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(H){case",":{X.pop(),X.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{Y=K,X.pop();break}default:{Y=K;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{G(H,K,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{X.pop(),Y=K;break}case"INSIDE_NUMBER":{switch(H){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{Y=K;break}case"e":case"E":case"-":case".":break;case",":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(H,K);if(X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")W(H,K);break}case"}":{if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")W(H,K);break}case"]":{if(X.pop(),X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(H,K);break}default:{X.pop();break}}break}case"INSIDE_LITERAL":{let V=Q.substring(J,K+1);if(!"false".startsWith(V)&&!"true".startsWith(V)&&!"null".startsWith(V)){if(X.pop(),X[X.length-1]==="INSIDE_OBJECT_AFTER_VALUE")W(H,K);else if(X[X.length-1]==="INSIDE_ARRAY_AFTER_VALUE")Z(H,K)}else Y=K;break}}}let $=Q.slice(0,Y+1);for(let K=X.length-1;K>=0;K--)switch(X[K]){case"INSIDE_STRING":{$+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{$+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{$+="]";break}case"INSIDE_LITERAL":{let F=Q.substring(J,Q.length);if("true".startsWith(F))$+="true".slice(F.length);else if("false".startsWith(F))$+="false".slice(F.length);else if("null".startsWith(F))$+="null".slice(F.length)}}return $}async function yP(Q){if(Q===void 0)return{value:void 0,state:"undefined-input"};let X=await JY({text:Q});if(X.success)return{value:X.value,state:"successful-parse"};if(X=await JY({text:Vf6(Q)}),X.success)return{value:X.value,state:"repaired-parse"};return{value:void 0,state:"failed-parse"}}var GQ0=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:Q}){return Q},async parsePartialOutput({text:Q}){return{partial:Q}},createElementStreamTransform(){return}}),qf6=({schema:Q,name:X,description:Y})=>{let J=ZW(Q);return{name:"object",responseFormat:N9(J.jsonSchema).then((G)=>({type:"json",schema:G,...X!=null&&{name:X},...Y!=null&&{description:Y}})),async parseCompleteOutput({text:G},W){let Z=await JY({text:G});if(!Z.success)throw new XK({message:"No object generated: could not parse the response.",cause:Z.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});let $=await wX({value:Z.value,schema:J});if(!$.success)throw new XK({message:"No object generated: response did not match schema.",cause:$.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});return $.value},async parsePartialOutput({text:G}){let W=await yP(G);switch(W.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:W.value}}},createElementStreamTransform(){return}}},zf6=({element:Q,name:X,description:Y})=>{let J=ZW(Q);return{name:"array",responseFormat:N9(J.jsonSchema).then((G)=>{let{$schema:W,...Z}=G;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:Z}},required:["elements"],additionalProperties:!1},...X!=null&&{name:X},...Y!=null&&{description:Y}}}),async parseCompleteOutput({text:G},W){let Z=await JY({text:G});if(!Z.success)throw new XK({message:"No object generated: could not parse the response.",cause:Z.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});let $=Z.value;if($==null||typeof $!=="object"||!("elements"in $)||!Array.isArray($.elements))throw new XK({message:"No object generated: response did not match schema.",cause:new y5({value:$,cause:"response must be an object with an elements array"}),text:G,response:W.response,usage:W.usage,finishReason:W.finishReason});for(let K of $.elements){let H=await wX({value:K,schema:J});if(!H.success)throw new XK({message:"No object generated: response did not match schema.",cause:H.error,text:G,response:W.response,usage:W.usage,finishReason:W.finishReason})}return $.elements},async parsePartialOutput({text:G}){let W=await yP(G);switch(W.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let Z=W.value;if(Z==null||typeof Z!=="object"||!("elements"in Z)||!Array.isArray(Z.elements))return;let $=W.state==="repaired-parse"&&Z.elements.length>0?Z.elements.slice(0,-1):Z.elements,K=[];for(let H of $){let F=await wX({value:H,schema:J});if(F.success)K.push(F.value)}return{partial:K}}}},createElementStreamTransform(){let G=0;return new TransformStream({transform({partialOutput:W},Z){if(W!=null)for(;G<W.length;G++)Z.enqueue(W[G])}})}}},Uf6=({options:Q,name:X,description:Y})=>{return{name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:Q}},required:["result"],additionalProperties:!1},...X!=null&&{name:X},...Y!=null&&{description:Y}}),async parseCompleteOutput({text:J},G){let W=await JY({text:J});if(!W.success)throw new XK({message:"No object generated: could not parse the response.",cause:W.error,text:J,response:G.response,usage:G.usage,finishReason:G.finishReason});let Z=W.value;if(Z==null||typeof Z!=="object"||!("result"in Z)||typeof Z.result!=="string"||!Q.includes(Z.result))throw new XK({message:"No object generated: response did not match schema.",cause:new y5({value:Z,cause:"response must be an object that contains a choice value."}),text:J,response:G.response,usage:G.usage,finishReason:G.finishReason});return Z.result},async parsePartialOutput({text:J}){let G=await yP(J);switch(G.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let W=G.value;if(W==null||typeof W!=="object"||!("result"in W)||typeof W.result!=="string")return;let Z=Q.filter(($)=>$.startsWith(W.result));if(G.state==="successful-parse")return Z.includes(W.result)?{partial:W.result}:void 0;else return Z.length===1?{partial:Z[0]}:void 0}}},createElementStreamTransform(){return}}},Bf6=({name:Q,description:X}={})=>{return{name:"json",responseFormat:Promise.resolve({type:"json",...Q!=null&&{name:Q},...X!=null&&{description:X}}),async parseCompleteOutput({text:Y},J){let G=await JY({text:Y});if(!G.success)throw new XK({message:"No object generated: could not parse the response.",cause:G.error,text:Y,response:J.response,usage:J.usage,finishReason:J.finishReason});return G.value},async parsePartialOutput({text:Y}){let J=await yP(Y);switch(J.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return J.value===void 0?void 0:{partial:J.value}}},createElementStreamTransform(){return}}};async function Df6({toolCall:Q,tools:X,repairToolCall:Y,system:J,messages:G}){var W;try{if(X==null){if(Q.providerExecuted&&Q.dynamic)return await V71(Q);throw new QQ0({toolName:Q.toolName})}try{return await zW1({toolCall:Q,tools:X})}catch(Z){if(Y==null||!(QQ0.isInstance(Z)||$Q0.isInstance(Z)))throw Z;let $=null;try{$=await Y({toolCall:Q,tools:X,inputSchema:async({toolName:K})=>{let{inputSchema:H}=X[K];return await ZW(H).jsonSchema},system:J,messages:G,error:Z})}catch(K){throw new Yb6({cause:K,originalError:Z})}if($==null)throw Z;return await zW1({toolCall:$,tools:X})}}catch(Z){let $=await JY({text:Q.input}),K=$.success?$.value:Q.input;return{type:"tool-call",toolCallId:Q.toolCallId,toolName:Q.toolName,input:K,dynamic:!0,invalid:!0,error:Z,title:(W=X==null?void 0:X[Q.toolName])==null?void 0:W.title,providerExecuted:Q.providerExecuted,providerMetadata:Q.providerMetadata}}}async function V71(Q){let X=Q.input.trim()===""?{success:!0,value:{}}:await JY({text:Q.input});if(X.success===!1)throw new $Q0({toolName:Q.toolName,toolInput:Q.input,cause:X.error});return{type:"tool-call",toolCallId:Q.toolCallId,toolName:Q.toolName,input:X.value,providerExecuted:!0,dynamic:!0,providerMetadata:Q.providerMetadata}}async function zW1({toolCall:Q,tools:X}){let Y=Q.toolName,J=X[Y];if(J==null){if(Q.providerExecuted&&Q.dynamic)return await V71(Q);throw new QQ0({toolName:Q.toolName,availableTools:Object.keys(X)})}let G=ZW(J.inputSchema),W=Q.input.trim()===""?await wX({value:{},schema:G}):await JY({text:Q.input,schema:G});if(W.success===!1)throw new $Q0({toolName:Y,toolInput:Q.input,cause:W.error});return J.type==="dynamic"?{type:"tool-call",toolCallId:Q.toolCallId,toolName:Q.toolName,input:W.value,providerExecuted:Q.providerExecuted,providerMetadata:Q.providerMetadata,dynamic:!0,title:J.title}:{type:"tool-call",toolCallId:Q.toolCallId,toolName:Y,input:W.value,providerExecuted:Q.providerExecuted,providerMetadata:Q.providerMetadata,title:J.title}}var Nf6=class{constructor({content:Q,finishReason:X,rawFinishReason:Y,usage:J,warnings:G,request:W,response:Z,providerMetadata:$}){this.content=Q,this.finishReason=X,this.rawFinishReason=Y,this.usage=J,this.warnings=G,this.request=W,this.response=Z,this.providerMetadata=$}get text(){return this.content.filter((Q)=>Q.type==="text").map((Q)=>Q.text).join("")}get reasoning(){return this.content.filter((Q)=>Q.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map((Q)=>Q.text).join("")}get files(){return this.content.filter((Q)=>Q.type==="file").map((Q)=>Q.file)}get sources(){return this.content.filter((Q)=>Q.type==="source")}get toolCalls(){return this.content.filter((Q)=>Q.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter((Q)=>Q.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter((Q)=>Q.dynamic===!0)}get toolResults(){return this.content.filter((Q)=>Q.type==="tool-result")}get staticToolResults(){return this.toolResults.filter((Q)=>Q.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter((Q)=>Q.dynamic===!0)}};function HQ0(Q){return({steps:X})=>X.length===Q}async function Of6({stopConditions:Q,steps:X}){return(await Promise.all(Q.map((Y)=>Y({steps:X})))).some((Y)=>Y)}async function UW1({content:Q,tools:X}){let Y=[],J=[];for(let W of Q){if(W.type==="source")continue;if((W.type==="tool-result"||W.type==="tool-error")&&!W.providerExecuted)continue;if(W.type==="text"&&W.text.length===0)continue;switch(W.type){case"text":J.push({type:"text",text:W.text,providerOptions:W.providerMetadata});break;case"reasoning":J.push({type:"reasoning",text:W.text,providerOptions:W.providerMetadata});break;case"file":J.push({type:"file",data:W.file.base64,mediaType:W.file.mediaType,providerOptions:W.providerMetadata});break;case"tool-call":J.push({type:"tool-call",toolCallId:W.toolCallId,toolName:W.toolName,input:W.input,providerExecuted:W.providerExecuted,providerOptions:W.providerMetadata});break;case"tool-result":{let Z=await cU({toolCallId:W.toolCallId,input:W.input,tool:X==null?void 0:X[W.toolName],output:W.output,errorMode:"none"});J.push({type:"tool-result",toolCallId:W.toolCallId,toolName:W.toolName,output:Z,providerOptions:W.providerMetadata});break}case"tool-error":{let Z=await cU({toolCallId:W.toolCallId,input:W.input,tool:X==null?void 0:X[W.toolName],output:W.error,errorMode:"json"});J.push({type:"tool-result",toolCallId:W.toolCallId,toolName:W.toolName,output:Z,providerOptions:W.providerMetadata});break}case"tool-approval-request":J.push({type:"tool-approval-request",approvalId:W.approvalId,toolCallId:W.toolCall.toolCallId});break}}if(J.length>0)Y.push({role:"assistant",content:J});let G=[];for(let W of Q){if(!(W.type==="tool-result"||W.type==="tool-error")||W.providerExecuted)continue;let Z=await cU({toolCallId:W.toolCallId,input:W.input,tool:X==null?void 0:X[W.toolName],output:W.type==="tool-result"?W.output:W.error,errorMode:W.type==="tool-error"?"text":"none"});G.push({type:"tool-result",toolCallId:W.toolCallId,toolName:W.toolName,output:Z,...W.providerMetadata!=null?{providerOptions:W.providerMetadata}:{}})}if(G.length>0)Y.push({role:"tool",content:G});return Y}function Lf6(...Q){let X=Q.filter((J)=>J!=null);if(X.length===0)return;if(X.length===1)return X[0];let Y=new AbortController;for(let J of X){if(J.aborted)return Y.abort(J.reason),Y.signal;J.addEventListener("abort",()=>{Y.abort(J.reason)},{once:!0})}return Y.signal}var Id4=WW({prefix:"aitxt",size:24});function Yb(Q,X){let Y=new Headers(Q!=null?Q:{});for(let[J,G]of Object.entries(X))if(!Y.has(J))Y.set(J,G);return Y}function wf6({status:Q,statusText:X,headers:Y,textStream:J}){return new Response(J.pipeThrough(new TextEncoderStream),{status:Q!=null?Q:200,statusText:X,headers:Yb(Y,{"content-type":"text/plain; charset=utf-8"})})}function q71({response:Q,status:X,statusText:Y,headers:J,stream:G}){let W=X!=null?X:200;if(Y!==void 0)Q.writeHead(W,Y,J);else Q.writeHead(W,J);let Z=G.getReader();(async()=>{try{while(!0){let{done:K,value:H}=await Z.read();if(K)break;if(!Q.write(H))await new Promise((V)=>{Q.once("drain",V)})}}catch(K){throw K}finally{Q.end()}})()}function Mf6({response:Q,status:X,statusText:Y,headers:J,textStream:G}){q71({response:Q,status:X,statusText:Y,headers:Object.fromEntries(Yb(J,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:G.pipeThrough(new TextEncoderStream)})}var z71=class extends TransformStream{constructor(){super({transform(Q,X){X.enqueue(`data: ${JSON.stringify(Q)}
|
|
1074
1074
|
|
|
1075
1075
|
`)},flush(Q){Q.enqueue(`data: [DONE]
|
|
1076
1076
|
|
|
1077
|
-
`)}})}},U71={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Pf6({status:Q,statusText:X,headers:Y,stream:J,consumeSseStream:G}){let W=J.pipeThrough(new z71);if(G){let[Z,$]=W.tee();W=Z,G({stream:$})}return new Response(W.pipeThrough(new TextEncoderStream),{status:Q,statusText:X,headers:Yb(Y,U71)})}function Tf6({originalMessages:Q,responseMessageId:X}){if(Q==null)return;let Y=Q[Q.length-1];return(Y==null?void 0:Y.role)==="assistant"?Y.id:typeof X==="function"?X():X}var _d4=dQ(()=>JQ(N.union([N.strictObject({type:N.literal("text-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("error"),errorText:N.string()}),N.strictObject({type:N.literal("tool-input-start"),toolCallId:N.string(),toolName:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-delta"),toolCallId:N.string(),inputTextDelta:N.string()}),N.strictObject({type:N.literal("tool-input-available"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-error"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),errorText:N.string(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),N.strictObject({type:N.literal("tool-output-available"),toolCallId:N.string(),output:N.unknown(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),preliminary:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-error"),toolCallId:N.string(),errorText:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-denied"),toolCallId:N.string()}),N.strictObject({type:N.literal("reasoning-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("file"),url:N.string(),mediaType:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.custom((Q)=>typeof Q==="string"&&Q.startsWith("data-"),{message:'Type must start with "data-"'}),id:N.string().optional(),data:N.unknown(),transient:N.boolean().optional()}),N.strictObject({type:N.literal("start-step")}),N.strictObject({type:N.literal("finish-step")}),N.strictObject({type:N.literal("start"),messageId:N.string().optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("finish"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("abort"),reason:N.string().optional()}),N.strictObject({type:N.literal("message-metadata"),messageMetadata:N.unknown()})])));function Af6(Q){return Q.type.startsWith("data-")}function o80(Q){return Q.type.startsWith("data-")}function s80(Q){return Q.type==="text"}function t80(Q){return Q.type==="file"}function BW1(Q){return Q.type==="reasoning"}function WQ0(Q){return Q.type.startsWith("tool-")}function B71(Q){return Q.type==="dynamic-tool"}function kP(Q){return WQ0(Q)||B71(Q)}function ZQ0(Q){return Q.type.split("-").slice(1).join("-")}function e80(Q){return B71(Q)?Q.toolName:ZQ0(Q)}function Ef6({lastMessage:Q,messageId:X}){return{message:(Q==null?void 0:Q.role)==="assistant"?Q:{id:X,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function jf6({stream:Q,messageMetadataSchema:X,dataPartSchemas:Y,runUpdateMessageJob:J,onError:G,onToolCall:W,onData:Z}){return Q.pipeThrough(new TransformStream({async transform($,K){await J(async({state:H,write:F})=>{var V,q,z,B;function D(A){let T=H.message.parts.filter(kP).find((j)=>j.toolCallId===A);if(T==null)throw Error(`no tool invocation found for tool call ${A}`);return T}function L(A){var E;let T=H.message.parts.find((v)=>WQ0(v)&&v.toolCallId===A.toolCallId),j=A,R=T;if(T!=null){if(T.state=A.state,R.input=j.input,R.output=j.output,R.errorText=j.errorText,R.rawInput=j.rawInput,R.preliminary=j.preliminary,A.title!==void 0)R.title=A.title;if(R.providerExecuted=(E=j.providerExecuted)!=null?E:T.providerExecuted,j.providerMetadata!=null&&T.state==="input-available")T.callProviderMetadata=j.providerMetadata}else H.message.parts.push({type:`tool-${A.toolName}`,toolCallId:A.toolCallId,state:A.state,title:A.title,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function M(A){var E,T;let j=H.message.parts.find((y)=>y.type==="dynamic-tool"&&y.toolCallId===A.toolCallId),R=A,v=j;if(j!=null){if(j.state=A.state,v.toolName=A.toolName,v.input=R.input,v.output=R.output,v.errorText=R.errorText,v.rawInput=(E=R.rawInput)!=null?E:v.rawInput,v.preliminary=R.preliminary,A.title!==void 0)v.title=A.title;if(v.providerExecuted=(T=R.providerExecuted)!=null?T:j.providerExecuted,R.providerMetadata!=null&&j.state==="input-available")j.callProviderMetadata=R.providerMetadata}else H.message.parts.push({type:"dynamic-tool",toolName:A.toolName,toolCallId:A.toolCallId,state:A.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,title:A.title,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function C(A){if(A!=null){let E=H.message.metadata!=null?KQ0(H.message.metadata,A):A;if(X!=null)await jP({value:E,schema:X});H.message.metadata=E}}switch($.type){case"text-start":{let A={type:"text",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeTextParts[$.id]=A,H.message.parts.push(A),F();break}case"text-delta":{let A=H.activeTextParts[$.id];A.text+=$.delta,A.providerMetadata=(V=$.providerMetadata)!=null?V:A.providerMetadata,F();break}case"text-end":{let A=H.activeTextParts[$.id];A.state="done",A.providerMetadata=(q=$.providerMetadata)!=null?q:A.providerMetadata,delete H.activeTextParts[$.id],F();break}case"reasoning-start":{let A={type:"reasoning",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeReasoningParts[$.id]=A,H.message.parts.push(A),F();break}case"reasoning-delta":{let A=H.activeReasoningParts[$.id];A.text+=$.delta,A.providerMetadata=(z=$.providerMetadata)!=null?z:A.providerMetadata,F();break}case"reasoning-end":{let A=H.activeReasoningParts[$.id];A.providerMetadata=(B=$.providerMetadata)!=null?B:A.providerMetadata,A.state="done",delete H.activeReasoningParts[$.id],F();break}case"file":{H.message.parts.push({type:"file",mediaType:$.mediaType,url:$.url}),F();break}case"source-url":{H.message.parts.push({type:"source-url",sourceId:$.sourceId,url:$.url,title:$.title,providerMetadata:$.providerMetadata}),F();break}case"source-document":{H.message.parts.push({type:"source-document",sourceId:$.sourceId,mediaType:$.mediaType,title:$.title,filename:$.filename,providerMetadata:$.providerMetadata}),F();break}case"tool-input-start":{let A=H.message.parts.filter(WQ0);if(H.partialToolCalls[$.toolCallId]={text:"",toolName:$.toolName,index:A.length,dynamic:$.dynamic,title:$.title},$.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});F();break}case"tool-input-delta":{let A=H.partialToolCalls[$.toolCallId];A.text+=$.inputTextDelta;let{value:E}=await yP(A.text);if(A.dynamic)M({toolCallId:$.toolCallId,toolName:A.toolName,state:"input-streaming",input:E,title:A.title});else L({toolCallId:$.toolCallId,toolName:A.toolName,state:"input-streaming",input:E,title:A.title});F();break}case"tool-input-available":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});if(F(),W&&!$.providerExecuted)await W({toolCall:$});break}case"tool-input-error":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:void 0,rawInput:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});F();break}case"tool-approval-request":{let A=D($.toolCallId);A.state="approval-requested",A.approval={id:$.approvalId},F();break}case"tool-output-denied":{let A=D($.toolCallId);A.state="output-denied",F();break}case"tool-output-available":{let A=D($.toolCallId);if(A.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:A.toolName,state:"output-available",input:A.input,output:$.output,preliminary:$.preliminary,providerExecuted:$.providerExecuted,title:A.title});else L({toolCallId:$.toolCallId,toolName:ZQ0(A),state:"output-available",input:A.input,output:$.output,providerExecuted:$.providerExecuted,preliminary:$.preliminary,title:A.title});F();break}case"tool-output-error":{let A=D($.toolCallId);if(A.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:A.toolName,state:"output-error",input:A.input,errorText:$.errorText,providerExecuted:$.providerExecuted,title:A.title});else L({toolCallId:$.toolCallId,toolName:ZQ0(A),state:"output-error",input:A.input,rawInput:A.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,title:A.title});F();break}case"start-step":{H.message.parts.push({type:"step-start"});break}case"finish-step":{H.activeTextParts={},H.activeReasoningParts={};break}case"start":{if($.messageId!=null)H.message.id=$.messageId;if(await C($.messageMetadata),$.messageId!=null||$.messageMetadata!=null)F();break}case"finish":{if($.finishReason!=null)H.finishReason=$.finishReason;if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"message-metadata":{if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"error":{G==null||G(Error($.errorText));break}default:if(Af6($)){if((Y==null?void 0:Y[$.type])!=null)await jP({value:$.data,schema:Y[$.type]});let A=$;if(A.transient){Z==null||Z(A);break}let E=A.id!=null?H.message.parts.find((T)=>A.type===T.type&&A.id===T.id):void 0;if(E!=null)E.data=A.data;else H.message.parts.push(A);Z==null||Z(A),F()}}K.enqueue($)})}}))}function Cf6({messageId:Q,originalMessages:X=[],onFinish:Y,onError:J,stream:G}){let W=X==null?void 0:X[X.length-1];if((W==null?void 0:W.role)!=="assistant")W=void 0;else Q=W.id;let Z=!1,$=G.pipeThrough(new TransformStream({transform(q,z){if(q.type==="start"){let B=q;if(B.messageId==null&&Q!=null)B.messageId=Q}if(q.type==="abort")Z=!0;z.enqueue(q)}}));if(Y==null)return $;let K=Ef6({lastMessage:W?structuredClone(W):void 0,messageId:Q!=null?Q:""}),H=async(q)=>{await q({state:K,write:()=>{}})},F=!1,V=async()=>{if(F||!Y)return;F=!0;let q=K.message.id===(W==null?void 0:W.id);await Y({isAborted:Z,isContinuation:q,responseMessage:K.message,messages:[...q?X.slice(0,-1):X,K.message],finishReason:K.finishReason})};return jf6({stream:$,runUpdateMessageJob:H,onError:J}).pipeThrough(new TransformStream({transform(q,z){z.enqueue(q)},async cancel(){await V()},async flush(){await V()}}))}function If6({response:Q,status:X,statusText:Y,headers:J,stream:G,consumeSseStream:W}){let Z=G.pipeThrough(new z71);if(W){let[$,K]=Z.tee();Z=$,W({stream:K})}q71({response:Q,status:X,statusText:Y,headers:Object.fromEntries(Yb(J,U71).entries()),stream:Z.pipeThrough(new TextEncoderStream)})}function vP(Q){let X=Q.pipeThrough(new TransformStream);return X[Symbol.asyncIterator]=function(){let Y=this.getReader(),J=!1;async function G(W){var Z;if(J)return;J=!0;try{if(W)await((Z=Y.cancel)==null?void 0:Z.call(Y))}finally{try{Y.releaseLock()}catch($){}}}return{async next(){if(J)return{done:!0,value:void 0};let{done:W,value:Z}=await Y.read();if(W)return await G(!0),{done:!0,value:void 0};return{done:!1,value:Z}},async return(){return await G(!0),{done:!0,value:void 0}},async throw(W){throw await G(!0),W}}},X}async function Rf6({stream:Q,onError:X}){let Y=Q.getReader();try{while(!0){let{done:J}=await Y.read();if(J)break}}catch(J){X==null||X(J)}finally{Y.releaseLock()}}function DW1(){let Q,X;return{promise:new Promise((J,G)=>{Q=J,X=G}),resolve:Q,reject:X}}function Sf6(){let Q=[],X=null,Y=!1,J=DW1(),G=()=>{Y=!0,J.resolve(),Q.forEach((Z)=>Z.cancel()),Q=[],X==null||X.close()},W=async()=>{if(Y&&Q.length===0){X==null||X.close();return}if(Q.length===0)return J=DW1(),await J.promise,W();try{let{value:Z,done:$}=await Q[0].read();if($)if(Q.shift(),Q.length===0&&Y)X==null||X.close();else await W();else X==null||X.enqueue(Z)}catch(Z){X==null||X.error(Z),Q.shift(),G()}};return{stream:new ReadableStream({start(Z){X=Z},pull:W,async cancel(){for(let Z of Q)await Z.cancel();Q=[],Y=!0}}),addStream:(Z)=>{if(Y)throw Error("Cannot add inner stream: outer stream is closed");Q.push(Z.getReader()),J.resolve()},close:()=>{if(Y=!0,J.resolve(),Q.length===0)X==null||X.close()},terminate:G}}function vf6(){var Q,X;return(X=(Q=globalThis==null?void 0:globalThis.performance)==null?void 0:Q.now())!=null?X:Date.now()}function kf6({tools:Q,generatorStream:X,tracer:Y,telemetry:J,system:G,messages:W,abortSignal:Z,repairToolCall:$,experimental_context:K,generateId:H}){let F=null,V=new ReadableStream({start(A){F=A}}),q=new Set,z=new Map,B=new Map,D=!1,L=void 0;function M(){if(D&&q.size===0){if(L!=null)F.enqueue(L);F.close()}}let C=new TransformStream({async transform(A,E){let T=A.type;switch(T){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{E.enqueue(A);break}case"file":{E.enqueue({type:"file",file:new Kf6({data:A.data,mediaType:A.mediaType})});break}case"finish":{L={type:"finish",finishReason:A.finishReason.unified,rawFinishReason:A.finishReason.raw,usage:Xf6(A.usage),providerMetadata:A.providerMetadata};break}case"tool-approval-request":{let j=B.get(A.toolCallId);if(j==null){F.enqueue({type:"error",error:new RW1({toolCallId:A.toolCallId,approvalId:A.approvalId})});break}E.enqueue({type:"tool-approval-request",approvalId:A.approvalId,toolCall:j});break}case"tool-call":{try{let j=await Df6({toolCall:A,tools:Q,repairToolCall:$,system:G,messages:W});if(B.set(j.toolCallId,j),E.enqueue(j),j.invalid){F.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:AP(j.error),dynamic:!0,title:j.title});break}let R=Q==null?void 0:Q[j.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:W,abortSignal:Z,experimental_context:K});if(await Hf6({tool:R,toolCall:j,messages:W,experimental_context:K})){F.enqueue({type:"tool-approval-request",approvalId:H(),toolCall:j});break}if(z.set(j.toolCallId,j.input),R.execute!=null&&j.providerExecuted!==!0){let v=H();q.add(v),F71({toolCall:j,tools:Q,tracer:Y,telemetry:J,messages:W,abortSignal:Z,experimental_context:K,onPreliminaryToolResult:(y)=>{F.enqueue(y)}}).then((y)=>{F.enqueue(y)}).catch((y)=>{F.enqueue({type:"error",error:y})}).finally(()=>{q.delete(v),M()})}}catch(j){F.enqueue({type:"error",error:j})}break}case"tool-result":{let j=A.toolName;if(A.isError)F.enqueue({type:"tool-error",toolCallId:A.toolCallId,toolName:j,input:z.get(A.toolCallId),providerExecuted:!0,error:A.result,dynamic:A.dynamic});else E.enqueue({type:"tool-result",toolCallId:A.toolCallId,toolName:j,input:z.get(A.toolCallId),output:A.result,providerExecuted:!0,dynamic:A.dynamic});break}default:throw Error(`Unhandled chunk type: ${T}`)}},flush(){D=!0,M()}});return new ReadableStream({async start(A){return Promise.all([X.pipeThrough(C).pipeTo(new WritableStream({write(E){A.enqueue(E)},close(){}})),V.pipeTo(new WritableStream({write(E){A.enqueue(E)},close(){A.close()}}))])}})}var _f6=WW({prefix:"aitxt",size:24});function D71({model:Q,tools:X,toolChoice:Y,system:J,prompt:G,messages:W,maxRetries:Z,abortSignal:$,timeout:K,headers:H,stopWhen:F=HQ0(1),experimental_output:V,output:q=V,experimental_telemetry:z,prepareStep:B,providerOptions:D,experimental_activeTools:L,activeTools:M=L,experimental_repairToolCall:C,experimental_transform:A,experimental_download:E,includeRawChunks:T=!1,onChunk:j,onError:R=({error:m})=>{console.error(m)},onFinish:v,onAbort:y,onStepFinish:b,experimental_context:h,_internal:{now:a=vf6,generateId:f=_f6}={},...S}){let m=X71(K),Q0=Lb6(K),r=wb6(K),Y0=Q0!=null?new AbortController:void 0,F0=r!=null?new AbortController:void 0;return new bf6({model:Q71(Q),telemetry:z,headers:H,settings:S,maxRetries:Z,abortSignal:Lf6($,m!=null?AbortSignal.timeout(m):void 0,Y0==null?void 0:Y0.signal,F0==null?void 0:F0.signal),stepTimeoutMs:Q0,stepAbortController:Y0,chunkTimeoutMs:r,chunkAbortController:F0,system:J,prompt:G,messages:W,tools:X,toolChoice:Y,transforms:Xb(A),activeTools:M,repairToolCall:C,stopConditions:Xb(F),output:q,providerOptions:D,prepareStep:B,includeRawChunks:T,onChunk:j,onError:R,onFinish:v,onAbort:y,onStepFinish:b,now:a,generateId:f,experimental_context:h,download:E})}function yf6(Q){let X=void 0,Y="",J="",G=void 0,W="";function Z({controller:$,partialOutput:K=void 0}){$.enqueue({part:{type:"text-delta",id:X,text:J,providerMetadata:G},partialOutput:K}),J=""}return new TransformStream({async transform($,K){var H;if($.type==="finish-step"&&J.length>0)Z({controller:K});if($.type!=="text-delta"&&$.type!=="text-start"&&$.type!=="text-end"){K.enqueue({part:$,partialOutput:void 0});return}if(X==null)X=$.id;else if($.id!==X){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-start"){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-end"){if(J.length>0)Z({controller:K});K.enqueue({part:$,partialOutput:void 0});return}Y+=$.text,J+=$.text,G=(H=$.providerMetadata)!=null?H:G;let F=await Q.parsePartialOutput({text:Y});if(F!==void 0){let V=JSON.stringify(F.partial);if(V!==W)Z({controller:K,partialOutput:F.partial}),W=V}}})}var bf6=class{constructor({model:Q,telemetry:X,headers:Y,settings:J,maxRetries:G,abortSignal:W,stepTimeoutMs:Z,stepAbortController:$,chunkTimeoutMs:K,chunkAbortController:H,system:F,prompt:V,messages:q,tools:z,toolChoice:B,transforms:D,activeTools:L,repairToolCall:M,stopConditions:C,output:A,providerOptions:E,prepareStep:T,includeRawChunks:j,now:R,generateId:v,onChunk:y,onError:b,onFinish:h,onAbort:a,onStepFinish:f,experimental_context:S,download:m}){this._totalUsage=new ZF,this._finishReason=new ZF,this._rawFinishReason=new ZF,this._steps=new ZF,this.outputSpecification=A,this.includeRawChunks=j,this.tools=z;let Q0,r=[],Y0=[],F0=void 0,Z0=void 0,B0=void 0,T0={},b0=[],Y1=[],D0=new Map,G0,R0={},_1={},h1=new TransformStream({async transform(I1,b1){var s1,E1,X1,C0;b1.enqueue(I1);let{part:P0}=I1;if(P0.type==="text-delta"||P0.type==="reasoning-delta"||P0.type==="source"||P0.type==="tool-call"||P0.type==="tool-result"||P0.type==="tool-input-start"||P0.type==="tool-input-delta"||P0.type==="raw")await(y==null?void 0:y({chunk:P0}));if(P0.type==="error")await b({error:rb6(P0.error)});if(P0.type==="text-start")R0[P0.id]={type:"text",text:"",providerMetadata:P0.providerMetadata},r.push(R0[P0.id]);if(P0.type==="text-delta"){let a1=R0[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`text part ${P0.id} not found`},partialOutput:void 0});return}a1.text+=P0.text,a1.providerMetadata=(s1=P0.providerMetadata)!=null?s1:a1.providerMetadata}if(P0.type==="text-end"){let a1=R0[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`text part ${P0.id} not found`},partialOutput:void 0});return}a1.providerMetadata=(E1=P0.providerMetadata)!=null?E1:a1.providerMetadata,delete R0[P0.id]}if(P0.type==="reasoning-start")_1[P0.id]={type:"reasoning",text:"",providerMetadata:P0.providerMetadata},r.push(_1[P0.id]);if(P0.type==="reasoning-delta"){let a1=_1[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`reasoning part ${P0.id} not found`},partialOutput:void 0});return}a1.text+=P0.text,a1.providerMetadata=(X1=P0.providerMetadata)!=null?X1:a1.providerMetadata}if(P0.type==="reasoning-end"){let a1=_1[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`reasoning part ${P0.id} not found`},partialOutput:void 0});return}a1.providerMetadata=(C0=P0.providerMetadata)!=null?C0:a1.providerMetadata,delete _1[P0.id]}if(P0.type==="file")r.push({type:"file",file:P0.file});if(P0.type==="source")r.push(P0);if(P0.type==="tool-call")r.push(P0);if(P0.type==="tool-result"&&!P0.preliminary)r.push(P0);if(P0.type==="tool-approval-request")r.push(P0);if(P0.type==="tool-error")r.push(P0);if(P0.type==="start-step")r=[],_1={},R0={},T0=P0.request,b0=P0.warnings;if(P0.type==="finish-step"){let a1=await UW1({content:r,tools:z}),M4=new Nf6({content:r,finishReason:P0.finishReason,rawFinishReason:P0.rawFinishReason,usage:P0.usage,warnings:b0,request:T0,response:{...P0.response,messages:[...Y0,...a1]},providerMetadata:P0.providerMetadata});await(f==null?void 0:f(M4)),sW1({warnings:b0,provider:Q.provider,model:Q.modelId}),Y1.push(M4),Y0.push(...a1),Q0.resolve()}if(P0.type==="finish")B0=P0.totalUsage,F0=P0.finishReason,Z0=P0.rawFinishReason},async flush(I1){try{if(Y1.length===0){let X1=(W==null?void 0:W.aborted)?W.reason:new ey6({message:"No output generated. Check the stream for errors."});v0._finishReason.reject(X1),v0._rawFinishReason.reject(X1),v0._totalUsage.reject(X1),v0._steps.reject(X1);return}let b1=F0!=null?F0:"other",s1=B0!=null?B0:r80();v0._finishReason.resolve(b1),v0._rawFinishReason.resolve(Z0),v0._totalUsage.resolve(s1),v0._steps.resolve(Y1);let E1=Y1[Y1.length-1];await(h==null?void 0:h({finishReason:E1.finishReason,rawFinishReason:E1.rawFinishReason,totalUsage:s1,usage:E1.usage,content:E1.content,text:E1.text,reasoningText:E1.reasoningText,reasoning:E1.reasoning,files:E1.files,sources:E1.sources,toolCalls:E1.toolCalls,staticToolCalls:E1.staticToolCalls,dynamicToolCalls:E1.dynamicToolCalls,toolResults:E1.toolResults,staticToolResults:E1.staticToolResults,dynamicToolResults:E1.dynamicToolResults,request:E1.request,response:E1.response,warnings:E1.warnings,providerMetadata:E1.providerMetadata,steps:Y1,experimental_context:S})),G0.setAttributes(await pU({telemetry:X,attributes:{"ai.response.finishReason":b1,"ai.response.text":{output:()=>E1.text},"ai.response.toolCalls":{output:()=>{var X1;return((X1=E1.toolCalls)==null?void 0:X1.length)?JSON.stringify(E1.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(E1.providerMetadata),"ai.usage.inputTokens":s1.inputTokens,"ai.usage.outputTokens":s1.outputTokens,"ai.usage.totalTokens":s1.totalTokens,"ai.usage.reasoningTokens":s1.reasoningTokens,"ai.usage.cachedInputTokens":s1.cachedInputTokens}}))}catch(b1){I1.error(b1)}finally{G0.end()}}}),y0=Sf6();this.addStream=y0.addStream,this.closeStream=y0.close;let w0=y0.stream.getReader(),$0=new ReadableStream({async start(I1){I1.enqueue({type:"start"})},async pull(I1){function b1(){a==null||a({steps:Y1}),I1.enqueue({type:"abort",...(W==null?void 0:W.reason)!==void 0?{reason:_5(W.reason)}:{}}),I1.close()}try{let{done:s1,value:E1}=await w0.read();if(s1){I1.close();return}if(W==null?void 0:W.aborted){b1();return}I1.enqueue(E1)}catch(s1){if(u7(s1)&&(W==null?void 0:W.aborted))b1();else I1.error(s1)}},cancel(I1){return y0.stream.cancel(I1)}});for(let I1 of D)$0=$0.pipeThrough(I1({tools:z,stopStream(){y0.terminate()}}));this.baseStream=$0.pipeThrough(yf6(A!=null?A:GQ0())).pipeThrough(h1);let{maxRetries:j0,retry:H0}=Wf6({maxRetries:G,abortSignal:W}),O0=eb6(X),t0=yb6(J),k0=ob6({model:Q,telemetry:X,headers:Y,settings:{...t0,maxRetries:j0}}),v0=this;JQ0({name:"ai.streamText",attributes:pU({telemetry:X,attributes:{...XQ0({operationId:"ai.streamText",telemetry:X}),...k0,"ai.prompt":{input:()=>JSON.stringify({system:F,prompt:V,messages:q})}}}),tracer:O0,endWhenDone:!1,fn:async(I1)=>{G0=I1;let b1=await ab6({system:F,prompt:V,messages:q}),s1=b1.messages,E1=[],{approvedToolApprovals:X1,deniedToolApprovals:C0}=Zf6({messages:s1});if(C0.length>0||X1.length>0){let a1=[...X1,...C0].filter((O)=>O.toolCall.providerExecuted),M4=X1.filter((O)=>!O.toolCall.providerExecuted),_8=C0.filter((O)=>!O.toolCall.providerExecuted),g1=C0.filter((O)=>O.toolCall.providerExecuted),I0,GY=new ReadableStream({start(O){I0=O}});v0.addStream(GY);try{for(let _ of[..._8,...g1])I0==null||I0.enqueue({type:"tool-output-denied",toolCallId:_.toolCall.toolCallId,toolName:_.toolCall.toolName});let O=[];if(await Promise.all(M4.map(async(_)=>{let s=await F71({toolCall:_.toolCall,tools:z,tracer:O0,telemetry:X,messages:s1,abortSignal:W,experimental_context:S,onPreliminaryToolResult:(J0)=>{I0==null||I0.enqueue(J0)}});if(s!=null)I0==null||I0.enqueue(s),O.push(s)})),a1.length>0)E1.push({role:"tool",content:a1.map((_)=>({type:"tool-approval-response",approvalId:_.approvalResponse.approvalId,approved:_.approvalResponse.approved,reason:_.approvalResponse.reason,providerExecuted:!0}))});if(O.length>0||_8.length>0){let _=[];for(let s of O)_.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:await cU({toolCallId:s.toolCallId,input:s.input,tool:z==null?void 0:z[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"json":"none"})});for(let s of _8)_.push({type:"tool-result",toolCallId:s.toolCall.toolCallId,toolName:s.toolCall.toolName,output:{type:"execution-denied",reason:s.approvalResponse.reason}});E1.push({role:"tool",content:_})}}finally{I0==null||I0.close()}}Y0.push(...E1);async function P0({currentStep:a1,responseMessages:M4,usage:_8}){var g1,I0,GY,O,_,s;let J0=v0.includeRawChunks,U=Z!=null?setTimeout(()=>$.abort(),Z):void 0,w=void 0;function k(){if(K!=null){if(w!=null)clearTimeout(w);w=setTimeout(()=>H.abort(),K)}}function c(){if(w!=null)clearTimeout(w),w=void 0}function t(){if(U!=null)clearTimeout(U)}Q0=new ZF;let u=[...s1,...M4],N0=await(T==null?void 0:T({model:Q,steps:Y1,stepNumber:Y1.length,messages:u,experimental_context:S})),r0=Q71((g1=N0==null?void 0:N0.model)!=null?g1:Q),w1=await Sb6({prompt:{system:(I0=N0==null?void 0:N0.system)!=null?I0:b1.system,messages:(GY=N0==null?void 0:N0.messages)!=null?GY:u},supportedUrls:await r0.supportedUrls,download:m}),{toolChoice:_0,tools:z1}=await fb6({tools:z,toolChoice:(O=N0==null?void 0:N0.toolChoice)!=null?O:B,activeTools:(_=N0==null?void 0:N0.activeTools)!=null?_:L});S=(s=N0==null?void 0:N0.experimental_context)!=null?s:S;let H4=KQ0(E,N0==null?void 0:N0.providerOptions),{result:{stream:DQ,response:u6,request:WY},doStreamSpan:x5,startTimestampMs:YK}=await H0(()=>JQ0({name:"ai.streamText.doStream",attributes:pU({telemetry:X,attributes:{...XQ0({operationId:"ai.streamText.doStream",telemetry:X}),...k0,"ai.model.provider":r0.provider,"ai.model.id":r0.modelId,"ai.prompt.messages":{input:()=>Qf6(w1)},"ai.prompt.tools":{input:()=>z1==null?void 0:z1.map((p1)=>JSON.stringify(p1))},"ai.prompt.toolChoice":{input:()=>_0!=null?JSON.stringify(_0):void 0},"gen_ai.system":r0.provider,"gen_ai.request.model":r0.modelId,"gen_ai.request.frequency_penalty":t0.frequencyPenalty,"gen_ai.request.max_tokens":t0.maxOutputTokens,"gen_ai.request.presence_penalty":t0.presencePenalty,"gen_ai.request.stop_sequences":t0.stopSequences,"gen_ai.request.temperature":t0.temperature,"gen_ai.request.top_k":t0.topK,"gen_ai.request.top_p":t0.topP}}),tracer:O0,endWhenDone:!1,fn:async(p1)=>({startTimestampMs:R(),doStreamSpan:p1,result:await r0.doStream({...t0,tools:z1,toolChoice:_0,responseFormat:await(A==null?void 0:A.responseFormat),prompt:w1,providerOptions:H4,abortSignal:W,headers:Y,includeRawChunks:J0})})})),Q1=kf6({tools:z,generatorStream:DQ,tracer:O0,telemetry:X,system:F,messages:u,repairToolCall:M,abortSignal:W,experimental_context:S,generateId:v}),M6=WY!=null?WY:{},j8=[],O9=[],e0,P6={},y8="other",xY=void 0,ZY=r80(),Wb,FQ0=!0,g5={id:v(),timestamp:new Date,modelId:Q.modelId},VQ0="";v0.addStream(Q1.pipeThrough(new TransformStream({async transform(p1,pQ){var nU,iU,bP,NQ,VF;if(k(),p1.type==="stream-start"){e0=p1.warnings;return}if(FQ0){let GQ=R()-YK;FQ0=!1,x5.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":GQ}),x5.setAttributes({"ai.response.msToFirstChunk":GQ}),pQ.enqueue({type:"start-step",request:M6,warnings:e0!=null?e0:[]})}let Zb=p1.type;switch(Zb){case"tool-approval-request":case"text-start":case"text-end":{pQ.enqueue(p1);break}case"text-delta":{if(p1.delta.length>0)pQ.enqueue({type:"text-delta",id:p1.id,text:p1.delta,providerMetadata:p1.providerMetadata}),VQ0+=p1.delta;break}case"reasoning-start":case"reasoning-end":{pQ.enqueue(p1);break}case"reasoning-delta":{pQ.enqueue({type:"reasoning-delta",id:p1.id,text:p1.delta,providerMetadata:p1.providerMetadata});break}case"tool-call":{pQ.enqueue(p1),j8.push(p1);break}case"tool-result":{if(pQ.enqueue(p1),!p1.preliminary)O9.push(p1);break}case"tool-error":{pQ.enqueue(p1),O9.push(p1);break}case"response-metadata":{g5={id:(nU=p1.id)!=null?nU:g5.id,timestamp:(iU=p1.timestamp)!=null?iU:g5.timestamp,modelId:(bP=p1.modelId)!=null?bP:g5.modelId};break}case"finish":{ZY=p1.usage,y8=p1.finishReason,xY=p1.rawFinishReason,Wb=p1.providerMetadata;let GQ=R()-YK;x5.addEvent("ai.stream.finish"),x5.setAttributes({"ai.response.msToFinish":GQ,"ai.response.avgOutputTokensPerSecond":1000*((NQ=ZY.outputTokens)!=null?NQ:0)/GQ});break}case"file":{pQ.enqueue(p1);break}case"source":{pQ.enqueue(p1);break}case"tool-input-start":{P6[p1.id]=p1.toolName;let GQ=z==null?void 0:z[p1.toolName];if((GQ==null?void 0:GQ.onInputStart)!=null)await GQ.onInputStart({toolCallId:p1.id,messages:u,abortSignal:W,experimental_context:S});pQ.enqueue({...p1,dynamic:(VF=p1.dynamic)!=null?VF:(GQ==null?void 0:GQ.type)==="dynamic",title:GQ==null?void 0:GQ.title});break}case"tool-input-end":{delete P6[p1.id],pQ.enqueue(p1);break}case"tool-input-delta":{let GQ=P6[p1.id],$b=z==null?void 0:z[GQ];if(($b==null?void 0:$b.onInputDelta)!=null)await $b.onInputDelta({inputTextDelta:p1.delta,toolCallId:p1.id,messages:u,abortSignal:W,experimental_context:S});pQ.enqueue(p1);break}case"error":{pQ.enqueue(p1),y8="error";break}case"raw":{if(J0)pQ.enqueue(p1);break}default:throw Error(`Unknown chunk type: ${Zb}`)}},async flush(p1){let pQ=j8.length>0?JSON.stringify(j8):void 0;try{x5.setAttributes(await pU({telemetry:X,attributes:{"ai.response.finishReason":y8,"ai.response.text":{output:()=>VQ0},"ai.response.toolCalls":{output:()=>pQ},"ai.response.id":g5.id,"ai.response.model":g5.modelId,"ai.response.timestamp":g5.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Wb),"ai.usage.inputTokens":ZY.inputTokens,"ai.usage.outputTokens":ZY.outputTokens,"ai.usage.totalTokens":ZY.totalTokens,"ai.usage.reasoningTokens":ZY.reasoningTokens,"ai.usage.cachedInputTokens":ZY.cachedInputTokens,"gen_ai.response.finish_reasons":[y8],"gen_ai.response.id":g5.id,"gen_ai.response.model":g5.modelId,"gen_ai.usage.input_tokens":ZY.inputTokens,"gen_ai.usage.output_tokens":ZY.outputTokens}}))}catch(NQ){}finally{x5.end()}p1.enqueue({type:"finish-step",finishReason:y8,rawFinishReason:xY,usage:ZY,providerMetadata:Wb,response:{...g5,headers:u6==null?void 0:u6.headers}});let nU=Yf6(_8,ZY);await Q0.promise;let iU=j8.filter((NQ)=>NQ.providerExecuted!==!0),bP=O9.filter((NQ)=>NQ.providerExecuted!==!0);for(let NQ of j8){if(NQ.providerExecuted!==!0)continue;let VF=z==null?void 0:z[NQ.toolName];if((VF==null?void 0:VF.type)==="provider"&&VF.supportsDeferredResults){if(!O9.some((GQ)=>GQ.type==="tool-result"&&GQ.toolCallId===NQ.toolCallId))D0.set(NQ.toolCallId,{toolName:NQ.toolName})}}for(let NQ of O9)if(NQ.type==="tool-result")D0.delete(NQ.toolCallId);if(t(),c(),(iU.length>0&&bP.length===iU.length||D0.size>0)&&!await Of6({stopConditions:C,steps:Y1})){M4.push(...await UW1({content:Y1[Y1.length-1].content,tools:z}));try{await P0({currentStep:a1+1,responseMessages:M4,usage:nU})}catch(NQ){p1.enqueue({type:"error",error:NQ}),v0.closeStream()}}else p1.enqueue({type:"finish",finishReason:y8,rawFinishReason:xY,totalUsage:nU}),v0.closeStream()}})))}await P0({currentStep:0,responseMessages:E1,usage:r80()})}}).catch((I1)=>{v0.addStream(new ReadableStream({start(b1){b1.enqueue({type:"error",error:I1}),b1.close()}})),v0.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((Q)=>Q[Q.length-1])}get content(){return this.finalStep.then((Q)=>Q.content)}get warnings(){return this.finalStep.then((Q)=>Q.warnings)}get providerMetadata(){return this.finalStep.then((Q)=>Q.providerMetadata)}get text(){return this.finalStep.then((Q)=>Q.text)}get reasoningText(){return this.finalStep.then((Q)=>Q.reasoningText)}get reasoning(){return this.finalStep.then((Q)=>Q.reasoning)}get sources(){return this.finalStep.then((Q)=>Q.sources)}get files(){return this.finalStep.then((Q)=>Q.files)}get toolCalls(){return this.finalStep.then((Q)=>Q.toolCalls)}get staticToolCalls(){return this.finalStep.then((Q)=>Q.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((Q)=>Q.dynamicToolCalls)}get toolResults(){return this.finalStep.then((Q)=>Q.toolResults)}get staticToolResults(){return this.finalStep.then((Q)=>Q.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((Q)=>Q.dynamicToolResults)}get usage(){return this.finalStep.then((Q)=>Q.usage)}get request(){return this.finalStep.then((Q)=>Q.request)}get response(){return this.finalStep.then((Q)=>Q.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[Q,X]=this.baseStream.tee();return this.baseStream=X,Q}get textStream(){return vP(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){if(Q.type==="text-delta")X.enqueue(Q.text)}})))}get fullStream(){return vP(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){X.enqueue(Q)}})))}async consumeStream(Q){var X;try{await Rf6({stream:this.fullStream,onError:Q==null?void 0:Q.onError})}catch(Y){(X=Q==null?void 0:Q.onError)==null||X.call(Q,Y)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return vP(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:Q},X){if(Q!=null)X.enqueue(Q)}})))}get elementStream(){var Q,X,Y;let J=(Q=this.outputSpecification)==null?void 0:Q.createElementStreamTransform();if(J==null)throw new T51({functionality:`element streams in ${(Y=(X=this.outputSpecification)==null?void 0:X.name)!=null?Y:"text"} mode`});return vP(this.teeStream().pipeThrough(J))}get output(){return this.finalStep.then((Q)=>{var X;return((X=this.outputSpecification)!=null?X:GQ0()).parseCompleteOutput({text:Q.text},{response:Q.response,usage:Q.usage,finishReason:Q.finishReason})})}toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G=!0,sendSources:W=!1,sendStart:Z=!0,sendFinish:$=!0,onError:K=_5}={}){let H=X!=null?Tf6({originalMessages:Q,responseMessageId:X}):void 0,F=(q)=>{var z;let B=(z=this.tools)==null?void 0:z[q.toolName];if(B==null)return q.dynamic;return(B==null?void 0:B.type)==="dynamic"?!0:void 0},V=this.fullStream.pipeThrough(new TransformStream({transform:async(q,z)=>{let B=J==null?void 0:J({part:q}),D=q.type;switch(D){case"text-start":{z.enqueue({type:"text-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-delta":{z.enqueue({type:"text-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-end":{z.enqueue({type:"text-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-start":{z.enqueue({type:"reasoning-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-delta":{if(G)z.enqueue({type:"reasoning-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-end":{z.enqueue({type:"reasoning-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"file":{z.enqueue({type:"file",mediaType:q.file.mediaType,url:`data:${q.file.mediaType};base64,${q.file.base64}`});break}case"source":{if(W&&q.sourceType==="url")z.enqueue({type:"source-url",sourceId:q.id,url:q.url,title:q.title,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});if(W&&q.sourceType==="document")z.enqueue({type:"source-document",sourceId:q.id,mediaType:q.mediaType,title:q.title,filename:q.filename,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"tool-input-start":{let L=F(q);z.enqueue({type:"tool-input-start",toolCallId:q.id,toolName:q.toolName,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-input-delta":{z.enqueue({type:"tool-input-delta",toolCallId:q.id,inputTextDelta:q.delta});break}case"tool-call":{let L=F(q);if(q.invalid)z.enqueue({type:"tool-input-error",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},errorText:K(q.error),...q.title!=null?{title:q.title}:{}});else z.enqueue({type:"tool-input-available",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-approval-request":{z.enqueue({type:"tool-approval-request",approvalId:q.approvalId,toolCallId:q.toolCall.toolCallId});break}case"tool-result":{let L=F(q);z.enqueue({type:"tool-output-available",toolCallId:q.toolCallId,output:q.output,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.preliminary!=null?{preliminary:q.preliminary}:{},...L!=null?{dynamic:L}:{}});break}case"tool-error":{let L=F(q);z.enqueue({type:"tool-output-error",toolCallId:q.toolCallId,errorText:K(q.error),...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{}});break}case"tool-output-denied":{z.enqueue({type:"tool-output-denied",toolCallId:q.toolCallId});break}case"error":{z.enqueue({type:"error",errorText:K(q.error)});break}case"start-step":{z.enqueue({type:"start-step"});break}case"finish-step":{z.enqueue({type:"finish-step"});break}case"start":{if(Z)z.enqueue({type:"start",...B!=null?{messageMetadata:B}:{},...H!=null?{messageId:H}:{}});break}case"finish":{if($)z.enqueue({type:"finish",finishReason:q.finishReason,...B!=null?{messageMetadata:B}:{}});break}case"abort":{z.enqueue(q);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${D}`)}if(B!=null&&D!=="start"&&D!=="finish")z.enqueue({type:"message-metadata",messageMetadata:B})}}));return vP(Cf6({stream:V,messageId:H!=null?H:X==null?void 0:X(),originalMessages:Q,onFinish:Y,onError:K}))}pipeUIMessageStreamToResponse(Q,{originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H,...F}={}){If6({response:Q,stream:this.toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H}),...F})}pipeTextStreamToResponse(Q,X){Mf6({response:Q,textStream:this.textStream,...X})}toUIMessageStreamResponse({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K,...H}={}){return Pf6({stream:this.toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K}),...H})}toTextStreamResponse(Q){return wf6({textStream:this.textStream,...Q})}};async function N71(Q,X){let Y=[];if(X==null?void 0:X.ignoreIncompleteToolCalls)Q=Q.map((J)=>({...J,parts:J.parts.filter((G)=>!kP(G)||G.state!=="input-streaming"&&G.state!=="input-available")}));for(let J of Q)switch(J.role){case"system":{let G=J.parts.filter((Z)=>Z.type==="text"),W=G.reduce((Z,$)=>{if($.providerMetadata!=null)return{...Z,...$.providerMetadata};return Z},{});Y.push({role:"system",content:G.map((Z)=>Z.text).join(""),...Object.keys(W).length>0?{providerOptions:W}:{}});break}case"user":{Y.push({role:"user",content:J.parts.map((G)=>{var W;if(s80(G))return{type:"text",text:G.text,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(t80(G))return{type:"file",mediaType:G.mediaType,filename:G.filename,data:G.url,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(o80(G))return(W=X==null?void 0:X.convertDataPart)==null?void 0:W.call(X,G)}).filter(b51)});break}case"assistant":{if(J.parts!=null){let G=[];async function W(){var Z,$,K,H,F,V;if(G.length===0)return;let q=[];for(let B of G)if(s80(B))q.push({type:"text",text:B.text,...B.providerMetadata!=null?{providerOptions:B.providerMetadata}:{}});else if(t80(B))q.push({type:"file",mediaType:B.mediaType,filename:B.filename,data:B.url});else if(BW1(B))q.push({type:"reasoning",text:B.text,providerOptions:B.providerMetadata});else if(kP(B)){let D=e80(B);if(B.state!=="input-streaming"){if(q.push({type:"tool-call",toolCallId:B.toolCallId,toolName:D,input:B.state==="output-error"?(Z=B.input)!=null?Z:("rawInput"in B)?B.rawInput:void 0:B.input,providerExecuted:B.providerExecuted,...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}}),B.approval!=null)q.push({type:"tool-approval-request",approvalId:B.approval.id,toolCallId:B.toolCallId});if(B.providerExecuted===!0&&B.state!=="approval-responded"&&(B.state==="output-available"||B.state==="output-error"))q.push({type:"tool-result",toolCallId:B.toolCallId,toolName:D,output:await cU({toolCallId:B.toolCallId,input:B.input,output:B.state==="output-error"?B.errorText:B.output,tool:($=X==null?void 0:X.tools)==null?void 0:$[D],errorMode:B.state==="output-error"?"json":"none"}),...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}})}}else if(o80(B)){let D=(K=X==null?void 0:X.convertDataPart)==null?void 0:K.call(X,B);if(D!=null)q.push(D)}else throw Error(`Unsupported part: ${B}`);Y.push({role:"assistant",content:q});let z=G.filter((B)=>{var D;return kP(B)&&(B.providerExecuted!==!0||((D=B.approval)==null?void 0:D.approved)!=null)});if(z.length>0){let B=[];for(let D of z){if(((H=D.approval)==null?void 0:H.approved)!=null)B.push({type:"tool-approval-response",approvalId:D.approval.id,approved:D.approval.approved,reason:D.approval.reason,providerExecuted:D.providerExecuted});if(D.providerExecuted===!0)continue;switch(D.state){case"output-denied":{B.push({type:"tool-result",toolCallId:D.toolCallId,toolName:e80(D),output:{type:"error-text",value:(F=D.approval.reason)!=null?F:"Tool execution denied."},...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let L=e80(D);B.push({type:"tool-result",toolCallId:D.toolCallId,toolName:L,output:await cU({toolCallId:D.toolCallId,input:D.input,output:D.state==="output-error"?D.errorText:D.output,tool:(V=X==null?void 0:X.tools)==null?void 0:V[L],errorMode:D.state==="output-error"?"text":"none"}),...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}});break}}}if(B.length>0)Y.push({role:"tool",content:B})}G=[]}for(let Z of J.parts)if(s80(Z)||BW1(Z)||t80(Z)||kP(Z)||o80(Z))G.push(Z);else if(Z.type==="step-start")await W();await W();break}break}default:{let G=J.role;throw new Vb6({originalMessage:J,message:`Unsupported role: ${G}`})}}return Y}var xd4=dQ(()=>JQ(N.array(N.object({id:N.string(),role:N.enum(["system","user","assistant"]),metadata:N.unknown().optional(),parts:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("reasoning"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("file"),mediaType:N.string(),filename:N.string().optional(),url:N.string(),providerMetadata:i1.optional()}),N.object({type:N.literal("step-start")}),N.object({type:N.string().startsWith("data-"),id:N.string().optional(),data:N.unknown()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-streaming"),input:N.unknown().optional(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-error"),input:N.unknown(),rawInput:N.unknown().optional(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-denied"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-streaming"),providerExecuted:N.boolean().optional(),input:N.unknown().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-error"),providerExecuted:N.boolean().optional(),input:N.unknown(),rawInput:N.unknown().optional(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-denied"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var ud4=WW({prefix:"aiobj",size:24});var ld4=WW({prefix:"aiobj",size:24});function O71({messages:Q,reasoning:X="none",toolCalls:Y=[],emptyMessages:J="remove"}){if(X==="all"||X==="before-last-message")Q=Q.map((G,W)=>{if(G.role!=="assistant"||typeof G.content==="string"||X==="before-last-message"&&W===Q.length-1)return G;return{...G,content:G.content.filter((Z)=>Z.type!=="reasoning")}});if(Y==="none")Y=[];else if(Y==="all")Y=[{type:"all"}];else if(Y==="before-last-message")Y=[{type:"before-last-message"}];else if(typeof Y==="string")Y=[{type:Y}];for(let G of Y){let W=G.type==="all"?void 0:G.type==="before-last-message"?1:Number(G.type.slice(12).slice(0,-9)),Z=new Set,$=new Set;if(W!=null){for(let K of Q.slice(-W))if((K.role==="assistant"||K.role==="tool")&&typeof K.content!=="string"){for(let H of K.content)if(H.type==="tool-call"||H.type==="tool-result")Z.add(H.toolCallId);else if(H.type==="tool-approval-request"||H.type==="tool-approval-response")$.add(H.approvalId)}}Q=Q.map((K,H)=>{if(K.role!=="assistant"&&K.role!=="tool"||typeof K.content==="string"||W&&H>=Q.length-W)return K;let F={},V={};return{...K,content:K.content.filter((q)=>{if(q.type!=="tool-call"&&q.type!=="tool-result"&&q.type!=="tool-approval-request"&&q.type!=="tool-approval-response")return!0;if(q.type==="tool-call")F[q.toolCallId]=q.toolName;else if(q.type==="tool-approval-request")V[q.approvalId]=F[q.toolCallId];if((q.type==="tool-call"||q.type==="tool-result")&&Z.has(q.toolCallId)||(q.type==="tool-approval-request"||q.type==="tool-approval-response")&&$.has(q.approvalId))return!0;return G.tools!=null&&!G.tools.includes(q.type==="tool-call"||q.type==="tool-result"?q.toolName:V[q.approvalId])})}})}if(J==="remove")Q=Q.filter((G)=>G.content.length>0);return Q}var ff6="AI_NoSuchProviderError",hf6=`vercel.ai.error.${ff6}`,xf6=Symbol.for(hf6),gf6;gf6=xf6;G1();function L71(Q){let X=Q.trim();if(!X)return null;if(X.startsWith("event:"))return null;if(X.startsWith("id:"))return null;if(X.startsWith("retry:"))return null;let Y=X;if(Y.startsWith("data:")){if(Y=Y.slice(5).trim(),!Y)return null;if(Y==="[DONE]")return null}try{return JSON.parse(Y)}catch(J){return console.warn("[llm-provider] Failed to parse stream line as JSON. Skipping line.",{line:Y.slice(0,200)},J),null}}function uf6(Q){if(!Q.body)throw Error("Response body is null");let X="";return Q.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(Y,J){X+=Y;let G=X.split(`
|
|
1077
|
+
`)}})}},U71={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Pf6({status:Q,statusText:X,headers:Y,stream:J,consumeSseStream:G}){let W=J.pipeThrough(new z71);if(G){let[Z,$]=W.tee();W=Z,G({stream:$})}return new Response(W.pipeThrough(new TextEncoderStream),{status:Q,statusText:X,headers:Yb(Y,U71)})}function Tf6({originalMessages:Q,responseMessageId:X}){if(Q==null)return;let Y=Q[Q.length-1];return(Y==null?void 0:Y.role)==="assistant"?Y.id:typeof X==="function"?X():X}var yd4=dQ(()=>JQ(N.union([N.strictObject({type:N.literal("text-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("text-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("error"),errorText:N.string()}),N.strictObject({type:N.literal("tool-input-start"),toolCallId:N.string(),toolName:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-delta"),toolCallId:N.string(),inputTextDelta:N.string()}),N.strictObject({type:N.literal("tool-input-available"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-input-error"),toolCallId:N.string(),toolName:N.string(),input:N.unknown(),providerExecuted:N.boolean().optional(),providerMetadata:i1.optional(),dynamic:N.boolean().optional(),errorText:N.string(),title:N.string().optional()}),N.strictObject({type:N.literal("tool-approval-request"),approvalId:N.string(),toolCallId:N.string()}),N.strictObject({type:N.literal("tool-output-available"),toolCallId:N.string(),output:N.unknown(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional(),preliminary:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-error"),toolCallId:N.string(),errorText:N.string(),providerExecuted:N.boolean().optional(),dynamic:N.boolean().optional()}),N.strictObject({type:N.literal("tool-output-denied"),toolCallId:N.string()}),N.strictObject({type:N.literal("reasoning-start"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-delta"),id:N.string(),delta:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("reasoning-end"),id:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.strictObject({type:N.literal("file"),url:N.string(),mediaType:N.string(),providerMetadata:i1.optional()}),N.strictObject({type:N.custom((Q)=>typeof Q==="string"&&Q.startsWith("data-"),{message:'Type must start with "data-"'}),id:N.string().optional(),data:N.unknown(),transient:N.boolean().optional()}),N.strictObject({type:N.literal("start-step")}),N.strictObject({type:N.literal("finish-step")}),N.strictObject({type:N.literal("start"),messageId:N.string().optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("finish"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:N.unknown().optional()}),N.strictObject({type:N.literal("abort"),reason:N.string().optional()}),N.strictObject({type:N.literal("message-metadata"),messageMetadata:N.unknown()})])));function Af6(Q){return Q.type.startsWith("data-")}function o80(Q){return Q.type.startsWith("data-")}function s80(Q){return Q.type==="text"}function t80(Q){return Q.type==="file"}function BW1(Q){return Q.type==="reasoning"}function WQ0(Q){return Q.type.startsWith("tool-")}function B71(Q){return Q.type==="dynamic-tool"}function kP(Q){return WQ0(Q)||B71(Q)}function ZQ0(Q){return Q.type.split("-").slice(1).join("-")}function e80(Q){return B71(Q)?Q.toolName:ZQ0(Q)}function Ef6({lastMessage:Q,messageId:X}){return{message:(Q==null?void 0:Q.role)==="assistant"?Q:{id:X,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function jf6({stream:Q,messageMetadataSchema:X,dataPartSchemas:Y,runUpdateMessageJob:J,onError:G,onToolCall:W,onData:Z}){return Q.pipeThrough(new TransformStream({async transform($,K){await J(async({state:H,write:F})=>{var V,q,z,B;function D(A){let T=H.message.parts.filter(kP).find((j)=>j.toolCallId===A);if(T==null)throw Error(`no tool invocation found for tool call ${A}`);return T}function L(A){var E;let T=H.message.parts.find((v)=>WQ0(v)&&v.toolCallId===A.toolCallId),j=A,R=T;if(T!=null){if(T.state=A.state,R.input=j.input,R.output=j.output,R.errorText=j.errorText,R.rawInput=j.rawInput,R.preliminary=j.preliminary,A.title!==void 0)R.title=A.title;if(R.providerExecuted=(E=j.providerExecuted)!=null?E:T.providerExecuted,j.providerMetadata!=null&&T.state==="input-available")T.callProviderMetadata=j.providerMetadata}else H.message.parts.push({type:`tool-${A.toolName}`,toolCallId:A.toolCallId,state:A.state,title:A.title,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function M(A){var E,T;let j=H.message.parts.find((y)=>y.type==="dynamic-tool"&&y.toolCallId===A.toolCallId),R=A,v=j;if(j!=null){if(j.state=A.state,v.toolName=A.toolName,v.input=R.input,v.output=R.output,v.errorText=R.errorText,v.rawInput=(E=R.rawInput)!=null?E:v.rawInput,v.preliminary=R.preliminary,A.title!==void 0)v.title=A.title;if(v.providerExecuted=(T=R.providerExecuted)!=null?T:j.providerExecuted,R.providerMetadata!=null&&j.state==="input-available")j.callProviderMetadata=R.providerMetadata}else H.message.parts.push({type:"dynamic-tool",toolName:A.toolName,toolCallId:A.toolCallId,state:A.state,input:R.input,output:R.output,errorText:R.errorText,preliminary:R.preliminary,providerExecuted:R.providerExecuted,title:A.title,...R.providerMetadata!=null?{callProviderMetadata:R.providerMetadata}:{}})}async function C(A){if(A!=null){let E=H.message.metadata!=null?KQ0(H.message.metadata,A):A;if(X!=null)await jP({value:E,schema:X});H.message.metadata=E}}switch($.type){case"text-start":{let A={type:"text",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeTextParts[$.id]=A,H.message.parts.push(A),F();break}case"text-delta":{let A=H.activeTextParts[$.id];A.text+=$.delta,A.providerMetadata=(V=$.providerMetadata)!=null?V:A.providerMetadata,F();break}case"text-end":{let A=H.activeTextParts[$.id];A.state="done",A.providerMetadata=(q=$.providerMetadata)!=null?q:A.providerMetadata,delete H.activeTextParts[$.id],F();break}case"reasoning-start":{let A={type:"reasoning",text:"",providerMetadata:$.providerMetadata,state:"streaming"};H.activeReasoningParts[$.id]=A,H.message.parts.push(A),F();break}case"reasoning-delta":{let A=H.activeReasoningParts[$.id];A.text+=$.delta,A.providerMetadata=(z=$.providerMetadata)!=null?z:A.providerMetadata,F();break}case"reasoning-end":{let A=H.activeReasoningParts[$.id];A.providerMetadata=(B=$.providerMetadata)!=null?B:A.providerMetadata,A.state="done",delete H.activeReasoningParts[$.id],F();break}case"file":{H.message.parts.push({type:"file",mediaType:$.mediaType,url:$.url}),F();break}case"source-url":{H.message.parts.push({type:"source-url",sourceId:$.sourceId,url:$.url,title:$.title,providerMetadata:$.providerMetadata}),F();break}case"source-document":{H.message.parts.push({type:"source-document",sourceId:$.sourceId,mediaType:$.mediaType,title:$.title,filename:$.filename,providerMetadata:$.providerMetadata}),F();break}case"tool-input-start":{let A=H.message.parts.filter(WQ0);if(H.partialToolCalls[$.toolCallId]={text:"",toolName:$.toolName,index:A.length,dynamic:$.dynamic,title:$.title},$.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-streaming",input:void 0,providerExecuted:$.providerExecuted,title:$.title});F();break}case"tool-input-delta":{let A=H.partialToolCalls[$.toolCallId];A.text+=$.inputTextDelta;let{value:E}=await yP(A.text);if(A.dynamic)M({toolCallId:$.toolCallId,toolName:A.toolName,state:"input-streaming",input:E,title:A.title});else L({toolCallId:$.toolCallId,toolName:A.toolName,state:"input-streaming",input:E,title:A.title});F();break}case"tool-input-available":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"input-available",input:$.input,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata,title:$.title});if(F(),W&&!$.providerExecuted)await W({toolCall:$});break}case"tool-input-error":{if($.dynamic)M({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});else L({toolCallId:$.toolCallId,toolName:$.toolName,state:"output-error",input:void 0,rawInput:$.input,errorText:$.errorText,providerExecuted:$.providerExecuted,providerMetadata:$.providerMetadata});F();break}case"tool-approval-request":{let A=D($.toolCallId);A.state="approval-requested",A.approval={id:$.approvalId},F();break}case"tool-output-denied":{let A=D($.toolCallId);A.state="output-denied",F();break}case"tool-output-available":{let A=D($.toolCallId);if(A.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:A.toolName,state:"output-available",input:A.input,output:$.output,preliminary:$.preliminary,providerExecuted:$.providerExecuted,title:A.title});else L({toolCallId:$.toolCallId,toolName:ZQ0(A),state:"output-available",input:A.input,output:$.output,providerExecuted:$.providerExecuted,preliminary:$.preliminary,title:A.title});F();break}case"tool-output-error":{let A=D($.toolCallId);if(A.type==="dynamic-tool")M({toolCallId:$.toolCallId,toolName:A.toolName,state:"output-error",input:A.input,errorText:$.errorText,providerExecuted:$.providerExecuted,title:A.title});else L({toolCallId:$.toolCallId,toolName:ZQ0(A),state:"output-error",input:A.input,rawInput:A.rawInput,errorText:$.errorText,providerExecuted:$.providerExecuted,title:A.title});F();break}case"start-step":{H.message.parts.push({type:"step-start"});break}case"finish-step":{H.activeTextParts={},H.activeReasoningParts={};break}case"start":{if($.messageId!=null)H.message.id=$.messageId;if(await C($.messageMetadata),$.messageId!=null||$.messageMetadata!=null)F();break}case"finish":{if($.finishReason!=null)H.finishReason=$.finishReason;if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"message-metadata":{if(await C($.messageMetadata),$.messageMetadata!=null)F();break}case"error":{G==null||G(Error($.errorText));break}default:if(Af6($)){if((Y==null?void 0:Y[$.type])!=null)await jP({value:$.data,schema:Y[$.type]});let A=$;if(A.transient){Z==null||Z(A);break}let E=A.id!=null?H.message.parts.find((T)=>A.type===T.type&&A.id===T.id):void 0;if(E!=null)E.data=A.data;else H.message.parts.push(A);Z==null||Z(A),F()}}K.enqueue($)})}}))}function Cf6({messageId:Q,originalMessages:X=[],onFinish:Y,onError:J,stream:G}){let W=X==null?void 0:X[X.length-1];if((W==null?void 0:W.role)!=="assistant")W=void 0;else Q=W.id;let Z=!1,$=G.pipeThrough(new TransformStream({transform(q,z){if(q.type==="start"){let B=q;if(B.messageId==null&&Q!=null)B.messageId=Q}if(q.type==="abort")Z=!0;z.enqueue(q)}}));if(Y==null)return $;let K=Ef6({lastMessage:W?structuredClone(W):void 0,messageId:Q!=null?Q:""}),H=async(q)=>{await q({state:K,write:()=>{}})},F=!1,V=async()=>{if(F||!Y)return;F=!0;let q=K.message.id===(W==null?void 0:W.id);await Y({isAborted:Z,isContinuation:q,responseMessage:K.message,messages:[...q?X.slice(0,-1):X,K.message],finishReason:K.finishReason})};return jf6({stream:$,runUpdateMessageJob:H,onError:J}).pipeThrough(new TransformStream({transform(q,z){z.enqueue(q)},async cancel(){await V()},async flush(){await V()}}))}function If6({response:Q,status:X,statusText:Y,headers:J,stream:G,consumeSseStream:W}){let Z=G.pipeThrough(new z71);if(W){let[$,K]=Z.tee();Z=$,W({stream:K})}q71({response:Q,status:X,statusText:Y,headers:Object.fromEntries(Yb(J,U71).entries()),stream:Z.pipeThrough(new TextEncoderStream)})}function vP(Q){let X=Q.pipeThrough(new TransformStream);return X[Symbol.asyncIterator]=function(){let Y=this.getReader(),J=!1;async function G(W){var Z;if(J)return;J=!0;try{if(W)await((Z=Y.cancel)==null?void 0:Z.call(Y))}finally{try{Y.releaseLock()}catch($){}}}return{async next(){if(J)return{done:!0,value:void 0};let{done:W,value:Z}=await Y.read();if(W)return await G(!0),{done:!0,value:void 0};return{done:!1,value:Z}},async return(){return await G(!0),{done:!0,value:void 0}},async throw(W){throw await G(!0),W}}},X}async function Rf6({stream:Q,onError:X}){let Y=Q.getReader();try{while(!0){let{done:J}=await Y.read();if(J)break}}catch(J){X==null||X(J)}finally{Y.releaseLock()}}function DW1(){let Q,X;return{promise:new Promise((J,G)=>{Q=J,X=G}),resolve:Q,reject:X}}function Sf6(){let Q=[],X=null,Y=!1,J=DW1(),G=()=>{Y=!0,J.resolve(),Q.forEach((Z)=>Z.cancel()),Q=[],X==null||X.close()},W=async()=>{if(Y&&Q.length===0){X==null||X.close();return}if(Q.length===0)return J=DW1(),await J.promise,W();try{let{value:Z,done:$}=await Q[0].read();if($)if(Q.shift(),Q.length===0&&Y)X==null||X.close();else await W();else X==null||X.enqueue(Z)}catch(Z){X==null||X.error(Z),Q.shift(),G()}};return{stream:new ReadableStream({start(Z){X=Z},pull:W,async cancel(){for(let Z of Q)await Z.cancel();Q=[],Y=!0}}),addStream:(Z)=>{if(Y)throw Error("Cannot add inner stream: outer stream is closed");Q.push(Z.getReader()),J.resolve()},close:()=>{if(Y=!0,J.resolve(),Q.length===0)X==null||X.close()},terminate:G}}function vf6(){var Q,X;return(X=(Q=globalThis==null?void 0:globalThis.performance)==null?void 0:Q.now())!=null?X:Date.now()}function kf6({tools:Q,generatorStream:X,tracer:Y,telemetry:J,system:G,messages:W,abortSignal:Z,repairToolCall:$,experimental_context:K,generateId:H}){let F=null,V=new ReadableStream({start(A){F=A}}),q=new Set,z=new Map,B=new Map,D=!1,L=void 0;function M(){if(D&&q.size===0){if(L!=null)F.enqueue(L);F.close()}}let C=new TransformStream({async transform(A,E){let T=A.type;switch(T){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{E.enqueue(A);break}case"file":{E.enqueue({type:"file",file:new Kf6({data:A.data,mediaType:A.mediaType})});break}case"finish":{L={type:"finish",finishReason:A.finishReason.unified,rawFinishReason:A.finishReason.raw,usage:Xf6(A.usage),providerMetadata:A.providerMetadata};break}case"tool-approval-request":{let j=B.get(A.toolCallId);if(j==null){F.enqueue({type:"error",error:new RW1({toolCallId:A.toolCallId,approvalId:A.approvalId})});break}E.enqueue({type:"tool-approval-request",approvalId:A.approvalId,toolCall:j});break}case"tool-call":{try{let j=await Df6({toolCall:A,tools:Q,repairToolCall:$,system:G,messages:W});if(B.set(j.toolCallId,j),E.enqueue(j),j.invalid){F.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:AP(j.error),dynamic:!0,title:j.title});break}let R=Q==null?void 0:Q[j.toolName];if(R==null)break;if(R.onInputAvailable!=null)await R.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:W,abortSignal:Z,experimental_context:K});if(await Hf6({tool:R,toolCall:j,messages:W,experimental_context:K})){F.enqueue({type:"tool-approval-request",approvalId:H(),toolCall:j});break}if(z.set(j.toolCallId,j.input),R.execute!=null&&j.providerExecuted!==!0){let v=H();q.add(v),F71({toolCall:j,tools:Q,tracer:Y,telemetry:J,messages:W,abortSignal:Z,experimental_context:K,onPreliminaryToolResult:(y)=>{F.enqueue(y)}}).then((y)=>{F.enqueue(y)}).catch((y)=>{F.enqueue({type:"error",error:y})}).finally(()=>{q.delete(v),M()})}}catch(j){F.enqueue({type:"error",error:j})}break}case"tool-result":{let j=A.toolName;if(A.isError)F.enqueue({type:"tool-error",toolCallId:A.toolCallId,toolName:j,input:z.get(A.toolCallId),providerExecuted:!0,error:A.result,dynamic:A.dynamic});else E.enqueue({type:"tool-result",toolCallId:A.toolCallId,toolName:j,input:z.get(A.toolCallId),output:A.result,providerExecuted:!0,dynamic:A.dynamic});break}default:throw Error(`Unhandled chunk type: ${T}`)}},flush(){D=!0,M()}});return new ReadableStream({async start(A){return Promise.all([X.pipeThrough(C).pipeTo(new WritableStream({write(E){A.enqueue(E)},close(){}})),V.pipeTo(new WritableStream({write(E){A.enqueue(E)},close(){A.close()}}))])}})}var _f6=WW({prefix:"aitxt",size:24});function D71({model:Q,tools:X,toolChoice:Y,system:J,prompt:G,messages:W,maxRetries:Z,abortSignal:$,timeout:K,headers:H,stopWhen:F=HQ0(1),experimental_output:V,output:q=V,experimental_telemetry:z,prepareStep:B,providerOptions:D,experimental_activeTools:L,activeTools:M=L,experimental_repairToolCall:C,experimental_transform:A,experimental_download:E,includeRawChunks:T=!1,onChunk:j,onError:R=({error:m})=>{console.error(m)},onFinish:v,onAbort:y,onStepFinish:b,experimental_context:h,_internal:{now:a=vf6,generateId:f=_f6}={},...S}){let m=X71(K),Q0=Lb6(K),r=wb6(K),Y0=Q0!=null?new AbortController:void 0,F0=r!=null?new AbortController:void 0;return new bf6({model:Q71(Q),telemetry:z,headers:H,settings:S,maxRetries:Z,abortSignal:Lf6($,m!=null?AbortSignal.timeout(m):void 0,Y0==null?void 0:Y0.signal,F0==null?void 0:F0.signal),stepTimeoutMs:Q0,stepAbortController:Y0,chunkTimeoutMs:r,chunkAbortController:F0,system:J,prompt:G,messages:W,tools:X,toolChoice:Y,transforms:Xb(A),activeTools:M,repairToolCall:C,stopConditions:Xb(F),output:q,providerOptions:D,prepareStep:B,includeRawChunks:T,onChunk:j,onError:R,onFinish:v,onAbort:y,onStepFinish:b,now:a,generateId:f,experimental_context:h,download:E})}function yf6(Q){let X=void 0,Y="",J="",G=void 0,W="";function Z({controller:$,partialOutput:K=void 0}){$.enqueue({part:{type:"text-delta",id:X,text:J,providerMetadata:G},partialOutput:K}),J=""}return new TransformStream({async transform($,K){var H;if($.type==="finish-step"&&J.length>0)Z({controller:K});if($.type!=="text-delta"&&$.type!=="text-start"&&$.type!=="text-end"){K.enqueue({part:$,partialOutput:void 0});return}if(X==null)X=$.id;else if($.id!==X){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-start"){K.enqueue({part:$,partialOutput:void 0});return}if($.type==="text-end"){if(J.length>0)Z({controller:K});K.enqueue({part:$,partialOutput:void 0});return}Y+=$.text,J+=$.text,G=(H=$.providerMetadata)!=null?H:G;let F=await Q.parsePartialOutput({text:Y});if(F!==void 0){let V=JSON.stringify(F.partial);if(V!==W)Z({controller:K,partialOutput:F.partial}),W=V}}})}var bf6=class{constructor({model:Q,telemetry:X,headers:Y,settings:J,maxRetries:G,abortSignal:W,stepTimeoutMs:Z,stepAbortController:$,chunkTimeoutMs:K,chunkAbortController:H,system:F,prompt:V,messages:q,tools:z,toolChoice:B,transforms:D,activeTools:L,repairToolCall:M,stopConditions:C,output:A,providerOptions:E,prepareStep:T,includeRawChunks:j,now:R,generateId:v,onChunk:y,onError:b,onFinish:h,onAbort:a,onStepFinish:f,experimental_context:S,download:m}){this._totalUsage=new ZF,this._finishReason=new ZF,this._rawFinishReason=new ZF,this._steps=new ZF,this.outputSpecification=A,this.includeRawChunks=j,this.tools=z;let Q0,r=[],Y0=[],F0=void 0,Z0=void 0,B0=void 0,T0={},b0=[],Y1=[],D0=new Map,G0,R0={},_1={},h1=new TransformStream({async transform(I1,b1){var s1,E1,X1,C0;b1.enqueue(I1);let{part:P0}=I1;if(P0.type==="text-delta"||P0.type==="reasoning-delta"||P0.type==="source"||P0.type==="tool-call"||P0.type==="tool-result"||P0.type==="tool-input-start"||P0.type==="tool-input-delta"||P0.type==="raw")await(y==null?void 0:y({chunk:P0}));if(P0.type==="error")await b({error:rb6(P0.error)});if(P0.type==="text-start")R0[P0.id]={type:"text",text:"",providerMetadata:P0.providerMetadata},r.push(R0[P0.id]);if(P0.type==="text-delta"){let a1=R0[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`text part ${P0.id} not found`},partialOutput:void 0});return}a1.text+=P0.text,a1.providerMetadata=(s1=P0.providerMetadata)!=null?s1:a1.providerMetadata}if(P0.type==="text-end"){let a1=R0[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`text part ${P0.id} not found`},partialOutput:void 0});return}a1.providerMetadata=(E1=P0.providerMetadata)!=null?E1:a1.providerMetadata,delete R0[P0.id]}if(P0.type==="reasoning-start")_1[P0.id]={type:"reasoning",text:"",providerMetadata:P0.providerMetadata},r.push(_1[P0.id]);if(P0.type==="reasoning-delta"){let a1=_1[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`reasoning part ${P0.id} not found`},partialOutput:void 0});return}a1.text+=P0.text,a1.providerMetadata=(X1=P0.providerMetadata)!=null?X1:a1.providerMetadata}if(P0.type==="reasoning-end"){let a1=_1[P0.id];if(a1==null){b1.enqueue({part:{type:"error",error:`reasoning part ${P0.id} not found`},partialOutput:void 0});return}a1.providerMetadata=(C0=P0.providerMetadata)!=null?C0:a1.providerMetadata,delete _1[P0.id]}if(P0.type==="file")r.push({type:"file",file:P0.file});if(P0.type==="source")r.push(P0);if(P0.type==="tool-call")r.push(P0);if(P0.type==="tool-result"&&!P0.preliminary)r.push(P0);if(P0.type==="tool-approval-request")r.push(P0);if(P0.type==="tool-error")r.push(P0);if(P0.type==="start-step")r=[],_1={},R0={},T0=P0.request,b0=P0.warnings;if(P0.type==="finish-step"){let a1=await UW1({content:r,tools:z}),M4=new Nf6({content:r,finishReason:P0.finishReason,rawFinishReason:P0.rawFinishReason,usage:P0.usage,warnings:b0,request:T0,response:{...P0.response,messages:[...Y0,...a1]},providerMetadata:P0.providerMetadata});await(f==null?void 0:f(M4)),sW1({warnings:b0,provider:Q.provider,model:Q.modelId}),Y1.push(M4),Y0.push(...a1),Q0.resolve()}if(P0.type==="finish")B0=P0.totalUsage,F0=P0.finishReason,Z0=P0.rawFinishReason},async flush(I1){try{if(Y1.length===0){let X1=(W==null?void 0:W.aborted)?W.reason:new ey6({message:"No output generated. Check the stream for errors."});v0._finishReason.reject(X1),v0._rawFinishReason.reject(X1),v0._totalUsage.reject(X1),v0._steps.reject(X1);return}let b1=F0!=null?F0:"other",s1=B0!=null?B0:r80();v0._finishReason.resolve(b1),v0._rawFinishReason.resolve(Z0),v0._totalUsage.resolve(s1),v0._steps.resolve(Y1);let E1=Y1[Y1.length-1];await(h==null?void 0:h({finishReason:E1.finishReason,rawFinishReason:E1.rawFinishReason,totalUsage:s1,usage:E1.usage,content:E1.content,text:E1.text,reasoningText:E1.reasoningText,reasoning:E1.reasoning,files:E1.files,sources:E1.sources,toolCalls:E1.toolCalls,staticToolCalls:E1.staticToolCalls,dynamicToolCalls:E1.dynamicToolCalls,toolResults:E1.toolResults,staticToolResults:E1.staticToolResults,dynamicToolResults:E1.dynamicToolResults,request:E1.request,response:E1.response,warnings:E1.warnings,providerMetadata:E1.providerMetadata,steps:Y1,experimental_context:S})),G0.setAttributes(await pU({telemetry:X,attributes:{"ai.response.finishReason":b1,"ai.response.text":{output:()=>E1.text},"ai.response.toolCalls":{output:()=>{var X1;return((X1=E1.toolCalls)==null?void 0:X1.length)?JSON.stringify(E1.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(E1.providerMetadata),"ai.usage.inputTokens":s1.inputTokens,"ai.usage.outputTokens":s1.outputTokens,"ai.usage.totalTokens":s1.totalTokens,"ai.usage.reasoningTokens":s1.reasoningTokens,"ai.usage.cachedInputTokens":s1.cachedInputTokens}}))}catch(b1){I1.error(b1)}finally{G0.end()}}}),y0=Sf6();this.addStream=y0.addStream,this.closeStream=y0.close;let w0=y0.stream.getReader(),$0=new ReadableStream({async start(I1){I1.enqueue({type:"start"})},async pull(I1){function b1(){a==null||a({steps:Y1}),I1.enqueue({type:"abort",...(W==null?void 0:W.reason)!==void 0?{reason:_5(W.reason)}:{}}),I1.close()}try{let{done:s1,value:E1}=await w0.read();if(s1){I1.close();return}if(W==null?void 0:W.aborted){b1();return}I1.enqueue(E1)}catch(s1){if(u7(s1)&&(W==null?void 0:W.aborted))b1();else I1.error(s1)}},cancel(I1){return y0.stream.cancel(I1)}});for(let I1 of D)$0=$0.pipeThrough(I1({tools:z,stopStream(){y0.terminate()}}));this.baseStream=$0.pipeThrough(yf6(A!=null?A:GQ0())).pipeThrough(h1);let{maxRetries:j0,retry:H0}=Wf6({maxRetries:G,abortSignal:W}),O0=eb6(X),t0=yb6(J),k0=ob6({model:Q,telemetry:X,headers:Y,settings:{...t0,maxRetries:j0}}),v0=this;JQ0({name:"ai.streamText",attributes:pU({telemetry:X,attributes:{...XQ0({operationId:"ai.streamText",telemetry:X}),...k0,"ai.prompt":{input:()=>JSON.stringify({system:F,prompt:V,messages:q})}}}),tracer:O0,endWhenDone:!1,fn:async(I1)=>{G0=I1;let b1=await ab6({system:F,prompt:V,messages:q}),s1=b1.messages,E1=[],{approvedToolApprovals:X1,deniedToolApprovals:C0}=Zf6({messages:s1});if(C0.length>0||X1.length>0){let a1=[...X1,...C0].filter((O)=>O.toolCall.providerExecuted),M4=X1.filter((O)=>!O.toolCall.providerExecuted),_8=C0.filter((O)=>!O.toolCall.providerExecuted),g1=C0.filter((O)=>O.toolCall.providerExecuted),I0,GY=new ReadableStream({start(O){I0=O}});v0.addStream(GY);try{for(let _ of[..._8,...g1])I0==null||I0.enqueue({type:"tool-output-denied",toolCallId:_.toolCall.toolCallId,toolName:_.toolCall.toolName});let O=[];if(await Promise.all(M4.map(async(_)=>{let s=await F71({toolCall:_.toolCall,tools:z,tracer:O0,telemetry:X,messages:s1,abortSignal:W,experimental_context:S,onPreliminaryToolResult:(J0)=>{I0==null||I0.enqueue(J0)}});if(s!=null)I0==null||I0.enqueue(s),O.push(s)})),a1.length>0)E1.push({role:"tool",content:a1.map((_)=>({type:"tool-approval-response",approvalId:_.approvalResponse.approvalId,approved:_.approvalResponse.approved,reason:_.approvalResponse.reason,providerExecuted:!0}))});if(O.length>0||_8.length>0){let _=[];for(let s of O)_.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:await cU({toolCallId:s.toolCallId,input:s.input,tool:z==null?void 0:z[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"json":"none"})});for(let s of _8)_.push({type:"tool-result",toolCallId:s.toolCall.toolCallId,toolName:s.toolCall.toolName,output:{type:"execution-denied",reason:s.approvalResponse.reason}});E1.push({role:"tool",content:_})}}finally{I0==null||I0.close()}}Y0.push(...E1);async function P0({currentStep:a1,responseMessages:M4,usage:_8}){var g1,I0,GY,O,_,s;let J0=v0.includeRawChunks,U=Z!=null?setTimeout(()=>$.abort(),Z):void 0,w=void 0;function k(){if(K!=null){if(w!=null)clearTimeout(w);w=setTimeout(()=>H.abort(),K)}}function c(){if(w!=null)clearTimeout(w),w=void 0}function t(){if(U!=null)clearTimeout(U)}Q0=new ZF;let u=[...s1,...M4],N0=await(T==null?void 0:T({model:Q,steps:Y1,stepNumber:Y1.length,messages:u,experimental_context:S})),r0=Q71((g1=N0==null?void 0:N0.model)!=null?g1:Q),w1=await Sb6({prompt:{system:(I0=N0==null?void 0:N0.system)!=null?I0:b1.system,messages:(GY=N0==null?void 0:N0.messages)!=null?GY:u},supportedUrls:await r0.supportedUrls,download:m}),{toolChoice:_0,tools:z1}=await fb6({tools:z,toolChoice:(O=N0==null?void 0:N0.toolChoice)!=null?O:B,activeTools:(_=N0==null?void 0:N0.activeTools)!=null?_:L});S=(s=N0==null?void 0:N0.experimental_context)!=null?s:S;let H4=KQ0(E,N0==null?void 0:N0.providerOptions),{result:{stream:DQ,response:u6,request:WY},doStreamSpan:x5,startTimestampMs:YK}=await H0(()=>JQ0({name:"ai.streamText.doStream",attributes:pU({telemetry:X,attributes:{...XQ0({operationId:"ai.streamText.doStream",telemetry:X}),...k0,"ai.model.provider":r0.provider,"ai.model.id":r0.modelId,"ai.prompt.messages":{input:()=>Qf6(w1)},"ai.prompt.tools":{input:()=>z1==null?void 0:z1.map((p1)=>JSON.stringify(p1))},"ai.prompt.toolChoice":{input:()=>_0!=null?JSON.stringify(_0):void 0},"gen_ai.system":r0.provider,"gen_ai.request.model":r0.modelId,"gen_ai.request.frequency_penalty":t0.frequencyPenalty,"gen_ai.request.max_tokens":t0.maxOutputTokens,"gen_ai.request.presence_penalty":t0.presencePenalty,"gen_ai.request.stop_sequences":t0.stopSequences,"gen_ai.request.temperature":t0.temperature,"gen_ai.request.top_k":t0.topK,"gen_ai.request.top_p":t0.topP}}),tracer:O0,endWhenDone:!1,fn:async(p1)=>({startTimestampMs:R(),doStreamSpan:p1,result:await r0.doStream({...t0,tools:z1,toolChoice:_0,responseFormat:await(A==null?void 0:A.responseFormat),prompt:w1,providerOptions:H4,abortSignal:W,headers:Y,includeRawChunks:J0})})})),Q1=kf6({tools:z,generatorStream:DQ,tracer:O0,telemetry:X,system:F,messages:u,repairToolCall:M,abortSignal:W,experimental_context:S,generateId:v}),M6=WY!=null?WY:{},j8=[],O9=[],e0,P6={},y8="other",xY=void 0,ZY=r80(),Wb,FQ0=!0,g5={id:v(),timestamp:new Date,modelId:Q.modelId},VQ0="";v0.addStream(Q1.pipeThrough(new TransformStream({async transform(p1,pQ){var nU,iU,bP,NQ,VF;if(k(),p1.type==="stream-start"){e0=p1.warnings;return}if(FQ0){let GQ=R()-YK;FQ0=!1,x5.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":GQ}),x5.setAttributes({"ai.response.msToFirstChunk":GQ}),pQ.enqueue({type:"start-step",request:M6,warnings:e0!=null?e0:[]})}let Zb=p1.type;switch(Zb){case"tool-approval-request":case"text-start":case"text-end":{pQ.enqueue(p1);break}case"text-delta":{if(p1.delta.length>0)pQ.enqueue({type:"text-delta",id:p1.id,text:p1.delta,providerMetadata:p1.providerMetadata}),VQ0+=p1.delta;break}case"reasoning-start":case"reasoning-end":{pQ.enqueue(p1);break}case"reasoning-delta":{pQ.enqueue({type:"reasoning-delta",id:p1.id,text:p1.delta,providerMetadata:p1.providerMetadata});break}case"tool-call":{pQ.enqueue(p1),j8.push(p1);break}case"tool-result":{if(pQ.enqueue(p1),!p1.preliminary)O9.push(p1);break}case"tool-error":{pQ.enqueue(p1),O9.push(p1);break}case"response-metadata":{g5={id:(nU=p1.id)!=null?nU:g5.id,timestamp:(iU=p1.timestamp)!=null?iU:g5.timestamp,modelId:(bP=p1.modelId)!=null?bP:g5.modelId};break}case"finish":{ZY=p1.usage,y8=p1.finishReason,xY=p1.rawFinishReason,Wb=p1.providerMetadata;let GQ=R()-YK;x5.addEvent("ai.stream.finish"),x5.setAttributes({"ai.response.msToFinish":GQ,"ai.response.avgOutputTokensPerSecond":1000*((NQ=ZY.outputTokens)!=null?NQ:0)/GQ});break}case"file":{pQ.enqueue(p1);break}case"source":{pQ.enqueue(p1);break}case"tool-input-start":{P6[p1.id]=p1.toolName;let GQ=z==null?void 0:z[p1.toolName];if((GQ==null?void 0:GQ.onInputStart)!=null)await GQ.onInputStart({toolCallId:p1.id,messages:u,abortSignal:W,experimental_context:S});pQ.enqueue({...p1,dynamic:(VF=p1.dynamic)!=null?VF:(GQ==null?void 0:GQ.type)==="dynamic",title:GQ==null?void 0:GQ.title});break}case"tool-input-end":{delete P6[p1.id],pQ.enqueue(p1);break}case"tool-input-delta":{let GQ=P6[p1.id],$b=z==null?void 0:z[GQ];if(($b==null?void 0:$b.onInputDelta)!=null)await $b.onInputDelta({inputTextDelta:p1.delta,toolCallId:p1.id,messages:u,abortSignal:W,experimental_context:S});pQ.enqueue(p1);break}case"error":{pQ.enqueue(p1),y8="error";break}case"raw":{if(J0)pQ.enqueue(p1);break}default:throw Error(`Unknown chunk type: ${Zb}`)}},async flush(p1){let pQ=j8.length>0?JSON.stringify(j8):void 0;try{x5.setAttributes(await pU({telemetry:X,attributes:{"ai.response.finishReason":y8,"ai.response.text":{output:()=>VQ0},"ai.response.toolCalls":{output:()=>pQ},"ai.response.id":g5.id,"ai.response.model":g5.modelId,"ai.response.timestamp":g5.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Wb),"ai.usage.inputTokens":ZY.inputTokens,"ai.usage.outputTokens":ZY.outputTokens,"ai.usage.totalTokens":ZY.totalTokens,"ai.usage.reasoningTokens":ZY.reasoningTokens,"ai.usage.cachedInputTokens":ZY.cachedInputTokens,"gen_ai.response.finish_reasons":[y8],"gen_ai.response.id":g5.id,"gen_ai.response.model":g5.modelId,"gen_ai.usage.input_tokens":ZY.inputTokens,"gen_ai.usage.output_tokens":ZY.outputTokens}}))}catch(NQ){}finally{x5.end()}p1.enqueue({type:"finish-step",finishReason:y8,rawFinishReason:xY,usage:ZY,providerMetadata:Wb,response:{...g5,headers:u6==null?void 0:u6.headers}});let nU=Yf6(_8,ZY);await Q0.promise;let iU=j8.filter((NQ)=>NQ.providerExecuted!==!0),bP=O9.filter((NQ)=>NQ.providerExecuted!==!0);for(let NQ of j8){if(NQ.providerExecuted!==!0)continue;let VF=z==null?void 0:z[NQ.toolName];if((VF==null?void 0:VF.type)==="provider"&&VF.supportsDeferredResults){if(!O9.some((GQ)=>GQ.type==="tool-result"&&GQ.toolCallId===NQ.toolCallId))D0.set(NQ.toolCallId,{toolName:NQ.toolName})}}for(let NQ of O9)if(NQ.type==="tool-result")D0.delete(NQ.toolCallId);if(t(),c(),(iU.length>0&&bP.length===iU.length||D0.size>0)&&!await Of6({stopConditions:C,steps:Y1})){M4.push(...await UW1({content:Y1[Y1.length-1].content,tools:z}));try{await P0({currentStep:a1+1,responseMessages:M4,usage:nU})}catch(NQ){p1.enqueue({type:"error",error:NQ}),v0.closeStream()}}else p1.enqueue({type:"finish",finishReason:y8,rawFinishReason:xY,totalUsage:nU}),v0.closeStream()}})))}await P0({currentStep:0,responseMessages:E1,usage:r80()})}}).catch((I1)=>{v0.addStream(new ReadableStream({start(b1){b1.enqueue({type:"error",error:I1}),b1.close()}})),v0.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then((Q)=>Q[Q.length-1])}get content(){return this.finalStep.then((Q)=>Q.content)}get warnings(){return this.finalStep.then((Q)=>Q.warnings)}get providerMetadata(){return this.finalStep.then((Q)=>Q.providerMetadata)}get text(){return this.finalStep.then((Q)=>Q.text)}get reasoningText(){return this.finalStep.then((Q)=>Q.reasoningText)}get reasoning(){return this.finalStep.then((Q)=>Q.reasoning)}get sources(){return this.finalStep.then((Q)=>Q.sources)}get files(){return this.finalStep.then((Q)=>Q.files)}get toolCalls(){return this.finalStep.then((Q)=>Q.toolCalls)}get staticToolCalls(){return this.finalStep.then((Q)=>Q.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then((Q)=>Q.dynamicToolCalls)}get toolResults(){return this.finalStep.then((Q)=>Q.toolResults)}get staticToolResults(){return this.finalStep.then((Q)=>Q.staticToolResults)}get dynamicToolResults(){return this.finalStep.then((Q)=>Q.dynamicToolResults)}get usage(){return this.finalStep.then((Q)=>Q.usage)}get request(){return this.finalStep.then((Q)=>Q.request)}get response(){return this.finalStep.then((Q)=>Q.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[Q,X]=this.baseStream.tee();return this.baseStream=X,Q}get textStream(){return vP(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){if(Q.type==="text-delta")X.enqueue(Q.text)}})))}get fullStream(){return vP(this.teeStream().pipeThrough(new TransformStream({transform({part:Q},X){X.enqueue(Q)}})))}async consumeStream(Q){var X;try{await Rf6({stream:this.fullStream,onError:Q==null?void 0:Q.onError})}catch(Y){(X=Q==null?void 0:Q.onError)==null||X.call(Q,Y)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return vP(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:Q},X){if(Q!=null)X.enqueue(Q)}})))}get elementStream(){var Q,X,Y;let J=(Q=this.outputSpecification)==null?void 0:Q.createElementStreamTransform();if(J==null)throw new A51({functionality:`element streams in ${(Y=(X=this.outputSpecification)==null?void 0:X.name)!=null?Y:"text"} mode`});return vP(this.teeStream().pipeThrough(J))}get output(){return this.finalStep.then((Q)=>{var X;return((X=this.outputSpecification)!=null?X:GQ0()).parseCompleteOutput({text:Q.text},{response:Q.response,usage:Q.usage,finishReason:Q.finishReason})})}toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G=!0,sendSources:W=!1,sendStart:Z=!0,sendFinish:$=!0,onError:K=_5}={}){let H=X!=null?Tf6({originalMessages:Q,responseMessageId:X}):void 0,F=(q)=>{var z;let B=(z=this.tools)==null?void 0:z[q.toolName];if(B==null)return q.dynamic;return(B==null?void 0:B.type)==="dynamic"?!0:void 0},V=this.fullStream.pipeThrough(new TransformStream({transform:async(q,z)=>{let B=J==null?void 0:J({part:q}),D=q.type;switch(D){case"text-start":{z.enqueue({type:"text-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-delta":{z.enqueue({type:"text-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"text-end":{z.enqueue({type:"text-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-start":{z.enqueue({type:"reasoning-start",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-delta":{if(G)z.enqueue({type:"reasoning-delta",id:q.id,delta:q.text,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"reasoning-end":{z.enqueue({type:"reasoning-end",id:q.id,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"file":{z.enqueue({type:"file",mediaType:q.file.mediaType,url:`data:${q.file.mediaType};base64,${q.file.base64}`});break}case"source":{if(W&&q.sourceType==="url")z.enqueue({type:"source-url",sourceId:q.id,url:q.url,title:q.title,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});if(W&&q.sourceType==="document")z.enqueue({type:"source-document",sourceId:q.id,mediaType:q.mediaType,title:q.title,filename:q.filename,...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{}});break}case"tool-input-start":{let L=F(q);z.enqueue({type:"tool-input-start",toolCallId:q.id,toolName:q.toolName,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-input-delta":{z.enqueue({type:"tool-input-delta",toolCallId:q.id,inputTextDelta:q.delta});break}case"tool-call":{let L=F(q);if(q.invalid)z.enqueue({type:"tool-input-error",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},errorText:K(q.error),...q.title!=null?{title:q.title}:{}});else z.enqueue({type:"tool-input-available",toolCallId:q.toolCallId,toolName:q.toolName,input:q.input,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.providerMetadata!=null?{providerMetadata:q.providerMetadata}:{},...L!=null?{dynamic:L}:{},...q.title!=null?{title:q.title}:{}});break}case"tool-approval-request":{z.enqueue({type:"tool-approval-request",approvalId:q.approvalId,toolCallId:q.toolCall.toolCallId});break}case"tool-result":{let L=F(q);z.enqueue({type:"tool-output-available",toolCallId:q.toolCallId,output:q.output,...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...q.preliminary!=null?{preliminary:q.preliminary}:{},...L!=null?{dynamic:L}:{}});break}case"tool-error":{let L=F(q);z.enqueue({type:"tool-output-error",toolCallId:q.toolCallId,errorText:K(q.error),...q.providerExecuted!=null?{providerExecuted:q.providerExecuted}:{},...L!=null?{dynamic:L}:{}});break}case"tool-output-denied":{z.enqueue({type:"tool-output-denied",toolCallId:q.toolCallId});break}case"error":{z.enqueue({type:"error",errorText:K(q.error)});break}case"start-step":{z.enqueue({type:"start-step"});break}case"finish-step":{z.enqueue({type:"finish-step"});break}case"start":{if(Z)z.enqueue({type:"start",...B!=null?{messageMetadata:B}:{},...H!=null?{messageId:H}:{}});break}case"finish":{if($)z.enqueue({type:"finish",finishReason:q.finishReason,...B!=null?{messageMetadata:B}:{}});break}case"abort":{z.enqueue(q);break}case"tool-input-end":break;case"raw":break;default:throw Error(`Unknown chunk type: ${D}`)}if(B!=null&&D!=="start"&&D!=="finish")z.enqueue({type:"message-metadata",messageMetadata:B})}}));return vP(Cf6({stream:V,messageId:H!=null?H:X==null?void 0:X(),originalMessages:Q,onFinish:Y,onError:K}))}pipeUIMessageStreamToResponse(Q,{originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H,...F}={}){If6({response:Q,stream:this.toUIMessageStream({originalMessages:X,generateMessageId:Y,onFinish:J,messageMetadata:G,sendReasoning:W,sendSources:Z,sendFinish:$,sendStart:K,onError:H}),...F})}pipeTextStreamToResponse(Q,X){Mf6({response:Q,textStream:this.textStream,...X})}toUIMessageStreamResponse({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K,...H}={}){return Pf6({stream:this.toUIMessageStream({originalMessages:Q,generateMessageId:X,onFinish:Y,messageMetadata:J,sendReasoning:G,sendSources:W,sendFinish:Z,sendStart:$,onError:K}),...H})}toTextStreamResponse(Q){return wf6({textStream:this.textStream,...Q})}};async function N71(Q,X){let Y=[];if(X==null?void 0:X.ignoreIncompleteToolCalls)Q=Q.map((J)=>({...J,parts:J.parts.filter((G)=>!kP(G)||G.state!=="input-streaming"&&G.state!=="input-available")}));for(let J of Q)switch(J.role){case"system":{let G=J.parts.filter((Z)=>Z.type==="text"),W=G.reduce((Z,$)=>{if($.providerMetadata!=null)return{...Z,...$.providerMetadata};return Z},{});Y.push({role:"system",content:G.map((Z)=>Z.text).join(""),...Object.keys(W).length>0?{providerOptions:W}:{}});break}case"user":{Y.push({role:"user",content:J.parts.map((G)=>{var W;if(s80(G))return{type:"text",text:G.text,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(t80(G))return{type:"file",mediaType:G.mediaType,filename:G.filename,data:G.url,...G.providerMetadata!=null?{providerOptions:G.providerMetadata}:{}};if(o80(G))return(W=X==null?void 0:X.convertDataPart)==null?void 0:W.call(X,G)}).filter(f51)});break}case"assistant":{if(J.parts!=null){let G=[];async function W(){var Z,$,K,H,F,V;if(G.length===0)return;let q=[];for(let B of G)if(s80(B))q.push({type:"text",text:B.text,...B.providerMetadata!=null?{providerOptions:B.providerMetadata}:{}});else if(t80(B))q.push({type:"file",mediaType:B.mediaType,filename:B.filename,data:B.url});else if(BW1(B))q.push({type:"reasoning",text:B.text,providerOptions:B.providerMetadata});else if(kP(B)){let D=e80(B);if(B.state!=="input-streaming"){if(q.push({type:"tool-call",toolCallId:B.toolCallId,toolName:D,input:B.state==="output-error"?(Z=B.input)!=null?Z:("rawInput"in B)?B.rawInput:void 0:B.input,providerExecuted:B.providerExecuted,...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}}),B.approval!=null)q.push({type:"tool-approval-request",approvalId:B.approval.id,toolCallId:B.toolCallId});if(B.providerExecuted===!0&&B.state!=="approval-responded"&&(B.state==="output-available"||B.state==="output-error"))q.push({type:"tool-result",toolCallId:B.toolCallId,toolName:D,output:await cU({toolCallId:B.toolCallId,input:B.input,output:B.state==="output-error"?B.errorText:B.output,tool:($=X==null?void 0:X.tools)==null?void 0:$[D],errorMode:B.state==="output-error"?"json":"none"}),...B.callProviderMetadata!=null?{providerOptions:B.callProviderMetadata}:{}})}}else if(o80(B)){let D=(K=X==null?void 0:X.convertDataPart)==null?void 0:K.call(X,B);if(D!=null)q.push(D)}else throw Error(`Unsupported part: ${B}`);Y.push({role:"assistant",content:q});let z=G.filter((B)=>{var D;return kP(B)&&(B.providerExecuted!==!0||((D=B.approval)==null?void 0:D.approved)!=null)});if(z.length>0){let B=[];for(let D of z){if(((H=D.approval)==null?void 0:H.approved)!=null)B.push({type:"tool-approval-response",approvalId:D.approval.id,approved:D.approval.approved,reason:D.approval.reason,providerExecuted:D.providerExecuted});if(D.providerExecuted===!0)continue;switch(D.state){case"output-denied":{B.push({type:"tool-result",toolCallId:D.toolCallId,toolName:e80(D),output:{type:"error-text",value:(F=D.approval.reason)!=null?F:"Tool execution denied."},...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}});break}case"output-error":case"output-available":{let L=e80(D);B.push({type:"tool-result",toolCallId:D.toolCallId,toolName:L,output:await cU({toolCallId:D.toolCallId,input:D.input,output:D.state==="output-error"?D.errorText:D.output,tool:(V=X==null?void 0:X.tools)==null?void 0:V[L],errorMode:D.state==="output-error"?"text":"none"}),...D.callProviderMetadata!=null?{providerOptions:D.callProviderMetadata}:{}});break}}}if(B.length>0)Y.push({role:"tool",content:B})}G=[]}for(let Z of J.parts)if(s80(Z)||BW1(Z)||t80(Z)||kP(Z)||o80(Z))G.push(Z);else if(Z.type==="step-start")await W();await W();break}break}default:{let G=J.role;throw new Vb6({originalMessage:J,message:`Unsupported role: ${G}`})}}return Y}var gd4=dQ(()=>JQ(N.array(N.object({id:N.string(),role:N.enum(["system","user","assistant"]),metadata:N.unknown().optional(),parts:N.array(N.union([N.object({type:N.literal("text"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("reasoning"),text:N.string(),state:N.enum(["streaming","done"]).optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-url"),sourceId:N.string(),url:N.string(),title:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("source-document"),sourceId:N.string(),mediaType:N.string(),title:N.string(),filename:N.string().optional(),providerMetadata:i1.optional()}),N.object({type:N.literal("file"),mediaType:N.string(),filename:N.string().optional(),url:N.string(),providerMetadata:i1.optional()}),N.object({type:N.literal("step-start")}),N.object({type:N.string().startsWith("data-"),id:N.string().optional(),data:N.unknown()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-streaming"),input:N.unknown().optional(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("input-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-available"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-error"),input:N.unknown(),rawInput:N.unknown().optional(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.literal("dynamic-tool"),toolName:N.string(),toolCallId:N.string(),state:N.literal("output-denied"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-streaming"),providerExecuted:N.boolean().optional(),input:N.unknown().optional(),output:N.never().optional(),errorText:N.never().optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("input-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.never().optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-requested"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.never().optional(),reason:N.never().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("approval-responded"),input:N.unknown(),providerExecuted:N.boolean().optional(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.boolean(),reason:N.string().optional()})}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-available"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.unknown(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),preliminary:N.boolean().optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-error"),providerExecuted:N.boolean().optional(),input:N.unknown(),rawInput:N.unknown().optional(),output:N.never().optional(),errorText:N.string(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!0),reason:N.string().optional()}).optional()}),N.object({type:N.string().startsWith("tool-"),toolCallId:N.string(),state:N.literal("output-denied"),providerExecuted:N.boolean().optional(),input:N.unknown(),output:N.never().optional(),errorText:N.never().optional(),callProviderMetadata:i1.optional(),approval:N.object({id:N.string(),approved:N.literal(!1),reason:N.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var md4=WW({prefix:"aiobj",size:24});var dd4=WW({prefix:"aiobj",size:24});function O71({messages:Q,reasoning:X="none",toolCalls:Y=[],emptyMessages:J="remove"}){if(X==="all"||X==="before-last-message")Q=Q.map((G,W)=>{if(G.role!=="assistant"||typeof G.content==="string"||X==="before-last-message"&&W===Q.length-1)return G;return{...G,content:G.content.filter((Z)=>Z.type!=="reasoning")}});if(Y==="none")Y=[];else if(Y==="all")Y=[{type:"all"}];else if(Y==="before-last-message")Y=[{type:"before-last-message"}];else if(typeof Y==="string")Y=[{type:Y}];for(let G of Y){let W=G.type==="all"?void 0:G.type==="before-last-message"?1:Number(G.type.slice(12).slice(0,-9)),Z=new Set,$=new Set;if(W!=null){for(let K of Q.slice(-W))if((K.role==="assistant"||K.role==="tool")&&typeof K.content!=="string"){for(let H of K.content)if(H.type==="tool-call"||H.type==="tool-result")Z.add(H.toolCallId);else if(H.type==="tool-approval-request"||H.type==="tool-approval-response")$.add(H.approvalId)}}Q=Q.map((K,H)=>{if(K.role!=="assistant"&&K.role!=="tool"||typeof K.content==="string"||W&&H>=Q.length-W)return K;let F={},V={};return{...K,content:K.content.filter((q)=>{if(q.type!=="tool-call"&&q.type!=="tool-result"&&q.type!=="tool-approval-request"&&q.type!=="tool-approval-response")return!0;if(q.type==="tool-call")F[q.toolCallId]=q.toolName;else if(q.type==="tool-approval-request")V[q.approvalId]=F[q.toolCallId];if((q.type==="tool-call"||q.type==="tool-result")&&Z.has(q.toolCallId)||(q.type==="tool-approval-request"||q.type==="tool-approval-response")&&$.has(q.approvalId))return!0;return G.tools!=null&&!G.tools.includes(q.type==="tool-call"||q.type==="tool-result"?q.toolName:V[q.approvalId])})}})}if(J==="remove")Q=Q.filter((G)=>G.content.length>0);return Q}var ff6="AI_NoSuchProviderError",hf6=`vercel.ai.error.${ff6}`,xf6=Symbol.for(hf6),gf6;gf6=xf6;G1();function L71(Q){let X=Q.trim();if(!X)return null;if(X.startsWith("event:"))return null;if(X.startsWith("id:"))return null;if(X.startsWith("retry:"))return null;let Y=X;if(Y.startsWith("data:")){if(Y=Y.slice(5).trim(),!Y)return null;if(Y==="[DONE]")return null}try{return JSON.parse(Y)}catch(J){return console.warn("[llm-provider] Failed to parse stream line as JSON. Skipping line.",{line:Y.slice(0,200)},J),null}}function uf6(Q){if(!Q.body)throw Error("Response body is null");let X="";return Q.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(Y,J){X+=Y;let G=X.split(`
|
|
1078
1078
|
`);X=G.pop()??"";for(let W of G)if(W.trim()){let Z=L71(W);if(Z)J.enqueue(Z)}},flush(Y){if(X.trim()){let J=L71(X);if(J)Y.enqueue(J)}}}))}var mf6=(Q)=>{return Object.fromEntries(Object.entries(Q).map(([X,Y])=>[X,Y.map((J)=>new RegExp(J))]))},w71=(Q)=>{return{imageModel:()=>{throw Error("Image models are not supported by this provider")},textEmbeddingModel:()=>{throw Error("Text embedding models are not supported by this provider")},listModels:async()=>{return await Q.COLLECTION_LLM_LIST({})},languageModel:(X)=>{let Y=GW(()=>Q.LLM_METADATA({modelId:X}).then((J)=>mf6(J.supportedUrls)));return{specificationVersion:"v2",provider:"llm-binding",modelId:X,supportedUrls:Y,doGenerate:async(J)=>{let G=await Q.LLM_DO_GENERATE({callOptions:J,modelId:X}),W=G.response?.timestamp?new Date(G.response.timestamp):void 0;return{...G,response:{...G.response,timestamp:W},usage:{inputTokens:G.usage.inputTokens??void 0,outputTokens:G.usage.outputTokens??void 0,totalTokens:G.usage.totalTokens??void 0,reasoningTokens:G.usage.reasoningTokens??void 0}}},doStream:async(J)=>{let G=await Q.LLM_DO_STREAM({callOptions:J,modelId:X});if(!G.ok)throw Error(`Streaming failed for model ${X} with the status code: ${G.status}
|
|
1079
1079
|
${await G.text()}`);return{stream:uf6(G),response:{headers:Object.fromEntries(G.headers?.entries()??[])}}}}}}};var lf6=32768,df6=50,pf6=N.object({messages:N.any(),model:N.object({id:N.string(),connectionId:N.string(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable(),limits:N.object({contextWindow:N.number().optional(),maxOutputTokens:N.number().optional()}).optional()}).loose(),gateway:N.object({id:N.string()}).loose(),stream:N.boolean().optional(),temperature:N.number().optional(),maxWindowSize:N.number().optional(),thread_id:N.string().optional()}),M71=new ZQ;function cf6(Q,X){if(!Q.organization)throw Error("Organization context is required");if((Q.organization.slug??Q.organization.id)!==X)throw Error("Organization mismatch");return Q.organization}async function nf6(Q,X,Y){let J=await Q.storage.connections.findById(Y);if(!J)return null;if(J.organization_id!==X)throw Error("Connection does not belong to organization");if(J.status!=="active")throw Error(`Connection is ${J.status.toUpperCase()}, not active`);return J}var if6=async(Q,X)=>{let J=(await Q.listTools()).tools.map((G)=>{let{name:W,title:Z,description:$,inputSchema:K,outputSchema:H}=G;return[W,iy({title:Z??W,description:$,inputSchema:e$(K),outputSchema:H?e$(H):void 0,execute:(F,V)=>{let q=X&&Object.keys(X).length>0?{...F,_meta:{properties:X}}:F;return Q.callTool({name:G.name,arguments:q},tG,{signal:V.abortSignal})},toModelOutput:({output:F})=>{if(F.isError)return{type:"error-text",value:F.content.map((q)=>q.type==="text"?q.text:null).filter(Boolean).join(`
|
|
1080
|
-
`)||"Unknown error"};if("structuredContent"in F)return{type:"json",value:F.structuredContent};return{type:"content",value:F.content}}})]});return Object.fromEntries(J)};function af6(Q,X){let Y=ky(new URL(Q.url)),J=`${Y.protocol}//${Y.host}`,G=new Headers,W=["cookie","authorization"];for(let
|
|
1080
|
+
`)||"Unknown error"};if("structuredContent"in F)return{type:"json",value:F.structuredContent};return{type:"content",value:F.content}}})]});return Object.fromEntries(J)};function af6(Q,X){let Y=ky(new URL(Q.url)),J=`${Y.protocol}//${Y.host}`,G=new Headers,W=["cookie","authorization"];for(let $ of W)if(Q.headers.has($))G.set($,Q.headers.get($));let Z=new URL(`/mcp/gateway/${X}`,J);return Z.searchParams.set("mode","code_execution"),new _7(Z,{requestInit:{headers:G}})}M71.post("/:org/models/stream",async(Q)=>{let X=Q.get("meshContext"),Y=Q.req.param("org"),J=null;try{let G=cf6(X,Y),W=await Q.req.json(),Z=pf6.safeParse(W);if(!Z.success)return Q.json({error:"Invalid request body",details:Z.error.issues},400);let $=Z.data,{model:K,gateway:H,messages:F,temperature:V,maxWindowSize:q=df6,thread_id:z}=$,B=K.limits?.maxOutputTokens??lf6,D=af6(Q.req.raw,H.id),L=new QY({name:"mcp-mesh-proxy",version:"1.0.0"}),[M,C]=await Promise.all([N71(F,{ignoreIncompleteToolCalls:!0}),nf6(X,G.id,K.connectionId),L.connect(D)]);if(!C)return Q.json({error:`Model connection not found: ${K.connectionId}`},404);J=L;let A=M.find((f)=>f.role==="system"),E=A?.role==="system"?A.content:void 0,T=M.filter((f)=>f.role!=="system"),j=O71({messages:T,reasoning:"before-last-message",emptyMessages:"remove",toolCalls:"none"}).slice(-q),R=z?{thread_id:z}:void 0,[v,y]=await Promise.all([X.createMCPProxy(C),if6(L,R)]),b=x91.forClient(v),h=w71(b).languageModel(K.id);return D71({model:h,system:E,messages:j,tools:y,temperature:V,maxOutputTokens:B,abortSignal:Q.req.raw.signal,stopWhen:HQ0(30),onError:async(f)=>{console.error("[models:stream] Error",f),await L.close().catch(console.error)},onFinish:async()=>{await L.close().catch(console.error)}}).toUIMessageStreamResponse({messageMetadata:({part:f})=>{if(f.type==="start")return{gateway:H,model:K,created_at:new Date,thread_id:z};if(f.type==="finish-step")return{usage:{...f.usage,providerMetadata:f.providerMetadata}};return{}}})}catch(G){let W=G;if(await J?.close().catch(console.error),W.name==="AbortError")return console.warn("[models:stream] Aborted",JSON.stringify({org:Y})),Q.json({error:"Request aborted"},400);return console.error("[models:stream] Failed",JSON.stringify({org:Y,error:W.message,stack:W.stack})),Q.json({error:W.message},500)}});var P71=M71;var T71=new ZQ;T71.get("/",(Q)=>{let X={theme:br0()};return Q.json({success:!0,config:X})});var A71=T71;y3();var Jb=null;async function rf6(Q,X){let J=(await Q.storage.connections.list(X)).find((G)=>G.connection_url?.startsWith(zt0));if(!J?.configuration_state)return null;return J.configuration_state.project_locator}function of6(Q){let X=new URLSearchParams;if(Q){let[Y,J]=Q.split("/");if(Y)X.set("workspace_hint",Y);if(J)X.set("project_hint",J)}else X.set("auto_personal","true");return X}var sf6=new E71.PrometheusSerializer,tf6=()=>Qe(h7),ef6=()=>et(h7);function j71(Q={}){let X=Q.database??Mk();if(Jb&&Jb.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(Jb.stop()).catch((Z)=>{console.error("[EventBus] Error stopping previous worker:",Z)});let Y;if(Q.eventBus)Y=Q.eventBus;else Y=jY1(X);Jb=Y;let J=new ZQ;J.use("*",Cl({enabled:(Z)=>tk0(Z,"debug")==="1"})),J.use("/*",rk0({origin:(Z)=>{if(Z.includes("localhost")||Z.includes("127.0.0.1"))return Z;return Z},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]})),J.use("*",ak0()),J.use("*",async(Z,$)=>{if(await $(),Z.res.status>=500){let H=await Z.res.clone().text();console.error(`[5xx Response] ${Z.req.method} ${Z.req.path} - ${Z.res.status}:`,H)}}),J.get(DP.HEALTH,(Z)=>{return Z.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),J.get(DP.METRICS,async(Z)=>{try{let $=await Nl.collect(),K=sf6.serialize($.resourceMetrics);return Z.text(K,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch($){return console.error("Failed to collect metrics:",$),Z.text("# Error collecting metrics",500)}}),J.route("/api/config",A71),J.route("/api/auth/custom",RY1),J.all("/api/auth/*",async(Z)=>{return await h7.handler(Z.req.raw)}),J.route("/",YY1),J.all("/oauth-proxy/:connectionId/*",async(Z)=>{let $=Z.req.param("connectionId"),K=Z.req.path.split("/").filter(Boolean),H=K[K.length-1],F=Z.get("meshContext");if(!F)F=await o$.create(Z.req.raw),Z.set("meshContext",F);let V=await F.storage.connections.findById($);if(!V?.connection_url)return Z.json({error:"Connection not found"},404);let q=await vy(V.connection_url),z,B=new URL(V.connection_url);if(q.ok)z=(await q.json()).authorization_servers?.[0];if(!z)z=B.origin;let D=await Y80(z);if(!D.ok)return Z.json({error:"Failed to get auth server metadata"},502);let L=await D.json(),M;if(H==="authorize")M=L.authorization_endpoint;else if(H==="token")M=L.token_endpoint;else if(H==="register")M=L.registration_endpoint;if(!M)return Z.json({error:`Unknown OAuth endpoint: ${H}`},404);let C=new URL(M),A=new URL(Z.req.url);if(C.search=A.search,H==="authorize"){if(C.searchParams.has("resource"))C.searchParams.set("resource",V.connection_url);if(Ut0(V.connection_url))try{let h=await rf6(F,V.organization_id),a=of6(h);for(let[f,S]of a)C.searchParams.set(f,S)}catch(h){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",h)}return Z.redirect(C.toString(),302)}let E={Accept:Z.req.header("Accept")||"application/json"},T=Z.req.header("Content-Type");if(T)E["Content-Type"]=T;let j=Z.req.header("Authorization");if(j)E.Authorization=j;let R;if(Z.req.method!=="GET"&&Z.req.method!=="HEAD")if(H==="token"&&T?.includes("application/x-www-form-urlencoded")){let h=await Z.req.formData();if(h.has("resource"))h.set("resource",V.connection_url);let a=new URLSearchParams;for(let[f,S]of h.entries())a.append(f,S.toString());R=a.toString()}else R=Z.req.raw.body??void 0;let v=await fetch(C.toString(),{method:Z.req.method,headers:E,body:R,duplex:"half",redirect:"manual"}),y=new Headers,b=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[h,a]of v.headers.entries())if(!b.includes(h.toLowerCase()))y.set(h,a);return new Response(v.body,{status:v.status,statusText:v.statusText,headers:y})}),J.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async(Z)=>{let K=await tf6()(Z.req.raw),H=await K.json();return Response.json(H,K)});let G=async(Z)=>{let K=await ef6()(Z.req.raw),H=await K.json();return Response.json(H,K)};J.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",G),o$.set(zY1({db:X.db,databaseType:X.type,auth:h7,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:xD,meter:cE},eventBus:Y})),Promise.resolve(Y.start()).then(()=>{console.log("[EventBus] Worker started")}),J.use("*",async(Z,$)=>{if(DY1(Z.req.path))return $();let K={measure:async(F,V)=>{TV(Z,F);try{return await V()}finally{QH(Z,F)}}},H=await o$.create(Z.req.raw,{timings:K});return Z.set("meshContext",H),$()}),J.get("/api/tools/management",(Z)=>{return Z.json({tools:Rl,grouped:cD()})}),J.use("/mcp/*",async(Z,$)=>{TV(Z,"mcp");try{return await $()}finally{QH(Z,"mcp")}});let W=async(Z,$)=>{let K=Z.var.meshContext;if(!K.auth.user?.id&&!K.auth.apiKey?.id){let H=new URL(Z.req.url);return Z.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${H.origin}${H.pathname}/.well-known/oauth-protected-resource"`}})}return await $()};return J.use("/mcp/:connectionId?",W),J.use("/mcp/gateway/:gatewayId?",W),J.route("/mcp",OJ1),J.route("/mcp",wJ1),J.route("/mcp",FY1),J.use("/api/:org/models/*",async(Z,$)=>{TV(Z,"llm_models");try{return await $()}finally{QH(Z,"llm_models")}}),J.route("/api",P71),J.post("/org/:organizationId/events/:type",async(Z)=>{let $=Z.req.param("organizationId");return await Z.var.meshContext.eventBus.publish($,lz.SELF($),{data:await Z.req.json(),type:`public:${Z.req.param("type")}`,subject:Z.req.query("subject"),deliverAt:Z.req.query("deliverAt"),cron:Z.req.query("cron")}),Z.json({success:!0})}),J.route("/api",SY1),J.notFound((Z)=>{return Z.json({error:"Not Found",path:Z.req.path},404)}),J.onError((Z,$)=>{console.error("Server error :",Z);let K=Z instanceof Error?Z.message:"Unknown error";return $.json({error:"Internal Server Error",message:K},500)}),J}var C71=parseInt(process.env.PORT||"3000",10),Gb="\x1B[0m",Qh6="\x1B[1m",Xh6="\x1B[2m",Yh6="\x1B[32m",Jh6="\x1B[36m",Gh6="\x1B[4m",Wh6=`http://localhost:${C71}`,Zh6=Ak0({clientDir:Tk0(import.meta.url,"../client"),isServerPath:BY1}),$h6=j71();console.log("");console.log(`${Yh6}\u2713${Gb} ${Qh6}Ready${Gb}`);console.log("");console.log(` ${Xh6}Open in browser:${Gb} ${Jh6}${Gh6}${Wh6}${Gb}`);console.log("");Bun.serve({idleTimeout:0,port:C71,hostname:"0.0.0.0",fetch:async(Q)=>{return await Zh6(Q)??$h6.fetch(Q)},development:!1});
|