@decocms/mesh 1.0.0-alpha.28 → 1.0.0-alpha.29
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/server/cli.js +1 -1
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
package/dist/server/cli.js
CHANGED
|
@@ -1077,7 +1077,7 @@ ${W}
|
|
|
1077
1077
|
${$}`.trim()}_serializeSingularDataPoint(Q,J,X){let G="";Q=KQ0(Q,J);let{value:Y,attributes:W}=X,$=(0,eW1.hrTimeToMilliseconds)(X.endTime);return G+=zy(Q,W,Y,this._appendTimestamp?$:void 0,this._additionalAttributes),G}_serializeHistogramDataPoint(Q,J,X){let G="";Q=KQ0(Q,J);let{attributes:Y,value:W}=X,$=(0,eW1.hrTimeToMilliseconds)(X.endTime);for(let q of["count","sum"]){let F=W[q];if(F!=null)G+=zy(Q+"_"+q,Y,F,this._appendTimestamp?$:void 0,this._additionalAttributes)}let K=0,Z=W.buckets.counts.entries(),H=!1;for(let[q,F]of Z){K+=F;let V=W.buckets.boundaries[q];if(V===void 0&&H)break;if(V===1/0)H=!0;G+=zy(Q+"_bucket",Y,K,this._appendTimestamp?$:void 0,Object.assign({},this._additionalAttributes??{},{le:V===void 0||V===1/0?"+Inf":String(V)}))}return G}_serializeResource(Q){if(this._withoutTargetInfo===!0)return"";let J="target_info",X=`# HELP ${J} Target metadata`,G=`# TYPE ${J} gauge`,Y=zy(J,Q.attributes,1).trim();return`${X}
|
|
1078
1078
|
${G}
|
|
1079
1079
|
${Y}
|
|
1080
|
-
`}}X$1.PrometheusSerializer=J$1});var $$1=C((G$1)=>{Object.defineProperty(G$1,"__esModule",{value:!0});G$1.PrometheusExporter=void 0;var AM=F1(),B_4=W4(),qQ0=dW(),O_4=A0("http"),D_4=HQ0(),L_4=A0("url");class Y$ extends qQ0.MetricReader{static DEFAULT_OPTIONS={host:void 0,port:9464,endpoint:"/metrics",prefix:"",appendTimestamp:!1,withResourceConstantLabels:void 0,withoutTargetInfo:!1};_host;_port;_baseUrl;_endpoint;_server;_prefix;_appendTimestamp;_serializer;_startServerPromise;constructor(Q={},J=()=>{}){super({aggregationSelector:(Y)=>{return{type:qQ0.AggregationType.DEFAULT}},aggregationTemporalitySelector:(Y)=>qQ0.AggregationTemporality.CUMULATIVE,metricProducers:Q.metricProducers});this._host=Q.host||process.env.OTEL_EXPORTER_PROMETHEUS_HOST||Y$.DEFAULT_OPTIONS.host,this._port=Q.port||Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT)||Y$.DEFAULT_OPTIONS.port,this._prefix=Q.prefix||Y$.DEFAULT_OPTIONS.prefix,this._appendTimestamp=typeof Q.appendTimestamp==="boolean"?Q.appendTimestamp:Y$.DEFAULT_OPTIONS.appendTimestamp;let X=Q.withResourceConstantLabels||Y$.DEFAULT_OPTIONS.withResourceConstantLabels,G=Q.withoutTargetInfo||Y$.DEFAULT_OPTIONS.withoutTargetInfo;if(this._server=(0,O_4.createServer)(this._requestHandler).unref(),this._serializer=new D_4.PrometheusSerializer(this._prefix,this._appendTimestamp,X,G),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(Q.endpoint||Y$.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,"/$1"),Q.preventServerStart!==!0)this.startServer().then(J,(Y)=>{AM.diag.error(Y),J(Y)});else if(J)queueMicrotask(J)}async onForceFlush(){}onShutdown(){return this.stopServer()}stopServer(){if(!this._server)return AM.diag.debug("Prometheus stopServer() was called but server was never started."),Promise.resolve();else return new Promise((Q)=>{this._server.close((J)=>{if(!J)AM.diag.debug("Prometheus exporter was stopped");else if(J.code!=="ERR_SERVER_NOT_RUNNING")(0,B_4.globalErrorHandler)(J);Q()})})}startServer(){return this._startServerPromise??=new Promise((Q,J)=>{this._server.once("error",J),this._server.listen({port:this._port,host:this._host},()=>{AM.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`),Q()})}),this._startServerPromise}getMetricsRequestHandler(Q,J){this._exportMetrics(J)}_requestHandler=(Q,J)=>{if(Q.url!=null&&new L_4.URL(Q.url,this._baseUrl).pathname===this._endpoint)this._exportMetrics(J);else this._notFound(J)};_exportMetrics=(Q)=>{Q.statusCode=200,Q.setHeader("content-type","text/plain"),this.collect().then((J)=>{let{resourceMetrics:X,errors:G}=J;if(G.length)AM.diag.error("PrometheusExporter: metrics collection errors",...G);Q.end(this._serializer.serialize(X))},(J)=>{Q.end(`# failed to export metrics: ${J}`)})};_notFound=(Q)=>{Q.statusCode=404,Q.end()}}G$1.PrometheusExporter=Y$});var FQ0=C((Ny)=>{Object.defineProperty(Ny,"__esModule",{value:!0});Ny.PrometheusSerializer=Ny.PrometheusExporter=void 0;var w_4=$$1();Object.defineProperty(Ny,"PrometheusExporter",{enumerable:!0,get:function(){return w_4.PrometheusExporter}});var P_4=HQ0();Object.defineProperty(Ny,"PrometheusSerializer",{enumerable:!0,get:function(){return P_4.PrometheusSerializer}})});var By,K$1,Z$1,H$1,VQ0,T_4,EM,q$1;var Oy=h(()=>{By=l4(F1(),1),K$1=l4(tW1(),1),Z$1=l4(FQ0(),1),H$1=l4(g50(),1),VQ0=new Z$1.PrometheusExporter({preventServerStart:!0}),T_4=new K$1.NodeSDK({serviceName:"mcp-mesh",traceExporter:new H$1.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:VQ0});T_4.start();EM=By.trace.getTracer("mcp-mesh","1.0.0"),q$1=By.metrics.getMeter("mcp-mesh","1.0.0")});var zQ0=(Q,J,X)=>{return(G,Y)=>{let W=-1;return $(0);async function $(K){if(K<=W)throw Error("next() called multiple times");W=K;let Z,H=!1,q;if(Q[K])q=Q[K][0][0],G.req.routeIndex=K;else q=K===Q.length&&Y||void 0;if(q)try{Z=await q(G,()=>$(K+1))}catch(F){if(F instanceof Error&&J)G.error=F,Z=await J(F,G),H=!0;else throw F}else if(G.finalized===!1&&X)Z=await X(G);if(Z&&(G.finalized===!1||H))G.res=Z;return G}}};var F$1=()=>{};var UQ0;var NQ0=h(()=>{UQ0=class extends Error{res;status;constructor(Q=500,J){super(J?.message,{cause:J?.cause});this.res=J?.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 V$1;var z$1=h(()=>{V$1=Symbol()});async function A_4(Q,J){let X=await Q.formData();if(X)return E_4(X,J);return{}}function E_4(Q,J){let X=Object.create(null);if(Q.forEach((G,Y)=>{if(!(J.all||Y.endsWith("[]")))X[Y]=G;else j_4(X,Y,G)}),J.dot)Object.entries(X).forEach(([G,Y])=>{if(G.includes("."))I_4(X,G,Y),delete X[G]});return X}var U$1=async(Q,J=Object.create(null))=>{let{all:X=!1,dot:G=!1}=J,W=(Q instanceof Dy?Q.raw.headers:Q.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return A_4(Q,{all:X,dot:G});return{}},j_4=(Q,J,X)=>{if(Q[J]!==void 0)if(Array.isArray(Q[J]))Q[J].push(X);else Q[J]=[Q[J],X];else if(!J.endsWith("[]"))Q[J]=X;else Q[J]=[X]},I_4=(Q,J,X)=>{let G=Q,Y=J.split(".");Y.forEach((W,$)=>{if($===Y.length-1)G[W]=X;else{if(!G[W]||typeof G[W]!=="object"||Array.isArray(G[W])||G[W]instanceof File)G[W]=Object.create(null);G=G[W]}})};var N$1=h(()=>{BQ0()});var DQ0=(Q)=>{let J=Q.split("/");if(J[0]==="")J.shift();return J},B$1=(Q)=>{let{groups:J,path:X}=C_4(Q),G=DQ0(X);return R_4(G,J)},C_4=(Q)=>{let J=[];return Q=Q.replace(/\{[^}]+\}/g,(X,G)=>{let Y=`@${G}`;return J.push([Y,X]),Y}),{groups:J,path:Q}},R_4=(Q,J)=>{for(let X=J.length-1;X>=0;X--){let[G]=J[X];for(let Y=Q.length-1;Y>=0;Y--)if(Q[Y].includes(G)){Q[Y]=Q[Y].replace(G,J[X][1]);break}}return Q},Ly,O$1=(Q,J)=>{if(Q==="*")return"*";let X=Q.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(X){let G=`${Q}#${J}`;if(!Ly[G])if(X[2])Ly[G]=J&&J[0]!==":"&&J[0]!=="*"?[G,X[1],new RegExp(`^${X[2]}(?=/${J})`)]:[Q,X[1],new RegExp(`^${X[2]}$`)];else Ly[G]=[Q,X[1],!0];return Ly[G]}return null},wy=(Q,J)=>{try{return J(Q)}catch{return Q.replace(/(?:%[0-9A-Fa-f]{2})+/g,(X)=>{try{return J(X)}catch{return X}})}},S_4=(Q)=>wy(Q,decodeURI),LQ0=(Q)=>{let J=Q.url,X=J.indexOf("/",J.indexOf(":")+4),G=X;for(;G<J.length;G++){let Y=J.charCodeAt(G);if(Y===37){let W=J.indexOf("?",G),$=J.slice(X,W===-1?void 0:W);return S_4($.includes("%25")?$.replace(/%25/g,"%2525"):$)}else if(Y===63)break}return J.slice(X,G)},D$1=(Q)=>{let J=LQ0(Q);return J.length>1&&J.at(-1)==="/"?J.slice(0,-1):J},gq=(Q,J,...X)=>{if(X.length)J=gq(J,...X);return`${Q?.[0]==="/"?"":"/"}${Q}${J==="/"?"":`${Q?.at(-1)==="/"?"":"/"}${J?.[0]==="/"?J.slice(1):J}`}`},Py=(Q)=>{if(Q.charCodeAt(Q.length-1)!==63||!Q.includes(":"))return null;let J=Q.split("/"),X=[],G="";return J.forEach((Y)=>{if(Y!==""&&!/\:/.test(Y))G+="/"+Y;else if(/\:/.test(Y))if(/\?/.test(Y)){if(X.length===0&&G==="")X.push("/");else X.push(G);let W=Y.replace("?","");G+="/"+W,X.push(G)}else G+="/"+Y}),X.filter((Y,W,$)=>$.indexOf(Y)===W)},OQ0=(Q)=>{if(!/[%+]/.test(Q))return Q;if(Q.indexOf("+")!==-1)Q=Q.replace(/\+/g," ");return Q.indexOf("%")!==-1?wy(Q,wQ0):Q},L$1=(Q,J,X)=>{let G;if(!X&&J&&!/[%+]/.test(J)){let $=Q.indexOf("?",8);if($===-1)return;if(!Q.startsWith(J,$+1))$=Q.indexOf(`&${J}`,$+1);while($!==-1){let K=Q.charCodeAt($+J.length+1);if(K===61){let Z=$+J.length+2,H=Q.indexOf("&",Z);return OQ0(Q.slice(Z,H===-1?void 0:H))}else if(K==38||isNaN(K))return"";$=Q.indexOf(`&${J}`,$+1)}if(G=/[%+]/.test(Q),!G)return}let Y={};G??=/[%+]/.test(Q);let W=Q.indexOf("?",8);while(W!==-1){let $=Q.indexOf("&",W+1),K=Q.indexOf("=",W);if(K>$&&$!==-1)K=-1;let Z=Q.slice(W+1,K===-1?$===-1?void 0:$:K);if(G)Z=OQ0(Z);if(W=$,Z==="")continue;let H;if(K===-1)H="";else if(H=Q.slice(K+1,$===-1?void 0:$),G)H=OQ0(H);if(X){if(!(Y[Z]&&Array.isArray(Y[Z])))Y[Z]=[];Y[Z].push(H)}else Y[Z]??=H}return J?Y[J]:Y},w$1,P$1=(Q,J)=>{return L$1(Q,J,!0)},wQ0;var PN=h(()=>{Ly={},w$1=L$1,wQ0=decodeURIComponent});var M$1=(Q)=>wy(Q,wQ0),Dy;var BQ0=h(()=>{NQ0();z$1();N$1();PN();Dy=class{raw;#Q;#J;routeIndex=0;path;bodyCache={};constructor(Q,J="/",X=[[]]){this.raw=Q,this.path=J,this.#J=X,this.#Q={}}param(Q){return Q?this.#X(Q):this.#Y()}#X(Q){let J=this.#J[0][this.routeIndex][1][Q],X=this.#W(J);return X&&/\%/.test(X)?M$1(X):X}#Y(){let Q={},J=Object.keys(this.#J[0][this.routeIndex][1]);for(let X of J){let G=this.#W(this.#J[0][this.routeIndex][1][X]);if(G!==void 0)Q[X]=/\%/.test(G)?M$1(G):G}return Q}#W(Q){return this.#J[1]?this.#J[1][Q]:Q}query(Q){return w$1(this.url,Q)}queries(Q){return P$1(this.url,Q)}header(Q){if(Q)return this.raw.headers.get(Q)??void 0;let J={};return this.raw.headers.forEach((X,G)=>{J[G]=X}),J}async parseBody(Q){return this.bodyCache.parsedBody??=await U$1(this,Q)}#G=(Q)=>{let{bodyCache:J,raw:X}=this,G=J[Q];if(G)return G;let Y=Object.keys(J)[0];if(Y)return J[Y].then((W)=>{if(Y==="json")W=JSON.stringify(W);return new Response(W)[Q]()});return J[Q]=X[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,J){this.#Q[Q]=J}valid(Q){return this.#Q[Q]}get url(){return this.raw.url}get method(){return this.raw.method}get[V$1](){return this.#J}get matchedRoutes(){return this.#J[0].map(([[,Q]])=>Q)}get routePath(){return this.#J[0].map(([[,Q]])=>Q)[this.routeIndex].path}}});var T$1,v_4=(Q,J)=>{let X=new String(Q);return X.isEscaped=!0,X.callbacks=J,X},PQ0=async(Q,J,X,G,Y)=>{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(Y)Y[0]+=Q;else Y=[Q];let $=Promise.all(W.map((K)=>K({phase:J,buffer:Y,context:G}))).then((K)=>Promise.all(K.filter(Boolean).map((Z)=>PQ0(Z,J,!1,G,Y))).then(()=>Y[0]));if(X)return v_4(await $,W);else return $};var A$1=h(()=>{T$1={Stringify:1,BeforeStream:2,Stream:3}});var k_4="text/plain; charset=UTF-8",MQ0=(Q,J)=>{return{"Content-Type":Q,...J}},E$1=class{#Q;#J;env={};#X;finalized=!1;error;#Y;#W;#G;#K;#$;#H;#Z;#F;#V;constructor(Q,J){if(this.#Q=Q,J)this.#W=J.executionCtx,this.env=J.env,this.#H=J.notFoundHandler,this.#V=J.path,this.#F=J.matchResult}get req(){return this.#J??=new Dy(this.#Q,this.#V,this.#F),this.#J}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.#Z??=new Headers})}set res(Q){if(this.#G&&Q){Q=new Response(Q.body,Q);for(let[J,X]of this.#G.headers.entries()){if(J==="content-type")continue;if(J==="set-cookie"){let G=this.#G.headers.getSetCookie();Q.headers.delete("set-cookie");for(let Y of G)Q.headers.append("set-cookie",Y)}else Q.headers.set(J,X)}}this.#G=Q,this.finalized=!0}render=(...Q)=>{return this.#$??=(J)=>this.html(J),this.#$(...Q)};setLayout=(Q)=>this.#K=Q;getLayout=()=>this.#K;setRenderer=(Q)=>{this.#$=Q};header=(Q,J,X)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let G=this.#G?this.#G.headers:this.#Z??=new Headers;if(J===void 0)G.delete(Q);else if(X?.append)G.append(Q,J);else G.set(Q,J)};status=(Q)=>{this.#Y=Q};set=(Q,J)=>{this.#X??=new Map,this.#X.set(Q,J)};get=(Q)=>{return this.#X?this.#X.get(Q):void 0};get var(){if(!this.#X)return{};return Object.fromEntries(this.#X)}#q(Q,J,X){let G=this.#G?new Headers(this.#G.headers):this.#Z??new Headers;if(typeof J==="object"&&"headers"in J){let W=J.headers instanceof Headers?J.headers:new Headers(J.headers);for(let[$,K]of W)if($.toLowerCase()==="set-cookie")G.append($,K);else G.set($,K)}if(X)for(let[W,$]of Object.entries(X))if(typeof $==="string")G.set(W,$);else{G.delete(W);for(let K of $)G.append(W,K)}let Y=typeof J==="number"?J:J?.status??this.#Y;return new Response(Q,{status:Y,headers:G})}newResponse=(...Q)=>this.#q(...Q);body=(Q,J,X)=>this.#q(Q,J,X);text=(Q,J,X)=>{return!this.#Z&&!this.#Y&&!J&&!X&&!this.finalized?new Response(Q):this.#q(Q,J,MQ0(k_4,X))};json=(Q,J,X)=>{return this.#q(JSON.stringify(Q),J,MQ0("application/json",X))};html=(Q,J,X)=>{let G=(Y)=>this.#q(Y,J,MQ0("text/html; charset=UTF-8",X));return typeof Q==="object"?PQ0(Q,T$1.Stringify,!1,{}).then(G):G(Q)};redirect=(Q,J)=>{let X=String(Q);return this.header("Location",!/[^\x00-\xFF]/.test(X)?X:encodeURI(X)),this.newResponse(null,J??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var j$1=h(()=>{BQ0();A$1()});var Z8="ALL",I$1="all",C$1,My="Can not add a route since the matcher is already built.",Ty;var uq=h(()=>{C$1=["get","post","put","delete","options","patch"],Ty=class extends Error{}});var R$1="__COMPOSED_HANDLER";var S$1=()=>{};var __4=(Q)=>{return Q.text("404 Not Found",404)},v$1=(Q,J)=>{if("getResponse"in Q){let X=Q.getResponse();return J.newResponse(X.body,X)}return console.error(Q),J.text("Internal Server Error",500)},k$1=class Q{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Q="/";routes=[];constructor(J={}){[...C$1,I$1].forEach((W)=>{this[W]=($,...K)=>{if(typeof $==="string")this.#Q=$;else this.#Y(W,this.#Q,$);return K.forEach((Z)=>{this.#Y(W,this.#Q,Z)}),this}}),this.on=(W,$,...K)=>{for(let Z of[$].flat()){this.#Q=Z;for(let H of[W].flat())K.map((q)=>{this.#Y(H.toUpperCase(),this.#Q,q)})}return this},this.use=(W,...$)=>{if(typeof W==="string")this.#Q=W;else this.#Q="*",$.unshift(W);return $.forEach((K)=>{this.#Y(Z8,this.#Q,K)}),this};let{strict:G,...Y}=J;Object.assign(this,Y),this.getPath=G??!0?J.getPath??LQ0:D$1}#J(){let J=new Q({router:this.router,getPath:this.getPath});return J.errorHandler=this.errorHandler,J.#X=this.#X,J.routes=this.routes,J}#X=__4;errorHandler=v$1;route(J,X){let G=this.basePath(J);return X.routes.map((Y)=>{let W;if(X.errorHandler===v$1)W=Y.handler;else W=async($,K)=>(await zQ0([],X.errorHandler)($,()=>Y.handler($,K))).res,W[R$1]=Y.handler;G.#Y(Y.method,Y.path,W)}),this}basePath(J){let X=this.#J();return X._basePath=gq(this._basePath,J),X}onError=(J)=>{return this.errorHandler=J,this};notFound=(J)=>{return this.#X=J,this};mount(J,X,G){let Y,W;if(G)if(typeof G==="function")W=G;else if(W=G.optionHandler,G.replaceRequest===!1)Y=(Z)=>Z;else Y=G.replaceRequest;let $=W?(Z)=>{let H=W(Z);return Array.isArray(H)?H:[H]}:(Z)=>{let H=void 0;try{H=Z.executionCtx}catch{}return[Z.env,H]};Y||=(()=>{let Z=gq(this._basePath,J),H=Z==="/"?0:Z.length;return(q)=>{let F=new URL(q.url);return F.pathname=F.pathname.slice(H)||"/",new Request(F,q)}})();let K=async(Z,H)=>{let q=await X(Y(Z.req.raw),...$(Z));if(q)return q;await H()};return this.#Y(Z8,gq(J,"*"),K),this}#Y(J,X,G){J=J.toUpperCase(),X=gq(this._basePath,X);let Y={basePath:this._basePath,path:X,method:J,handler:G};this.router.add(J,X,[G,Y]),this.routes.push(Y)}#W(J,X){if(J instanceof Error)return this.errorHandler(J,X);throw J}#G(J,X,G,Y){if(Y==="HEAD")return(async()=>new Response(null,await this.#G(J,X,G,"GET")))();let W=this.getPath(J,{env:G}),$=this.router.match(Y,W),K=new E$1(J,{path:W,matchResult:$,env:G,executionCtx:X,notFoundHandler:this.#X});if($[0].length===1){let H;try{H=$[0][0][0][0](K,async()=>{K.res=await this.#X(K)})}catch(q){return this.#W(q,K)}return H instanceof Promise?H.then((q)=>q||(K.finalized?K.res:this.#X(K))).catch((q)=>this.#W(q,K)):H??this.#X(K)}let Z=zQ0($[0],this.errorHandler,this.#X);return(async()=>{try{let H=await Z(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,K)}})()}fetch=(J,...X)=>{return this.#G(J,X[1],X[0],J.method)};request=(J,X,G,Y)=>{if(J instanceof Request)return this.fetch(X?new Request(J,X):J,G,Y);return J=J.toString(),this.fetch(new Request(/^https?:\/\//.test(J)?J:`http://localhost${gq("/",J)}`,X),G,Y)};fire=()=>{addEventListener("fetch",(J)=>{J.respondWith(this.#G(J.request,J,void 0,J.request.method))})}};var _$1=h(()=>{F$1();j$1();uq();S$1();PN()});function Ay(Q,J){let X=this.buildAllMatchers(),G=(Y,W)=>{let $=X[Y]||X[Z8],K=$[2][W];if(K)return K;let Z=W.match($[0]);if(!Z)return[[],jM];let H=Z.indexOf("",1);return[$[1][H],Z]};return this.match=G,G(Q,J)}var jM;var TQ0=h(()=>{uq();jM=[]});function h_4(Q,J){if(Q.length===1)return J.length===1?Q<J?-1:1:-1;if(J.length===1)return 1;if(Q===IM||Q===CM)return 1;else if(J===IM||J===CM)return-1;if(Q===Ey)return 1;else if(J===Ey)return-1;return Q.length===J.length?Q<J?-1:1:J.length-Q.length}var Ey="[^/]+",IM=".*",CM="(?:|/.*)",mq,y_4,y$1=class Q{#Q;#J;#X=Object.create(null);insert(J,X,G,Y,W){if(J.length===0){if(this.#Q!==void 0)throw mq;if(W)return;this.#Q=X;return}let[$,...K]=J,Z=$==="*"?K.length===0?["","",IM]:["","",Ey]:$==="/*"?["","",CM]:$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(Z){let q=Z[1],F=Z[2]||Ey;if(q&&Z[2]){if(F===".*")throw mq;if(F=F.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(F))throw mq}if(H=this.#X[F],!H){if(Object.keys(this.#X).some((V)=>V!==IM&&V!==CM))throw mq;if(W)return;if(H=this.#X[F]=new Q,q!=="")H.#J=Y.varIndex++}if(!W&&q!=="")G.push([q,H.#J])}else if(H=this.#X[$],!H){if(Object.keys(this.#X).some((q)=>q.length>1&&q!==IM&&q!==CM))throw mq;if(W)return;H=this.#X[$]=new Q}H.insert(K,X,G,Y,W)}buildRegExpStr(){let X=Object.keys(this.#X).sort(h_4).map((G)=>{let Y=this.#X[G];return(typeof Y.#J==="number"?`(${G})@${Y.#J}`:y_4.has(G)?`\\${G}`:G)+Y.buildRegExpStr()});if(typeof this.#Q==="number")X.unshift(`#${this.#Q}`);if(X.length===0)return"";if(X.length===1)return X[0];return"(?:"+X.join("|")+")"}};var AQ0=h(()=>{mq=Symbol(),y_4=new Set(".\\+*[^]$()")});var h$1=class{#Q={varIndex:0};#J=new y$1;insert(Q,J,X){let G=[],Y=[];for(let $=0;;){let K=!1;if(Q=Q.replace(/\{[^}]+\}/g,(Z)=>{let H=`@\\${$}`;return Y[$]=[H,Z],$++,K=!0,H}),!K)break}let W=Q.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let $=Y.length-1;$>=0;$--){let[K]=Y[$];for(let Z=W.length-1;Z>=0;Z--)if(W[Z].indexOf(K)!==-1){W[Z]=W[Z].replace(K,Y[$][1]);break}}return this.#J.insert(W,J,G,this.#Q,X),G}buildRegExp(){let Q=this.#J.buildRegExpStr();if(Q==="")return[/^$/,[],[]];let J=0,X=[],G=[];return Q=Q.replace(/#(\d+)|@(\d+)|\.\*\$/g,(Y,W,$)=>{if(W!==void 0)return X[++J]=Number(W),"$()";if($!==void 0)return G[Number($)]=++J,"";return""}),[new RegExp(`^${Q}`),X,G]}};var f$1=h(()=>{AQ0()});function x$1(Q){return b$1[Q]??=new RegExp(Q==="*"?"":`^${Q.replace(/\/\*$|([.\\+*[^\]$()])/g,(J,X)=>X?`\\${X}`:"(?:|/.*)")}$`)}function b_4(){b$1=Object.create(null)}function x_4(Q){let J=new h$1,X=[];if(Q.length===0)return f_4;let G=Q.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,q],[F,V])=>H?1:F?-1:q.length-V.length),Y=Object.create(null);for(let H=0,q=-1,F=G.length;H<F;H++){let[V,z,U]=G[H];if(V)Y[z]=[U.map(([D])=>[D,Object.create(null)]),jM];else q++;let N;try{N=J.insert(z,q,V)}catch(D){throw D===mq?new Ty(z):D}if(V)continue;X[q]=U.map(([D,w])=>{let A=Object.create(null);w-=1;for(;w>=0;w--){let[P,M]=N[w];A[P]=M}return[D,A]})}let[W,$,K]=J.buildRegExp();for(let H=0,q=X.length;H<q;H++)for(let F=0,V=X[H].length;F<V;F++){let z=X[H][F]?.[1];if(!z)continue;let U=Object.keys(z);for(let N=0,D=U.length;N<D;N++)z[U[N]]=K[z[U[N]]]}let Z=[];for(let H in $)Z[H]=X[$[H]];return[W,Z,Y]}function MN(Q,J){if(!Q)return;for(let X of Object.keys(Q).sort((G,Y)=>Y.length-G.length))if(x$1(X).test(J))return[...Q[X]];return}var f_4,b$1,jy=class{name="RegExpRouter";#Q;#J;constructor(){this.#Q={[Z8]:Object.create(null)},this.#J={[Z8]:Object.create(null)}}add(Q,J,X){let G=this.#Q,Y=this.#J;if(!G||!Y)throw Error(My);if(!G[Q])[G,Y].forEach((K)=>{K[Q]=Object.create(null),Object.keys(K[Z8]).forEach((Z)=>{K[Q][Z]=[...K[Z8][Z]]})});if(J==="/*")J="*";let W=(J.match(/\/:/g)||[]).length;if(/\*$/.test(J)){let K=x$1(J);if(Q===Z8)Object.keys(G).forEach((Z)=>{G[Z][J]||=MN(G[Z],J)||MN(G[Z8],J)||[]});else G[Q][J]||=MN(G[Q],J)||MN(G[Z8],J)||[];Object.keys(G).forEach((Z)=>{if(Q===Z8||Q===Z)Object.keys(G[Z]).forEach((H)=>{K.test(H)&&G[Z][H].push([X,W])})}),Object.keys(Y).forEach((Z)=>{if(Q===Z8||Q===Z)Object.keys(Y[Z]).forEach((H)=>K.test(H)&&Y[Z][H].push([X,W]))});return}let $=Py(J)||[J];for(let K=0,Z=$.length;K<Z;K++){let H=$[K];Object.keys(Y).forEach((q)=>{if(Q===Z8||Q===q)Y[q][H]||=[...MN(G[q],H)||MN(G[Z8],H)||[]],Y[q][H].push([X,W-Z+K+1])})}}match=Ay;buildAllMatchers(){let Q=Object.create(null);return Object.keys(this.#J).concat(Object.keys(this.#Q)).forEach((J)=>{Q[J]||=this.#X(J)}),this.#Q=this.#J=void 0,b_4(),Q}#X(Q){let J=[],X=Q===Z8;if([this.#Q,this.#J].forEach((G)=>{let Y=G[Q]?Object.keys(G[Q]).map((W)=>[W,G[Q][W]]):[];if(Y.length!==0)X||=!0,J.push(...Y);else if(Q!==Z8)J.push(...Object.keys(G[Z8]).map((W)=>[W,G[Z8][W]]))}),!X)return null;else return x_4(J)}};var EQ0=h(()=>{uq();PN();TQ0();AQ0();f$1();f_4=[/^$/,[],Object.create(null)],b$1=Object.create(null)});var g_4=class{name="PreparedRegExpRouter";#Q;#J;constructor(Q,J){this.#Q=Q,this.#J=J}#X(Q,J){let X=this.#Q[Q];X[1].forEach((G)=>G&&G.push(J)),Object.values(X[2]).forEach((G)=>G[0].push(J))}#Y(Q,J,X,G,Y){let W=this.#Q[Q];if(!Y)W[2][J][0].push([X,{}]);else G.forEach(($)=>{if(typeof $==="number")W[1][$].push([X,Y]);else W[2][$||J][0].push([X,Y])})}add(Q,J,X){if(!this.#Q[Q]){let Y=this.#Q[Z8],W={};for(let $ in Y[2])W[$]=[Y[2][$][0].slice(),jM];this.#Q[Q]=[Y[0],Y[1].map(($)=>Array.isArray($)?$.slice():0),W]}if(J==="/*"||J==="*"){let Y=[X,{}];if(Q===Z8)for(let W in this.#Q)this.#X(W,Y);else this.#X(Q,Y);return}let G=this.#J[J];if(!G)throw Error(`Path ${J} is not registered`);for(let[Y,W]of G)if(Q===Z8)for(let $ in this.#Q)this.#Y($,J,X,Y,W);else this.#Y(Q,J,X,Y,W)}buildAllMatchers(){return this.#Q}match=Ay};var g$1=h(()=>{uq();TQ0();EQ0()});var u$1=h(()=>{EQ0();g$1()});var jQ0=class{name="SmartRouter";#Q=[];#J=[];constructor(Q){this.#Q=Q.routers}add(Q,J,X){if(!this.#J)throw Error(My);this.#J.push([Q,J,X])}match(Q,J){if(!this.#J)throw Error("Fatal error");let X=this.#Q,G=this.#J,Y=X.length,W=0,$;for(;W<Y;W++){let K=X[W];try{for(let Z=0,H=G.length;Z<H;Z++)K.add(...G[Z]);$=K.match(Q,J)}catch(Z){if(Z instanceof Ty)continue;throw Z}this.match=K.match.bind(K),this.#Q=[K],this.#J=void 0;break}if(W===Y)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,$}get activeRouter(){if(this.#J||this.#Q.length!==1)throw Error("No active router has been determined yet.");return this.#Q[0]}};var m$1=h(()=>{uq()});var l$1=h(()=>{m$1()});var RM,d$1=class Q{#Q;#J;#X;#Y=0;#W=RM;constructor(J,X,G){if(this.#J=G||Object.create(null),this.#Q=[],J&&X){let Y=Object.create(null);Y[J]={handler:X,possibleKeys:[],score:0},this.#Q=[Y]}this.#X=[]}insert(J,X,G){this.#Y=++this.#Y;let Y=this,W=B$1(X),$=[];for(let K=0,Z=W.length;K<Z;K++){let H=W[K],q=W[K+1],F=O$1(H,q),V=Array.isArray(F)?F[0]:H;if(V in Y.#J){if(Y=Y.#J[V],F)$.push(F[1]);continue}if(Y.#J[V]=new Q,F)Y.#X.push(F),$.push(F[1]);Y=Y.#J[V]}return Y.#Q.push({[J]:{handler:G,possibleKeys:$.filter((K,Z,H)=>H.indexOf(K)===Z),score:this.#Y}}),Y}#G(J,X,G,Y){let W=[];for(let $=0,K=J.#Q.length;$<K;$++){let Z=J.#Q[$],H=Z[X]||Z[Z8],q={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),G!==RM||Y&&Y!==RM)for(let F=0,V=H.possibleKeys.length;F<V;F++){let z=H.possibleKeys[F],U=q[H.score];H.params[z]=Y?.[z]&&!U?Y[z]:G[z]??Y?.[z],q[H.score]=!0}}}return W}search(J,X){let G=[];this.#W=RM;let W=[this],$=DQ0(X),K=[];for(let Z=0,H=$.length;Z<H;Z++){let q=$[Z],F=Z===H-1,V=[];for(let z=0,U=W.length;z<U;z++){let N=W[z],D=N.#J[q];if(D)if(D.#W=N.#W,F){if(D.#J["*"])G.push(...this.#G(D.#J["*"],J,N.#W));G.push(...this.#G(D,J,N.#W))}else V.push(D);for(let w=0,A=N.#X.length;w<A;w++){let P=N.#X[w],M=N.#W===RM?{}:{...N.#W};if(P==="*"){let y=N.#J["*"];if(y)G.push(...this.#G(y,J,N.#W)),y.#W=M,V.push(y);continue}let[T,E,R]=P;if(!q&&!(R instanceof RegExp))continue;let k=N.#J[T],_=$.slice(Z).join("/");if(R instanceof RegExp){let y=R.exec(_);if(y){if(M[E]=y[0],G.push(...this.#G(k,J,N.#W,M)),Object.keys(k.#J).length){k.#W=M;let b=y[0].match(/\//)?.length??0;(K[b]||=[]).push(k)}continue}}if(R===!0||R.test(q))if(M[E]=q,F){if(G.push(...this.#G(k,J,M,N.#W)),k.#J["*"])G.push(...this.#G(k.#J["*"],J,M,N.#W))}else k.#W=M,V.push(k)}}W=V.concat(K.shift()??[])}if(G.length>1)G.sort((Z,H)=>{return Z.score-H.score});return[G.map(({handler:Z,params:H})=>[Z,H])]}};var p$1=h(()=>{uq();PN();RM=Object.create(null)});var IQ0=class{name="TrieRouter";#Q;constructor(){this.#Q=new d$1}add(Q,J,X){let G=Py(J);if(G){for(let Y=0,W=G.length;Y<W;Y++)this.#Q.insert(Q,G[Y],X);return}this.#Q.insert(Q,J,X)}match(Q,J){return this.#Q.search(Q,J)}};var c$1=h(()=>{PN();p$1()});var n$1=h(()=>{c$1()});var gQ;var i$1=h(()=>{_$1();u$1();l$1();n$1();gQ=class extends k$1{constructor(Q={}){super(Q);this.router=Q.router??new jQ0({routers:[new jy,new IQ0]})}}});var vZ=h(()=>{i$1()});var r$1=(Q)=>{let X={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Q},G=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return($)=>W===$?$:null;else if(typeof W==="function")return W;else return($)=>W.includes($)?$:null})(X.origin),Y=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(X.allowMethods);return async function($,K){function Z(q,F){$.res.headers.set(q,F)}let H=await G($.req.header("origin")||"",$);if(H)Z("Access-Control-Allow-Origin",H);if(X.credentials)Z("Access-Control-Allow-Credentials","true");if(X.exposeHeaders?.length)Z("Access-Control-Expose-Headers",X.exposeHeaders.join(","));if($.req.method==="OPTIONS"){if(X.origin!=="*")Z("Vary","Origin");if(X.maxAge!=null)Z("Access-Control-Max-Age",X.maxAge.toString());let q=await Y($.req.header("origin")||"",$);if(q.length)Z("Access-Control-Allow-Methods",q.join(","));let F=X.allowHeaders;if(!F?.length){let V=$.req.header("Access-Control-Request-Headers");if(V)F=V.split(/\s*,\s*/)}if(F?.length)Z("Access-Control-Allow-Headers",F.join(",")),$.res.headers.append("Vary","Access-Control-Request-Headers");return $.res.headers.delete("Content-Length"),$.res.headers.delete("Content-Type"),new Response(null,{headers:$.res.headers,status:204,statusText:"No Content"})}if(await K(),X.origin!=="*")$.header("Vary","Origin",{append:!0})}};var a$1=()=>{};function u_4(){let{process:Q,Deno:J}=globalThis;return!(typeof J?.noColor==="boolean"?J.noColor:Q!==void 0?"NO_COLOR"in Q?.env:!1)}async function o$1(){let{navigator:Q}=globalThis,J="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}})():!u_4())}var s$1=()=>{};async function t$1(Q,J,X,G,Y=0,W){let $=J==="<--"?`${J} ${X} ${G}`:`${J} ${X} ${G} ${await d_4(Y)} ${W}`;Q($)}var m_4=(Q)=>{let[J,X]=[",","."];return Q.map((Y)=>Y.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+J)).join(X)},l_4=(Q)=>{let J=Date.now()-Q;return m_4([J<1000?J+"ms":Math.round(J/1000)+"s"])},d_4=async(Q)=>{if(await o$1())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}`},e$1=(Q=console.log)=>{return async function(X,G){let{method:Y,url:W}=X.req,$=W.slice(W.indexOf("/",8));await t$1(Q,"<--",Y,$);let K=Date.now();await G(),await t$1(Q,"-->",Y,$,X.res.status,l_4(K))}};var QK1=h(()=>{s$1()});import{randomBytes as p_4}from"crypto";function JK1(){if(SM)return SM;let Q=process.env.MESH_JWT_SECRET??F9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Q)SM=new TextEncoder().encode(Q);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),SM=new Uint8Array(p_4(32));return SM}async function XK1(Q,J="5m"){let X=JK1();return await new cQ(Q).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(J).sign(X)}async function YK1(Q){try{let J=JK1(),{payload:X}=await O8(Q,J);return X}catch{return}}var SM=null;var CQ0=h(()=>{jJ();BU()});class RQ0{db;constructor(Q){this.db=Q}async get(Q){let J=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Q).executeTakeFirst();if(!J)return null;return{organizationId:J.organizationId,sidebar_items:J.sidebar_items?typeof J.sidebar_items==="string"?JSON.parse(J.sidebar_items):J.sidebar_items:null,createdAt:J.createdAt,updatedAt:J.updatedAt}}async upsert(Q,J){let X=new Date().toISOString(),G=J?.sidebar_items?JSON.stringify(J.sidebar_items):null;await this.db.insertInto("organization_settings").values({organizationId:Q,sidebar_items:G,createdAt:X,updatedAt:X}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:G?G:void 0,updatedAt:X})).execute();let Y=await this.get(Q);if(!Y)return{organizationId:Q,sidebar_items:J?.sidebar_items??null,createdAt:X,updatedAt:X};return Y}}var GK1,SQ0,TN;var vQ0=h(()=>{wH();GK1=class GK1 extends Error{constructor(Q){super(Q);this.name="UnauthorizedError"}};SQ0=class SQ0 extends Error{constructor(Q){super(Q);this.name="ForbiddenError"}};TN=class TN{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(Q,J,X,G,Y,W=vY.SELF){this.userId=J;this.toolName=X;this.boundAuth=G;this.role=Y;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 GK1("Authentication required. Please provide a valid OAuth token or API key.");let J=Q.length>0?Q:this.toolName?[this.toolName]:[];if(J.length===0)throw new SQ0("No resources specified for access check");for(let X of J)if(await this.checkResource(X)){this.grant();return}throw new SQ0(`Access denied to: ${J.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 J={};if(this.connectionId)J[this.connectionId]=[Q];return this.boundAuth.hasPermission(J)}granted(){return this._granted}}});class kQ0{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 EM.startActiveSpan("redactor.redact",(J)=>{try{if(Q===null||Q===void 0)return Q;if(typeof Q==="string")return J.setAttribute("data.type","string"),this.redactString(Q);if(Array.isArray(Q))return J.setAttribute("data.type","array"),J.setAttribute("data.length",Q.length),Q.map((X)=>this.redact(X));if(typeof Q==="object"){J.setAttribute("data.type","object");let X={};for(let[G,Y]of Object.entries(Q)){let W=this.redactString(G);X[W]=this.redact(Y)}return X}return J.setAttribute("data.type",typeof Q),Q}finally{J.end()}})}redactString(Q){return EM.startActiveSpan("redactor.redactString",(J)=>{try{J.setAttribute("text.length",Q.length);let X=Q,G=0;for(let Y of this.patterns){let W=Q.match(Y.regex);if(W)G+=W.length,J.setAttribute(`redaction.${Y.type}.count`,W.length);X=X.replace(Y.regex,`[REDACTED:${Y.type}]`)}return J.setAttribute("redaction.total_count",G),X}finally{J.end()}})}}var WK1=h(()=>{Oy()});class _Q0{db;redactor;constructor(Q){this.db=Q;this.redactor=new kQ0}async log(Q){await this.logBatch([Q])}async logBatch(Q){if(Q.length===0)return;let J=Q.map((X)=>({...X,input:this.redactor.redact(X.input),output:this.redactor.redact(X.output)}));await this.db.transaction().execute(async(X)=>{await X.insertInto("monitoring_logs").values(J.map((G)=>this.toDbRow(G))).execute()})}async query(Q){let J=this.db.selectFrom("monitoring_logs").selectAll(),X=this.db.selectFrom("monitoring_logs").select((K)=>K.fn.count("id").as("count"));if(Q.organizationId)J=J.where("organization_id","=",Q.organizationId),X=X.where("organization_id","=",Q.organizationId);if(Q.connectionId)J=J.where("connection_id","=",Q.connectionId),X=X.where("connection_id","=",Q.connectionId);if(Q.gatewayId)J=J.where("gateway_id","=",Q.gatewayId),X=X.where("gateway_id","=",Q.gatewayId);if(Q.toolName)J=J.where("tool_name","=",Q.toolName),X=X.where("tool_name","=",Q.toolName);if(Q.isError!==void 0)J=J.where("is_error","=",Q.isError?1:0),X=X.where("is_error","=",Q.isError?1:0);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString()),X=X.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString()),X=X.where("timestamp","<=",Q.endDate.toISOString());if(J=J.orderBy("timestamp","desc"),Q.limit)J=J.limit(Q.limit);if(Q.offset)J=J.offset(Q.offset);let[G,Y]=await Promise.all([J.execute(),X.executeTakeFirst()]),W=Number(Y?.count||0);return{logs:G.map((K)=>this.fromDbRow(K)),total:W}}async getStats(Q){let J=this.db.selectFrom("monitoring_logs").where("organization_id","=",Q.organizationId);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString());let X=await J.select([($)=>$.fn.count("id").as("total_count"),($)=>$.fn.sum($.ref("is_error")).as("error_count"),($)=>$.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),G=Number(X?.total_count||0),Y=Number(X?.error_count||0),W=Number(X?.avg_duration||0);return{totalCalls:G,errorRate:G>0?Y/G:0,avgDurationMs:W}}toDbRow(Q){return{id:Q.id||JG("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}}fromDbRow(Q){let J=typeof Q.input==="string"?JSON.parse(Q.input):Q.input,X=typeof Q.output==="string"?JSON.parse(Q.output):Q.output,G=typeof Q.timestamp==="string"?new Date(Q.timestamp):Q.timestamp;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,connectionTitle:Q.connection_title,toolName:Q.tool_name,input:J,output:X,isError:Q.is_error===1,errorMessage:Q.error_message,durationMs:Q.duration_ms,timestamp:G,userId:Q.user_id,requestId:Q.request_id,userAgent:Q.user_agent,gatewayId:Q.gateway_id}}}var $K1=h(()=>{WK1();UR()});function KK1(Q){let J=null;return()=>{if(J)return J;return J=Q().catch((X)=>{throw J=null,X}),J}}class ZK1{factory;promise=null;constructor(Q){this.factory=Q}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Q,J){return this.getOrCreatePromise().then(Q,J)}catch(Q){return this.getOrCreatePromise().catch(Q)}finally(Q){return this.getOrCreatePromise().finally(Q)}}function RG(Q){return new ZK1(Q)}async function HK1(Q,J){return(await J.storage.connections.findById(Q))?.connection_url??null}async function Cy(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=new URL(Q);G.pathname=`${X}/.well-known/oauth-protected-resource`;let Y=await fetch(G.toString(),{method:"GET",headers:{Accept:"application/json"}});if(Y.ok)return Y;if(Y.status!==404&&Y.status!==401)return Y;let W=new URL(Q);if(W.pathname=`/.well-known/oauth-protected-resource${X}`,Y=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y.status!==404&&Y.status!==401)return Y;let $=new URL(Q);return $.pathname="/.well-known/oauth-protected-resource",Y=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y}async function c_4(Q,J){let X=await HK1(Q,J);if(!X)return null;try{let G=await Cy(X);if(!G.ok)return null;return(await G.json()).authorization_servers?.[0]??null}catch{return null}}async function qK1(Q){let J=Q.get("meshContext");if(!J)J=await kZ.create(Q.req.raw),Q.set("meshContext",J);return J}async function FK1({error:Q,reqUrl:J,connectionId:X,connectionUrl:G,headers:Y}){if(!(Q.status===401||Q.message?.includes("401")||Q.message?.toLowerCase().includes("unauthorized")))return null;if(await fetch(G,{method:"POST",headers:{...Y,"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"}}})}).then((K)=>K.headers.has("WWW-Authenticate")).catch(()=>!1))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${J.origin}/mcp/${X}/.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"}})}async function yQ0(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=X!==""&&X!=="/",Y=[];if(G){let $=new URL(Q);$.pathname=`/.well-known/oauth-authorization-server${X}`,Y.push($);let K=new URL(Q);K.pathname=`/.well-known/openid-configuration${X}`,Y.push(K);let Z=new URL(Q);Z.pathname=`${X}/.well-known/openid-configuration`,Y.push(Z)}else{let $=new URL(Q);$.pathname="/.well-known/oauth-authorization-server",Y.push($);let K=new URL(Q);K.pathname="/.well-known/openid-configuration",Y.push(K)}let W=null;for(let $ of Y){if(W=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}var Iy,Ry=(Q)=>{if(!(Q.hostname==="localhost"||Q.hostname==="127.0.0.1"))Q.protocol="https:";return Q},VK1=async(Q)=>{let J=Q.req.param("connectionId"),X=await qK1(Q),G=await HK1(J,X);if(!G)return Q.json({error:"Connection not found"},404);try{let Y=await Cy(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),$=Ry(new URL(Q.req.url)),K=`${$.origin}/mcp/${J}`,Z=`${$.origin}/oauth-proxy/${J}`,H={...W,resource:K,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",W),Q.json({error:"Failed to proxy OAuth metadata",message:W.message},502)}},zK1;var Sy=h(()=>{vZ();vy();Iy=new gQ;Iy.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Q)=>VK1(Q));Iy.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Q)=>VK1(Q));Iy.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=await qK1(Q),G=await c_4(J,X);if(!G)return Q.json({error:"Connection not found or no auth server"},404);try{let Y=await yQ0(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),K=`${Ry(new URL(Q.req.url)).origin}/oauth-proxy/${J}`,Z={...W,authorization_endpoint:W.authorization_endpoint?`${K}/authorize`:void 0,token_endpoint:W.token_endpoint?`${K}/token`:void 0,registration_endpoint:W.registration_endpoint?`${K}/register`:void 0};return new Response(JSON.stringify(Z),{status:200,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;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)}});zK1=Iy});function n_4(Q){if(!Q.isError)return;let J=Q.content;if(!Array.isArray(J))return;for(let X of J)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function UK1(Q){if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q,X=J.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return J}return{value:Q}}async function i_4(Q,J){let X=Q.body;if(!X)return{text:"",truncated:!1};let G=X.getReader(),Y=new TextDecoder,W=!1,$=0,K=[];try{while(!0){let{value:Z,done:H}=await G.read();if(H)break;if(Z){if($+=Z.byteLength,$>J){W=!0;let q=J-($-Z.byteLength);if(q>0)K.push(Y.decode(Z.slice(0,q),{stream:!0}));break}K.push(Y.decode(Z,{stream:!0}))}}}finally{G.releaseLock()}return K.push(Y.decode()),{text:K.join(""),truncated:W}}async function vM(Q){let{ctx:J,enabled:X}=Q,G=Q.organizationId??J.organization?.id;if(!X||!G)return;await J.storage.monitoring.log({organizationId:G,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:J.auth.user?.id||J.auth.apiKey?.userId||null,requestId:J.metadata.requestId,userAgent:J.metadata.userAgent,gatewayId:J.gatewayId})}function NK1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=Date.now()-K;return await vM({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:UK1(Z),isError:Boolean(Z.isError),errorMessage:n_4(Z),durationMs:H}),Z}catch(Z){let H=Z,q=Date.now()-K;throw await vM({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}function BK1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=J.organization?.id;if(X&&H){let q=Z.clone();(async()=>{try{let{text:F,truncated:V}=await i_4(q,262144),z=Date.now()-K,U=q.headers.get("content-type")??"",N=F;if(U.includes("application/json"))try{N=F.length?JSON.parse(F):null}catch{N=F}let D=Z.status>=400,w=D&&N&&typeof N==="object"&&"error"in N?N.error:void 0,A=typeof w==="string"&&w?w:D&&typeof N==="string"&&N.trim()?N.slice(0,500):D?`HTTP ${Z.status} ${Z.statusText}`.trim():V?"Response body truncated to 262144 bytes":void 0;await vM({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:UK1(N),isError:D,errorMessage:A,durationMs:z})}catch(F){let V=Date.now()-K;await vM({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${F.message}`,durationMs:V})}})()}return Z}catch(Z){let H=Z,q=Date.now()-K;throw await vM({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}function r_4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new TN(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return{content:[{type:"text",text:`Authorization failed: ${Y.message}`}],isError:!0}}}}function a_4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new TN(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return new Response(JSON.stringify({error:`Authorization failed: ${Y.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function DK1(Q,J,{superUser:X}){let G=typeof Q==="string"?await J.storage.connections.findById(Q,J.organization?.id):Q;if(!G)throw Error("Connection not found");let Y=G?.id;if(J.organization&&G.organization_id!==J.organization.id)throw Error("Connection does not belong to the active organization");if(J.organization??={id:G.organization_id},G.status!=="active")throw Error(`Connection inactive: ${G.status}`);let W,$=J.auth.user?.connectionId,K=KK1(async()=>{let y=U00(G.configuration_state,G.configuration_scopes),b=J.auth.user?.id??J.auth.apiKey?.userId;if(!b){console.error("User ID required to issue configuration token");return}try{W=await XK1({sub:b,user:{id:b},metadata:{state:G.configuration_state??void 0,meshUrl:process.env.MESH_URL??J.baseUrl,connectionId:Y,organizationId:J.organization?.id},permissions:y})}catch(l){console.error("Failed to issue configuration token:",l)}}),Z=async()=>{await K();let y={...$?{"x-caller-id":$}:{}};if(G.connection_token)y.Authorization=`Bearer ${G.connection_token}`;if(W)y["x-mesh-token"]=W;if(G.connection_headers)Object.assign(y,G.connection_headers);return y},H=async()=>{let y=await Z(),b=new SW(new URL(G.connection_url),{requestInit:{headers:y}}),l=new vH({name:"mcp-mesh-proxy",version:"1.0.0"});return await l.connect(b),l},q=X?async(y,b)=>await b():r_4(J,Y),F=X?async(y,b)=>await b():a_4(J,Y),V={enabled:XM0().enabled,connectionId:Y,connectionTitle:G.title,ctx:J},z=NK1(V),U=BK1(V),N=zw(z,q),D=zw(U,F),w=async(y)=>{return N(y,async()=>{let b=await H(),l=Date.now();return await J.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":Y,"tool.name":y.params.name}},async(x)=>{try{let v=await b.callTool(y.params),g=Date.now()-l;return J.meter.createHistogram("connection.proxy.duration").record(g,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),J.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),x.end(),v}catch(v){let g=v,Q0=Date.now()-l;throw J.meter.createHistogram("connection.proxy.duration").record(Q0,{"connection.id":Y,"tool.name":y.params.name,status:"error"}),J.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":Y,"tool.name":y.params.name,error:g.message}),x.recordException(g),x.end(),v}})})};return{fetch:async(y)=>{let b=new URL(y.url),l;try{l=await H()}catch(g){let Q0=await FK1({error:g,reqUrl:b,connectionId:Y,connectionUrl:G.connection_url,headers:await Z()});if(Q0)return Q0;throw g}let x=new _H({name:"mcp-mesh",version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),v=new lH({enableJsonResponse:y.headers.get("Accept")?.includes("application/json")??!1});return await x.connect(v),x.server.setRequestHandler(lK,async(g)=>{return await l.listTools()}),x.server.setRequestHandler(dK,w),x.server.setRequestHandler(bK,async()=>{if(l.getServerCapabilities()?.resources)return await l.listResources();return{resources:[]}}),x.server.setRequestHandler(gK,async(g)=>{return await l.readResource(g.params)}),x.server.setRequestHandler(xK,async()=>{if(l.getServerCapabilities()?.resourceTemplates)return await l.listResourceTemplates();return{resourceTemplates:[]}}),x.server.setRequestHandler(uK,async()=>{if(l.getServerCapabilities()?.prompts)return await l.listPrompts();return{prompts:[]}}),x.server.setRequestHandler(mK,async(g)=>{return await l.getPrompt(g.params)}),await v.handleMessage(y)},client:{callTool:(y)=>{return w({method:"tools/call",params:y})},listTools:async()=>{if(G.tools&&G.tools.length>0)return{tools:G.tools.map((b)=>({name:b.name,description:b.description,inputSchema:b.inputSchema}))};return await(await H()).listTools()},listResources:async()=>{return await(await H()).listResources()},readResource:async(y)=>{return await(await H()).readResource(y)},listResourceTemplates:async()=>{return await(await H()).listResourceTemplates()},listPrompts:async()=>{return await(await H()).listPrompts()},getPrompt:async(y)=>{return await(await H()).getPrompt(y)}},callStreamableTool:async(y,b)=>{let l={method:"tools/call",params:{name:y,arguments:b}};return D(l,async()=>{let x=await Z(),v=new URL(G.connection_url);return v.pathname=v.pathname.replace(/\/$/,"")+`/call-tool/${l.params.name}`,await J.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":Y,"tool.name":l.params.name}},async(g)=>{let Q0=Date.now();try{let n=await fetch(v.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(l.params.arguments),headers:{...x,"Content-Type":"application/json"}}),G0=Date.now()-Q0;return J.meter.createHistogram("connection.proxy.streamable.duration").record(G0,{"connection.id":Y,"tool.name":l.params.name,status:n.ok?"success":"error"}),J.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":Y,"tool.name":l.params.name,status:n.ok?"success":"error"}),g.end(),n}catch(n){let G0=n,U0=Date.now()-Q0;throw J.meter.createHistogram("connection.proxy.streamable.duration").record(U0,{"connection.id":Y,"tool.name":l.params.name,status:"error"}),J.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":Y,"tool.name":l.params.name,error:G0.message}),g.recordException(G0),g.end(),n}})})}}}async function LK1(Q,J){return DK1(Q,J,{superUser:!1})}async function wK1(Q,J){return DK1(Q,J,{superUser:!0})}var OK1,PK1;var ky=h(()=>{N00();qa();tR();Jw();ES();aJ();vZ();CQ0();vQ0();oS();Sy();OK1=new gQ;OK1.all("/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=Q.get("meshContext");try{return await(await X.createMCPProxy(J)).fetch(Q.req.raw)}catch(G){let Y=G;if(Y.message.includes("not found"))return Q.json({error:Y.message},404);if(Y.message.includes("does not belong to the active organization"))return Q.json({error:"Connection not found"},404);if(Y.message.includes("inactive"))return Q.json({error:Y.message},503);return Q.json({error:"Internal server error",message:Y.message},500)}});PK1=OK1});function o_4(Q,J){for(let[X,G]of Object.entries(J)){let Y=Q[X];if(!Y||Y.length===0){let W=Q["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let $ of G)if(!W.includes($))return!1;continue}if(Y.includes("*"))continue;for(let W of G)if(!Y.includes(W))return!1}return!0}function s_4(Q){let{auth:J,headers:X,role:G,permissions:Y,userId:W}=Q,$=J.api.hasPermission;return{hasPermission:async(K)=>{if(G&&o00.includes(G))return!0;if(Y)return o_4(Y,K);if(!$)return console.error("[Auth] hasPermission API not available"),!1;try{if((await $({headers:X,body:{permission:K}}))?.success===!0)return!0;let H={};for(let F of Object.keys(K))H[F]=["*"];return(await $({headers:X,body:{permission:H}}))?.success===!0}catch(Z){return console.error("[Auth] Permission check failed:",Z),!1}},organization:{create:async(K)=>{return J.api.createOrganization({headers:X,body:K})},update:async(K)=>{return J.api.updateOrganization({headers:X,body:K})},delete:async(K)=>{await J.api.deleteOrganization({headers:X,body:{organizationId:K}})},get:async(K)=>{return J.api.getFullOrganization({headers:X,query:K?{organizationId:K}:void 0})},list:async(K)=>{return J.api.listOrganizations({headers:X,query:K?{userId:K}:void 0})},addMember:async(K)=>{return J.api.addMember({headers:X,body:K})},removeMember:async(K)=>{await J.api.removeMember({headers:X,body:K})},listMembers:async(K)=>{return J.api.listMembers({headers:X,query:K?{organizationId:K.organizationId,limit:K.limit,offset:K.offset}:void 0})},updateMemberRole:async(K)=>{return J.api.updateMemberRole({headers:X,body:K})}},apiKey:{create:async(K)=>{return J.api.createApiKey({body:{...K,userId:W}})},list:async()=>{return J.api.listApiKeys({headers:X})},update:async(K)=>{return J.api.updateApiKey({body:{...K,userId:W}})},delete:async(K)=>{await J.api.deleteApiKey({headers:X,body:{keyId:K}})}}}}async function t_4(Q,J,X){if(o00.includes(X))return;let G=await Q.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",J).where("role","=",X).executeTakeFirst();if(!G?.permission)return;try{return JSON.parse(G.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function e_4(Q,J,X){let G=Q.headers.get("Authorization");try{let Y=new Headers(Q.headers);Y.set("X-MCP-Session-Auth","true");let W=await J.api.getMcpSession({headers:Y});if(W){let $=W.userId,K=await X.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(),Z=K?.role,H=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,q;if(K&&Z)q=await t_4(X,K.organizationId,Z);return{user:{id:$,role:Z},role:Z,permissions:q,organization:H}}}catch(Y){console.error("[Auth] OAuth session check failed:",Y)}if(G?.startsWith("Bearer ")){let Y=G.replace("Bearer ","").trim();try{let W=await YK1(Y);if(W)return{user:{id:W.sub,connectionId:W.metadata?.connectionId},permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}catch{}try{let W=await J.api.verifyApiKey({body:{key:Y}});if(W?.valid&&W.key){let $=W.key.metadata?.organization,K=W.key.permissions;return{apiKeyId:W.key.id,user:{id:W.key.userId},permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let Y=await J.api.getSession({headers:Q.headers});if(Y){let W,$;if(Y.session.activeOrganizationId){let K=await J.api.getFullOrganization({headers:Q.headers}).catch(()=>null);if(K)W={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((H)=>H.userId===Y.user.id)?.role;else W={id:Y.session.activeOrganizationId,slug:"",name:""}}return{user:{id:Y.user.id,email:Y.user.email,role:$},role:$,organization:W}}}catch(Y){console.error("[Auth] Session check failed:",Y)}return{user:void 0}}function TK1(Q){let J=new yL(Q.encryption.key),X={connections:new hL(Q.db,J),organizationSettings:new RQ0(Q.db),monitoring:new _Q0(Q.db),gateways:new fL(Q.db)};return async(G)=>{let Y=G?.headers.get("x-caller-id")??void 0,W=G?await e_4(G,Q.auth,Q.db):{user:void 0},$=s_4({auth:Q.auth,headers:G?.headers??new Headers,role:W.role,permissions:W.permissions,userId:W.user?.id}),K={user:W.user};if(W.apiKeyId)K.apiKey={id:W.apiKeyId,name:"",userId:""};let Z=W.organization,H=G?new URL(G.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${H.protocol}//${H.host}`,F=new TN(Q.auth,K.user?.id,void 0,$,W.role,vY.SELF),V={auth:K,connectionId:Y,organization:Z,storage:X,vault:J,authInstance:Q.auth,boundAuth:$,access:F,db:Q.db,tracer:Q.observability.tracer,meter:Q.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:G?.headers.get("x-mesh-client")||G?.headers.get("User-Agent")||void 0,ipAddress:(G?.headers.get("CF-Connecting-IP")||G?.headers.get("X-Forwarded-For"))??void 0},eventBus:Q.eventBus,createMCPProxy:async(z)=>{return await LK1(z,V)}};return V}}var MK1,kZ;var vy=h(()=>{CQ0();ta();ea();Qo();vQ0();$K1();s00();wH();ky();kZ={set:(Q)=>{MK1=Q},create:async(Q)=>{return await MK1(Q)}}});function AK1(Q){return Q===kM.HEALTH||Q===kM.METRICS||Q.startsWith(_M.WELL_KNOWN)}function Jy4(Q){return Q.startsWith(_M.API)}function Xy4(Q){return Q==="/mcp"||Q.startsWith(_M.MCP)}function Yy4(Q){return Q.startsWith(_M.OAUTH_PROXY)}function Gy4(Q){return Qy4.test(Q)}function EK1(Q){return Jy4(Q)||Xy4(Q)||Yy4(Q)||AK1(Q)}function jK1(Q){return Q==="/"||Q.startsWith(_M.API_AUTH)||AK1(Q)||Gy4(Q)}var kM,_M,Qy4;var hQ0=h(()=>{kM={HEALTH:"/health",METRICS:"/metrics"},_M={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known"},Qy4=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/});class IK1{db;constructor(Q){this.db=Q}async publishEvent(Q){let J=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:J,updated_at:J}).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:J,updatedAt:J}}async subscribe(Q){let J=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("connection_id","=",Q.connectionId).where("event_type","=",Q.eventType);if(Q.publisher)J=J.where("publisher","=",Q.publisher);else J=J.where("publisher","is",null);if(Q.filter)J=J.where("filter","=",Q.filter);else J=J.where("filter","is",null);let X=await J.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let G=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:G,updated_at:G}).execute(),{id:Q.id,organizationId:Q.organizationId,connectionId:Q.connectionId,publisher:Q.publisher??null,eventType:Q.eventType,filter:Q.filter??null,enabled:!0,createdAt:G,updatedAt:G}}async unsubscribe(Q,J){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Q).where("organization_id","=",J).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Q,J){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q);if(J)X=X.where("connection_id","=",J);return(await X.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 getSubscription(Q,J){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.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((X)=>X.or([X("publisher","is",null),X("publisher","=",Q.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Q,J,X){if(J.length===0)return;let G=new Date().toISOString(),Y=X??null,W=J.map(($)=>({id:crypto.randomUUID(),event_id:Q,subscription_id:$,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:Y,created_at:G}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(Q){let J=new Date().toISOString(),X;try{X=(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(($)=>$.or([$("d.next_retry_at","is",null),$("d.next_retry_at","<=",J)])).orderBy("d.created_at","asc").limit(Q)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let Y=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","<=",J)])).orderBy("d.created_at","asc").limit(Q).execute();if(Y.length===0)return[];X=Y.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.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",X).where("d.status","=","processing").execute()).map((Y)=>({delivery:{id:Y.delivery_id,eventId:Y.event_id,subscriptionId:Y.subscription_id,status:Y.delivery_status,attempts:Y.delivery_attempts,lastError:Y.delivery_last_error,deliveredAt:Y.delivered_at,nextRetryAt:Y.delivery_next_retry_at,createdAt:Y.delivery_created_at},event:{id:Y.event_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.event_status,attempts:Y.event_attempts,lastError:Y.event_last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.event_created_at,updatedAt:Y.event_updated_at},subscription:{id:Y.subscription_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.subscription_created_at,updatedAt:Y.subscription_updated_at}}))}async markDeliveriesDelivered(Q){if(Q.length===0)return;let J=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:J}).where("id","in",Q).execute()}async markDeliveriesFailed(Q,J,X=20,G=1000,Y=3600000){if(Q.length===0)return;for(let W of Q){let $=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!$)continue;let K=$.attempts+1;if(K>=X)await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let Z=Math.min(G*Math.pow(2,K-1),Y),H=new Date(Date.now()+Z).toISOString();await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(Q){let J=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Q).execute();if(J.length===0)return;let X=J.every((W)=>W.status==="delivered"),G=J.some((W)=>W.status==="failed"),Y=J.some((W)=>W.status==="pending"||W.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Q).execute();else if(G&&!Y)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,J){let X=await this.db.selectFrom("events").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async cancelEvent(Q,J,X){let G=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Q).where("organization_id","=",J).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((G.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:(G.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Q,J){if(Q.length===0)return;let X=new Date(Date.now()+J).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Q).execute()}async ackDelivery(Q,J,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Q).where("organization_id","=",J).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(($)=>$.exists($.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",J))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(Q);return{success:W}}async syncSubscriptions(Q){let{organizationId:J,connectionId:X,subscriptions:G}=Q,Y=(w,A)=>{return`${w}::${A??""}`},W=await this.listSubscriptions(J,X),$=new Map;for(let w of W)$.set(Y(w.eventType,w.publisher),w);let K=new Map;for(let w of G)K.set(Y(w.eventType,w.publisher),w);let Z=new Date().toISOString(),H=[],q=[],F=[],V=0;for(let[w,A]of K){let P=$.get(w);if(!P)H.push({id:crypto.randomUUID(),organization_id:J,connection_id:X,event_type:A.eventType,publisher:A.publisher??null,filter:A.filter??null,enabled:1,created_at:Z,updated_at:Z});else{let M=P.filter??null,T=A.filter??null;if(M!==T)q.push({id:P.id,filter:T});else V++}}for(let[w,A]of $)if(!K.has(w))F.push(A.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(q.length>0)await Promise.all(q.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:Z}).where("id","=",w.id).execute()));if(F.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",F).execute();let z=H.length,U=q.length,N=F.length,D=await this.listSubscriptions(J,X);return{created:z,updated:U,deleted:N,unchanged:V,subscriptions:D}}}function CK1(Q){return new IK1(Q)}function $Q(Q,J,X,G,Y,W,$,K){return $Q.fromTZ($Q.tp(Q,J,X,G,Y,W,$),K)}function fQ0(Q,J=new Date){let X=J.toLocaleString("en-US",{timeZone:Q,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],G=J.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${G} GMT`)-Date.parse(`${G} ${X}`)}function Wy4(Q,J){let X=new Date(Date.parse(Q));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let G=Q.substring(9);return Q.includes("Z")||G.includes("-")||G.includes("+")?$Q.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):$Q.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),J)}function $y4(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 HY(Q.startAt,Q.timezone)),Q.stopAt&&(Q.stopAt=new HY(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 yM(Q){return Object.prototype.toString.call(Q)==="[object Function]"||typeof Q=="function"||Q instanceof Function}function Ky4(Q){return yM(Q)}function Zy4(Q){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Q):Q&&typeof Q.unref<"u"&&Q.unref()}var bQ0=32,hM,kK1,RK1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Q,J){this.pattern=Q,this.timezone=J,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 J=new HY(new Date,this.timezone).getDate(!0);Q[0]=Q[0].replace("?",J.getSeconds().toString()),Q[1]=Q[1].replace("?",J.getMinutes().toString()),Q[2]=Q[2].replace("?",J.getHours().toString()),this.starDOM||(Q[3]=Q[3].replace("?",J.getDate().toString())),Q[4]=Q[4].replace("?",(J.getMonth()+1).toString()),this.starDOW||(Q[5]=Q[5].replace("?",J.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,hM),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Q,J,X,G){let Y=this[Q],W=Q==="day"&&this.lastDayOfMonth;if(J===""&&!W)throw TypeError("CronPattern: configuration entry "+Q+" ("+J+") is empty, check for trailing spaces.");if(J==="*")return Y.fill(G);let $=J.split(",");if($.length>1)for(let K=0;K<$.length;K++)this.partToArray(Q,$[K],X,G);else J.indexOf("-")!==-1&&J.indexOf("/")!==-1?this.handleRangeWithStepping(J,Q,X,G):J.indexOf("-")!==-1?this.handleRange(J,Q,X,G):J.indexOf("/")!==-1?this.handleStepping(J,Q,X,G):J!==""&&this.handleNumber(J,Q,X,G)}throwAtIllegalCharacters(Q){for(let J=0;J<Q.length;J++)if((J===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Q[J]))throw TypeError("CronPattern: configuration entry "+J+" ("+Q[J]+") contains illegal characters.")}handleNumber(Q,J,X,G){let Y=this.extractNth(Q,J),W=parseInt(Y[0],10)+X;if(isNaN(W))throw TypeError("CronPattern: "+J+" is not a number: '"+Q+"'");this.setPart(J,W,Y[1]||G)}setPart(Q,J,X){if(!Object.prototype.hasOwnProperty.call(this,Q))throw TypeError("CronPattern: Invalid part specified: "+Q);if(Q==="dayOfWeek"){if(J===7&&(J=0),J<0||J>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+J);this.setNthWeekdayOfMonth(J,X);return}if(Q==="second"||Q==="minute"){if(J<0||J>=60)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="hour"){if(J<0||J>=24)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="day"){if(J<0||J>=31)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="month"&&(J<0||J>=12))throw RangeError("CronPattern: Invalid value for "+Q+": "+J);this[Q][J]=X}handleRangeWithStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Q+"'");let[,$,K,Z]=W,H=parseInt($,10)+X,q=parseInt(K,10)+X,F=parseInt(Z,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(q))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(F===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(F>this[J].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[J].length+")");if(H>q)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let V=H;V<=q;V+=F)this.setPart(J,V,Y[1]||G)}extractNth(Q,J){let X=Q,G;if(X.includes("#")){if(J!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");G=X.split("#")[1],X=X.split("#")[0]}return[X,G]}handleRange(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Q+"'");let $=parseInt(W[0],10)+X,K=parseInt(W[1],10)+X;if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if($>K)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let Z=$;Z<=K;Z++)this.setPart(J,Z,Y[1]||G)}handleStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Q+"'");W[0]===""&&(W[0]="*");let $=0;W[0]!=="*"&&($=parseInt(W[0],10)+X);let K=parseInt(W[1],10);if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(K===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(K>this[J].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[J].length+")");for(let Z=$;Z<this[J].length;Z+=K)this.setPart(J,Z,Y[1]||G)}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 J=Q.trim().toLowerCase();return J==="@yearly"||J==="@annually"?"0 0 1 1 *":J==="@monthly"?"0 0 1 * *":J==="@weekly"?"0 0 * * 0":J==="@daily"?"0 0 * * *":J==="@hourly"?"0 * * * *":Q}setNthWeekdayOfMonth(Q,J){if(typeof J!="number"&&J==="L")this.dayOfWeek[Q]=this.dayOfWeek[Q]|bQ0;else if(J===hM)this.dayOfWeek[Q]=hM;else if(J<6&&J>0)this.dayOfWeek[Q]=this.dayOfWeek[Q]|kK1[J-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${J}, Type: ${typeof J}`)}},SK1,G$,HY=class Q{tz;ms;second;minute;hour;day;month;year;constructor(J,X){if(this.tz=X,J&&J instanceof Date)if(!isNaN(J))this.fromDate(J);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(J===void 0)this.fromDate(new Date);else if(J&&typeof J=="string")this.fromString(J);else if(J instanceof Q)this.fromCronDate(J);else throw TypeError("CronDate: Invalid type ("+typeof J+") passed to CronDate constructor")}isNthWeekdayOfMonth(J,X,G,Y){let W=new Date(Date.UTC(J,X,G)).getUTCDay(),$=0;for(let K=1;K<=G;K++)new Date(Date.UTC(J,X,K)).getUTCDay()===W&&$++;if(Y&hM&&kK1[$-1]&Y)return!0;if(Y&bQ0){let K=new Date(Date.UTC(J,X+1,0)).getUTCDate();for(let Z=G+1;Z<=K;Z++)if(new Date(Date.UTC(J,X,Z)).getUTCDay()===W)return!1;return!0}return!1}fromDate(J){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes()+this.tz,this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),this.apply();else{let X=$Q.toTZ(J,this.tz);this.ms=J.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=J.getMilliseconds(),this.second=J.getSeconds(),this.minute=J.getMinutes(),this.hour=J.getHours(),this.day=J.getDate(),this.month=J.getMonth(),this.year=J.getFullYear()}fromCronDate(J){this.tz=J.tz,this.year=J.year,this.month=J.month,this.day=J.day,this.hour=J.hour,this.minute=J.minute,this.second=J.second,this.ms=J.ms}apply(){if(this.month>11||this.day>SK1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let J=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes(),this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),!0}else return!1}fromString(J){if(typeof this.tz=="number"){let X=$Q.fromTZISO(J);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(),this.apply()}else return this.fromDate($Q.fromTZISO(J,this.tz))}findNext(J,X,G,Y){let W=this[X],$;G.lastDayOfMonth&&(this.month!==1?$=SK1[this.month]:$=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let K=!G.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let Z=this[X]+Y;Z<G[X].length;Z++){let H=G[X][Z];if(X==="day"&&G.lastDayOfMonth&&Z-Y==$&&(H=1),X==="day"&&!G.starDOW){let q=G.dayOfWeek[(K+(Z-Y-1))%7];if(q&&q&hM)q=this.isNthWeekdayOfMonth(this.year,this.month,Z-Y,q)?1:0;else if(q)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${q}`);J.legacyMode&&!G.starDOM?H=H||q:H=H&&q}if(H)return this[X]=Z-Y,W!==this[X]?2:1}return 3}recurse(J,X,G){let Y=this.findNext(X,G$[G][0],J,G$[G][2]);if(Y>1){let W=G+1;for(;W<G$.length;)this[G$[W][0]]=-G$[W][2],W++;if(Y===3)return this[G$[G][1]]++,this[G$[G][0]]=-G$[G][2],this.apply(),this.recurse(J,X,0);if(this.apply())return this.recurse(J,X,G-1)}return G+=1,G>=G$.length?this:this.year>=3000?null:this.recurse(J,X,G)}increment(J,X,G){return this.second+=X.interval!==void 0&&X.interval>1&&G?X.interval:1,this.ms=0,this.apply(),this.recurse(J,X,0)}getDate(J){return J||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)):$Q.fromTZ($Q.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},vK1=30000,_y,yy=class{name;options;_states;fn;constructor(Q,J,X){let G,Y;if(yM(J))Y=J;else if(typeof J=="object")G=J;else if(J!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(yM(X))Y=X;else if(typeof X=="object")G=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=G?.name,this.options=$y4(G),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:G?G.maxRuns:void 0,paused:G?G.paused:!1,pattern:new RK1("* * * * *")},Q&&(Q instanceof Date||typeof Q=="string"&&Q.indexOf(":")>0)?this._states.once=new HY(Q,this.options.timezone||this.options.utcOffset):this._states.pattern=new RK1(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 Y!==void 0&&Ky4(Y)&&(this.fn=Y,this.schedule()),this}nextRun(Q){let J=this._next(Q);return J?J.getDate(!1):null}nextRuns(Q,J){this._states.maxRuns!==void 0&&Q>this._states.maxRuns&&(Q=this._states.maxRuns);let X=[],G=J||this._states.currentRun||void 0;for(;Q--&&(G=this.nextRun(G));)X.push(G);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Q=this.nextRun(this._states.currentRun),J=!this._states.paused,X=this.fn!==void 0,G=!this._states.kill;return J&&X&&G&&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 J=this._next(Q);return J?Q instanceof HY||Q instanceof Date?J.getTime()-Q.getTime():J.getTime()-new HY(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 J=this.msToNext(),X=this.nextRun(this._states.currentRun);return J==null||isNaN(J)||X===null?this:(J>vK1&&(J=vK1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),J),this._states.currentTimeout&&this.options.unref&&Zy4(this._states.currentTimeout),this)}async _trigger(Q){if(this._states.blocking=!0,this._states.currentRun=new HY(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(J){yM(this.options.catch)&&this.options.catch(J,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new HY(Q,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Q){let J=new Date,X=!this._states.paused&&J.getTime()>=Q.getTime(),G=this._states.blocking&&this.options.protect;X&&!G?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&G&&yM(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Q){let J=!!(Q||this._states.currentRun),X=!1;!Q&&this.options.startAt&&this.options.interval&&([Q,J]=this._calculatePreviousRun(Q,J),X=!Q),Q=new HY(Q,this.options.timezone||this.options.utcOffset),this.options.startAt&&Q&&Q.getTime()<this.options.startAt.getTime()&&(Q=this.options.startAt);let G=this._states.once||new HY(Q,this.options.timezone||this.options.utcOffset);return!X&&G!==this._states.once&&(G=G.increment(this._states.pattern,this.options,J)),this._states.once&&this._states.once.getTime()<=Q.getTime()||G===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&G.getTime()>=this.options.stopAt.getTime()?null:G}_calculatePreviousRun(Q,J){let X=new HY(void 0,this.options.timezone||this.options.utcOffset),G=Q;if(this.options.startAt.getTime()<=X.getTime()){G=this.options.startAt;let Y=G.getTime()+this.options.interval*1000;for(;Y<=X.getTime();)G=new HY(G,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),Y=G.getTime()+this.options.interval*1000;J=!0}return G===null&&(G=void 0),[G,J]}};var xQ0=h(()=>{$Q.fromTZISO=(Q,J,X)=>$Q.fromTZ(Wy4(Q,J),X);$Q.fromTZ=function(Q,J){let X=new Date(Date.UTC(Q.y,Q.m-1,Q.d,Q.h,Q.i,Q.s)),G=fQ0(Q.tz,X),Y=new Date(X.getTime()-G),W=fQ0(Q.tz,Y);if(W-G===0)return Y;{let $=new Date(X.getTime()-W),K=fQ0(Q.tz,$);if(K-W===0)return $;if(!J&&K-W>0)return $;if(J)throw Error("Invalid date passed to fromTZ()");return Y}};$Q.toTZ=function(Q,J){let X=Q.toLocaleString("en-US",{timeZone:J}).replace(/[\u202f]/," "),G=new Date(X);return{y:G.getFullYear(),m:G.getMonth()+1,d:G.getDate(),h:G.getHours(),i:G.getMinutes(),s:G.getSeconds(),tz:J}};$Q.tp=(Q,J,X,G,Y,W,$)=>({y:Q,m:J,d:X,h:G,i:Y,s:W,tz:$});$Q.minitz=$Q;hM=31|bQ0,kK1=[1,2,4,8,16],SK1=[31,28,31,30,31,30,31,31,30,31,30,31],G$=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];_y=[]});var hy;var gQ0=h(()=>{hy={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function _K1(){return async(Q,J)=>{try{let X=await kZ.create(),G=await wK1(Q,{...X,auth:{...X.auth,user:{id:"notify-worker"}}}),W=await Z00.forClient(G).ON_EVENTS({events:J});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(X){let G=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Q}:`,G),{success:!1,error:G}}}}var yK1=h(()=>{vy();qv();ky()});function hK1(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 Hy4(Q){let J=new Map;for(let G of Q){let Y=G.subscription.connectionId,W=J.get(Y);if(W){if(W.deliveryIds.push(G.delivery.id),!W.seenEventIds.has(G.event.id))W.seenEventIds.add(G.event.id),W.events.push(hK1(G.event))}else J.set(Y,{connectionId:G.subscription.connectionId,deliveryIds:[G.delivery.id],events:[hK1(G.event)],seenEventIds:new Set([G.event.id])})}let X=new Map;for(let[G,Y]of J)X.set(G,{connectionId:Y.connectionId,deliveryIds:Y.deliveryIds,events:Y.events});return X}class uQ0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Q,J){this.storage=Q;this.notifySubscriber=_K1(),this.config={...hy,...J}}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 J=Hy4(Q),X=new Set;for(let[G,Y]of J){try{let W=await this.notifySubscriber(Y.connectionId,Y.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(Y,W);else if(W.success)await this.storage.markDeliveriesDelivered(Y.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(Y.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(Y.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let $=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${G}:`,$),await this.storage.markDeliveriesFailed(Y.deliveryIds,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of Q)if(Y.deliveryIds.includes(W.delivery.id))X.add(W.event.id)}for(let G of X)try{await this.storage.updateEventStatus(G);let Y=Q.find((W)=>W.event.id===G)?.event;if(Y?.cron)await this.scheduleNextCronDelivery(Y)}catch(Y){console.error(`[EventBus] Failed to update event status ${G}:`,Y)}}async processPerEventResults(Q,J){let X=[],G=new Map,Y=[],W=new Map;for(let $=0;$<Q.events.length;$++){let K=Q.events?.[$];if(!K)continue;let Z=Q.deliveryIds?.[$];if(!Z)continue;W.set(K.id,Z)}for(let $ of Q.events){let K=W.get($.id);if(!K)continue;let Z=J.results?.[$.id];if(Z)if(Z.success)X.push(K);else if(Z.retryAfter&&Z.retryAfter>0){let H=G.get(Z.retryAfter)||[];H.push(K),G.set(Z.retryAfter,H)}else Y.push({deliveryId:K,error:Z.error||"Event processing failed"});else if(J.success)X.push(K);else if(J.retryAfter&&J.retryAfter>0){let H=G.get(J.retryAfter)||[];H.push(K),G.set(J.retryAfter,H)}else Y.push({deliveryId:K,error:J.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[$,K]of G)await this.storage.scheduleRetryWithoutAttemptIncrement(K,$);if(Y.length>0){let $=new Map;for(let{deliveryId:K,error:Z}of Y){let H=$.get(Z)||[];H.push(K),$.set(Z,H)}for(let[K,Z]of $)await this.storage.markDeliveriesFailed(Z,K,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Q){if(!Q.cron)return;try{let X=new yy(Q.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Q.id} has no more runs`);return}let G=X.toISOString(),Y=await this.storage.getMatchingSubscriptions(Q);if(Y.length===0){console.log(`[EventBus] No subscriptions for cron event ${Q.id}, skipping next delivery`);return}await this.storage.createDeliveries(Q.id,Y.map((W)=>W.id),G),console.log(`[EventBus] Scheduled next cron delivery for event ${Q.id} at ${G}`)}catch(J){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Q.id}:`,J)}}}var fK1=h(()=>{xQ0();gQ0();yK1()});class mQ0{storage;worker;notifyStrategy;running=!1;constructor(Q){this.storage=Q.storage,this.notifyStrategy=Q.notifyStrategy,this.worker=new uQ0(this.storage,Q.config)}async publish(Q,J,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let G;if(X.cron)try{let H=new yy(X.cron).nextRun();if(!H)throw Error("Cron expression does not produce a next run time");G=H.toISOString()}catch(Z){throw Error(`Invalid cron expression: ${Z instanceof Error?Z.message:String(Z)}`)}let Y=crypto.randomUUID(),W=new Date().toISOString(),$=await this.storage.publishEvent({id:Y,organizationId:Q,type:X.type,source:J,subject:X.subject,time:W,data:X.data,cron:X.cron}),K=await this.storage.getMatchingSubscriptions($);if(K.length>0){let Z=X.deliverAt??G;if(await this.storage.createDeliveries(Y,K.map((H)=>H.id),Z),this.notifyStrategy&&!Z)await this.notifyStrategy.notify(Y).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return $}async subscribe(Q,J){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Q,connectionId:J.connectionId,publisher:J.publisher,eventType:J.eventType,filter:J.filter})}async unsubscribe(Q,J){return this.storage.unsubscribe(J,Q)}async listSubscriptions(Q,J){return this.storage.listSubscriptions(Q,J)}async getSubscription(Q,J){return this.storage.getSubscription(J,Q)}async getEvent(Q,J){return this.storage.getEvent(J,Q)}async cancelEvent(Q,J,X){return this.storage.cancelEvent(J,Q,X)}async ackEvent(Q,J,X){return this.storage.ackDelivery(J,Q,X)}async syncSubscriptions(Q,J){return this.storage.syncSubscriptions({organizationId:Q,...J})}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}}var bK1=h(()=>{xQ0();fK1()});function xK1(...Q){return{async start(J){await Promise.all(Q.map((X)=>X.start(J)))},async stop(){await Promise.all(Q.map((J)=>J.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(J){await Promise.all(Q.map((X)=>X.notify(J).catch((G)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",G)})))}}}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 qy4}from"kysely";class lQ0{db;pool;listenClient=null;onNotify=null;constructor(Q,J){this.db=Q;this.pool=J}async start(Q){if(this.listenClient)return;this.onNotify=Q;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(J)=>{if(J.channel===AN&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(J)=>{console.error("[PostgresNotify] Connection error:",J),this.cleanup()}),await this.listenClient.query(`LISTEN ${AN}`),console.log("[PostgresNotify] Started LISTEN on",AN)}catch(J){console.error("[PostgresNotify] Failed to start LISTEN:",J),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${AN}`),console.log("[PostgresNotify] Stopped LISTEN on",AN)}catch{}this.cleanup()}}async notify(Q){try{await qy4`SELECT pg_notify(${AN}, ${Q})`.execute(this.db)}catch(J){console.warn("[PostgresNotify] Failed to send NOTIFY:",J)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var AN="mesh_events";var gK1=()=>{};function uK1(Q,J){let X=CK1(Q.db),G=J?.pollIntervalMs??hy.pollIntervalMs,Y=Q.type==="postgres"?xK1(new fy(G),new lQ0(Q.db,Q.pool)):new fy(G);return new mQ0({storage:X,config:J,notifyStrategy:Y})}var mK1=h(()=>{bK1();gQ0();gK1()});var lK1;var dK1=h(()=>{lK1={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 pK1,cK1;var nK1=h(()=>{vZ();BU();dK1();pK1=new gQ;pK1.get("/config",async(Q)=>{try{let J=Object.keys(F9.socialProviders??{}),X=J.length>0,G=J.map((W)=>({name:W,icon:lK1[W].icon})),Y={emailAndPassword:{enabled:F9.emailAndPassword?.enabled??!1},magicLink:{enabled:F9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:X,providers:G},sso:F9.ssoConfig?{enabled:!0,providerId:F9.ssoConfig.providerId}:{enabled:!1}};return Q.json({success:!0,config:Y})}catch(J){let X=J instanceof Error?J.message:"Failed to load auth config";return Q.json({success:!1,error:X},500)}});cK1=pK1});class fM{proxies=new Map;constructor(){}static async create(Q,J){let X=new fM,G=await Promise.allSettled(Q.map(async({connection:Y,selectedTools:W})=>{try{let $=await J.createMCPProxy(Y);return{connection:Y,proxy:$,selectedTools:W}}catch($){return console.error(`[gateway] Failed to create proxy for connection ${Y.id}:`,$),null}}));for(let Y of G)if(Y.status==="fulfilled"&&Y.value)X.proxies.set(Y.value.connection.id,Y.value);return X}get(Q){return this.proxies.get(Q)}entries(){return this.proxies.entries()}forEach(Q){this.proxies.forEach((J,X)=>Q(J,X))}async mapAsync(Q){let J=[];for(let[X,G]of this.proxies.entries())J.push(Q(G,X));return await Promise.all(J)}async mapSettled(Q){return Promise.allSettled(Array.from(this.proxies.entries()).map(([J,X])=>Q(X,J)))}get size(){return this.proxies.size}}function Fy4(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((J)=>J.length>=2)}function Vy4(Q,J){let X=0,G=J.name.toLowerCase(),Y=(J.description??"").toLowerCase(),W=J.connectionTitle.toLowerCase();for(let $ of Q){if(G===$)X+=10;else if(G.includes($))X+=3;if(Y.includes($))X+=2;if(W.includes($))X+=1}return X}function zy4(Q,J,X){let G=Fy4(Q);if(G.length===0)return J.slice(0,X);return J.map((Y)=>({tool:Y,score:Vy4(G,Y)})).filter((Y)=>Y.score>0).sort((Y,W)=>W.score-Y.score).slice(0,X).map((Y)=>Y.tool)}function Uy4(Q){let J=Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:"",X=Q.tools.map((G)=>G.name);return[{name:_Z.SEARCH,description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${J} Total tools: ${Q.tools.length}.`,inputSchema:{type:"object",properties:{query:{type:"string",description:"Natural language search query (e.g., 'send email', 'create order')"},limit:{type:"number",description:"Maximum results to return (default: 10)",default:10}},required:["query"]}},{name:_Z.DESCRIBE,description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:{type:"object",properties:{tools:{type:"array",items:{type:"string",enum:X},description:"Array of tool names to get detailed schemas for"}},required:["tools"]}},{name:_Z.CALL,description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:{type:"object",properties:{name:{type:"string",enum:X,description:"The name of the tool to execute"},arguments:{type:"object",description:"Arguments to pass to the tool",additionalProperties:!0}},required:["name"]}}]}function rK1(Q){switch(Q){case"smart_tool_selection":return Ny4;case"code_execution":return iK1;case"passthrough":default:return iK1}}var iK1=(Q)=>({tools:Q.tools,callTool:(J,X)=>Q.callTool(J,X)}),_Z,Ny4=(Q)=>{let J=new Map(Q.tools.map((G)=>[G.name,G])),X=async(G,Y)=>{switch(G){case _Z.SEARCH:{let W=Y.query??"",$=Y.limit??10,K=zy4(W,Q.tools,$);return{content:[{type:"text",text:JSON.stringify({query:W,results:K.map((Z)=>({name:Z.name,description:Z.description,connection:Z.connectionTitle})),totalAvailable:Q.tools.length},null,2)}]}}case _Z.DESCRIBE:{let W=Y.tools??[];if(W.length===0)return{content:[{type:"text",text:JSON.stringify({error:"No tool names provided"})}],isError:!0};let $=W.map((K)=>J.get(K)).filter((K)=>K!==void 0);return{content:[{type:"text",text:JSON.stringify({tools:$.map((K)=>({name:K.name,description:K.description,connection:K.connectionTitle,inputSchema:K.inputSchema,outputSchema:K.outputSchema})),notFound:W.filter((K)=>!J.has(K))},null,2)}]}}case _Z.CALL:{let W=Y.name,$=Y.arguments??{};if(!W)return{content:[{type:"text",text:JSON.stringify({error:"Tool name is required"})}],isError:!0};if(!J.has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use ${_Z.SEARCH} to find available tools.`}],isError:!0};return Q.callTool(W,$)}default:return{content:[{type:"text",text:`Unknown meta-tool: ${G}. Available: ${Object.values(_Z).join(", ")}`}],isError:!0}}};return{tools:Uy4(Q),callTool:X}};var aK1=h(()=>{_Z={SEARCH:"GATEWAY_SEARCH_TOOLS",DESCRIBE:"GATEWAY_DESCRIBE_TOOLS",CALL:"GATEWAY_CALL_TOOL"}});class by{proxies;options;cache;constructor(Q,J){this.proxies=Q;this.options=J;this.cache=RG(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(Z,H)=>{try{let F=(await Z.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>!V.has(z.name))}}else if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>V.has(z.name))}return{connectionId:H,connectionTitle:Z.connection.title,tools:F}}catch(q){return console.error(`[gateway] Failed to list tools for connection ${H}:`,q),null}}),J=new Set,X=[],G=new Map,Y=new Set;for(let Z of Q){if(Z.status!=="fulfilled"||!Z.value)continue;let{connectionId:H,connectionTitle:q,tools:F}=Z.value;Y.add(q);for(let V of F){if(J.has(V.name))continue;J.add(V.name),X.push({...V,connectionId:H,connectionTitle:q}),G.set(V.name,{connectionId:H,originalName:V.name})}}let W=async(Z,H)=>{let q=G.get(Z);if(!q)return{content:[{type:"text",text:`Tool not found: ${Z}`}],isError:!0};let F=this.proxies.get(q.connectionId);if(!F)return{content:[{type:"text",text:`Connection not found for tool: ${Z}`}],isError:!0};return await F.proxy.client.callTool({name:q.originalName,arguments:H})},K=rK1(this.options.strategy)({tools:X,callTool:W,categories:Array.from(Y).sort()});return{tools:X,mappings:G,strategyResult:K}}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,J){let X=await this.cache,G=X.mappings.get(Q);if(G){let W=this.proxies.get(G.connectionId);if(W)return W.proxy.callStreamableTool(G.originalName,J)}let Y=await X.strategyResult.callTool(Q,J);return new Response(JSON.stringify(Y),{headers:{"Content-Type":"application/json"}})}}var oK1=h(()=>{aK1()});class xy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=RG(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listResources();return{connectionId:W,resources:$.resources}}catch($){return console.error(`[gateway] Failed to list resources for connection ${W}:`,$),{connectionId:W,resources:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,resources:$}=Y.value;for(let K of $){if(J.has(K.uri))continue;J.add(K.uri),X.push(K),G.set(K.uri,W)}}return{resources:X,mappings:G}}async list(){return{resources:(await this.cache).resources}}async read(Q){let X=(await this.cache).mappings.get(Q.uri);if(!X)throw Error(`Resource not found: ${Q.uri}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for resource: ${Q.uri}`);return await G.proxy.client.readResource(Q)}}var sK1=()=>{};class gy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=RG(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(X,G)=>{try{let Y=await X.proxy.client.listResourceTemplates();return{connectionId:G,templates:Y.resourceTemplates}}catch(Y){return console.error(`[gateway] Failed to list resource templates for connection ${G}:`,Y),{connectionId:G,templates:[]}}}),J=[];for(let X of Q){if(X.status!=="fulfilled")continue;let{templates:G}=X.value;for(let Y of G)J.push(Y)}return{templates:J}}async list(){return{resourceTemplates:(await this.cache).templates}}}var tK1=()=>{};class uy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=RG(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listPrompts();return{connectionId:W,prompts:$.prompts}}catch($){return console.error(`[gateway] Failed to list prompts for connection ${W}:`,$),{connectionId:W,prompts:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,prompts:$}=Y.value;for(let K of $){if(J.has(K.name))continue;J.add(K.name),X.push(K),G.set(K.name,W)}}return{prompts:X,mappings:G}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let X=(await this.cache).mappings.get(Q.name);if(!X)throw Error(`Prompt not found: ${Q.name}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for prompt: ${Q.name}`);return await G.proxy.client.getPrompt(Q)}}var eK1=()=>{};var QZ1=h(()=>{oK1();sK1();tK1();eK1()});async function By4(Q,J){let X=await fM.create(Q.connections,J),G=new by(X,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),Y=new xy(X),W=new gy(X),$=new uy(X);return{client:{listTools:G.list.bind(G),callTool:G.call.bind(G),listResources:Y.list.bind(Y),readResource:Y.read.bind(Y),listResourceTemplates:W.list.bind(W),listPrompts:$.list.bind($),getPrompt:$.get.bind($)},callStreamableTool:G.callStreamable.bind(G)}}async function Oy4(Q,J){let X;if(Q.toolSelectionMode==="exclusion"){let W=(await J.storage.connections.list(Q.organizationId)).filter((K)=>K.status==="active"),$=new Map;for(let K of Q.connections)$.set(K.connectionId,K.selectedTools);X=[];for(let K of W){let Z=$.get(K.id);if(Z===void 0)X.push({connection:K,selectedTools:null});else if(Z===null||Z.length===0);else X.push({connection:K,selectedTools:Z})}}else{let Y=Q.connections.map(($)=>$.connectionId),W=[];for(let $ of Y){let K=await J.storage.connections.findById($);if(K&&K.status==="active")W.push(K)}X=W.map(($)=>{let K=Q.connections.find((Z)=>Z.connectionId===$.id);return{connection:$,selectedTools:K?.selectedTools??null}})}let G={connections:X,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Q.toolSelectionStrategy};return By4(G,J)}var JZ1,XZ1;var YZ1=h(()=>{ES();aJ();vZ();QZ1();oS();JZ1=new gQ;JZ1.all("/gateway/:gatewayId?",async(Q)=>{let J=Q.req.param("gatewayId"),X=Q.get("meshContext");try{let G=null;if(J)G=await X.storage.gateways.findById(J);else{let Z=Q.req.header("x-org-id"),H=Q.req.header("x-org-slug");if(Z)G=await X.storage.gateways.getDefaultByOrgId(Z);else if(H)G=await X.storage.gateways.getDefaultByOrgSlug(H);else return Q.json({error:"Gateway ID required, or provide x-org-id or x-org-slug header for default gateway"},400)}if(!G){if(J)return Q.json({error:`Gateway not found: ${J}`},404);return Q.json({error:"No default gateway configured for this organization"},404)}if(X.gatewayId=G.id,G.status!=="active")return Q.json({error:`Gateway is inactive: ${G.id}`},503);let Y=await X.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",G.organizationId).executeTakeFirst();if(Y)X.organization={id:Y.id,slug:Y.slug,name:Y.name};let W=await Oy4(G,X),$=new _H({name:`mcp-gateway-${G.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),K=new lH({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await $.connect(K),$.server.setRequestHandler(lK,async(Z)=>{return W.client.listTools()}),$.server.setRequestHandler(dK,async(Z)=>{return await W.client.callTool(Z.params)}),$.server.setRequestHandler(bK,async()=>{return W.client.listResources()}),$.server.setRequestHandler(gK,async(Z)=>{return W.client.readResource(Z.params)}),$.server.setRequestHandler(xK,async()=>{return W.client.listResourceTemplates()}),$.server.setRequestHandler(uK,async()=>{return W.client.listPrompts()}),$.server.setRequestHandler(mK,async(Z)=>{return W.client.getPrompt(Z.params)}),await K.handleMessage(Q.req.raw).then(async(Z)=>{return Z})}catch(G){let Y=G;return console.error("[gateway] Error handling gateway request:",Y),Q.json({error:"Internal server error",message:Y.message},500)}});XZ1=JZ1});var GZ1,WZ1;var $Z1=h(()=>{vZ();a00();GZ1=new gQ;GZ1.all("/",async(Q)=>{return r00(Q.get("meshContext")).fetch(Q.req.raw)});WZ1=GZ1});function SG(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 hZ1="vercel.ai.error",Dy4,KZ1,ZZ1,L1,fZ1="AI_APICallError",bZ1,Ly4,HZ1,qZ1,O9,xZ1="AI_EmptyResponseBodyError",gZ1,wy4,FZ1,VZ1,uZ1,mZ1="AI_InvalidArgumentError",lZ1,Py4,zZ1,UZ1,dZ1,pZ1="AI_InvalidPromptError",cZ1,My4,NZ1,BZ1,lq,nZ1="AI_InvalidResponseDataError",iZ1,Ty4,OZ1,DZ1,up6,rZ1="AI_JSONParseError",aZ1,Ay4,LZ1,wZ1,bM,oZ1="AI_LoadAPIKeyError",sZ1,Ey4,PZ1,MZ1,mp6,tZ1="AI_LoadSettingError",eZ1,jy4,TZ1,AZ1,lp6,Q31="AI_NoContentGeneratedError",J31,Iy4,EZ1,jZ1,dp6,X31="AI_NoSuchModelError",Y31,Cy4,IZ1,CZ1,pp6,G31="AI_TooManyEmbeddingValuesForCallError",W31,Ry4,RZ1,SZ1,cp6,$31="AI_TypeValidationError",K31,Sy4,vZ1,kZ1,$7,Z31="AI_UnsupportedFunctionalityError",H31,vy4,_Z1,yZ1,np6;var D6=h(()=>{Dy4=Symbol.for(hZ1),L1=class Q extends(ZZ1=Error,KZ1=Dy4,ZZ1){constructor({name:J,message:X,cause:G}){super(X);this[KZ1]=!0,this.name=J,this.cause=G}static isInstance(J){return Q.hasMarker(J,hZ1)}static hasMarker(J,X){let G=Symbol.for(X);return J!=null&&typeof J==="object"&&G in J&&typeof J[G]==="boolean"&&J[G]===!0}},bZ1=`vercel.ai.error.${fZ1}`,Ly4=Symbol.for(bZ1),O9=class extends(qZ1=L1,HZ1=Ly4,qZ1){constructor({message:Q,url:J,requestBodyValues:X,statusCode:G,responseHeaders:Y,responseBody:W,cause:$,isRetryable:K=G!=null&&(G===408||G===409||G===429||G>=500),data:Z}){super({name:fZ1,message:Q,cause:$});this[HZ1]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=G,this.responseHeaders=Y,this.responseBody=W,this.isRetryable=K,this.data=Z}static isInstance(Q){return L1.hasMarker(Q,bZ1)}},gZ1=`vercel.ai.error.${xZ1}`,wy4=Symbol.for(gZ1),uZ1=class extends(VZ1=L1,FZ1=wy4,VZ1){constructor({message:Q="Empty response body"}={}){super({name:xZ1,message:Q});this[FZ1]=!0}static isInstance(Q){return L1.hasMarker(Q,gZ1)}};lZ1=`vercel.ai.error.${mZ1}`,Py4=Symbol.for(lZ1),dZ1=class extends(UZ1=L1,zZ1=Py4,UZ1){constructor({message:Q,cause:J,argument:X}){super({name:mZ1,message:Q,cause:J});this[zZ1]=!0,this.argument=X}static isInstance(Q){return L1.hasMarker(Q,lZ1)}},cZ1=`vercel.ai.error.${pZ1}`,My4=Symbol.for(cZ1),lq=class extends(BZ1=L1,NZ1=My4,BZ1){constructor({prompt:Q,message:J,cause:X}){super({name:pZ1,message:`Invalid prompt: ${J}`,cause:X});this[NZ1]=!0,this.prompt=Q}static isInstance(Q){return L1.hasMarker(Q,cZ1)}},iZ1=`vercel.ai.error.${nZ1}`,Ty4=Symbol.for(iZ1),up6=class extends(DZ1=L1,OZ1=Ty4,DZ1){constructor({data:Q,message:J=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:nZ1,message:J});this[OZ1]=!0,this.data=Q}static isInstance(Q){return L1.hasMarker(Q,iZ1)}},aZ1=`vercel.ai.error.${rZ1}`,Ay4=Symbol.for(aZ1),bM=class extends(wZ1=L1,LZ1=Ay4,wZ1){constructor({text:Q,cause:J}){super({name:rZ1,message:`JSON parsing failed: Text: ${Q}.
|
|
1080
|
+
`}}X$1.PrometheusSerializer=J$1});var $$1=C((G$1)=>{Object.defineProperty(G$1,"__esModule",{value:!0});G$1.PrometheusExporter=void 0;var AM=F1(),B_4=W4(),qQ0=dW(),O_4=A0("http"),D_4=HQ0(),L_4=A0("url");class Y$ extends qQ0.MetricReader{static DEFAULT_OPTIONS={host:void 0,port:9464,endpoint:"/metrics",prefix:"",appendTimestamp:!1,withResourceConstantLabels:void 0,withoutTargetInfo:!1};_host;_port;_baseUrl;_endpoint;_server;_prefix;_appendTimestamp;_serializer;_startServerPromise;constructor(Q={},J=()=>{}){super({aggregationSelector:(Y)=>{return{type:qQ0.AggregationType.DEFAULT}},aggregationTemporalitySelector:(Y)=>qQ0.AggregationTemporality.CUMULATIVE,metricProducers:Q.metricProducers});this._host=Q.host||process.env.OTEL_EXPORTER_PROMETHEUS_HOST||Y$.DEFAULT_OPTIONS.host,this._port=Q.port||Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT)||Y$.DEFAULT_OPTIONS.port,this._prefix=Q.prefix||Y$.DEFAULT_OPTIONS.prefix,this._appendTimestamp=typeof Q.appendTimestamp==="boolean"?Q.appendTimestamp:Y$.DEFAULT_OPTIONS.appendTimestamp;let X=Q.withResourceConstantLabels||Y$.DEFAULT_OPTIONS.withResourceConstantLabels,G=Q.withoutTargetInfo||Y$.DEFAULT_OPTIONS.withoutTargetInfo;if(this._server=(0,O_4.createServer)(this._requestHandler).unref(),this._serializer=new D_4.PrometheusSerializer(this._prefix,this._appendTimestamp,X,G),this._baseUrl=`http://${this._host}:${this._port}/`,this._endpoint=(Q.endpoint||Y$.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/,"/$1"),Q.preventServerStart!==!0)this.startServer().then(J,(Y)=>{AM.diag.error(Y),J(Y)});else if(J)queueMicrotask(J)}async onForceFlush(){}onShutdown(){return this.stopServer()}stopServer(){if(!this._server)return AM.diag.debug("Prometheus stopServer() was called but server was never started."),Promise.resolve();else return new Promise((Q)=>{this._server.close((J)=>{if(!J)AM.diag.debug("Prometheus exporter was stopped");else if(J.code!=="ERR_SERVER_NOT_RUNNING")(0,B_4.globalErrorHandler)(J);Q()})})}startServer(){return this._startServerPromise??=new Promise((Q,J)=>{this._server.once("error",J),this._server.listen({port:this._port,host:this._host},()=>{AM.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`),Q()})}),this._startServerPromise}getMetricsRequestHandler(Q,J){this._exportMetrics(J)}_requestHandler=(Q,J)=>{if(Q.url!=null&&new L_4.URL(Q.url,this._baseUrl).pathname===this._endpoint)this._exportMetrics(J);else this._notFound(J)};_exportMetrics=(Q)=>{Q.statusCode=200,Q.setHeader("content-type","text/plain"),this.collect().then((J)=>{let{resourceMetrics:X,errors:G}=J;if(G.length)AM.diag.error("PrometheusExporter: metrics collection errors",...G);Q.end(this._serializer.serialize(X))},(J)=>{Q.end(`# failed to export metrics: ${J}`)})};_notFound=(Q)=>{Q.statusCode=404,Q.end()}}G$1.PrometheusExporter=Y$});var FQ0=C((Ny)=>{Object.defineProperty(Ny,"__esModule",{value:!0});Ny.PrometheusSerializer=Ny.PrometheusExporter=void 0;var w_4=$$1();Object.defineProperty(Ny,"PrometheusExporter",{enumerable:!0,get:function(){return w_4.PrometheusExporter}});var P_4=HQ0();Object.defineProperty(Ny,"PrometheusSerializer",{enumerable:!0,get:function(){return P_4.PrometheusSerializer}})});var By,K$1,Z$1,H$1,VQ0,T_4,EM,q$1;var Oy=h(()=>{By=l4(F1(),1),K$1=l4(tW1(),1),Z$1=l4(FQ0(),1),H$1=l4(g50(),1),VQ0=new Z$1.PrometheusExporter({preventServerStart:!0}),T_4=new K$1.NodeSDK({serviceName:"mcp-mesh",traceExporter:new H$1.OTLPTraceExporter({url:process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"http://localhost:4318/v1/traces"}),metricReader:VQ0});T_4.start();EM=By.trace.getTracer("mcp-mesh","1.0.0"),q$1=By.metrics.getMeter("mcp-mesh","1.0.0")});var zQ0=(Q,J,X)=>{return(G,Y)=>{let W=-1;return $(0);async function $(K){if(K<=W)throw Error("next() called multiple times");W=K;let Z,H=!1,q;if(Q[K])q=Q[K][0][0],G.req.routeIndex=K;else q=K===Q.length&&Y||void 0;if(q)try{Z=await q(G,()=>$(K+1))}catch(F){if(F instanceof Error&&J)G.error=F,Z=await J(F,G),H=!0;else throw F}else if(G.finalized===!1&&X)Z=await X(G);if(Z&&(G.finalized===!1||H))G.res=Z;return G}}};var F$1=()=>{};var UQ0;var NQ0=h(()=>{UQ0=class extends Error{res;status;constructor(Q=500,J){super(J?.message,{cause:J?.cause});this.res=J?.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 V$1;var z$1=h(()=>{V$1=Symbol()});async function A_4(Q,J){let X=await Q.formData();if(X)return E_4(X,J);return{}}function E_4(Q,J){let X=Object.create(null);if(Q.forEach((G,Y)=>{if(!(J.all||Y.endsWith("[]")))X[Y]=G;else j_4(X,Y,G)}),J.dot)Object.entries(X).forEach(([G,Y])=>{if(G.includes("."))I_4(X,G,Y),delete X[G]});return X}var U$1=async(Q,J=Object.create(null))=>{let{all:X=!1,dot:G=!1}=J,W=(Q instanceof Dy?Q.raw.headers:Q.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return A_4(Q,{all:X,dot:G});return{}},j_4=(Q,J,X)=>{if(Q[J]!==void 0)if(Array.isArray(Q[J]))Q[J].push(X);else Q[J]=[Q[J],X];else if(!J.endsWith("[]"))Q[J]=X;else Q[J]=[X]},I_4=(Q,J,X)=>{let G=Q,Y=J.split(".");Y.forEach((W,$)=>{if($===Y.length-1)G[W]=X;else{if(!G[W]||typeof G[W]!=="object"||Array.isArray(G[W])||G[W]instanceof File)G[W]=Object.create(null);G=G[W]}})};var N$1=h(()=>{BQ0()});var DQ0=(Q)=>{let J=Q.split("/");if(J[0]==="")J.shift();return J},B$1=(Q)=>{let{groups:J,path:X}=C_4(Q),G=DQ0(X);return R_4(G,J)},C_4=(Q)=>{let J=[];return Q=Q.replace(/\{[^}]+\}/g,(X,G)=>{let Y=`@${G}`;return J.push([Y,X]),Y}),{groups:J,path:Q}},R_4=(Q,J)=>{for(let X=J.length-1;X>=0;X--){let[G]=J[X];for(let Y=Q.length-1;Y>=0;Y--)if(Q[Y].includes(G)){Q[Y]=Q[Y].replace(G,J[X][1]);break}}return Q},Ly,O$1=(Q,J)=>{if(Q==="*")return"*";let X=Q.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(X){let G=`${Q}#${J}`;if(!Ly[G])if(X[2])Ly[G]=J&&J[0]!==":"&&J[0]!=="*"?[G,X[1],new RegExp(`^${X[2]}(?=/${J})`)]:[Q,X[1],new RegExp(`^${X[2]}$`)];else Ly[G]=[Q,X[1],!0];return Ly[G]}return null},wy=(Q,J)=>{try{return J(Q)}catch{return Q.replace(/(?:%[0-9A-Fa-f]{2})+/g,(X)=>{try{return J(X)}catch{return X}})}},S_4=(Q)=>wy(Q,decodeURI),LQ0=(Q)=>{let J=Q.url,X=J.indexOf("/",J.indexOf(":")+4),G=X;for(;G<J.length;G++){let Y=J.charCodeAt(G);if(Y===37){let W=J.indexOf("?",G),$=J.slice(X,W===-1?void 0:W);return S_4($.includes("%25")?$.replace(/%25/g,"%2525"):$)}else if(Y===63)break}return J.slice(X,G)},D$1=(Q)=>{let J=LQ0(Q);return J.length>1&&J.at(-1)==="/"?J.slice(0,-1):J},gq=(Q,J,...X)=>{if(X.length)J=gq(J,...X);return`${Q?.[0]==="/"?"":"/"}${Q}${J==="/"?"":`${Q?.at(-1)==="/"?"":"/"}${J?.[0]==="/"?J.slice(1):J}`}`},Py=(Q)=>{if(Q.charCodeAt(Q.length-1)!==63||!Q.includes(":"))return null;let J=Q.split("/"),X=[],G="";return J.forEach((Y)=>{if(Y!==""&&!/\:/.test(Y))G+="/"+Y;else if(/\:/.test(Y))if(/\?/.test(Y)){if(X.length===0&&G==="")X.push("/");else X.push(G);let W=Y.replace("?","");G+="/"+W,X.push(G)}else G+="/"+Y}),X.filter((Y,W,$)=>$.indexOf(Y)===W)},OQ0=(Q)=>{if(!/[%+]/.test(Q))return Q;if(Q.indexOf("+")!==-1)Q=Q.replace(/\+/g," ");return Q.indexOf("%")!==-1?wy(Q,wQ0):Q},L$1=(Q,J,X)=>{let G;if(!X&&J&&!/[%+]/.test(J)){let $=Q.indexOf("?",8);if($===-1)return;if(!Q.startsWith(J,$+1))$=Q.indexOf(`&${J}`,$+1);while($!==-1){let K=Q.charCodeAt($+J.length+1);if(K===61){let Z=$+J.length+2,H=Q.indexOf("&",Z);return OQ0(Q.slice(Z,H===-1?void 0:H))}else if(K==38||isNaN(K))return"";$=Q.indexOf(`&${J}`,$+1)}if(G=/[%+]/.test(Q),!G)return}let Y={};G??=/[%+]/.test(Q);let W=Q.indexOf("?",8);while(W!==-1){let $=Q.indexOf("&",W+1),K=Q.indexOf("=",W);if(K>$&&$!==-1)K=-1;let Z=Q.slice(W+1,K===-1?$===-1?void 0:$:K);if(G)Z=OQ0(Z);if(W=$,Z==="")continue;let H;if(K===-1)H="";else if(H=Q.slice(K+1,$===-1?void 0:$),G)H=OQ0(H);if(X){if(!(Y[Z]&&Array.isArray(Y[Z])))Y[Z]=[];Y[Z].push(H)}else Y[Z]??=H}return J?Y[J]:Y},w$1,P$1=(Q,J)=>{return L$1(Q,J,!0)},wQ0;var PN=h(()=>{Ly={},w$1=L$1,wQ0=decodeURIComponent});var M$1=(Q)=>wy(Q,wQ0),Dy;var BQ0=h(()=>{NQ0();z$1();N$1();PN();Dy=class{raw;#Q;#J;routeIndex=0;path;bodyCache={};constructor(Q,J="/",X=[[]]){this.raw=Q,this.path=J,this.#J=X,this.#Q={}}param(Q){return Q?this.#X(Q):this.#Y()}#X(Q){let J=this.#J[0][this.routeIndex][1][Q],X=this.#W(J);return X&&/\%/.test(X)?M$1(X):X}#Y(){let Q={},J=Object.keys(this.#J[0][this.routeIndex][1]);for(let X of J){let G=this.#W(this.#J[0][this.routeIndex][1][X]);if(G!==void 0)Q[X]=/\%/.test(G)?M$1(G):G}return Q}#W(Q){return this.#J[1]?this.#J[1][Q]:Q}query(Q){return w$1(this.url,Q)}queries(Q){return P$1(this.url,Q)}header(Q){if(Q)return this.raw.headers.get(Q)??void 0;let J={};return this.raw.headers.forEach((X,G)=>{J[G]=X}),J}async parseBody(Q){return this.bodyCache.parsedBody??=await U$1(this,Q)}#G=(Q)=>{let{bodyCache:J,raw:X}=this,G=J[Q];if(G)return G;let Y=Object.keys(J)[0];if(Y)return J[Y].then((W)=>{if(Y==="json")W=JSON.stringify(W);return new Response(W)[Q]()});return J[Q]=X[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,J){this.#Q[Q]=J}valid(Q){return this.#Q[Q]}get url(){return this.raw.url}get method(){return this.raw.method}get[V$1](){return this.#J}get matchedRoutes(){return this.#J[0].map(([[,Q]])=>Q)}get routePath(){return this.#J[0].map(([[,Q]])=>Q)[this.routeIndex].path}}});var T$1,v_4=(Q,J)=>{let X=new String(Q);return X.isEscaped=!0,X.callbacks=J,X},PQ0=async(Q,J,X,G,Y)=>{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(Y)Y[0]+=Q;else Y=[Q];let $=Promise.all(W.map((K)=>K({phase:J,buffer:Y,context:G}))).then((K)=>Promise.all(K.filter(Boolean).map((Z)=>PQ0(Z,J,!1,G,Y))).then(()=>Y[0]));if(X)return v_4(await $,W);else return $};var A$1=h(()=>{T$1={Stringify:1,BeforeStream:2,Stream:3}});var k_4="text/plain; charset=UTF-8",MQ0=(Q,J)=>{return{"Content-Type":Q,...J}},E$1=class{#Q;#J;env={};#X;finalized=!1;error;#Y;#W;#G;#K;#$;#H;#Z;#F;#V;constructor(Q,J){if(this.#Q=Q,J)this.#W=J.executionCtx,this.env=J.env,this.#H=J.notFoundHandler,this.#V=J.path,this.#F=J.matchResult}get req(){return this.#J??=new Dy(this.#Q,this.#V,this.#F),this.#J}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.#Z??=new Headers})}set res(Q){if(this.#G&&Q){Q=new Response(Q.body,Q);for(let[J,X]of this.#G.headers.entries()){if(J==="content-type")continue;if(J==="set-cookie"){let G=this.#G.headers.getSetCookie();Q.headers.delete("set-cookie");for(let Y of G)Q.headers.append("set-cookie",Y)}else Q.headers.set(J,X)}}this.#G=Q,this.finalized=!0}render=(...Q)=>{return this.#$??=(J)=>this.html(J),this.#$(...Q)};setLayout=(Q)=>this.#K=Q;getLayout=()=>this.#K;setRenderer=(Q)=>{this.#$=Q};header=(Q,J,X)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let G=this.#G?this.#G.headers:this.#Z??=new Headers;if(J===void 0)G.delete(Q);else if(X?.append)G.append(Q,J);else G.set(Q,J)};status=(Q)=>{this.#Y=Q};set=(Q,J)=>{this.#X??=new Map,this.#X.set(Q,J)};get=(Q)=>{return this.#X?this.#X.get(Q):void 0};get var(){if(!this.#X)return{};return Object.fromEntries(this.#X)}#q(Q,J,X){let G=this.#G?new Headers(this.#G.headers):this.#Z??new Headers;if(typeof J==="object"&&"headers"in J){let W=J.headers instanceof Headers?J.headers:new Headers(J.headers);for(let[$,K]of W)if($.toLowerCase()==="set-cookie")G.append($,K);else G.set($,K)}if(X)for(let[W,$]of Object.entries(X))if(typeof $==="string")G.set(W,$);else{G.delete(W);for(let K of $)G.append(W,K)}let Y=typeof J==="number"?J:J?.status??this.#Y;return new Response(Q,{status:Y,headers:G})}newResponse=(...Q)=>this.#q(...Q);body=(Q,J,X)=>this.#q(Q,J,X);text=(Q,J,X)=>{return!this.#Z&&!this.#Y&&!J&&!X&&!this.finalized?new Response(Q):this.#q(Q,J,MQ0(k_4,X))};json=(Q,J,X)=>{return this.#q(JSON.stringify(Q),J,MQ0("application/json",X))};html=(Q,J,X)=>{let G=(Y)=>this.#q(Y,J,MQ0("text/html; charset=UTF-8",X));return typeof Q==="object"?PQ0(Q,T$1.Stringify,!1,{}).then(G):G(Q)};redirect=(Q,J)=>{let X=String(Q);return this.header("Location",!/[^\x00-\xFF]/.test(X)?X:encodeURI(X)),this.newResponse(null,J??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var j$1=h(()=>{BQ0();A$1()});var Z8="ALL",I$1="all",C$1,My="Can not add a route since the matcher is already built.",Ty;var uq=h(()=>{C$1=["get","post","put","delete","options","patch"],Ty=class extends Error{}});var R$1="__COMPOSED_HANDLER";var S$1=()=>{};var __4=(Q)=>{return Q.text("404 Not Found",404)},v$1=(Q,J)=>{if("getResponse"in Q){let X=Q.getResponse();return J.newResponse(X.body,X)}return console.error(Q),J.text("Internal Server Error",500)},k$1=class Q{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Q="/";routes=[];constructor(J={}){[...C$1,I$1].forEach((W)=>{this[W]=($,...K)=>{if(typeof $==="string")this.#Q=$;else this.#Y(W,this.#Q,$);return K.forEach((Z)=>{this.#Y(W,this.#Q,Z)}),this}}),this.on=(W,$,...K)=>{for(let Z of[$].flat()){this.#Q=Z;for(let H of[W].flat())K.map((q)=>{this.#Y(H.toUpperCase(),this.#Q,q)})}return this},this.use=(W,...$)=>{if(typeof W==="string")this.#Q=W;else this.#Q="*",$.unshift(W);return $.forEach((K)=>{this.#Y(Z8,this.#Q,K)}),this};let{strict:G,...Y}=J;Object.assign(this,Y),this.getPath=G??!0?J.getPath??LQ0:D$1}#J(){let J=new Q({router:this.router,getPath:this.getPath});return J.errorHandler=this.errorHandler,J.#X=this.#X,J.routes=this.routes,J}#X=__4;errorHandler=v$1;route(J,X){let G=this.basePath(J);return X.routes.map((Y)=>{let W;if(X.errorHandler===v$1)W=Y.handler;else W=async($,K)=>(await zQ0([],X.errorHandler)($,()=>Y.handler($,K))).res,W[R$1]=Y.handler;G.#Y(Y.method,Y.path,W)}),this}basePath(J){let X=this.#J();return X._basePath=gq(this._basePath,J),X}onError=(J)=>{return this.errorHandler=J,this};notFound=(J)=>{return this.#X=J,this};mount(J,X,G){let Y,W;if(G)if(typeof G==="function")W=G;else if(W=G.optionHandler,G.replaceRequest===!1)Y=(Z)=>Z;else Y=G.replaceRequest;let $=W?(Z)=>{let H=W(Z);return Array.isArray(H)?H:[H]}:(Z)=>{let H=void 0;try{H=Z.executionCtx}catch{}return[Z.env,H]};Y||=(()=>{let Z=gq(this._basePath,J),H=Z==="/"?0:Z.length;return(q)=>{let F=new URL(q.url);return F.pathname=F.pathname.slice(H)||"/",new Request(F,q)}})();let K=async(Z,H)=>{let q=await X(Y(Z.req.raw),...$(Z));if(q)return q;await H()};return this.#Y(Z8,gq(J,"*"),K),this}#Y(J,X,G){J=J.toUpperCase(),X=gq(this._basePath,X);let Y={basePath:this._basePath,path:X,method:J,handler:G};this.router.add(J,X,[G,Y]),this.routes.push(Y)}#W(J,X){if(J instanceof Error)return this.errorHandler(J,X);throw J}#G(J,X,G,Y){if(Y==="HEAD")return(async()=>new Response(null,await this.#G(J,X,G,"GET")))();let W=this.getPath(J,{env:G}),$=this.router.match(Y,W),K=new E$1(J,{path:W,matchResult:$,env:G,executionCtx:X,notFoundHandler:this.#X});if($[0].length===1){let H;try{H=$[0][0][0][0](K,async()=>{K.res=await this.#X(K)})}catch(q){return this.#W(q,K)}return H instanceof Promise?H.then((q)=>q||(K.finalized?K.res:this.#X(K))).catch((q)=>this.#W(q,K)):H??this.#X(K)}let Z=zQ0($[0],this.errorHandler,this.#X);return(async()=>{try{let H=await Z(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,K)}})()}fetch=(J,...X)=>{return this.#G(J,X[1],X[0],J.method)};request=(J,X,G,Y)=>{if(J instanceof Request)return this.fetch(X?new Request(J,X):J,G,Y);return J=J.toString(),this.fetch(new Request(/^https?:\/\//.test(J)?J:`http://localhost${gq("/",J)}`,X),G,Y)};fire=()=>{addEventListener("fetch",(J)=>{J.respondWith(this.#G(J.request,J,void 0,J.request.method))})}};var _$1=h(()=>{F$1();j$1();uq();S$1();PN()});function Ay(Q,J){let X=this.buildAllMatchers(),G=(Y,W)=>{let $=X[Y]||X[Z8],K=$[2][W];if(K)return K;let Z=W.match($[0]);if(!Z)return[[],jM];let H=Z.indexOf("",1);return[$[1][H],Z]};return this.match=G,G(Q,J)}var jM;var TQ0=h(()=>{uq();jM=[]});function h_4(Q,J){if(Q.length===1)return J.length===1?Q<J?-1:1:-1;if(J.length===1)return 1;if(Q===IM||Q===CM)return 1;else if(J===IM||J===CM)return-1;if(Q===Ey)return 1;else if(J===Ey)return-1;return Q.length===J.length?Q<J?-1:1:J.length-Q.length}var Ey="[^/]+",IM=".*",CM="(?:|/.*)",mq,y_4,y$1=class Q{#Q;#J;#X=Object.create(null);insert(J,X,G,Y,W){if(J.length===0){if(this.#Q!==void 0)throw mq;if(W)return;this.#Q=X;return}let[$,...K]=J,Z=$==="*"?K.length===0?["","",IM]:["","",Ey]:$==="/*"?["","",CM]:$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(Z){let q=Z[1],F=Z[2]||Ey;if(q&&Z[2]){if(F===".*")throw mq;if(F=F.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(F))throw mq}if(H=this.#X[F],!H){if(Object.keys(this.#X).some((V)=>V!==IM&&V!==CM))throw mq;if(W)return;if(H=this.#X[F]=new Q,q!=="")H.#J=Y.varIndex++}if(!W&&q!=="")G.push([q,H.#J])}else if(H=this.#X[$],!H){if(Object.keys(this.#X).some((q)=>q.length>1&&q!==IM&&q!==CM))throw mq;if(W)return;H=this.#X[$]=new Q}H.insert(K,X,G,Y,W)}buildRegExpStr(){let X=Object.keys(this.#X).sort(h_4).map((G)=>{let Y=this.#X[G];return(typeof Y.#J==="number"?`(${G})@${Y.#J}`:y_4.has(G)?`\\${G}`:G)+Y.buildRegExpStr()});if(typeof this.#Q==="number")X.unshift(`#${this.#Q}`);if(X.length===0)return"";if(X.length===1)return X[0];return"(?:"+X.join("|")+")"}};var AQ0=h(()=>{mq=Symbol(),y_4=new Set(".\\+*[^]$()")});var h$1=class{#Q={varIndex:0};#J=new y$1;insert(Q,J,X){let G=[],Y=[];for(let $=0;;){let K=!1;if(Q=Q.replace(/\{[^}]+\}/g,(Z)=>{let H=`@\\${$}`;return Y[$]=[H,Z],$++,K=!0,H}),!K)break}let W=Q.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let $=Y.length-1;$>=0;$--){let[K]=Y[$];for(let Z=W.length-1;Z>=0;Z--)if(W[Z].indexOf(K)!==-1){W[Z]=W[Z].replace(K,Y[$][1]);break}}return this.#J.insert(W,J,G,this.#Q,X),G}buildRegExp(){let Q=this.#J.buildRegExpStr();if(Q==="")return[/^$/,[],[]];let J=0,X=[],G=[];return Q=Q.replace(/#(\d+)|@(\d+)|\.\*\$/g,(Y,W,$)=>{if(W!==void 0)return X[++J]=Number(W),"$()";if($!==void 0)return G[Number($)]=++J,"";return""}),[new RegExp(`^${Q}`),X,G]}};var f$1=h(()=>{AQ0()});function x$1(Q){return b$1[Q]??=new RegExp(Q==="*"?"":`^${Q.replace(/\/\*$|([.\\+*[^\]$()])/g,(J,X)=>X?`\\${X}`:"(?:|/.*)")}$`)}function b_4(){b$1=Object.create(null)}function x_4(Q){let J=new h$1,X=[];if(Q.length===0)return f_4;let G=Q.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,q],[F,V])=>H?1:F?-1:q.length-V.length),Y=Object.create(null);for(let H=0,q=-1,F=G.length;H<F;H++){let[V,z,U]=G[H];if(V)Y[z]=[U.map(([D])=>[D,Object.create(null)]),jM];else q++;let N;try{N=J.insert(z,q,V)}catch(D){throw D===mq?new Ty(z):D}if(V)continue;X[q]=U.map(([D,w])=>{let A=Object.create(null);w-=1;for(;w>=0;w--){let[P,M]=N[w];A[P]=M}return[D,A]})}let[W,$,K]=J.buildRegExp();for(let H=0,q=X.length;H<q;H++)for(let F=0,V=X[H].length;F<V;F++){let z=X[H][F]?.[1];if(!z)continue;let U=Object.keys(z);for(let N=0,D=U.length;N<D;N++)z[U[N]]=K[z[U[N]]]}let Z=[];for(let H in $)Z[H]=X[$[H]];return[W,Z,Y]}function MN(Q,J){if(!Q)return;for(let X of Object.keys(Q).sort((G,Y)=>Y.length-G.length))if(x$1(X).test(J))return[...Q[X]];return}var f_4,b$1,jy=class{name="RegExpRouter";#Q;#J;constructor(){this.#Q={[Z8]:Object.create(null)},this.#J={[Z8]:Object.create(null)}}add(Q,J,X){let G=this.#Q,Y=this.#J;if(!G||!Y)throw Error(My);if(!G[Q])[G,Y].forEach((K)=>{K[Q]=Object.create(null),Object.keys(K[Z8]).forEach((Z)=>{K[Q][Z]=[...K[Z8][Z]]})});if(J==="/*")J="*";let W=(J.match(/\/:/g)||[]).length;if(/\*$/.test(J)){let K=x$1(J);if(Q===Z8)Object.keys(G).forEach((Z)=>{G[Z][J]||=MN(G[Z],J)||MN(G[Z8],J)||[]});else G[Q][J]||=MN(G[Q],J)||MN(G[Z8],J)||[];Object.keys(G).forEach((Z)=>{if(Q===Z8||Q===Z)Object.keys(G[Z]).forEach((H)=>{K.test(H)&&G[Z][H].push([X,W])})}),Object.keys(Y).forEach((Z)=>{if(Q===Z8||Q===Z)Object.keys(Y[Z]).forEach((H)=>K.test(H)&&Y[Z][H].push([X,W]))});return}let $=Py(J)||[J];for(let K=0,Z=$.length;K<Z;K++){let H=$[K];Object.keys(Y).forEach((q)=>{if(Q===Z8||Q===q)Y[q][H]||=[...MN(G[q],H)||MN(G[Z8],H)||[]],Y[q][H].push([X,W-Z+K+1])})}}match=Ay;buildAllMatchers(){let Q=Object.create(null);return Object.keys(this.#J).concat(Object.keys(this.#Q)).forEach((J)=>{Q[J]||=this.#X(J)}),this.#Q=this.#J=void 0,b_4(),Q}#X(Q){let J=[],X=Q===Z8;if([this.#Q,this.#J].forEach((G)=>{let Y=G[Q]?Object.keys(G[Q]).map((W)=>[W,G[Q][W]]):[];if(Y.length!==0)X||=!0,J.push(...Y);else if(Q!==Z8)J.push(...Object.keys(G[Z8]).map((W)=>[W,G[Z8][W]]))}),!X)return null;else return x_4(J)}};var EQ0=h(()=>{uq();PN();TQ0();AQ0();f$1();f_4=[/^$/,[],Object.create(null)],b$1=Object.create(null)});var g_4=class{name="PreparedRegExpRouter";#Q;#J;constructor(Q,J){this.#Q=Q,this.#J=J}#X(Q,J){let X=this.#Q[Q];X[1].forEach((G)=>G&&G.push(J)),Object.values(X[2]).forEach((G)=>G[0].push(J))}#Y(Q,J,X,G,Y){let W=this.#Q[Q];if(!Y)W[2][J][0].push([X,{}]);else G.forEach(($)=>{if(typeof $==="number")W[1][$].push([X,Y]);else W[2][$||J][0].push([X,Y])})}add(Q,J,X){if(!this.#Q[Q]){let Y=this.#Q[Z8],W={};for(let $ in Y[2])W[$]=[Y[2][$][0].slice(),jM];this.#Q[Q]=[Y[0],Y[1].map(($)=>Array.isArray($)?$.slice():0),W]}if(J==="/*"||J==="*"){let Y=[X,{}];if(Q===Z8)for(let W in this.#Q)this.#X(W,Y);else this.#X(Q,Y);return}let G=this.#J[J];if(!G)throw Error(`Path ${J} is not registered`);for(let[Y,W]of G)if(Q===Z8)for(let $ in this.#Q)this.#Y($,J,X,Y,W);else this.#Y(Q,J,X,Y,W)}buildAllMatchers(){return this.#Q}match=Ay};var g$1=h(()=>{uq();TQ0();EQ0()});var u$1=h(()=>{EQ0();g$1()});var jQ0=class{name="SmartRouter";#Q=[];#J=[];constructor(Q){this.#Q=Q.routers}add(Q,J,X){if(!this.#J)throw Error(My);this.#J.push([Q,J,X])}match(Q,J){if(!this.#J)throw Error("Fatal error");let X=this.#Q,G=this.#J,Y=X.length,W=0,$;for(;W<Y;W++){let K=X[W];try{for(let Z=0,H=G.length;Z<H;Z++)K.add(...G[Z]);$=K.match(Q,J)}catch(Z){if(Z instanceof Ty)continue;throw Z}this.match=K.match.bind(K),this.#Q=[K],this.#J=void 0;break}if(W===Y)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,$}get activeRouter(){if(this.#J||this.#Q.length!==1)throw Error("No active router has been determined yet.");return this.#Q[0]}};var m$1=h(()=>{uq()});var l$1=h(()=>{m$1()});var RM,d$1=class Q{#Q;#J;#X;#Y=0;#W=RM;constructor(J,X,G){if(this.#J=G||Object.create(null),this.#Q=[],J&&X){let Y=Object.create(null);Y[J]={handler:X,possibleKeys:[],score:0},this.#Q=[Y]}this.#X=[]}insert(J,X,G){this.#Y=++this.#Y;let Y=this,W=B$1(X),$=[];for(let K=0,Z=W.length;K<Z;K++){let H=W[K],q=W[K+1],F=O$1(H,q),V=Array.isArray(F)?F[0]:H;if(V in Y.#J){if(Y=Y.#J[V],F)$.push(F[1]);continue}if(Y.#J[V]=new Q,F)Y.#X.push(F),$.push(F[1]);Y=Y.#J[V]}return Y.#Q.push({[J]:{handler:G,possibleKeys:$.filter((K,Z,H)=>H.indexOf(K)===Z),score:this.#Y}}),Y}#G(J,X,G,Y){let W=[];for(let $=0,K=J.#Q.length;$<K;$++){let Z=J.#Q[$],H=Z[X]||Z[Z8],q={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),G!==RM||Y&&Y!==RM)for(let F=0,V=H.possibleKeys.length;F<V;F++){let z=H.possibleKeys[F],U=q[H.score];H.params[z]=Y?.[z]&&!U?Y[z]:G[z]??Y?.[z],q[H.score]=!0}}}return W}search(J,X){let G=[];this.#W=RM;let W=[this],$=DQ0(X),K=[];for(let Z=0,H=$.length;Z<H;Z++){let q=$[Z],F=Z===H-1,V=[];for(let z=0,U=W.length;z<U;z++){let N=W[z],D=N.#J[q];if(D)if(D.#W=N.#W,F){if(D.#J["*"])G.push(...this.#G(D.#J["*"],J,N.#W));G.push(...this.#G(D,J,N.#W))}else V.push(D);for(let w=0,A=N.#X.length;w<A;w++){let P=N.#X[w],M=N.#W===RM?{}:{...N.#W};if(P==="*"){let y=N.#J["*"];if(y)G.push(...this.#G(y,J,N.#W)),y.#W=M,V.push(y);continue}let[T,E,R]=P;if(!q&&!(R instanceof RegExp))continue;let k=N.#J[T],_=$.slice(Z).join("/");if(R instanceof RegExp){let y=R.exec(_);if(y){if(M[E]=y[0],G.push(...this.#G(k,J,N.#W,M)),Object.keys(k.#J).length){k.#W=M;let b=y[0].match(/\//)?.length??0;(K[b]||=[]).push(k)}continue}}if(R===!0||R.test(q))if(M[E]=q,F){if(G.push(...this.#G(k,J,M,N.#W)),k.#J["*"])G.push(...this.#G(k.#J["*"],J,M,N.#W))}else k.#W=M,V.push(k)}}W=V.concat(K.shift()??[])}if(G.length>1)G.sort((Z,H)=>{return Z.score-H.score});return[G.map(({handler:Z,params:H})=>[Z,H])]}};var p$1=h(()=>{uq();PN();RM=Object.create(null)});var IQ0=class{name="TrieRouter";#Q;constructor(){this.#Q=new d$1}add(Q,J,X){let G=Py(J);if(G){for(let Y=0,W=G.length;Y<W;Y++)this.#Q.insert(Q,G[Y],X);return}this.#Q.insert(Q,J,X)}match(Q,J){return this.#Q.search(Q,J)}};var c$1=h(()=>{PN();p$1()});var n$1=h(()=>{c$1()});var gQ;var i$1=h(()=>{_$1();u$1();l$1();n$1();gQ=class extends k$1{constructor(Q={}){super(Q);this.router=Q.router??new jQ0({routers:[new jy,new IQ0]})}}});var vZ=h(()=>{i$1()});var r$1=(Q)=>{let X={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Q},G=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return($)=>W===$?$:null;else if(typeof W==="function")return W;else return($)=>W.includes($)?$:null})(X.origin),Y=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(X.allowMethods);return async function($,K){function Z(q,F){$.res.headers.set(q,F)}let H=await G($.req.header("origin")||"",$);if(H)Z("Access-Control-Allow-Origin",H);if(X.credentials)Z("Access-Control-Allow-Credentials","true");if(X.exposeHeaders?.length)Z("Access-Control-Expose-Headers",X.exposeHeaders.join(","));if($.req.method==="OPTIONS"){if(X.origin!=="*")Z("Vary","Origin");if(X.maxAge!=null)Z("Access-Control-Max-Age",X.maxAge.toString());let q=await Y($.req.header("origin")||"",$);if(q.length)Z("Access-Control-Allow-Methods",q.join(","));let F=X.allowHeaders;if(!F?.length){let V=$.req.header("Access-Control-Request-Headers");if(V)F=V.split(/\s*,\s*/)}if(F?.length)Z("Access-Control-Allow-Headers",F.join(",")),$.res.headers.append("Vary","Access-Control-Request-Headers");return $.res.headers.delete("Content-Length"),$.res.headers.delete("Content-Type"),new Response(null,{headers:$.res.headers,status:204,statusText:"No Content"})}if(await K(),X.origin!=="*")$.header("Vary","Origin",{append:!0})}};var a$1=()=>{};function u_4(){let{process:Q,Deno:J}=globalThis;return!(typeof J?.noColor==="boolean"?J.noColor:Q!==void 0?"NO_COLOR"in Q?.env:!1)}async function o$1(){let{navigator:Q}=globalThis,J="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}})():!u_4())}var s$1=()=>{};async function t$1(Q,J,X,G,Y=0,W){let $=J==="<--"?`${J} ${X} ${G}`:`${J} ${X} ${G} ${await d_4(Y)} ${W}`;Q($)}var m_4=(Q)=>{let[J,X]=[",","."];return Q.map((Y)=>Y.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+J)).join(X)},l_4=(Q)=>{let J=Date.now()-Q;return m_4([J<1000?J+"ms":Math.round(J/1000)+"s"])},d_4=async(Q)=>{if(await o$1())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}`},e$1=(Q=console.log)=>{return async function(X,G){let{method:Y,url:W}=X.req,$=W.slice(W.indexOf("/",8));await t$1(Q,"<--",Y,$);let K=Date.now();await G(),await t$1(Q,"-->",Y,$,X.res.status,l_4(K))}};var QK1=h(()=>{s$1()});import{randomBytes as p_4}from"crypto";function JK1(){if(SM)return SM;let Q=process.env.MESH_JWT_SECRET??F9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Q)SM=new TextEncoder().encode(Q);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),SM=new Uint8Array(p_4(32));return SM}async function XK1(Q,J="5m"){let X=JK1();return await new cQ(Q).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(J).sign(X)}async function YK1(Q){try{let J=JK1(),{payload:X}=await O8(Q,J);return X}catch{return}}var SM=null;var CQ0=h(()=>{jJ();BU()});class RQ0{db;constructor(Q){this.db=Q}async get(Q){let J=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Q).executeTakeFirst();if(!J)return null;return{organizationId:J.organizationId,sidebar_items:J.sidebar_items?typeof J.sidebar_items==="string"?JSON.parse(J.sidebar_items):J.sidebar_items:null,createdAt:J.createdAt,updatedAt:J.updatedAt}}async upsert(Q,J){let X=new Date().toISOString(),G=J?.sidebar_items?JSON.stringify(J.sidebar_items):null;await this.db.insertInto("organization_settings").values({organizationId:Q,sidebar_items:G,createdAt:X,updatedAt:X}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:G?G:void 0,updatedAt:X})).execute();let Y=await this.get(Q);if(!Y)return{organizationId:Q,sidebar_items:J?.sidebar_items??null,createdAt:X,updatedAt:X};return Y}}var GK1,SQ0,TN;var vQ0=h(()=>{wH();GK1=class GK1 extends Error{constructor(Q){super(Q);this.name="UnauthorizedError"}};SQ0=class SQ0 extends Error{constructor(Q){super(Q);this.name="ForbiddenError"}};TN=class TN{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(Q,J,X,G,Y,W=vY.SELF){this.userId=J;this.toolName=X;this.boundAuth=G;this.role=Y;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 GK1("Authentication required. Please provide a valid OAuth token or API key.");let J=Q.length>0?Q:this.toolName?[this.toolName]:[];if(J.length===0)throw new SQ0("No resources specified for access check");for(let X of J)if(await this.checkResource(X)){this.grant();return}throw new SQ0(`Access denied to: ${J.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 J={};if(this.connectionId)J[this.connectionId]=[Q];return this.boundAuth.hasPermission(J)}granted(){return this._granted}}});class kQ0{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 EM.startActiveSpan("redactor.redact",(J)=>{try{if(Q===null||Q===void 0)return Q;if(typeof Q==="string")return J.setAttribute("data.type","string"),this.redactString(Q);if(Array.isArray(Q))return J.setAttribute("data.type","array"),J.setAttribute("data.length",Q.length),Q.map((X)=>this.redact(X));if(typeof Q==="object"){J.setAttribute("data.type","object");let X={};for(let[G,Y]of Object.entries(Q)){let W=this.redactString(G);X[W]=this.redact(Y)}return X}return J.setAttribute("data.type",typeof Q),Q}finally{J.end()}})}redactString(Q){return EM.startActiveSpan("redactor.redactString",(J)=>{try{J.setAttribute("text.length",Q.length);let X=Q,G=0;for(let Y of this.patterns){let W=Q.match(Y.regex);if(W)G+=W.length,J.setAttribute(`redaction.${Y.type}.count`,W.length);X=X.replace(Y.regex,`[REDACTED:${Y.type}]`)}return J.setAttribute("redaction.total_count",G),X}finally{J.end()}})}}var WK1=h(()=>{Oy()});class _Q0{db;redactor;constructor(Q){this.db=Q;this.redactor=new kQ0}async log(Q){await this.logBatch([Q])}async logBatch(Q){if(Q.length===0)return;let J=Q.map((X)=>({...X,input:this.redactor.redact(X.input),output:this.redactor.redact(X.output)}));await this.db.transaction().execute(async(X)=>{await X.insertInto("monitoring_logs").values(J.map((G)=>this.toDbRow(G))).execute()})}async query(Q){let J=this.db.selectFrom("monitoring_logs").selectAll(),X=this.db.selectFrom("monitoring_logs").select((K)=>K.fn.count("id").as("count"));if(Q.organizationId)J=J.where("organization_id","=",Q.organizationId),X=X.where("organization_id","=",Q.organizationId);if(Q.connectionId)J=J.where("connection_id","=",Q.connectionId),X=X.where("connection_id","=",Q.connectionId);if(Q.gatewayId)J=J.where("gateway_id","=",Q.gatewayId),X=X.where("gateway_id","=",Q.gatewayId);if(Q.toolName)J=J.where("tool_name","=",Q.toolName),X=X.where("tool_name","=",Q.toolName);if(Q.isError!==void 0)J=J.where("is_error","=",Q.isError?1:0),X=X.where("is_error","=",Q.isError?1:0);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString()),X=X.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString()),X=X.where("timestamp","<=",Q.endDate.toISOString());if(J=J.orderBy("timestamp","desc"),Q.limit)J=J.limit(Q.limit);if(Q.offset)J=J.offset(Q.offset);let[G,Y]=await Promise.all([J.execute(),X.executeTakeFirst()]),W=Number(Y?.count||0);return{logs:G.map((K)=>this.fromDbRow(K)),total:W}}async getStats(Q){let J=this.db.selectFrom("monitoring_logs").where("organization_id","=",Q.organizationId);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString());let X=await J.select([($)=>$.fn.count("id").as("total_count"),($)=>$.fn.sum($.ref("is_error")).as("error_count"),($)=>$.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),G=Number(X?.total_count||0),Y=Number(X?.error_count||0),W=Number(X?.avg_duration||0);return{totalCalls:G,errorRate:G>0?Y/G:0,avgDurationMs:W}}toDbRow(Q){return{id:Q.id||JG("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}}fromDbRow(Q){let J=typeof Q.input==="string"?JSON.parse(Q.input):Q.input,X=typeof Q.output==="string"?JSON.parse(Q.output):Q.output,G=typeof Q.timestamp==="string"?new Date(Q.timestamp):Q.timestamp;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,connectionTitle:Q.connection_title,toolName:Q.tool_name,input:J,output:X,isError:Q.is_error===1,errorMessage:Q.error_message,durationMs:Q.duration_ms,timestamp:G,userId:Q.user_id,requestId:Q.request_id,userAgent:Q.user_agent,gatewayId:Q.gateway_id}}}var $K1=h(()=>{WK1();UR()});function KK1(Q){let J=null;return()=>{if(J)return J;return J=Q().catch((X)=>{throw J=null,X}),J}}class ZK1{factory;promise=null;constructor(Q){this.factory=Q}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Q,J){return this.getOrCreatePromise().then(Q,J)}catch(Q){return this.getOrCreatePromise().catch(Q)}finally(Q){return this.getOrCreatePromise().finally(Q)}}function RG(Q){return new ZK1(Q)}async function HK1(Q,J){return(await J.storage.connections.findById(Q))?.connection_url??null}async function Cy(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=new URL(Q);G.pathname=`${X}/.well-known/oauth-protected-resource`;let Y=await fetch(G.toString(),{method:"GET",headers:{Accept:"application/json"}});if(Y.ok)return Y;if(Y.status!==404&&Y.status!==401)return Y;let W=new URL(Q);if(W.pathname=`/.well-known/oauth-protected-resource${X}`,Y=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y.status!==404&&Y.status!==401)return Y;let $=new URL(Q);return $.pathname="/.well-known/oauth-protected-resource",Y=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y}async function c_4(Q,J){let X=await HK1(Q,J);if(!X)return null;try{let G=await Cy(X);if(!G.ok)return null;return(await G.json()).authorization_servers?.[0]??null}catch{return null}}async function qK1(Q){let J=Q.get("meshContext");if(!J)J=await kZ.create(Q.req.raw),Q.set("meshContext",J);return J}async function FK1({error:Q,reqUrl:J,connectionId:X,connectionUrl:G,headers:Y}){if(!(Q.status===401||Q.message?.includes("401")||Q.message?.toLowerCase().includes("unauthorized")))return null;if(await fetch(G,{method:"POST",headers:{...Y,"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"}}})}).then((K)=>K.headers.has("WWW-Authenticate")).catch(()=>!1))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${J.origin}/mcp/${X}/.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"}})}async function yQ0(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=X!==""&&X!=="/",Y=[];if(G){let $=new URL(Q);$.pathname=`/.well-known/oauth-authorization-server${X}`,Y.push($);let K=new URL(Q);K.pathname=`/.well-known/openid-configuration${X}`,Y.push(K);let Z=new URL(Q);Z.pathname=`${X}/.well-known/openid-configuration`,Y.push(Z)}else{let $=new URL(Q);$.pathname="/.well-known/oauth-authorization-server",Y.push($);let K=new URL(Q);K.pathname="/.well-known/openid-configuration",Y.push(K)}let W=null;for(let $ of Y){if(W=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}var Iy,Ry=(Q)=>{if(!(Q.hostname==="localhost"||Q.hostname==="127.0.0.1"))Q.protocol="https:";return Q},VK1=async(Q)=>{let J=Q.req.param("connectionId"),X=await qK1(Q),G=await HK1(J,X);if(!G)return Q.json({error:"Connection not found"},404);try{let Y=await Cy(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),$=Ry(new URL(Q.req.url)),K=`${$.origin}/mcp/${J}`,Z=`${$.origin}/oauth-proxy/${J}`,H={...W,resource:K,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",W),Q.json({error:"Failed to proxy OAuth metadata",message:W.message},502)}},zK1;var Sy=h(()=>{vZ();vy();Iy=new gQ;Iy.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Q)=>VK1(Q));Iy.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Q)=>VK1(Q));Iy.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=await qK1(Q),G=await c_4(J,X);if(!G)return Q.json({error:"Connection not found or no auth server"},404);try{let Y=await yQ0(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),K=`${Ry(new URL(Q.req.url)).origin}/oauth-proxy/${J}`,Z={...W,authorization_endpoint:W.authorization_endpoint?`${K}/authorize`:void 0,token_endpoint:W.token_endpoint?`${K}/token`:void 0,registration_endpoint:W.registration_endpoint?`${K}/register`:void 0};return new Response(JSON.stringify(Z),{status:200,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;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)}});zK1=Iy});function n_4(Q){if(!Q.isError)return;let J=Q.content;if(!Array.isArray(J))return;for(let X of J)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function UK1(Q){if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q,X=J.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return J}return{value:Q}}async function i_4(Q,J){let X=Q.body;if(!X)return{text:"",truncated:!1};let G=X.getReader(),Y=new TextDecoder,W=!1,$=0,K=[];try{while(!0){let{value:Z,done:H}=await G.read();if(H)break;if(Z){if($+=Z.byteLength,$>J){W=!0;let q=J-($-Z.byteLength);if(q>0)K.push(Y.decode(Z.slice(0,q),{stream:!0}));break}K.push(Y.decode(Z,{stream:!0}))}}}finally{G.releaseLock()}return K.push(Y.decode()),{text:K.join(""),truncated:W}}async function vM(Q){let{ctx:J,enabled:X}=Q,G=Q.organizationId??J.organization?.id;if(!X||!G)return;await J.storage.monitoring.log({organizationId:G,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:J.auth.user?.id||J.auth.apiKey?.userId||null,requestId:J.metadata.requestId,userAgent:J.metadata.userAgent,gatewayId:J.gatewayId})}function NK1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=Date.now()-K;return await vM({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:UK1(Z),isError:Boolean(Z.isError),errorMessage:n_4(Z),durationMs:H}),Z}catch(Z){let H=Z,q=Date.now()-K;throw await vM({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}function BK1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=J.organization?.id;if(X&&H){let q=Z.clone();(async()=>{try{let{text:F,truncated:V}=await i_4(q,262144),z=Date.now()-K,U=q.headers.get("content-type")??"",N=F;if(U.includes("application/json"))try{N=F.length?JSON.parse(F):null}catch{N=F}let D=Z.status>=400,w=D&&N&&typeof N==="object"&&"error"in N?N.error:void 0,A=typeof w==="string"&&w?w:D&&typeof N==="string"&&N.trim()?N.slice(0,500):D?`HTTP ${Z.status} ${Z.statusText}`.trim():V?"Response body truncated to 262144 bytes":void 0;await vM({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:UK1(N),isError:D,errorMessage:A,durationMs:z})}catch(F){let V=Date.now()-K;await vM({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${F.message}`,durationMs:V})}})()}return Z}catch(Z){let H=Z,q=Date.now()-K;throw await vM({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}function r_4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new TN(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return{content:[{type:"text",text:`Authorization failed: ${Y.message}`}],isError:!0}}}}function a_4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new TN(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return new Response(JSON.stringify({error:`Authorization failed: ${Y.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function DK1(Q,J,{superUser:X}){let G=typeof Q==="string"?await J.storage.connections.findById(Q,J.organization?.id):Q;if(!G)throw Error("Connection not found");let Y=G?.id;if(J.organization&&G.organization_id!==J.organization.id)throw Error("Connection does not belong to the active organization");if(J.organization??={id:G.organization_id},G.status!=="active")throw Error(`Connection inactive: ${G.status}`);let W,$=J.auth.user?.connectionId,K=KK1(async()=>{let y=U00(G.configuration_state,G.configuration_scopes),b=J.auth.user?.id??J.auth.apiKey?.userId;if(!b){console.error("User ID required to issue configuration token");return}try{W=await XK1({sub:b,user:{id:b},metadata:{state:G.configuration_state??void 0,meshUrl:process.env.MESH_URL??J.baseUrl,connectionId:Y,organizationId:J.organization?.id},permissions:y})}catch(l){console.error("Failed to issue configuration token:",l)}}),Z=async()=>{await K();let y={...$?{"x-caller-id":$}:{}};if(G.connection_token)y.Authorization=`Bearer ${G.connection_token}`;if(W)y["x-mesh-token"]=W;if(G.connection_headers)Object.assign(y,G.connection_headers);return y},H=async()=>{let y=await Z(),b=new SW(new URL(G.connection_url),{requestInit:{headers:y}}),l=new vH({name:"mcp-mesh-proxy",version:"1.0.0"});return await l.connect(b),l},q=X?async(y,b)=>await b():r_4(J,Y),F=X?async(y,b)=>await b():a_4(J,Y),V={enabled:XM0().enabled,connectionId:Y,connectionTitle:G.title,ctx:J},z=NK1(V),U=BK1(V),N=zw(z,q),D=zw(U,F),w=async(y)=>{return N(y,async()=>{let b=await H(),l=Date.now();return await J.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":Y,"tool.name":y.params.name}},async(x)=>{try{let v=await b.callTool(y.params),g=Date.now()-l;return J.meter.createHistogram("connection.proxy.duration").record(g,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),J.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),x.end(),v}catch(v){let g=v,Q0=Date.now()-l;throw J.meter.createHistogram("connection.proxy.duration").record(Q0,{"connection.id":Y,"tool.name":y.params.name,status:"error"}),J.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":Y,"tool.name":y.params.name,error:g.message}),x.recordException(g),x.end(),v}finally{await b.close()}})})};return{fetch:async(y)=>{let b=new URL(y.url),l;try{l=await H()}catch(g){let Q0=await FK1({error:g,reqUrl:b,connectionId:Y,connectionUrl:G.connection_url,headers:await Z()});if(Q0)return Q0;throw g}let x=new _H({name:"mcp-mesh",version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),v=new lH({enableJsonResponse:y.headers.get("Accept")?.includes("application/json")??!1});return await x.connect(v),x.server.setRequestHandler(lK,async(g)=>{return await l.listTools()}),x.server.setRequestHandler(dK,w),x.server.setRequestHandler(bK,async()=>{if(l.getServerCapabilities()?.resources)return await l.listResources();return{resources:[]}}),x.server.setRequestHandler(gK,async(g)=>{return await l.readResource(g.params)}),x.server.setRequestHandler(xK,async()=>{if(l.getServerCapabilities()?.resourceTemplates)return await l.listResourceTemplates();return{resourceTemplates:[]}}),x.server.setRequestHandler(uK,async()=>{if(l.getServerCapabilities()?.prompts)return await l.listPrompts();return{prompts:[]}}),x.server.setRequestHandler(mK,async(g)=>{return await l.getPrompt(g.params)}),await v.handleMessage(y)},client:{callTool:(y)=>{return w({method:"tools/call",params:y})},listTools:async()=>{if(G.tools&&G.tools.length>0)return{tools:G.tools.map((b)=>({name:b.name,description:b.description,inputSchema:b.inputSchema}))};return await(await H()).listTools()},listResources:async()=>{return await(await H()).listResources()},readResource:async(y)=>{return await(await H()).readResource(y)},listResourceTemplates:async()=>{return await(await H()).listResourceTemplates()},listPrompts:async()=>{return await(await H()).listPrompts()},getPrompt:async(y)=>{return await(await H()).getPrompt(y)}},callStreamableTool:async(y,b)=>{let l={method:"tools/call",params:{name:y,arguments:b}};return D(l,async()=>{let x=await Z(),v=new URL(G.connection_url);return v.pathname=v.pathname.replace(/\/$/,"")+`/call-tool/${l.params.name}`,await J.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":Y,"tool.name":l.params.name}},async(g)=>{let Q0=Date.now();try{let n=await fetch(v.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(l.params.arguments),headers:{...x,"Content-Type":"application/json"}}),G0=Date.now()-Q0;return J.meter.createHistogram("connection.proxy.streamable.duration").record(G0,{"connection.id":Y,"tool.name":l.params.name,status:n.ok?"success":"error"}),J.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":Y,"tool.name":l.params.name,status:n.ok?"success":"error"}),g.end(),n}catch(n){let G0=n,U0=Date.now()-Q0;throw J.meter.createHistogram("connection.proxy.streamable.duration").record(U0,{"connection.id":Y,"tool.name":l.params.name,status:"error"}),J.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":Y,"tool.name":l.params.name,error:G0.message}),g.recordException(G0),g.end(),n}})})}}}async function LK1(Q,J){return DK1(Q,J,{superUser:!1})}async function wK1(Q,J){return DK1(Q,J,{superUser:!0})}var OK1,PK1;var ky=h(()=>{N00();qa();tR();Jw();ES();aJ();vZ();CQ0();vQ0();oS();Sy();OK1=new gQ;OK1.all("/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=Q.get("meshContext");try{return await(await X.createMCPProxy(J)).fetch(Q.req.raw)}catch(G){let Y=G;if(Y.message.includes("not found"))return Q.json({error:Y.message},404);if(Y.message.includes("does not belong to the active organization"))return Q.json({error:"Connection not found"},404);if(Y.message.includes("inactive"))return Q.json({error:Y.message},503);return Q.json({error:"Internal server error",message:Y.message},500)}});PK1=OK1});function o_4(Q,J){for(let[X,G]of Object.entries(J)){let Y=Q[X];if(!Y||Y.length===0){let W=Q["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let $ of G)if(!W.includes($))return!1;continue}if(Y.includes("*"))continue;for(let W of G)if(!Y.includes(W))return!1}return!0}function s_4(Q){let{auth:J,headers:X,role:G,permissions:Y,userId:W}=Q,$=J.api.hasPermission;return{hasPermission:async(K)=>{if(G&&o00.includes(G))return!0;if(Y)return o_4(Y,K);if(!$)return console.error("[Auth] hasPermission API not available"),!1;try{if((await $({headers:X,body:{permission:K}}))?.success===!0)return!0;let H={};for(let F of Object.keys(K))H[F]=["*"];return(await $({headers:X,body:{permission:H}}))?.success===!0}catch(Z){return console.error("[Auth] Permission check failed:",Z),!1}},organization:{create:async(K)=>{return J.api.createOrganization({headers:X,body:K})},update:async(K)=>{return J.api.updateOrganization({headers:X,body:K})},delete:async(K)=>{await J.api.deleteOrganization({headers:X,body:{organizationId:K}})},get:async(K)=>{return J.api.getFullOrganization({headers:X,query:K?{organizationId:K}:void 0})},list:async(K)=>{return J.api.listOrganizations({headers:X,query:K?{userId:K}:void 0})},addMember:async(K)=>{return J.api.addMember({headers:X,body:K})},removeMember:async(K)=>{await J.api.removeMember({headers:X,body:K})},listMembers:async(K)=>{return J.api.listMembers({headers:X,query:K?{organizationId:K.organizationId,limit:K.limit,offset:K.offset}:void 0})},updateMemberRole:async(K)=>{return J.api.updateMemberRole({headers:X,body:K})}},apiKey:{create:async(K)=>{return J.api.createApiKey({body:{...K,userId:W}})},list:async()=>{return J.api.listApiKeys({headers:X})},update:async(K)=>{return J.api.updateApiKey({body:{...K,userId:W}})},delete:async(K)=>{await J.api.deleteApiKey({headers:X,body:{keyId:K}})}}}}async function t_4(Q,J,X){if(o00.includes(X))return;let G=await Q.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",J).where("role","=",X).executeTakeFirst();if(!G?.permission)return;try{return JSON.parse(G.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function e_4(Q,J,X){let G=Q.headers.get("Authorization");try{let Y=new Headers(Q.headers);Y.set("X-MCP-Session-Auth","true");let W=await J.api.getMcpSession({headers:Y});if(W){let $=W.userId,K=await X.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(),Z=K?.role,H=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,q;if(K&&Z)q=await t_4(X,K.organizationId,Z);return{user:{id:$,role:Z},role:Z,permissions:q,organization:H}}}catch(Y){console.error("[Auth] OAuth session check failed:",Y)}if(G?.startsWith("Bearer ")){let Y=G.replace("Bearer ","").trim();try{let W=await YK1(Y);if(W)return{user:{id:W.sub,connectionId:W.metadata?.connectionId},permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}catch{}try{let W=await J.api.verifyApiKey({body:{key:Y}});if(W?.valid&&W.key){let $=W.key.metadata?.organization,K=W.key.permissions;return{apiKeyId:W.key.id,user:{id:W.key.userId},permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let Y=await J.api.getSession({headers:Q.headers});if(Y){let W,$;if(Y.session.activeOrganizationId){let K=await J.api.getFullOrganization({headers:Q.headers}).catch(()=>null);if(K)W={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((H)=>H.userId===Y.user.id)?.role;else W={id:Y.session.activeOrganizationId,slug:"",name:""}}return{user:{id:Y.user.id,email:Y.user.email,role:$},role:$,organization:W}}}catch(Y){console.error("[Auth] Session check failed:",Y)}return{user:void 0}}function TK1(Q){let J=new yL(Q.encryption.key),X={connections:new hL(Q.db,J),organizationSettings:new RQ0(Q.db),monitoring:new _Q0(Q.db),gateways:new fL(Q.db)};return async(G)=>{let Y=G?.headers.get("x-caller-id")??void 0,W=G?await e_4(G,Q.auth,Q.db):{user:void 0},$=s_4({auth:Q.auth,headers:G?.headers??new Headers,role:W.role,permissions:W.permissions,userId:W.user?.id}),K={user:W.user};if(W.apiKeyId)K.apiKey={id:W.apiKeyId,name:"",userId:""};let Z=W.organization,H=G?new URL(G.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${H.protocol}//${H.host}`,F=new TN(Q.auth,K.user?.id,void 0,$,W.role,vY.SELF),V={auth:K,connectionId:Y,organization:Z,storage:X,vault:J,authInstance:Q.auth,boundAuth:$,access:F,db:Q.db,tracer:Q.observability.tracer,meter:Q.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:G?.headers.get("x-mesh-client")||G?.headers.get("User-Agent")||void 0,ipAddress:(G?.headers.get("CF-Connecting-IP")||G?.headers.get("X-Forwarded-For"))??void 0},eventBus:Q.eventBus,createMCPProxy:async(z)=>{return await LK1(z,V)}};return V}}var MK1,kZ;var vy=h(()=>{CQ0();ta();ea();Qo();vQ0();$K1();s00();wH();ky();kZ={set:(Q)=>{MK1=Q},create:async(Q)=>{return await MK1(Q)}}});function AK1(Q){return Q===kM.HEALTH||Q===kM.METRICS||Q.startsWith(_M.WELL_KNOWN)}function Jy4(Q){return Q.startsWith(_M.API)}function Xy4(Q){return Q==="/mcp"||Q.startsWith(_M.MCP)}function Yy4(Q){return Q.startsWith(_M.OAUTH_PROXY)}function Gy4(Q){return Qy4.test(Q)}function EK1(Q){return Jy4(Q)||Xy4(Q)||Yy4(Q)||AK1(Q)}function jK1(Q){return Q==="/"||Q.startsWith(_M.API_AUTH)||AK1(Q)||Gy4(Q)}var kM,_M,Qy4;var hQ0=h(()=>{kM={HEALTH:"/health",METRICS:"/metrics"},_M={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known"},Qy4=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/});class IK1{db;constructor(Q){this.db=Q}async publishEvent(Q){let J=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:J,updated_at:J}).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:J,updatedAt:J}}async subscribe(Q){let J=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("connection_id","=",Q.connectionId).where("event_type","=",Q.eventType);if(Q.publisher)J=J.where("publisher","=",Q.publisher);else J=J.where("publisher","is",null);if(Q.filter)J=J.where("filter","=",Q.filter);else J=J.where("filter","is",null);let X=await J.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let G=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:G,updated_at:G}).execute(),{id:Q.id,organizationId:Q.organizationId,connectionId:Q.connectionId,publisher:Q.publisher??null,eventType:Q.eventType,filter:Q.filter??null,enabled:!0,createdAt:G,updatedAt:G}}async unsubscribe(Q,J){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Q).where("organization_id","=",J).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Q,J){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q);if(J)X=X.where("connection_id","=",J);return(await X.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 getSubscription(Q,J){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.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((X)=>X.or([X("publisher","is",null),X("publisher","=",Q.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Q,J,X){if(J.length===0)return;let G=new Date().toISOString(),Y=X??null,W=J.map(($)=>({id:crypto.randomUUID(),event_id:Q,subscription_id:$,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:Y,created_at:G}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(Q){let J=new Date().toISOString(),X;try{X=(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(($)=>$.or([$("d.next_retry_at","is",null),$("d.next_retry_at","<=",J)])).orderBy("d.created_at","asc").limit(Q)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let Y=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","<=",J)])).orderBy("d.created_at","asc").limit(Q).execute();if(Y.length===0)return[];X=Y.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.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",X).where("d.status","=","processing").execute()).map((Y)=>({delivery:{id:Y.delivery_id,eventId:Y.event_id,subscriptionId:Y.subscription_id,status:Y.delivery_status,attempts:Y.delivery_attempts,lastError:Y.delivery_last_error,deliveredAt:Y.delivered_at,nextRetryAt:Y.delivery_next_retry_at,createdAt:Y.delivery_created_at},event:{id:Y.event_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.event_status,attempts:Y.event_attempts,lastError:Y.event_last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.event_created_at,updatedAt:Y.event_updated_at},subscription:{id:Y.subscription_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.subscription_created_at,updatedAt:Y.subscription_updated_at}}))}async markDeliveriesDelivered(Q){if(Q.length===0)return;let J=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:J}).where("id","in",Q).execute()}async markDeliveriesFailed(Q,J,X=20,G=1000,Y=3600000){if(Q.length===0)return;for(let W of Q){let $=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!$)continue;let K=$.attempts+1;if(K>=X)await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let Z=Math.min(G*Math.pow(2,K-1),Y),H=new Date(Date.now()+Z).toISOString();await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(Q){let J=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Q).execute();if(J.length===0)return;let X=J.every((W)=>W.status==="delivered"),G=J.some((W)=>W.status==="failed"),Y=J.some((W)=>W.status==="pending"||W.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Q).execute();else if(G&&!Y)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,J){let X=await this.db.selectFrom("events").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async cancelEvent(Q,J,X){let G=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Q).where("organization_id","=",J).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((G.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:(G.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Q,J){if(Q.length===0)return;let X=new Date(Date.now()+J).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Q).execute()}async ackDelivery(Q,J,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Q).where("organization_id","=",J).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(($)=>$.exists($.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",J))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(Q);return{success:W}}async syncSubscriptions(Q){let{organizationId:J,connectionId:X,subscriptions:G}=Q,Y=(w,A)=>{return`${w}::${A??""}`},W=await this.listSubscriptions(J,X),$=new Map;for(let w of W)$.set(Y(w.eventType,w.publisher),w);let K=new Map;for(let w of G)K.set(Y(w.eventType,w.publisher),w);let Z=new Date().toISOString(),H=[],q=[],F=[],V=0;for(let[w,A]of K){let P=$.get(w);if(!P)H.push({id:crypto.randomUUID(),organization_id:J,connection_id:X,event_type:A.eventType,publisher:A.publisher??null,filter:A.filter??null,enabled:1,created_at:Z,updated_at:Z});else{let M=P.filter??null,T=A.filter??null;if(M!==T)q.push({id:P.id,filter:T});else V++}}for(let[w,A]of $)if(!K.has(w))F.push(A.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(q.length>0)await Promise.all(q.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:Z}).where("id","=",w.id).execute()));if(F.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",F).execute();let z=H.length,U=q.length,N=F.length,D=await this.listSubscriptions(J,X);return{created:z,updated:U,deleted:N,unchanged:V,subscriptions:D}}}function CK1(Q){return new IK1(Q)}function $Q(Q,J,X,G,Y,W,$,K){return $Q.fromTZ($Q.tp(Q,J,X,G,Y,W,$),K)}function fQ0(Q,J=new Date){let X=J.toLocaleString("en-US",{timeZone:Q,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],G=J.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${G} GMT`)-Date.parse(`${G} ${X}`)}function Wy4(Q,J){let X=new Date(Date.parse(Q));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let G=Q.substring(9);return Q.includes("Z")||G.includes("-")||G.includes("+")?$Q.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):$Q.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),J)}function $y4(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 HY(Q.startAt,Q.timezone)),Q.stopAt&&(Q.stopAt=new HY(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 yM(Q){return Object.prototype.toString.call(Q)==="[object Function]"||typeof Q=="function"||Q instanceof Function}function Ky4(Q){return yM(Q)}function Zy4(Q){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Q):Q&&typeof Q.unref<"u"&&Q.unref()}var bQ0=32,hM,kK1,RK1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Q,J){this.pattern=Q,this.timezone=J,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 J=new HY(new Date,this.timezone).getDate(!0);Q[0]=Q[0].replace("?",J.getSeconds().toString()),Q[1]=Q[1].replace("?",J.getMinutes().toString()),Q[2]=Q[2].replace("?",J.getHours().toString()),this.starDOM||(Q[3]=Q[3].replace("?",J.getDate().toString())),Q[4]=Q[4].replace("?",(J.getMonth()+1).toString()),this.starDOW||(Q[5]=Q[5].replace("?",J.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,hM),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Q,J,X,G){let Y=this[Q],W=Q==="day"&&this.lastDayOfMonth;if(J===""&&!W)throw TypeError("CronPattern: configuration entry "+Q+" ("+J+") is empty, check for trailing spaces.");if(J==="*")return Y.fill(G);let $=J.split(",");if($.length>1)for(let K=0;K<$.length;K++)this.partToArray(Q,$[K],X,G);else J.indexOf("-")!==-1&&J.indexOf("/")!==-1?this.handleRangeWithStepping(J,Q,X,G):J.indexOf("-")!==-1?this.handleRange(J,Q,X,G):J.indexOf("/")!==-1?this.handleStepping(J,Q,X,G):J!==""&&this.handleNumber(J,Q,X,G)}throwAtIllegalCharacters(Q){for(let J=0;J<Q.length;J++)if((J===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Q[J]))throw TypeError("CronPattern: configuration entry "+J+" ("+Q[J]+") contains illegal characters.")}handleNumber(Q,J,X,G){let Y=this.extractNth(Q,J),W=parseInt(Y[0],10)+X;if(isNaN(W))throw TypeError("CronPattern: "+J+" is not a number: '"+Q+"'");this.setPart(J,W,Y[1]||G)}setPart(Q,J,X){if(!Object.prototype.hasOwnProperty.call(this,Q))throw TypeError("CronPattern: Invalid part specified: "+Q);if(Q==="dayOfWeek"){if(J===7&&(J=0),J<0||J>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+J);this.setNthWeekdayOfMonth(J,X);return}if(Q==="second"||Q==="minute"){if(J<0||J>=60)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="hour"){if(J<0||J>=24)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="day"){if(J<0||J>=31)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="month"&&(J<0||J>=12))throw RangeError("CronPattern: Invalid value for "+Q+": "+J);this[Q][J]=X}handleRangeWithStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Q+"'");let[,$,K,Z]=W,H=parseInt($,10)+X,q=parseInt(K,10)+X,F=parseInt(Z,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(q))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(F===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(F>this[J].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[J].length+")");if(H>q)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let V=H;V<=q;V+=F)this.setPart(J,V,Y[1]||G)}extractNth(Q,J){let X=Q,G;if(X.includes("#")){if(J!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");G=X.split("#")[1],X=X.split("#")[0]}return[X,G]}handleRange(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Q+"'");let $=parseInt(W[0],10)+X,K=parseInt(W[1],10)+X;if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if($>K)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let Z=$;Z<=K;Z++)this.setPart(J,Z,Y[1]||G)}handleStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Q+"'");W[0]===""&&(W[0]="*");let $=0;W[0]!=="*"&&($=parseInt(W[0],10)+X);let K=parseInt(W[1],10);if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(K===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(K>this[J].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[J].length+")");for(let Z=$;Z<this[J].length;Z+=K)this.setPart(J,Z,Y[1]||G)}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 J=Q.trim().toLowerCase();return J==="@yearly"||J==="@annually"?"0 0 1 1 *":J==="@monthly"?"0 0 1 * *":J==="@weekly"?"0 0 * * 0":J==="@daily"?"0 0 * * *":J==="@hourly"?"0 * * * *":Q}setNthWeekdayOfMonth(Q,J){if(typeof J!="number"&&J==="L")this.dayOfWeek[Q]=this.dayOfWeek[Q]|bQ0;else if(J===hM)this.dayOfWeek[Q]=hM;else if(J<6&&J>0)this.dayOfWeek[Q]=this.dayOfWeek[Q]|kK1[J-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${J}, Type: ${typeof J}`)}},SK1,G$,HY=class Q{tz;ms;second;minute;hour;day;month;year;constructor(J,X){if(this.tz=X,J&&J instanceof Date)if(!isNaN(J))this.fromDate(J);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(J===void 0)this.fromDate(new Date);else if(J&&typeof J=="string")this.fromString(J);else if(J instanceof Q)this.fromCronDate(J);else throw TypeError("CronDate: Invalid type ("+typeof J+") passed to CronDate constructor")}isNthWeekdayOfMonth(J,X,G,Y){let W=new Date(Date.UTC(J,X,G)).getUTCDay(),$=0;for(let K=1;K<=G;K++)new Date(Date.UTC(J,X,K)).getUTCDay()===W&&$++;if(Y&hM&&kK1[$-1]&Y)return!0;if(Y&bQ0){let K=new Date(Date.UTC(J,X+1,0)).getUTCDate();for(let Z=G+1;Z<=K;Z++)if(new Date(Date.UTC(J,X,Z)).getUTCDay()===W)return!1;return!0}return!1}fromDate(J){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes()+this.tz,this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),this.apply();else{let X=$Q.toTZ(J,this.tz);this.ms=J.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=J.getMilliseconds(),this.second=J.getSeconds(),this.minute=J.getMinutes(),this.hour=J.getHours(),this.day=J.getDate(),this.month=J.getMonth(),this.year=J.getFullYear()}fromCronDate(J){this.tz=J.tz,this.year=J.year,this.month=J.month,this.day=J.day,this.hour=J.hour,this.minute=J.minute,this.second=J.second,this.ms=J.ms}apply(){if(this.month>11||this.day>SK1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let J=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes(),this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),!0}else return!1}fromString(J){if(typeof this.tz=="number"){let X=$Q.fromTZISO(J);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(),this.apply()}else return this.fromDate($Q.fromTZISO(J,this.tz))}findNext(J,X,G,Y){let W=this[X],$;G.lastDayOfMonth&&(this.month!==1?$=SK1[this.month]:$=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let K=!G.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let Z=this[X]+Y;Z<G[X].length;Z++){let H=G[X][Z];if(X==="day"&&G.lastDayOfMonth&&Z-Y==$&&(H=1),X==="day"&&!G.starDOW){let q=G.dayOfWeek[(K+(Z-Y-1))%7];if(q&&q&hM)q=this.isNthWeekdayOfMonth(this.year,this.month,Z-Y,q)?1:0;else if(q)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${q}`);J.legacyMode&&!G.starDOM?H=H||q:H=H&&q}if(H)return this[X]=Z-Y,W!==this[X]?2:1}return 3}recurse(J,X,G){let Y=this.findNext(X,G$[G][0],J,G$[G][2]);if(Y>1){let W=G+1;for(;W<G$.length;)this[G$[W][0]]=-G$[W][2],W++;if(Y===3)return this[G$[G][1]]++,this[G$[G][0]]=-G$[G][2],this.apply(),this.recurse(J,X,0);if(this.apply())return this.recurse(J,X,G-1)}return G+=1,G>=G$.length?this:this.year>=3000?null:this.recurse(J,X,G)}increment(J,X,G){return this.second+=X.interval!==void 0&&X.interval>1&&G?X.interval:1,this.ms=0,this.apply(),this.recurse(J,X,0)}getDate(J){return J||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)):$Q.fromTZ($Q.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},vK1=30000,_y,yy=class{name;options;_states;fn;constructor(Q,J,X){let G,Y;if(yM(J))Y=J;else if(typeof J=="object")G=J;else if(J!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(yM(X))Y=X;else if(typeof X=="object")G=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=G?.name,this.options=$y4(G),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:G?G.maxRuns:void 0,paused:G?G.paused:!1,pattern:new RK1("* * * * *")},Q&&(Q instanceof Date||typeof Q=="string"&&Q.indexOf(":")>0)?this._states.once=new HY(Q,this.options.timezone||this.options.utcOffset):this._states.pattern=new RK1(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 Y!==void 0&&Ky4(Y)&&(this.fn=Y,this.schedule()),this}nextRun(Q){let J=this._next(Q);return J?J.getDate(!1):null}nextRuns(Q,J){this._states.maxRuns!==void 0&&Q>this._states.maxRuns&&(Q=this._states.maxRuns);let X=[],G=J||this._states.currentRun||void 0;for(;Q--&&(G=this.nextRun(G));)X.push(G);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Q=this.nextRun(this._states.currentRun),J=!this._states.paused,X=this.fn!==void 0,G=!this._states.kill;return J&&X&&G&&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 J=this._next(Q);return J?Q instanceof HY||Q instanceof Date?J.getTime()-Q.getTime():J.getTime()-new HY(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 J=this.msToNext(),X=this.nextRun(this._states.currentRun);return J==null||isNaN(J)||X===null?this:(J>vK1&&(J=vK1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),J),this._states.currentTimeout&&this.options.unref&&Zy4(this._states.currentTimeout),this)}async _trigger(Q){if(this._states.blocking=!0,this._states.currentRun=new HY(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(J){yM(this.options.catch)&&this.options.catch(J,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new HY(Q,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Q){let J=new Date,X=!this._states.paused&&J.getTime()>=Q.getTime(),G=this._states.blocking&&this.options.protect;X&&!G?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&G&&yM(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Q){let J=!!(Q||this._states.currentRun),X=!1;!Q&&this.options.startAt&&this.options.interval&&([Q,J]=this._calculatePreviousRun(Q,J),X=!Q),Q=new HY(Q,this.options.timezone||this.options.utcOffset),this.options.startAt&&Q&&Q.getTime()<this.options.startAt.getTime()&&(Q=this.options.startAt);let G=this._states.once||new HY(Q,this.options.timezone||this.options.utcOffset);return!X&&G!==this._states.once&&(G=G.increment(this._states.pattern,this.options,J)),this._states.once&&this._states.once.getTime()<=Q.getTime()||G===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&G.getTime()>=this.options.stopAt.getTime()?null:G}_calculatePreviousRun(Q,J){let X=new HY(void 0,this.options.timezone||this.options.utcOffset),G=Q;if(this.options.startAt.getTime()<=X.getTime()){G=this.options.startAt;let Y=G.getTime()+this.options.interval*1000;for(;Y<=X.getTime();)G=new HY(G,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),Y=G.getTime()+this.options.interval*1000;J=!0}return G===null&&(G=void 0),[G,J]}};var xQ0=h(()=>{$Q.fromTZISO=(Q,J,X)=>$Q.fromTZ(Wy4(Q,J),X);$Q.fromTZ=function(Q,J){let X=new Date(Date.UTC(Q.y,Q.m-1,Q.d,Q.h,Q.i,Q.s)),G=fQ0(Q.tz,X),Y=new Date(X.getTime()-G),W=fQ0(Q.tz,Y);if(W-G===0)return Y;{let $=new Date(X.getTime()-W),K=fQ0(Q.tz,$);if(K-W===0)return $;if(!J&&K-W>0)return $;if(J)throw Error("Invalid date passed to fromTZ()");return Y}};$Q.toTZ=function(Q,J){let X=Q.toLocaleString("en-US",{timeZone:J}).replace(/[\u202f]/," "),G=new Date(X);return{y:G.getFullYear(),m:G.getMonth()+1,d:G.getDate(),h:G.getHours(),i:G.getMinutes(),s:G.getSeconds(),tz:J}};$Q.tp=(Q,J,X,G,Y,W,$)=>({y:Q,m:J,d:X,h:G,i:Y,s:W,tz:$});$Q.minitz=$Q;hM=31|bQ0,kK1=[1,2,4,8,16],SK1=[31,28,31,30,31,30,31,31,30,31,30,31],G$=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];_y=[]});var hy;var gQ0=h(()=>{hy={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function _K1(){return async(Q,J)=>{try{let X=await kZ.create(),G=await wK1(Q,{...X,auth:{...X.auth,user:{id:"notify-worker"}}}),W=await Z00.forClient(G).ON_EVENTS({events:J});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(X){let G=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Q}:`,G),{success:!1,error:G}}}}var yK1=h(()=>{vy();qv();ky()});function hK1(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 Hy4(Q){let J=new Map;for(let G of Q){let Y=G.subscription.connectionId,W=J.get(Y);if(W){if(W.deliveryIds.push(G.delivery.id),!W.seenEventIds.has(G.event.id))W.seenEventIds.add(G.event.id),W.events.push(hK1(G.event))}else J.set(Y,{connectionId:G.subscription.connectionId,deliveryIds:[G.delivery.id],events:[hK1(G.event)],seenEventIds:new Set([G.event.id])})}let X=new Map;for(let[G,Y]of J)X.set(G,{connectionId:Y.connectionId,deliveryIds:Y.deliveryIds,events:Y.events});return X}class uQ0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Q,J){this.storage=Q;this.notifySubscriber=_K1(),this.config={...hy,...J}}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 J=Hy4(Q),X=new Set;for(let[G,Y]of J){try{let W=await this.notifySubscriber(Y.connectionId,Y.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(Y,W);else if(W.success)await this.storage.markDeliveriesDelivered(Y.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(Y.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(Y.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let $=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${G}:`,$),await this.storage.markDeliveriesFailed(Y.deliveryIds,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of Q)if(Y.deliveryIds.includes(W.delivery.id))X.add(W.event.id)}for(let G of X)try{await this.storage.updateEventStatus(G);let Y=Q.find((W)=>W.event.id===G)?.event;if(Y?.cron)await this.scheduleNextCronDelivery(Y)}catch(Y){console.error(`[EventBus] Failed to update event status ${G}:`,Y)}}async processPerEventResults(Q,J){let X=[],G=new Map,Y=[],W=new Map;for(let $=0;$<Q.events.length;$++){let K=Q.events?.[$];if(!K)continue;let Z=Q.deliveryIds?.[$];if(!Z)continue;W.set(K.id,Z)}for(let $ of Q.events){let K=W.get($.id);if(!K)continue;let Z=J.results?.[$.id];if(Z)if(Z.success)X.push(K);else if(Z.retryAfter&&Z.retryAfter>0){let H=G.get(Z.retryAfter)||[];H.push(K),G.set(Z.retryAfter,H)}else Y.push({deliveryId:K,error:Z.error||"Event processing failed"});else if(J.success)X.push(K);else if(J.retryAfter&&J.retryAfter>0){let H=G.get(J.retryAfter)||[];H.push(K),G.set(J.retryAfter,H)}else Y.push({deliveryId:K,error:J.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[$,K]of G)await this.storage.scheduleRetryWithoutAttemptIncrement(K,$);if(Y.length>0){let $=new Map;for(let{deliveryId:K,error:Z}of Y){let H=$.get(Z)||[];H.push(K),$.set(Z,H)}for(let[K,Z]of $)await this.storage.markDeliveriesFailed(Z,K,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Q){if(!Q.cron)return;try{let X=new yy(Q.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Q.id} has no more runs`);return}let G=X.toISOString(),Y=await this.storage.getMatchingSubscriptions(Q);if(Y.length===0){console.log(`[EventBus] No subscriptions for cron event ${Q.id}, skipping next delivery`);return}await this.storage.createDeliveries(Q.id,Y.map((W)=>W.id),G),console.log(`[EventBus] Scheduled next cron delivery for event ${Q.id} at ${G}`)}catch(J){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Q.id}:`,J)}}}var fK1=h(()=>{xQ0();gQ0();yK1()});class mQ0{storage;worker;notifyStrategy;running=!1;constructor(Q){this.storage=Q.storage,this.notifyStrategy=Q.notifyStrategy,this.worker=new uQ0(this.storage,Q.config)}async publish(Q,J,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let G;if(X.cron)try{let H=new yy(X.cron).nextRun();if(!H)throw Error("Cron expression does not produce a next run time");G=H.toISOString()}catch(Z){throw Error(`Invalid cron expression: ${Z instanceof Error?Z.message:String(Z)}`)}let Y=crypto.randomUUID(),W=new Date().toISOString(),$=await this.storage.publishEvent({id:Y,organizationId:Q,type:X.type,source:J,subject:X.subject,time:W,data:X.data,cron:X.cron}),K=await this.storage.getMatchingSubscriptions($);if(K.length>0){let Z=X.deliverAt??G;if(await this.storage.createDeliveries(Y,K.map((H)=>H.id),Z),this.notifyStrategy&&!Z)await this.notifyStrategy.notify(Y).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return $}async subscribe(Q,J){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Q,connectionId:J.connectionId,publisher:J.publisher,eventType:J.eventType,filter:J.filter})}async unsubscribe(Q,J){return this.storage.unsubscribe(J,Q)}async listSubscriptions(Q,J){return this.storage.listSubscriptions(Q,J)}async getSubscription(Q,J){return this.storage.getSubscription(J,Q)}async getEvent(Q,J){return this.storage.getEvent(J,Q)}async cancelEvent(Q,J,X){return this.storage.cancelEvent(J,Q,X)}async ackEvent(Q,J,X){return this.storage.ackDelivery(J,Q,X)}async syncSubscriptions(Q,J){return this.storage.syncSubscriptions({organizationId:Q,...J})}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}}var bK1=h(()=>{xQ0();fK1()});function xK1(...Q){return{async start(J){await Promise.all(Q.map((X)=>X.start(J)))},async stop(){await Promise.all(Q.map((J)=>J.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(J){await Promise.all(Q.map((X)=>X.notify(J).catch((G)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",G)})))}}}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 qy4}from"kysely";class lQ0{db;pool;listenClient=null;onNotify=null;constructor(Q,J){this.db=Q;this.pool=J}async start(Q){if(this.listenClient)return;this.onNotify=Q;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(J)=>{if(J.channel===AN&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(J)=>{console.error("[PostgresNotify] Connection error:",J),this.cleanup()}),await this.listenClient.query(`LISTEN ${AN}`),console.log("[PostgresNotify] Started LISTEN on",AN)}catch(J){console.error("[PostgresNotify] Failed to start LISTEN:",J),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${AN}`),console.log("[PostgresNotify] Stopped LISTEN on",AN)}catch{}this.cleanup()}}async notify(Q){try{await qy4`SELECT pg_notify(${AN}, ${Q})`.execute(this.db)}catch(J){console.warn("[PostgresNotify] Failed to send NOTIFY:",J)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var AN="mesh_events";var gK1=()=>{};function uK1(Q,J){let X=CK1(Q.db),G=J?.pollIntervalMs??hy.pollIntervalMs,Y=Q.type==="postgres"?xK1(new fy(G),new lQ0(Q.db,Q.pool)):new fy(G);return new mQ0({storage:X,config:J,notifyStrategy:Y})}var mK1=h(()=>{bK1();gQ0();gK1()});var lK1;var dK1=h(()=>{lK1={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 pK1,cK1;var nK1=h(()=>{vZ();BU();dK1();pK1=new gQ;pK1.get("/config",async(Q)=>{try{let J=Object.keys(F9.socialProviders??{}),X=J.length>0,G=J.map((W)=>({name:W,icon:lK1[W].icon})),Y={emailAndPassword:{enabled:F9.emailAndPassword?.enabled??!1},magicLink:{enabled:F9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:X,providers:G},sso:F9.ssoConfig?{enabled:!0,providerId:F9.ssoConfig.providerId}:{enabled:!1}};return Q.json({success:!0,config:Y})}catch(J){let X=J instanceof Error?J.message:"Failed to load auth config";return Q.json({success:!1,error:X},500)}});cK1=pK1});class fM{proxies=new Map;constructor(){}static async create(Q,J){let X=new fM,G=await Promise.allSettled(Q.map(async({connection:Y,selectedTools:W})=>{try{let $=await J.createMCPProxy(Y);return{connection:Y,proxy:$,selectedTools:W}}catch($){return console.error(`[gateway] Failed to create proxy for connection ${Y.id}:`,$),null}}));for(let Y of G)if(Y.status==="fulfilled"&&Y.value)X.proxies.set(Y.value.connection.id,Y.value);return X}get(Q){return this.proxies.get(Q)}entries(){return this.proxies.entries()}forEach(Q){this.proxies.forEach((J,X)=>Q(J,X))}async mapAsync(Q){let J=[];for(let[X,G]of this.proxies.entries())J.push(Q(G,X));return await Promise.all(J)}async mapSettled(Q){return Promise.allSettled(Array.from(this.proxies.entries()).map(([J,X])=>Q(X,J)))}get size(){return this.proxies.size}}function Fy4(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((J)=>J.length>=2)}function Vy4(Q,J){let X=0,G=J.name.toLowerCase(),Y=(J.description??"").toLowerCase(),W=J.connectionTitle.toLowerCase();for(let $ of Q){if(G===$)X+=10;else if(G.includes($))X+=3;if(Y.includes($))X+=2;if(W.includes($))X+=1}return X}function zy4(Q,J,X){let G=Fy4(Q);if(G.length===0)return J.slice(0,X);return J.map((Y)=>({tool:Y,score:Vy4(G,Y)})).filter((Y)=>Y.score>0).sort((Y,W)=>W.score-Y.score).slice(0,X).map((Y)=>Y.tool)}function Uy4(Q){let J=Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:"",X=Q.tools.map((G)=>G.name);return[{name:_Z.SEARCH,description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${J} Total tools: ${Q.tools.length}.`,inputSchema:{type:"object",properties:{query:{type:"string",description:"Natural language search query (e.g., 'send email', 'create order')"},limit:{type:"number",description:"Maximum results to return (default: 10)",default:10}},required:["query"]}},{name:_Z.DESCRIBE,description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:{type:"object",properties:{tools:{type:"array",items:{type:"string",enum:X},description:"Array of tool names to get detailed schemas for"}},required:["tools"]}},{name:_Z.CALL,description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:{type:"object",properties:{name:{type:"string",enum:X,description:"The name of the tool to execute"},arguments:{type:"object",description:"Arguments to pass to the tool",additionalProperties:!0}},required:["name"]}}]}function rK1(Q){switch(Q){case"smart_tool_selection":return Ny4;case"code_execution":return iK1;case"passthrough":default:return iK1}}var iK1=(Q)=>({tools:Q.tools,callTool:(J,X)=>Q.callTool(J,X)}),_Z,Ny4=(Q)=>{let J=new Map(Q.tools.map((G)=>[G.name,G])),X=async(G,Y)=>{switch(G){case _Z.SEARCH:{let W=Y.query??"",$=Y.limit??10,K=zy4(W,Q.tools,$);return{content:[{type:"text",text:JSON.stringify({query:W,results:K.map((Z)=>({name:Z.name,description:Z.description,connection:Z.connectionTitle})),totalAvailable:Q.tools.length},null,2)}]}}case _Z.DESCRIBE:{let W=Y.tools??[];if(W.length===0)return{content:[{type:"text",text:JSON.stringify({error:"No tool names provided"})}],isError:!0};let $=W.map((K)=>J.get(K)).filter((K)=>K!==void 0);return{content:[{type:"text",text:JSON.stringify({tools:$.map((K)=>({name:K.name,description:K.description,connection:K.connectionTitle,inputSchema:K.inputSchema,outputSchema:K.outputSchema})),notFound:W.filter((K)=>!J.has(K))},null,2)}]}}case _Z.CALL:{let W=Y.name,$=Y.arguments??{};if(!W)return{content:[{type:"text",text:JSON.stringify({error:"Tool name is required"})}],isError:!0};if(!J.has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use ${_Z.SEARCH} to find available tools.`}],isError:!0};return Q.callTool(W,$)}default:return{content:[{type:"text",text:`Unknown meta-tool: ${G}. Available: ${Object.values(_Z).join(", ")}`}],isError:!0}}};return{tools:Uy4(Q),callTool:X}};var aK1=h(()=>{_Z={SEARCH:"GATEWAY_SEARCH_TOOLS",DESCRIBE:"GATEWAY_DESCRIBE_TOOLS",CALL:"GATEWAY_CALL_TOOL"}});class by{proxies;options;cache;constructor(Q,J){this.proxies=Q;this.options=J;this.cache=RG(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(Z,H)=>{try{let F=(await Z.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>!V.has(z.name))}}else if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>V.has(z.name))}return{connectionId:H,connectionTitle:Z.connection.title,tools:F}}catch(q){return console.error(`[gateway] Failed to list tools for connection ${H}:`,q),null}}),J=new Set,X=[],G=new Map,Y=new Set;for(let Z of Q){if(Z.status!=="fulfilled"||!Z.value)continue;let{connectionId:H,connectionTitle:q,tools:F}=Z.value;Y.add(q);for(let V of F){if(J.has(V.name))continue;J.add(V.name),X.push({...V,connectionId:H,connectionTitle:q}),G.set(V.name,{connectionId:H,originalName:V.name})}}let W=async(Z,H)=>{let q=G.get(Z);if(!q)return{content:[{type:"text",text:`Tool not found: ${Z}`}],isError:!0};let F=this.proxies.get(q.connectionId);if(!F)return{content:[{type:"text",text:`Connection not found for tool: ${Z}`}],isError:!0};return await F.proxy.client.callTool({name:q.originalName,arguments:H})},K=rK1(this.options.strategy)({tools:X,callTool:W,categories:Array.from(Y).sort()});return{tools:X,mappings:G,strategyResult:K}}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,J){let X=await this.cache,G=X.mappings.get(Q);if(G){let W=this.proxies.get(G.connectionId);if(W)return W.proxy.callStreamableTool(G.originalName,J)}let Y=await X.strategyResult.callTool(Q,J);return new Response(JSON.stringify(Y),{headers:{"Content-Type":"application/json"}})}}var oK1=h(()=>{aK1()});class xy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=RG(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listResources();return{connectionId:W,resources:$.resources}}catch($){return console.error(`[gateway] Failed to list resources for connection ${W}:`,$),{connectionId:W,resources:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,resources:$}=Y.value;for(let K of $){if(J.has(K.uri))continue;J.add(K.uri),X.push(K),G.set(K.uri,W)}}return{resources:X,mappings:G}}async list(){return{resources:(await this.cache).resources}}async read(Q){let X=(await this.cache).mappings.get(Q.uri);if(!X)throw Error(`Resource not found: ${Q.uri}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for resource: ${Q.uri}`);return await G.proxy.client.readResource(Q)}}var sK1=()=>{};class gy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=RG(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(X,G)=>{try{let Y=await X.proxy.client.listResourceTemplates();return{connectionId:G,templates:Y.resourceTemplates}}catch(Y){return console.error(`[gateway] Failed to list resource templates for connection ${G}:`,Y),{connectionId:G,templates:[]}}}),J=[];for(let X of Q){if(X.status!=="fulfilled")continue;let{templates:G}=X.value;for(let Y of G)J.push(Y)}return{templates:J}}async list(){return{resourceTemplates:(await this.cache).templates}}}var tK1=()=>{};class uy{proxies;cache;constructor(Q){this.proxies=Q;this.cache=RG(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listPrompts();return{connectionId:W,prompts:$.prompts}}catch($){return console.error(`[gateway] Failed to list prompts for connection ${W}:`,$),{connectionId:W,prompts:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,prompts:$}=Y.value;for(let K of $){if(J.has(K.name))continue;J.add(K.name),X.push(K),G.set(K.name,W)}}return{prompts:X,mappings:G}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let X=(await this.cache).mappings.get(Q.name);if(!X)throw Error(`Prompt not found: ${Q.name}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for prompt: ${Q.name}`);return await G.proxy.client.getPrompt(Q)}}var eK1=()=>{};var QZ1=h(()=>{oK1();sK1();tK1();eK1()});async function By4(Q,J){let X=await fM.create(Q.connections,J),G=new by(X,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),Y=new xy(X),W=new gy(X),$=new uy(X);return{client:{listTools:G.list.bind(G),callTool:G.call.bind(G),listResources:Y.list.bind(Y),readResource:Y.read.bind(Y),listResourceTemplates:W.list.bind(W),listPrompts:$.list.bind($),getPrompt:$.get.bind($)},callStreamableTool:G.callStreamable.bind(G)}}async function Oy4(Q,J){let X;if(Q.toolSelectionMode==="exclusion"){let W=(await J.storage.connections.list(Q.organizationId)).filter((K)=>K.status==="active"),$=new Map;for(let K of Q.connections)$.set(K.connectionId,K.selectedTools);X=[];for(let K of W){let Z=$.get(K.id);if(Z===void 0)X.push({connection:K,selectedTools:null});else if(Z===null||Z.length===0);else X.push({connection:K,selectedTools:Z})}}else{let Y=Q.connections.map(($)=>$.connectionId),W=[];for(let $ of Y){let K=await J.storage.connections.findById($);if(K&&K.status==="active")W.push(K)}X=W.map(($)=>{let K=Q.connections.find((Z)=>Z.connectionId===$.id);return{connection:$,selectedTools:K?.selectedTools??null}})}let G={connections:X,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Q.toolSelectionStrategy};return By4(G,J)}var JZ1,XZ1;var YZ1=h(()=>{ES();aJ();vZ();QZ1();oS();JZ1=new gQ;JZ1.all("/gateway/:gatewayId?",async(Q)=>{let J=Q.req.param("gatewayId"),X=Q.get("meshContext");try{let G=null;if(J)G=await X.storage.gateways.findById(J);else{let Z=Q.req.header("x-org-id"),H=Q.req.header("x-org-slug");if(Z)G=await X.storage.gateways.getDefaultByOrgId(Z);else if(H)G=await X.storage.gateways.getDefaultByOrgSlug(H);else return Q.json({error:"Gateway ID required, or provide x-org-id or x-org-slug header for default gateway"},400)}if(!G){if(J)return Q.json({error:`Gateway not found: ${J}`},404);return Q.json({error:"No default gateway configured for this organization"},404)}if(X.gatewayId=G.id,G.status!=="active")return Q.json({error:`Gateway is inactive: ${G.id}`},503);let Y=await X.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",G.organizationId).executeTakeFirst();if(Y)X.organization={id:Y.id,slug:Y.slug,name:Y.name};let W=await Oy4(G,X),$=new _H({name:`mcp-gateway-${G.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),K=new lH({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await $.connect(K),$.server.setRequestHandler(lK,async(Z)=>{return W.client.listTools()}),$.server.setRequestHandler(dK,async(Z)=>{return await W.client.callTool(Z.params)}),$.server.setRequestHandler(bK,async()=>{return W.client.listResources()}),$.server.setRequestHandler(gK,async(Z)=>{return W.client.readResource(Z.params)}),$.server.setRequestHandler(xK,async()=>{return W.client.listResourceTemplates()}),$.server.setRequestHandler(uK,async()=>{return W.client.listPrompts()}),$.server.setRequestHandler(mK,async(Z)=>{return W.client.getPrompt(Z.params)}),await K.handleMessage(Q.req.raw).then(async(Z)=>{return Z})}catch(G){let Y=G;return console.error("[gateway] Error handling gateway request:",Y),Q.json({error:"Internal server error",message:Y.message},500)}});XZ1=JZ1});var GZ1,WZ1;var $Z1=h(()=>{vZ();a00();GZ1=new gQ;GZ1.all("/",async(Q)=>{return r00(Q.get("meshContext")).fetch(Q.req.raw)});WZ1=GZ1});function SG(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 hZ1="vercel.ai.error",Dy4,KZ1,ZZ1,L1,fZ1="AI_APICallError",bZ1,Ly4,HZ1,qZ1,O9,xZ1="AI_EmptyResponseBodyError",gZ1,wy4,FZ1,VZ1,uZ1,mZ1="AI_InvalidArgumentError",lZ1,Py4,zZ1,UZ1,dZ1,pZ1="AI_InvalidPromptError",cZ1,My4,NZ1,BZ1,lq,nZ1="AI_InvalidResponseDataError",iZ1,Ty4,OZ1,DZ1,up6,rZ1="AI_JSONParseError",aZ1,Ay4,LZ1,wZ1,bM,oZ1="AI_LoadAPIKeyError",sZ1,Ey4,PZ1,MZ1,mp6,tZ1="AI_LoadSettingError",eZ1,jy4,TZ1,AZ1,lp6,Q31="AI_NoContentGeneratedError",J31,Iy4,EZ1,jZ1,dp6,X31="AI_NoSuchModelError",Y31,Cy4,IZ1,CZ1,pp6,G31="AI_TooManyEmbeddingValuesForCallError",W31,Ry4,RZ1,SZ1,cp6,$31="AI_TypeValidationError",K31,Sy4,vZ1,kZ1,$7,Z31="AI_UnsupportedFunctionalityError",H31,vy4,_Z1,yZ1,np6;var D6=h(()=>{Dy4=Symbol.for(hZ1),L1=class Q extends(ZZ1=Error,KZ1=Dy4,ZZ1){constructor({name:J,message:X,cause:G}){super(X);this[KZ1]=!0,this.name=J,this.cause=G}static isInstance(J){return Q.hasMarker(J,hZ1)}static hasMarker(J,X){let G=Symbol.for(X);return J!=null&&typeof J==="object"&&G in J&&typeof J[G]==="boolean"&&J[G]===!0}},bZ1=`vercel.ai.error.${fZ1}`,Ly4=Symbol.for(bZ1),O9=class extends(qZ1=L1,HZ1=Ly4,qZ1){constructor({message:Q,url:J,requestBodyValues:X,statusCode:G,responseHeaders:Y,responseBody:W,cause:$,isRetryable:K=G!=null&&(G===408||G===409||G===429||G>=500),data:Z}){super({name:fZ1,message:Q,cause:$});this[HZ1]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=G,this.responseHeaders=Y,this.responseBody=W,this.isRetryable=K,this.data=Z}static isInstance(Q){return L1.hasMarker(Q,bZ1)}},gZ1=`vercel.ai.error.${xZ1}`,wy4=Symbol.for(gZ1),uZ1=class extends(VZ1=L1,FZ1=wy4,VZ1){constructor({message:Q="Empty response body"}={}){super({name:xZ1,message:Q});this[FZ1]=!0}static isInstance(Q){return L1.hasMarker(Q,gZ1)}};lZ1=`vercel.ai.error.${mZ1}`,Py4=Symbol.for(lZ1),dZ1=class extends(UZ1=L1,zZ1=Py4,UZ1){constructor({message:Q,cause:J,argument:X}){super({name:mZ1,message:Q,cause:J});this[zZ1]=!0,this.argument=X}static isInstance(Q){return L1.hasMarker(Q,lZ1)}},cZ1=`vercel.ai.error.${pZ1}`,My4=Symbol.for(cZ1),lq=class extends(BZ1=L1,NZ1=My4,BZ1){constructor({prompt:Q,message:J,cause:X}){super({name:pZ1,message:`Invalid prompt: ${J}`,cause:X});this[NZ1]=!0,this.prompt=Q}static isInstance(Q){return L1.hasMarker(Q,cZ1)}},iZ1=`vercel.ai.error.${nZ1}`,Ty4=Symbol.for(iZ1),up6=class extends(DZ1=L1,OZ1=Ty4,DZ1){constructor({data:Q,message:J=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:nZ1,message:J});this[OZ1]=!0,this.data=Q}static isInstance(Q){return L1.hasMarker(Q,iZ1)}},aZ1=`vercel.ai.error.${rZ1}`,Ay4=Symbol.for(aZ1),bM=class extends(wZ1=L1,LZ1=Ay4,wZ1){constructor({text:Q,cause:J}){super({name:rZ1,message:`JSON parsing failed: Text: ${Q}.
|
|
1081
1081
|
Error message: ${SG(J)}`,cause:J});this[LZ1]=!0,this.text=Q}static isInstance(Q){return L1.hasMarker(Q,aZ1)}},sZ1=`vercel.ai.error.${oZ1}`,Ey4=Symbol.for(sZ1),mp6=class extends(MZ1=L1,PZ1=Ey4,MZ1){constructor({message:Q}){super({name:oZ1,message:Q});this[PZ1]=!0}static isInstance(Q){return L1.hasMarker(Q,sZ1)}},eZ1=`vercel.ai.error.${tZ1}`,jy4=Symbol.for(eZ1),lp6=class extends(AZ1=L1,TZ1=jy4,AZ1){constructor({message:Q}){super({name:tZ1,message:Q});this[TZ1]=!0}static isInstance(Q){return L1.hasMarker(Q,eZ1)}},J31=`vercel.ai.error.${Q31}`,Iy4=Symbol.for(J31),dp6=class extends(jZ1=L1,EZ1=Iy4,jZ1){constructor({message:Q="No content generated."}={}){super({name:Q31,message:Q});this[EZ1]=!0}static isInstance(Q){return L1.hasMarker(Q,J31)}},Y31=`vercel.ai.error.${X31}`,Cy4=Symbol.for(Y31),pp6=class extends(CZ1=L1,IZ1=Cy4,CZ1){constructor({errorName:Q=X31,modelId:J,modelType:X,message:G=`No such ${X}: ${J}`}){super({name:Q,message:G});this[IZ1]=!0,this.modelId=J,this.modelType=X}static isInstance(Q){return L1.hasMarker(Q,Y31)}},W31=`vercel.ai.error.${G31}`,Ry4=Symbol.for(W31),cp6=class extends(SZ1=L1,RZ1=Ry4,SZ1){constructor(Q){super({name:G31,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[RZ1]=!0,this.provider=Q.provider,this.modelId=Q.modelId,this.maxEmbeddingsPerCall=Q.maxEmbeddingsPerCall,this.values=Q.values}static isInstance(Q){return L1.hasMarker(Q,W31)}},K31=`vercel.ai.error.${$31}`,Sy4=Symbol.for(K31),$7=class Q extends(kZ1=L1,vZ1=Sy4,kZ1){constructor({value:J,cause:X}){super({name:$31,message:`Type validation failed: Value: ${JSON.stringify(J)}.
|
|
1082
1082
|
Error message: ${SG(X)}`,cause:X});this[vZ1]=!0,this.value=J}static isInstance(J){return L1.hasMarker(J,K31)}static wrap({value:J,cause:X}){return Q.isInstance(X)&&X.value===J?X:new Q({value:J,cause:X})}},H31=`vercel.ai.error.${Z31}`,vy4=Symbol.for(H31),np6=class extends(yZ1=L1,_Z1=vy4,yZ1){constructor({functionality:Q,message:J=`'${Q}' functionality not supported.`}){super({name:Z31,message:J});this[_Z1]=!0,this.functionality=Q}static isInstance(Q){return L1.hasMarker(Q,H31)}}});function T0(Q,J,X){function G(K,Z){var H;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(H=K._zod).traits??(H.traits=new Set),K._zod.traits.add(Q),J(K,Z);for(let q in $.prototype)if(!(q in K))Object.defineProperty(K,q,{value:$.prototype[q].bind(K)});K._zod.constr=$,K._zod.def=Z}let Y=X?.Parent??Object;class W extends Y{}Object.defineProperty(W,"name",{value:Q});function $(K){var Z;let H=X?.Parent?new W:this;G(H,K),(Z=H._zod).deferred??(Z.deferred=[]);for(let q of H._zod.deferred)q();return H}return Object.defineProperty($,"init",{value:G}),Object.defineProperty($,Symbol.hasInstance,{value:(K)=>{if(X?.Parent&&K instanceof X.Parent)return!0;return K?._zod?.traits?.has(Q)}}),Object.defineProperty($,"name",{value:Q}),$}function j9(Q){if(Q)Object.assign(xM,Q);return xM}var dQ0,pQ0,W$,xM;var EN=h(()=>{dQ0=Object.freeze({status:"aborted"});pQ0=Symbol("zod_brand");W$=class W$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};xM={}});var H1={};B4(H1,{unwrapMessage:()=>gM,stringifyPrimitive:()=>Z1,required:()=>ry4,randomString:()=>gy4,propertyKeyTypes:()=>dM,promiseAllObject:()=>xy4,primitiveTypes:()=>oQ0,prefixIssues:()=>LJ,pick:()=>dy4,partial:()=>iy4,optionalKeys:()=>sQ0,omit:()=>py4,numKeys:()=>uy4,nullish:()=>yZ,normalizeParams:()=>W1,merge:()=>ny4,jsonStringifyReplacer:()=>nQ0,joinValues:()=>g0,issue:()=>QJ0,isPlainObject:()=>IN,isObject:()=>jN,getSizableOrigin:()=>pM,getParsedType:()=>my4,getLengthableOrigin:()=>cM,getEnumValues:()=>uM,getElementAtPath:()=>by4,floatSafeRemainder:()=>iQ0,finalizeIssue:()=>GX,extend:()=>cy4,escapeRegex:()=>$$,esc:()=>dq,defineLazy:()=>I6,createTransparentProxy:()=>ly4,clone:()=>YX,cleanRegex:()=>lM,cleanEnum:()=>ay4,captureStackTrace:()=>my,cached:()=>mM,assignProp:()=>rQ0,assertNotEqual:()=>_y4,assertNever:()=>hy4,assertIs:()=>yy4,assertEqual:()=>ky4,assert:()=>fy4,allowsEval:()=>aQ0,aborted:()=>pq,NUMBER_FORMAT_RANGES:()=>tQ0,Class:()=>q31,BIGINT_FORMAT_RANGES:()=>eQ0});function ky4(Q){return Q}function _y4(Q){return Q}function yy4(Q){}function hy4(Q){throw Error()}function fy4(Q){}function uM(Q){let J=Object.values(Q).filter((G)=>typeof G==="number");return Object.entries(Q).filter(([G,Y])=>J.indexOf(+G)===-1).map(([G,Y])=>Y)}function g0(Q,J="|"){return Q.map((X)=>Z1(X)).join(J)}function nQ0(Q,J){if(typeof J==="bigint")return J.toString();return J}function mM(Q){return{get value(){{let X=Q();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function yZ(Q){return Q===null||Q===void 0}function lM(Q){let J=Q.startsWith("^")?1:0,X=Q.endsWith("$")?Q.length-1:Q.length;return Q.slice(J,X)}function iQ0(Q,J){let X=(Q.toString().split(".")[1]||"").length,G=(J.toString().split(".")[1]||"").length,Y=X>G?X:G,W=Number.parseInt(Q.toFixed(Y).replace(".","")),$=Number.parseInt(J.toFixed(Y).replace(".",""));return W%$/10**Y}function I6(Q,J,X){Object.defineProperty(Q,J,{get(){{let Y=X();return Q[J]=Y,Y}throw Error("cached value already set")},set(Y){Object.defineProperty(Q,J,{value:Y})},configurable:!0})}function rQ0(Q,J,X){Object.defineProperty(Q,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function by4(Q,J){if(!J)return Q;return J.reduce((X,G)=>X?.[G],Q)}function xy4(Q){let J=Object.keys(Q),X=J.map((G)=>Q[G]);return Promise.all(X).then((G)=>{let Y={};for(let W=0;W<J.length;W++)Y[J[W]]=G[W];return Y})}function gy4(Q=10){let X="";for(let G=0;G<Q;G++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function dq(Q){return JSON.stringify(Q)}function jN(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function IN(Q){if(jN(Q)===!1)return!1;let J=Q.constructor;if(J===void 0)return!0;let X=J.prototype;if(jN(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function uy4(Q){let J=0;for(let X in Q)if(Object.prototype.hasOwnProperty.call(Q,X))J++;return J}function $$(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YX(Q,J,X){let G=new Q._zod.constr(J??Q._zod.def);if(!J||X?.parent)G._zod.parent=Q;return G}function W1(Q){let J=Q;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function ly4(Q){let J;return new Proxy({},{get(X,G,Y){return J??(J=Q()),Reflect.get(J,G,Y)},set(X,G,Y,W){return J??(J=Q()),Reflect.set(J,G,Y,W)},has(X,G){return J??(J=Q()),Reflect.has(J,G)},deleteProperty(X,G){return J??(J=Q()),Reflect.deleteProperty(J,G)},ownKeys(X){return J??(J=Q()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(X,G){return J??(J=Q()),Reflect.getOwnPropertyDescriptor(J,G)},defineProperty(X,G,Y){return J??(J=Q()),Reflect.defineProperty(J,G,Y)}})}function Z1(Q){if(typeof Q==="bigint")return Q.toString()+"n";if(typeof Q==="string")return`"${Q}"`;return`${Q}`}function sQ0(Q){return Object.keys(Q).filter((J)=>{return Q[J]._zod.optin==="optional"&&Q[J]._zod.optout==="optional"})}function dy4(Q,J){let X={},G=Q._zod.def;for(let Y in J){if(!(Y in G.shape))throw Error(`Unrecognized key: "${Y}"`);if(!J[Y])continue;X[Y]=G.shape[Y]}return YX(Q,{...Q._zod.def,shape:X,checks:[]})}function py4(Q,J){let X={...Q._zod.def.shape},G=Q._zod.def;for(let Y in J){if(!(Y in G.shape))throw Error(`Unrecognized key: "${Y}"`);if(!J[Y])continue;delete X[Y]}return YX(Q,{...Q._zod.def,shape:X,checks:[]})}function cy4(Q,J){if(!IN(J))throw Error("Invalid input to extend: expected a plain object");let X={...Q._zod.def,get shape(){let G={...Q._zod.def.shape,...J};return rQ0(this,"shape",G),G},checks:[]};return YX(Q,X)}function ny4(Q,J){return YX(Q,{...Q._zod.def,get shape(){let X={...Q._zod.def.shape,...J._zod.def.shape};return rQ0(this,"shape",X),X},catchall:J._zod.def.catchall,checks:[]})}function iy4(Q,J,X){let G=J._zod.def.shape,Y={...G};if(X)for(let W in X){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;Y[W]=Q?new Q({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)Y[W]=Q?new Q({type:"optional",innerType:G[W]}):G[W];return YX(J,{...J._zod.def,shape:Y,checks:[]})}function ry4(Q,J,X){let G=J._zod.def.shape,Y={...G};if(X)for(let W in X){if(!(W in Y))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;Y[W]=new Q({type:"nonoptional",innerType:G[W]})}else for(let W in G)Y[W]=new Q({type:"nonoptional",innerType:G[W]});return YX(J,{...J._zod.def,shape:Y,checks:[]})}function pq(Q,J=0){for(let X=J;X<Q.issues.length;X++)if(Q.issues[X]?.continue!==!0)return!0;return!1}function LJ(Q,J){return J.map((X)=>{var G;return(G=X).path??(G.path=[]),X.path.unshift(Q),X})}function gM(Q){return typeof Q==="string"?Q:Q?.message}function GX(Q,J,X){let G={...Q,path:Q.path??[]};if(!Q.message){let Y=gM(Q.inst?._zod.def?.error?.(Q))??gM(J?.error?.(Q))??gM(X.customError?.(Q))??gM(X.localeError?.(Q))??"Invalid input";G.message=Y}if(delete G.inst,delete G.continue,!J?.reportInput)delete G.input;return G}function pM(Q){if(Q instanceof Set)return"set";if(Q instanceof Map)return"map";if(Q instanceof File)return"file";return"unknown"}function cM(Q){if(Array.isArray(Q))return"array";if(typeof Q==="string")return"string";return"unknown"}function QJ0(...Q){let[J,X,G]=Q;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:G};return{...J}}function ay4(Q){return Object.entries(Q).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}class q31{constructor(...Q){}}var my,aQ0,my4=(Q)=>{let J=typeof Q;switch(J){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Q)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return"promise";if(typeof Map<"u"&&Q instanceof Map)return"map";if(typeof Set<"u"&&Q instanceof Set)return"set";if(typeof Date<"u"&&Q instanceof Date)return"date";if(typeof File<"u"&&Q instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${J}`)}},dM,oQ0,tQ0,eQ0;var K4=h(()=>{my=Error.captureStackTrace?Error.captureStackTrace:(...Q)=>{};aQ0=mM(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Q){return!1}});dM=new Set(["string","number","symbol"]),oQ0=new Set(["string","number","bigint","boolean","symbol","undefined"]);tQ0={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},eQ0={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function iM(Q,J=(X)=>X.message){let X={},G=[];for(let Y of Q.issues)if(Y.path.length>0)X[Y.path[0]]=X[Y.path[0]]||[],X[Y.path[0]].push(J(Y));else G.push(J(Y));return{formErrors:G,fieldErrors:X}}function rM(Q,J){let X=J||function(W){return W.message},G={_errors:[]},Y=(W)=>{for(let $ of W.issues)if($.code==="invalid_union"&&$.errors.length)$.errors.map((K)=>Y({issues:K}));else if($.code==="invalid_key")Y({issues:$.issues});else if($.code==="invalid_element")Y({issues:$.issues});else if($.path.length===0)G._errors.push(X($));else{let K=G,Z=0;while(Z<$.path.length){let H=$.path[Z];if(Z!==$.path.length-1)K[H]=K[H]||{_errors:[]};else K[H]=K[H]||{_errors:[]},K[H]._errors.push(X($));K=K[H],Z++}}};return Y(Q),G}function JJ0(Q,J){let X=J||function(W){return W.message},G={errors:[]},Y=(W,$=[])=>{var K,Z;for(let H of W.issues)if(H.code==="invalid_union"&&H.errors.length)H.errors.map((q)=>Y({issues:q},H.path));else if(H.code==="invalid_key")Y({issues:H.issues},H.path);else if(H.code==="invalid_element")Y({issues:H.issues},H.path);else{let q=[...$,...H.path];if(q.length===0){G.errors.push(X(H));continue}let F=G,V=0;while(V<q.length){let z=q[V],U=V===q.length-1;if(typeof z==="string")F.properties??(F.properties={}),(K=F.properties)[z]??(K[z]={errors:[]}),F=F.properties[z];else F.items??(F.items=[]),(Z=F.items)[z]??(Z[z]={errors:[]}),F=F.items[z];if(U)F.errors.push(X(H));V++}}};return Y(Q),G}function V31(Q){let J=[];for(let X of Q)if(typeof X==="number")J.push(`[${X}]`);else if(typeof X==="symbol")J.push(`[${JSON.stringify(String(X))}]`);else if(/[^\w$]/.test(X))J.push(`[${JSON.stringify(X)}]`);else{if(J.length)J.push(".");J.push(X)}return J.join("")}function XJ0(Q){let J=[],X=[...Q.issues].sort((G,Y)=>G.path.length-Y.path.length);for(let G of X)if(J.push(`\u2716 ${G.message}`),G.path?.length)J.push(` \u2192 at ${V31(G.path)}`);return J.join(`
|
|
1083
1083
|
`)}var F31=(Q,J)=>{Q.name="$ZodError",Object.defineProperty(Q,"_zod",{value:Q._zod,enumerable:!1}),Object.defineProperty(Q,"issues",{value:J,enumerable:!1}),Object.defineProperty(Q,"message",{get(){return JSON.stringify(J,nQ0,2)},enumerable:!0}),Object.defineProperty(Q,"toString",{value:()=>Q.message,enumerable:!1})},nM,CN;var YJ0=h(()=>{EN();K4();nM=T0("$ZodError",F31),CN=T0("$ZodError",F31,{Parent:Error})});var ly=(Q)=>(J,X,G,Y)=>{let W=G?Object.assign(G,{async:!1}):{async:!1},$=J._zod.run({value:X,issues:[]},W);if($ instanceof Promise)throw new W$;if($.issues.length){let K=new(Y?.Err??Q)($.issues.map((Z)=>GX(Z,W,j9())));throw my(K,Y?.callee),K}return $.value},dy,py=(Q)=>async(J,X,G,Y)=>{let W=G?Object.assign(G,{async:!0}):{async:!0},$=J._zod.run({value:X,issues:[]},W);if($ instanceof Promise)$=await $;if($.issues.length){let K=new(Y?.Err??Q)($.issues.map((Z)=>GX(Z,W,j9())));throw my(K,Y?.callee),K}return $.value},cy,ny=(Q)=>(J,X,G)=>{let Y=G?{...G,async:!1}:{async:!1},W=J._zod.run({value:X,issues:[]},Y);if(W instanceof Promise)throw new W$;return W.issues.length?{success:!1,error:new(Q??nM)(W.issues.map(($)=>GX($,Y,j9())))}:{success:!0,data:W.value}},GJ0,iy=(Q)=>async(J,X,G)=>{let Y=G?Object.assign(G,{async:!0}):{async:!0},W=J._zod.run({value:X,issues:[]},Y);if(W instanceof Promise)W=await W;return W.issues.length?{success:!1,error:new Q(W.issues.map(($)=>GX($,Y,j9())))}:{success:!0,data:W.value}},WJ0;var ry=h(()=>{EN();YJ0();K4();dy=ly(CN),cy=py(CN),GJ0=ny(CN),WJ0=iy(CN)});var nq={};B4(nq,{xid:()=>HJ0,uuid7:()=>Qh4,uuid6:()=>ey4,uuid4:()=>ty4,uuid:()=>cq,uppercase:()=>yJ0,unicodeEmail:()=>Yh4,undefined:()=>kJ0,ulid:()=>ZJ0,time:()=>AJ0,string:()=>jJ0,rfc5322Email:()=>Xh4,number:()=>RJ0,null:()=>vJ0,nanoid:()=>FJ0,lowercase:()=>_J0,ksuid:()=>qJ0,ipv6:()=>OJ0,ipv4:()=>BJ0,integer:()=>CJ0,html5Email:()=>Jh4,hostname:()=>PJ0,guid:()=>zJ0,extendedDuration:()=>sy4,emoji:()=>NJ0,email:()=>UJ0,e164:()=>MJ0,duration:()=>VJ0,domain:()=>$h4,datetime:()=>EJ0,date:()=>TJ0,cuid2:()=>KJ0,cuid:()=>$J0,cidrv6:()=>LJ0,cidrv4:()=>DJ0,browserEmail:()=>Gh4,boolean:()=>SJ0,bigint:()=>IJ0,base64url:()=>ay,base64:()=>wJ0,_emoji:()=>Wh4});function NJ0(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function U31(Q){return typeof Q.precision==="number"?Q.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Q.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${Q.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function AJ0(Q){return new RegExp(`^${U31(Q)}$`)}function EJ0(Q){let J=U31({precision:Q.precision}),X=["Z"];if(Q.local)X.push("");if(Q.offset)X.push("([+-]\\d{2}:\\d{2})");let G=`${J}(?:${X.join("|")})`;return new RegExp(`^${z31}T(?:${G})$`)}var $J0,KJ0,ZJ0,HJ0,qJ0,FJ0,VJ0,sy4,zJ0,cq=(Q)=>{if(!Q)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Q}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},ty4,ey4,Qh4,UJ0,Jh4,Xh4,Yh4,Gh4,Wh4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",BJ0,OJ0,DJ0,LJ0,wJ0,ay,PJ0,$h4,MJ0,z31="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",TJ0,jJ0=(Q)=>{let J=Q?`[\\s\\S]{${Q?.minimum??0},${Q?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)},IJ0,CJ0,RJ0,SJ0,vJ0,kJ0,_J0,yJ0;var oy=h(()=>{$J0=/^[cC][^\s-]{8,}$/,KJ0=/^[0-9a-z]+$/,ZJ0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,HJ0=/^[0-9a-vA-V]{20}$/,qJ0=/^[A-Za-z0-9]{27}$/,FJ0=/^[a-zA-Z0-9_-]{21}$/,VJ0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sy4=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zJ0=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ty4=cq(4),ey4=cq(6),Qh4=cq(7),UJ0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Jh4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Xh4=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Yh4=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Gh4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;BJ0=/^(?:(?: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])$/,OJ0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,DJ0=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,LJ0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wJ0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ay=/^[A-Za-z0-9_-]*$/,PJ0=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$h4=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,MJ0=/^\+(?:[0-9]){6,14}[0-9]$/,TJ0=new RegExp(`^${z31}$`);IJ0=/^\d+n?$/,CJ0=/^\d+$/,RJ0=/^-?\d+(?:\.\d+)?/i,SJ0=/true|false/i,vJ0=/null/i,kJ0=/undefined/i,_J0=/^[^A-Z]*$/,yJ0=/^[^a-z]*$/});function N31(Q,J,X){if(Q.issues.length)J.issues.push(...LJ(X,Q.issues))}var a8,B31,sy,ty,hJ0,fJ0,bJ0,xJ0,gJ0,uJ0,mJ0,lJ0,dJ0,RN,pJ0,cJ0,nJ0,iJ0,rJ0,aJ0,oJ0,sJ0,tJ0;var ey=h(()=>{EN();oy();K4();a8=T0("$ZodCheck",(Q,J)=>{var X;Q._zod??(Q._zod={}),Q._zod.def=J,(X=Q._zod).onattach??(X.onattach=[])}),B31={number:"number",bigint:"bigint",object:"date"},sy=T0("$ZodCheckLessThan",(Q,J)=>{a8.init(Q,J);let X=B31[typeof J.value];Q._zod.onattach.push((G)=>{let Y=G._zod.bag,W=(J.inclusive?Y.maximum:Y.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<W)if(J.inclusive)Y.maximum=J.value;else Y.exclusiveMaximum=J.value}),Q._zod.check=(G)=>{if(J.inclusive?G.value<=J.value:G.value<J.value)return;G.issues.push({origin:X,code:"too_big",maximum:J.value,input:G.value,inclusive:J.inclusive,inst:Q,continue:!J.abort})}}),ty=T0("$ZodCheckGreaterThan",(Q,J)=>{a8.init(Q,J);let X=B31[typeof J.value];Q._zod.onattach.push((G)=>{let Y=G._zod.bag,W=(J.inclusive?Y.minimum:Y.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>W)if(J.inclusive)Y.minimum=J.value;else Y.exclusiveMinimum=J.value}),Q._zod.check=(G)=>{if(J.inclusive?G.value>=J.value:G.value>J.value)return;G.issues.push({origin:X,code:"too_small",minimum:J.value,input:G.value,inclusive:J.inclusive,inst:Q,continue:!J.abort})}}),hJ0=T0("$ZodCheckMultipleOf",(Q,J)=>{a8.init(Q,J),Q._zod.onattach.push((X)=>{var G;(G=X._zod.bag).multipleOf??(G.multipleOf=J.value)}),Q._zod.check=(X)=>{if(typeof X.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%J.value===BigInt(0):iQ0(X.value,J.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:J.value,input:X.value,inst:Q,continue:!J.abort})}}),fJ0=T0("$ZodCheckNumberFormat",(Q,J)=>{a8.init(Q,J),J.format=J.format||"float64";let X=J.format?.includes("int"),G=X?"int":"number",[Y,W]=tQ0[J.format];Q._zod.onattach.push(($)=>{let K=$._zod.bag;if(K.format=J.format,K.minimum=Y,K.maximum=W,X)K.pattern=CJ0}),Q._zod.check=($)=>{let K=$.value;if(X){if(!Number.isInteger(K)){$.issues.push({expected:G,format:J.format,code:"invalid_type",input:K,inst:Q});return}if(!Number.isSafeInteger(K)){if(K>0)$.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:G,continue:!J.abort});else $.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:G,continue:!J.abort});return}}if(K<Y)$.issues.push({origin:"number",input:K,code:"too_small",minimum:Y,inclusive:!0,inst:Q,continue:!J.abort});if(K>W)$.issues.push({origin:"number",input:K,code:"too_big",maximum:W,inst:Q})}}),bJ0=T0("$ZodCheckBigIntFormat",(Q,J)=>{a8.init(Q,J);let[X,G]=eQ0[J.format];Q._zod.onattach.push((Y)=>{let W=Y._zod.bag;W.format=J.format,W.minimum=X,W.maximum=G}),Q._zod.check=(Y)=>{let W=Y.value;if(W<X)Y.issues.push({origin:"bigint",input:W,code:"too_small",minimum:X,inclusive:!0,inst:Q,continue:!J.abort});if(W>G)Y.issues.push({origin:"bigint",input:W,code:"too_big",maximum:G,inst:Q})}}),xJ0=T0("$ZodCheckMaxSize",(Q,J)=>{var X;a8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!yZ(Y)&&Y.size!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<Y)G._zod.bag.maximum=J.maximum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.size<=J.maximum)return;G.issues.push({origin:pM(Y),code:"too_big",maximum:J.maximum,input:Y,inst:Q,continue:!J.abort})}}),gJ0=T0("$ZodCheckMinSize",(Q,J)=>{var X;a8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!yZ(Y)&&Y.size!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>Y)G._zod.bag.minimum=J.minimum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.size>=J.minimum)return;G.issues.push({origin:pM(Y),code:"too_small",minimum:J.minimum,input:Y,inst:Q,continue:!J.abort})}}),uJ0=T0("$ZodCheckSizeEquals",(Q,J)=>{var X;a8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!yZ(Y)&&Y.size!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.minimum=J.size,Y.maximum=J.size,Y.size=J.size}),Q._zod.check=(G)=>{let Y=G.value,W=Y.size;if(W===J.size)return;let $=W>J.size;G.issues.push({origin:pM(Y),...$?{code:"too_big",maximum:J.size}:{code:"too_small",minimum:J.size},inclusive:!0,exact:!0,input:G.value,inst:Q,continue:!J.abort})}}),mJ0=T0("$ZodCheckMaxLength",(Q,J)=>{var X;a8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!yZ(Y)&&Y.length!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<Y)G._zod.bag.maximum=J.maximum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.length<=J.maximum)return;let $=cM(Y);G.issues.push({origin:$,code:"too_big",maximum:J.maximum,inclusive:!0,input:Y,inst:Q,continue:!J.abort})}}),lJ0=T0("$ZodCheckMinLength",(Q,J)=>{var X;a8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!yZ(Y)&&Y.length!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>Y)G._zod.bag.minimum=J.minimum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.length>=J.minimum)return;let $=cM(Y);G.issues.push({origin:$,code:"too_small",minimum:J.minimum,inclusive:!0,input:Y,inst:Q,continue:!J.abort})}}),dJ0=T0("$ZodCheckLengthEquals",(Q,J)=>{var X;a8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!yZ(Y)&&Y.length!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.minimum=J.length,Y.maximum=J.length,Y.length=J.length}),Q._zod.check=(G)=>{let Y=G.value,W=Y.length;if(W===J.length)return;let $=cM(Y),K=W>J.length;G.issues.push({origin:$,...K?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:G.value,inst:Q,continue:!J.abort})}}),RN=T0("$ZodCheckStringFormat",(Q,J)=>{var X,G;if(a8.init(Q,J),Q._zod.onattach.push((Y)=>{let W=Y._zod.bag;if(W.format=J.format,J.pattern)W.patterns??(W.patterns=new Set),W.patterns.add(J.pattern)}),J.pattern)(X=Q._zod).check??(X.check=(Y)=>{if(J.pattern.lastIndex=0,J.pattern.test(Y.value))return;Y.issues.push({origin:"string",code:"invalid_format",format:J.format,input:Y.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Q,continue:!J.abort})});else(G=Q._zod).check??(G.check=()=>{})}),pJ0=T0("$ZodCheckRegex",(Q,J)=>{RN.init(Q,J),Q._zod.check=(X)=>{if(J.pattern.lastIndex=0,J.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:J.pattern.toString(),inst:Q,continue:!J.abort})}}),cJ0=T0("$ZodCheckLowerCase",(Q,J)=>{J.pattern??(J.pattern=_J0),RN.init(Q,J)}),nJ0=T0("$ZodCheckUpperCase",(Q,J)=>{J.pattern??(J.pattern=yJ0),RN.init(Q,J)}),iJ0=T0("$ZodCheckIncludes",(Q,J)=>{a8.init(Q,J);let X=$$(J.includes),G=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=G,Q._zod.onattach.push((Y)=>{let W=Y._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(G)}),Q._zod.check=(Y)=>{if(Y.value.includes(J.includes,J.position))return;Y.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:Y.value,inst:Q,continue:!J.abort})}}),rJ0=T0("$ZodCheckStartsWith",(Q,J)=>{a8.init(Q,J);let X=new RegExp(`^${$$(J.prefix)}.*`);J.pattern??(J.pattern=X),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.patterns??(Y.patterns=new Set),Y.patterns.add(X)}),Q._zod.check=(G)=>{if(G.value.startsWith(J.prefix))return;G.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:G.value,inst:Q,continue:!J.abort})}}),aJ0=T0("$ZodCheckEndsWith",(Q,J)=>{a8.init(Q,J);let X=new RegExp(`.*${$$(J.suffix)}$`);J.pattern??(J.pattern=X),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.patterns??(Y.patterns=new Set),Y.patterns.add(X)}),Q._zod.check=(G)=>{if(G.value.endsWith(J.suffix))return;G.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:G.value,inst:Q,continue:!J.abort})}});oJ0=T0("$ZodCheckProperty",(Q,J)=>{a8.init(Q,J),Q._zod.check=(X)=>{let G=J.schema._zod.run({value:X.value[J.property],issues:[]},{});if(G instanceof Promise)return G.then((Y)=>N31(Y,X,J.property));N31(G,X,J.property);return}}),sJ0=T0("$ZodCheckMimeType",(Q,J)=>{a8.init(Q,J);let X=new Set(J.mime);Q._zod.onattach.push((G)=>{G._zod.bag.mime=J.mime}),Q._zod.check=(G)=>{if(X.has(G.value.type))return;G.issues.push({code:"invalid_value",values:J.mime,input:G.value.type,inst:Q})}}),tJ0=T0("$ZodCheckOverwrite",(Q,J)=>{a8.init(Q,J),Q._zod.check=(X)=>{X.value=J.tx(X.value)}})});class Qh{constructor(Q=[]){if(this.content=[],this.indent=0,this)this.args=Q}indented(Q){this.indent+=1,Q(this),this.indent-=1}write(Q){if(typeof Q==="function"){Q(this,{execution:"sync"}),Q(this,{execution:"async"});return}let X=Q.split(`
|
package/dist/server/server.js
CHANGED
|
@@ -1065,7 +1065,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
|
|
|
1065
1065
|
<h2>You've been invited!</h2>
|
|
1066
1066
|
<p>${G} has invited you to join <strong>${X.organization.name}</strong>.</p>
|
|
1067
1067
|
<p><a href="${Y}">Click here to accept the invitation</a></p>
|
|
1068
|
-
`})}}}var LI4=[Z00({organizationCreation:{afterCreate:async(Q)=>{await LY1(Q.organization.id,Q.member.userId)}},ac:B_,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:wY1,resourceNameValidation:(Q)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Q)}}},roles:{user:BI4,admin:OI4,owner:DI4},sendInvitationEmail:EY1}),T00({loginPage:"/login",oidcConfig:{scopes:AY1,metadata:{scopes_supported:AY1},loginPage:"/login"}}),M00({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Q)=>{if(Q.headers?.get("X-MCP-Session-Auth")==="true")return null;let X=Q.headers?.get("Authorization");if(X?.startsWith("Bearer "))return X.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"]}}}),F00({defaultRole:"user",adminRoles:["admin","owner"]}),I00(),U00({jwt:{expirationTime:"5m"}}),rt0(Z9.ssoConfig?PY1(Z9.ssoConfig):void 0),...Z9.magicLinkConfig&&Z9.emailProviders&&Z9.emailProviders.length>0?[j00(H61(Z9.magicLinkConfig,Z9.emailProviders))]:[]],wI4=q10(),PI4=Z61(wI4),RW=Le({baseURL:process.env.BASE_URL||"http://localhost:3000",database:PI4,emailAndPassword:{enabled:!0},...Z9,plugins:LI4,databaseHooks:{user:{create:{after:async(Q)=>{if(Hv.autoCreateOrganizationOnSignup===!1)return;let J=Q.name?Q.name.split(" ")[0]:Q.email.split("@")[0],X=3;for(let G=0;G<X;G++){let Y=`${J} ${zI4()}`,W=VI4(Y);try{await RW.api.createOrganization({body:{name:Y,slug:W,userId:Q.id}});return}catch($){if(!($ instanceof Error&&("body"in $)&&$.body?.code==="ORGANIZATION_ALREADY_EXISTS")||G===X-1){console.error("Failed to create default organization:",$);return}}}}}}}});PJ();import{randomBytes as MI4}from"crypto";var yP=null;function jY1(){if(yP)return yP;let Q=process.env.MESH_JWT_SECRET??Z9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Q)yP=new TextEncoder().encode(Q);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),yP=new Uint8Array(MI4(32));return yP}async function IY1(Q,J="5m"){let X=jY1();return await new mQ(Q).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(J).sign(X)}async function CY1(Q){try{let J=jY1(),{payload:X}=await B8(Q,J);return X}catch{return}}class N90{db;constructor(Q){this.db=Q}async get(Q){let J=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Q).executeTakeFirst();if(!J)return null;return{organizationId:J.organizationId,sidebar_items:J.sidebar_items?typeof J.sidebar_items==="string"?JSON.parse(J.sidebar_items):J.sidebar_items:null,createdAt:J.createdAt,updatedAt:J.updatedAt}}async upsert(Q,J){let X=new Date().toISOString(),G=J?.sidebar_items?JSON.stringify(J.sidebar_items):null;await this.db.insertInto("organization_settings").values({organizationId:Q,sidebar_items:G,createdAt:X,updatedAt:X}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:G?G:void 0,updatedAt:X})).execute();let Y=await this.get(Q);if(!Y)return{organizationId:Q,sidebar_items:J?.sidebar_items??null,createdAt:X,updatedAt:X};return Y}}gH();class RY1 extends Error{constructor(Q){super(Q);this.name="UnauthorizedError"}}class B90 extends Error{constructor(Q){super(Q);this.name="ForbiddenError"}}class xU{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(Q,J,X,G,Y,W=EY.SELF){this.userId=J;this.toolName=X;this.boundAuth=G;this.role=Y;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 RY1("Authentication required. Please provide a valid OAuth token or API key.");let J=Q.length>0?Q:this.toolName?[this.toolName]:[];if(J.length===0)throw new B90("No resources specified for access check");for(let X of J)if(await this.checkResource(X)){this.grant();return}throw new B90(`Access denied to: ${J.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 J={};if(this.connectionId)J[this.connectionId]=[Q];return this.boundAuth.hasPermission(J)}granted(){return this._granted}}class O90{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 QO.startActiveSpan("redactor.redact",(J)=>{try{if(Q===null||Q===void 0)return Q;if(typeof Q==="string")return J.setAttribute("data.type","string"),this.redactString(Q);if(Array.isArray(Q))return J.setAttribute("data.type","array"),J.setAttribute("data.length",Q.length),Q.map((X)=>this.redact(X));if(typeof Q==="object"){J.setAttribute("data.type","object");let X={};for(let[G,Y]of Object.entries(Q)){let W=this.redactString(G);X[W]=this.redact(Y)}return X}return J.setAttribute("data.type",typeof Q),Q}finally{J.end()}})}redactString(Q){return QO.startActiveSpan("redactor.redactString",(J)=>{try{J.setAttribute("text.length",Q.length);let X=Q,G=0;for(let Y of this.patterns){let W=Q.match(Y.regex);if(W)G+=W.length,J.setAttribute(`redaction.${Y.type}.count`,W.length);X=X.replace(Y.regex,`[REDACTED:${Y.type}]`)}return J.setAttribute("redaction.total_count",G),X}finally{J.end()}})}}class D90{db;redactor;constructor(Q){this.db=Q;this.redactor=new O90}async log(Q){await this.logBatch([Q])}async logBatch(Q){if(Q.length===0)return;let J=Q.map((X)=>({...X,input:this.redactor.redact(X.input),output:this.redactor.redact(X.output)}));await this.db.transaction().execute(async(X)=>{await X.insertInto("monitoring_logs").values(J.map((G)=>this.toDbRow(G))).execute()})}async query(Q){let J=this.db.selectFrom("monitoring_logs").selectAll(),X=this.db.selectFrom("monitoring_logs").select((K)=>K.fn.count("id").as("count"));if(Q.organizationId)J=J.where("organization_id","=",Q.organizationId),X=X.where("organization_id","=",Q.organizationId);if(Q.connectionId)J=J.where("connection_id","=",Q.connectionId),X=X.where("connection_id","=",Q.connectionId);if(Q.gatewayId)J=J.where("gateway_id","=",Q.gatewayId),X=X.where("gateway_id","=",Q.gatewayId);if(Q.toolName)J=J.where("tool_name","=",Q.toolName),X=X.where("tool_name","=",Q.toolName);if(Q.isError!==void 0)J=J.where("is_error","=",Q.isError?1:0),X=X.where("is_error","=",Q.isError?1:0);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString()),X=X.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString()),X=X.where("timestamp","<=",Q.endDate.toISOString());if(J=J.orderBy("timestamp","desc"),Q.limit)J=J.limit(Q.limit);if(Q.offset)J=J.offset(Q.offset);let[G,Y]=await Promise.all([J.execute(),X.executeTakeFirst()]),W=Number(Y?.count||0);return{logs:G.map((K)=>this.fromDbRow(K)),total:W}}async getStats(Q){let J=this.db.selectFrom("monitoring_logs").where("organization_id","=",Q.organizationId);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString());let X=await J.select([($)=>$.fn.count("id").as("total_count"),($)=>$.fn.sum($.ref("is_error")).as("error_count"),($)=>$.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),G=Number(X?.total_count||0),Y=Number(X?.error_count||0),W=Number(X?.avg_duration||0);return{totalCalls:G,errorRate:G>0?Y/G:0,avgDurationMs:W}}toDbRow(Q){return{id:Q.id||a7("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}}fromDbRow(Q){let J=typeof Q.input==="string"?JSON.parse(Q.input):Q.input,X=typeof Q.output==="string"?JSON.parse(Q.output):Q.output,G=typeof Q.timestamp==="string"?new Date(Q.timestamp):Q.timestamp;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,connectionTitle:Q.connection_title,toolName:Q.tool_name,input:J,output:X,isError:Q.is_error===1,errorMessage:Q.error_message,durationMs:Q.duration_ms,timestamp:G,userId:Q.user_id,requestId:Q.request_id,userAgent:Q.user_agent,gatewayId:Q.gateway_id}}}gH();_80();function SY1(Q){let J=null;return()=>{if(J)return J;return J=Q().catch((X)=>{throw J=null,X}),J}}class vY1{factory;promise=null;constructor(Q){this.factory=Q}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Q,J){return this.getOrCreatePromise().then(Q,J)}catch(Q){return this.getOrCreatePromise().catch(Q)}finally(Q){return this.getOrCreatePromise().finally(Q)}}function XG(Q){return new vY1(Q)}Kk();QP();yk();yJ();W_();var O_=new i5;async function kY1(Q,J){return(await J.storage.connections.findById(Q))?.connection_url??null}async function D_(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=new URL(Q);G.pathname=`${X}/.well-known/oauth-protected-resource`;let Y=await fetch(G.toString(),{method:"GET",headers:{Accept:"application/json"}});if(Y.ok)return Y;if(Y.status!==404&&Y.status!==401)return Y;let W=new URL(Q);if(W.pathname=`/.well-known/oauth-protected-resource${X}`,Y=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y.status!==404&&Y.status!==401)return Y;let $=new URL(Q);return $.pathname="/.well-known/oauth-protected-resource",Y=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y}async function TI4(Q,J){let X=await kY1(Q,J);if(!X)return null;try{let G=await D_(X);if(!G.ok)return null;return(await G.json()).authorization_servers?.[0]??null}catch{return null}}async function _Y1(Q){let J=Q.get("meshContext");if(!J)J=await JZ.create(Q.req.raw),Q.set("meshContext",J);return J}async function yY1({error:Q,reqUrl:J,connectionId:X,connectionUrl:G,headers:Y}){if(!(Q.status===401||Q.message?.includes("401")||Q.message?.toLowerCase().includes("unauthorized")))return null;if(await fetch(G,{method:"POST",headers:{...Y,"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"}}})}).then((K)=>K.headers.has("WWW-Authenticate")).catch(()=>!1))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${J.origin}/mcp/${X}/.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 L_=(Q)=>{if(!(Q.hostname==="localhost"||Q.hostname==="127.0.0.1"))Q.protocol="https:";return Q},hY1=async(Q)=>{let J=Q.req.param("connectionId"),X=await _Y1(Q),G=await kY1(J,X);if(!G)return Q.json({error:"Connection not found"},404);try{let Y=await D_(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),$=L_(new URL(Q.req.url)),K=`${$.origin}/mcp/${J}`,Z=`${$.origin}/oauth-proxy/${J}`,H={...W,resource:K,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",W),Q.json({error:"Failed to proxy OAuth metadata",message:W.message},502)}};O_.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Q)=>hY1(Q));O_.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Q)=>hY1(Q));async function L90(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=X!==""&&X!=="/",Y=[];if(G){let $=new URL(Q);$.pathname=`/.well-known/oauth-authorization-server${X}`,Y.push($);let K=new URL(Q);K.pathname=`/.well-known/openid-configuration${X}`,Y.push(K);let Z=new URL(Q);Z.pathname=`${X}/.well-known/openid-configuration`,Y.push(Z)}else{let $=new URL(Q);$.pathname="/.well-known/oauth-authorization-server",Y.push($);let K=new URL(Q);K.pathname="/.well-known/openid-configuration",Y.push(K)}let W=null;for(let $ of Y){if(W=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}O_.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=await _Y1(Q),G=await TI4(J,X);if(!G)return Q.json({error:"Connection not found or no auth server"},404);try{let Y=await L90(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),K=`${L_(new URL(Q.req.url)).origin}/oauth-proxy/${J}`,Z={...W,authorization_endpoint:W.authorization_endpoint?`${K}/authorize`:void 0,token_endpoint:W.token_endpoint?`${K}/token`:void 0,registration_endpoint:W.registration_endpoint?`${K}/register`:void 0};return new Response(JSON.stringify(Z),{status:200,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;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 fY1=O_;function AI4(Q){if(!Q.isError)return;let J=Q.content;if(!Array.isArray(J))return;for(let X of J)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function bY1(Q){if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q,X=J.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return J}return{value:Q}}async function EI4(Q,J){let X=Q.body;if(!X)return{text:"",truncated:!1};let G=X.getReader(),Y=new TextDecoder,W=!1,$=0,K=[];try{while(!0){let{value:Z,done:H}=await G.read();if(H)break;if(Z){if($+=Z.byteLength,$>J){W=!0;let q=J-($-Z.byteLength);if(q>0)K.push(Y.decode(Z.slice(0,q),{stream:!0}));break}K.push(Y.decode(Z,{stream:!0}))}}}finally{G.releaseLock()}return K.push(Y.decode()),{text:K.join(""),truncated:W}}async function hP(Q){let{ctx:J,enabled:X}=Q,G=Q.organizationId??J.organization?.id;if(!X||!G)return;await J.storage.monitoring.log({organizationId:G,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:J.auth.user?.id||J.auth.apiKey?.userId||null,requestId:J.metadata.requestId,userAgent:J.metadata.userAgent,gatewayId:J.gatewayId})}function xY1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=Date.now()-K;return await hP({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:bY1(Z),isError:Boolean(Z.isError),errorMessage:AI4(Z),durationMs:H}),Z}catch(Z){let H=Z,q=Date.now()-K;throw await hP({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}function gY1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=J.organization?.id;if(X&&H){let q=Z.clone();(async()=>{try{let{text:F,truncated:V}=await EI4(q,262144),z=Date.now()-K,U=q.headers.get("content-type")??"",N=F;if(U.includes("application/json"))try{N=F.length?JSON.parse(F):null}catch{N=F}let D=Z.status>=400,w=D&&N&&typeof N==="object"&&"error"in N?N.error:void 0,A=typeof w==="string"&&w?w:D&&typeof N==="string"&&N.trim()?N.slice(0,500):D?`HTTP ${Z.status} ${Z.statusText}`.trim():V?"Response body truncated to 262144 bytes":void 0;await hP({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:bY1(N),isError:D,errorMessage:A,durationMs:z})}catch(F){let V=Date.now()-K;await hP({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${F.message}`,durationMs:V})}})()}return Z}catch(Z){let H=Z,q=Date.now()-K;throw await hP({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}var uY1=new i5;function jI4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new xU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return{content:[{type:"text",text:`Authorization failed: ${Y.message}`}],isError:!0}}}}function II4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new xU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return new Response(JSON.stringify({error:`Authorization failed: ${Y.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function mY1(Q,J,{superUser:X}){let G=typeof Q==="string"?await J.storage.connections.findById(Q,J.organization?.id):Q;if(!G)throw Error("Connection not found");let Y=G?.id;if(J.organization&&G.organization_id!==J.organization.id)throw Error("Connection does not belong to the active organization");if(J.organization??={id:G.organization_id},G.status!=="active")throw Error(`Connection inactive: ${G.status}`);let W,$=J.auth.user?.connectionId,K=SY1(async()=>{let y=k80(G.configuration_state,G.configuration_scopes),f=J.auth.user?.id??J.auth.apiKey?.userId;if(!f){console.error("User ID required to issue configuration token");return}try{W=await IY1({sub:f,user:{id:f},metadata:{state:G.configuration_state??void 0,meshUrl:process.env.MESH_URL??J.baseUrl,connectionId:Y,organizationId:J.organization?.id},permissions:y})}catch(m){console.error("Failed to issue configuration token:",m)}}),Z=async()=>{await K();let y={...$?{"x-caller-id":$}:{}};if(G.connection_token)y.Authorization=`Bearer ${G.connection_token}`;if(W)y["x-mesh-token"]=W;if(G.connection_headers)Object.assign(y,G.connection_headers);return y},H=async()=>{let y=await Z(),f=new MW(new URL(G.connection_url),{requestInit:{headers:y}}),m=new oH({name:"mcp-mesh-proxy",version:"1.0.0"});return await m.connect(f),m},q=X?async(y,f)=>await f():jI4(J,Y),F=X?async(y,f)=>await f():II4(J,Y),V={enabled:y01().enabled,connectionId:Y,connectionTitle:G.title,ctx:J},z=xY1(V),U=gY1(V),N=VP(z,q),D=VP(U,F),w=async(y)=>{return N(y,async()=>{let f=await H(),m=Date.now();return await J.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":Y,"tool.name":y.params.name}},async(b)=>{try{let v=await f.callTool(y.params),x=Date.now()-m;return J.meter.createHistogram("connection.proxy.duration").record(x,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),J.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),b.end(),v}catch(v){let x=v,Q0=Date.now()-m;throw J.meter.createHistogram("connection.proxy.duration").record(Q0,{"connection.id":Y,"tool.name":y.params.name,status:"error"}),J.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":Y,"tool.name":y.params.name,error:x.message}),b.recordException(x),b.end(),v}})})};return{fetch:async(y)=>{let f=new URL(y.url),m;try{m=await H()}catch(x){let Q0=await yY1({error:x,reqUrl:f,connectionId:Y,connectionUrl:G.connection_url,headers:await Z()});if(Q0)return Q0;throw x}let b=new tH({name:"mcp-mesh",version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),v=new Kq({enableJsonResponse:y.headers.get("Accept")?.includes("application/json")??!1});return await b.connect(v),b.server.setRequestHandler(bK,async(x)=>{return await m.listTools()}),b.server.setRequestHandler(xK,w),b.server.setRequestHandler(kK,async()=>{if(m.getServerCapabilities()?.resources)return await m.listResources();return{resources:[]}}),b.server.setRequestHandler(yK,async(x)=>{return await m.readResource(x.params)}),b.server.setRequestHandler(_K,async()=>{if(m.getServerCapabilities()?.resourceTemplates)return await m.listResourceTemplates();return{resourceTemplates:[]}}),b.server.setRequestHandler(hK,async()=>{if(m.getServerCapabilities()?.prompts)return await m.listPrompts();return{prompts:[]}}),b.server.setRequestHandler(fK,async(x)=>{return await m.getPrompt(x.params)}),await v.handleMessage(y)},client:{callTool:(y)=>{return w({method:"tools/call",params:y})},listTools:async()=>{if(G.tools&&G.tools.length>0)return{tools:G.tools.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))};return await(await H()).listTools()},listResources:async()=>{return await(await H()).listResources()},readResource:async(y)=>{return await(await H()).readResource(y)},listResourceTemplates:async()=>{return await(await H()).listResourceTemplates()},listPrompts:async()=>{return await(await H()).listPrompts()},getPrompt:async(y)=>{return await(await H()).getPrompt(y)}},callStreamableTool:async(y,f)=>{let m={method:"tools/call",params:{name:y,arguments:f}};return D(m,async()=>{let b=await Z(),v=new URL(G.connection_url);return v.pathname=v.pathname.replace(/\/$/,"")+`/call-tool/${m.params.name}`,await J.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":Y,"tool.name":m.params.name}},async(x)=>{let Q0=Date.now();try{let c=await fetch(v.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(m.params.arguments),headers:{...b,"Content-Type":"application/json"}}),G0=Date.now()-Q0;return J.meter.createHistogram("connection.proxy.streamable.duration").record(G0,{"connection.id":Y,"tool.name":m.params.name,status:c.ok?"success":"error"}),J.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":Y,"tool.name":m.params.name,status:c.ok?"success":"error"}),x.end(),c}catch(c){let G0=c,U0=Date.now()-Q0;throw J.meter.createHistogram("connection.proxy.streamable.duration").record(U0,{"connection.id":Y,"tool.name":m.params.name,status:"error"}),J.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":Y,"tool.name":m.params.name,error:G0.message}),x.recordException(G0),x.end(),c}})})}}}async function lY1(Q,J){return mY1(Q,J,{superUser:!1})}async function dY1(Q,J){return mY1(Q,J,{superUser:!0})}uY1.all("/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=Q.get("meshContext");try{return await(await X.createMCPProxy(J)).fetch(Q.req.raw)}catch(G){let Y=G;if(Y.message.includes("not found"))return Q.json({error:Y.message},404);if(Y.message.includes("does not belong to the active organization"))return Q.json({error:"Connection not found"},404);if(Y.message.includes("inactive"))return Q.json({error:Y.message},503);return Q.json({error:"Internal server error",message:Y.message},500)}});var pY1=uY1;function CI4(Q,J){for(let[X,G]of Object.entries(J)){let Y=Q[X];if(!Y||Y.length===0){let W=Q["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let $ of G)if(!W.includes($))return!1;continue}if(Y.includes("*"))continue;for(let W of G)if(!Y.includes(W))return!1}return!0}function RI4(Q){let{auth:J,headers:X,role:G,permissions:Y,userId:W}=Q,$=J.api.hasPermission;return{hasPermission:async(K)=>{if(G&&U90.includes(G))return!0;if(Y)return CI4(Y,K);if(!$)return console.error("[Auth] hasPermission API not available"),!1;try{if((await $({headers:X,body:{permission:K}}))?.success===!0)return!0;let H={};for(let F of Object.keys(K))H[F]=["*"];return(await $({headers:X,body:{permission:H}}))?.success===!0}catch(Z){return console.error("[Auth] Permission check failed:",Z),!1}},organization:{create:async(K)=>{return J.api.createOrganization({headers:X,body:K})},update:async(K)=>{return J.api.updateOrganization({headers:X,body:K})},delete:async(K)=>{await J.api.deleteOrganization({headers:X,body:{organizationId:K}})},get:async(K)=>{return J.api.getFullOrganization({headers:X,query:K?{organizationId:K}:void 0})},list:async(K)=>{return J.api.listOrganizations({headers:X,query:K?{userId:K}:void 0})},addMember:async(K)=>{return J.api.addMember({headers:X,body:K})},removeMember:async(K)=>{await J.api.removeMember({headers:X,body:K})},listMembers:async(K)=>{return J.api.listMembers({headers:X,query:K?{organizationId:K.organizationId,limit:K.limit,offset:K.offset}:void 0})},updateMemberRole:async(K)=>{return J.api.updateMemberRole({headers:X,body:K})}},apiKey:{create:async(K)=>{return J.api.createApiKey({body:{...K,userId:W}})},list:async()=>{return J.api.listApiKeys({headers:X})},update:async(K)=>{return J.api.updateApiKey({body:{...K,userId:W}})},delete:async(K)=>{await J.api.deleteApiKey({headers:X,body:{keyId:K}})}}}}async function SI4(Q,J,X){if(U90.includes(X))return;let G=await Q.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",J).where("role","=",X).executeTakeFirst();if(!G?.permission)return;try{return JSON.parse(G.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function vI4(Q,J,X){let G=Q.headers.get("Authorization");try{let Y=new Headers(Q.headers);Y.set("X-MCP-Session-Auth","true");let W=await J.api.getMcpSession({headers:Y});if(W){let $=W.userId,K=await X.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(),Z=K?.role,H=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,q;if(K&&Z)q=await SI4(X,K.organizationId,Z);return{user:{id:$,role:Z},role:Z,permissions:q,organization:H}}}catch(Y){console.error("[Auth] OAuth session check failed:",Y)}if(G?.startsWith("Bearer ")){let Y=G.replace("Bearer ","").trim();try{let W=await CY1(Y);if(W)return{user:{id:W.sub,connectionId:W.metadata?.connectionId},permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}catch{}try{let W=await J.api.verifyApiKey({body:{key:Y}});if(W?.valid&&W.key){let $=W.key.metadata?.organization,K=W.key.permissions;return{apiKeyId:W.key.id,user:{id:W.key.userId},permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let Y=await J.api.getSession({headers:Q.headers});if(Y){let W,$;if(Y.session.activeOrganizationId){let K=await J.api.getFullOrganization({headers:Q.headers}).catch(()=>null);if(K)W={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((H)=>H.userId===Y.user.id)?.role;else W={id:Y.session.activeOrganizationId,slug:"",name:""}}return{user:{id:Y.user.id,email:Y.user.email,role:$},role:$,organization:W}}}catch(Y){console.error("[Auth] Session check failed:",Y)}return{user:void 0}}var cY1,JZ={set:(Q)=>{cY1=Q},create:async(Q)=>{return await cY1(Q)}};function nY1(Q){let J=new _w(Q.encryption.key),X={connections:new yw(Q.db,J),organizationSettings:new N90(Q.db),monitoring:new D90(Q.db),gateways:new hw(Q.db)};return async(G)=>{let Y=G?.headers.get("x-caller-id")??void 0,W=G?await vI4(G,Q.auth,Q.db):{user:void 0},$=RI4({auth:Q.auth,headers:G?.headers??new Headers,role:W.role,permissions:W.permissions,userId:W.user?.id}),K={user:W.user};if(W.apiKeyId)K.apiKey={id:W.apiKeyId,name:"",userId:""};let Z=W.organization,H=G?new URL(G.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${H.protocol}//${H.host}`,F=new xU(Q.auth,K.user?.id,void 0,$,W.role,EY.SELF),V={auth:K,connectionId:Y,organization:Z,storage:X,vault:J,authInstance:Q.auth,boundAuth:$,access:F,db:Q.db,tracer:Q.observability.tracer,meter:Q.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:G?.headers.get("x-mesh-client")||G?.headers.get("User-Agent")||void 0,ipAddress:(G?.headers.get("CF-Connecting-IP")||G?.headers.get("X-Forwarded-For"))??void 0},eventBus:Q.eventBus,createMCPProxy:async(z)=>{return await lY1(z,V)}};return V}}var fP={HEALTH:"/health",METRICS:"/metrics"},bP={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known"},kI4=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/;function iY1(Q){return Q===fP.HEALTH||Q===fP.METRICS||Q.startsWith(bP.WELL_KNOWN)}function _I4(Q){return Q.startsWith(bP.API)}function yI4(Q){return Q==="/mcp"||Q.startsWith(bP.MCP)}function hI4(Q){return Q.startsWith(bP.OAUTH_PROXY)}function fI4(Q){return kI4.test(Q)}function rY1(Q){return _I4(Q)||yI4(Q)||hI4(Q)||iY1(Q)}function aY1(Q){return Q==="/"||Q.startsWith(bP.API_AUTH)||iY1(Q)||fI4(Q)}class oY1{db;constructor(Q){this.db=Q}async publishEvent(Q){let J=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:J,updated_at:J}).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:J,updatedAt:J}}async subscribe(Q){let J=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("connection_id","=",Q.connectionId).where("event_type","=",Q.eventType);if(Q.publisher)J=J.where("publisher","=",Q.publisher);else J=J.where("publisher","is",null);if(Q.filter)J=J.where("filter","=",Q.filter);else J=J.where("filter","is",null);let X=await J.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let G=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:G,updated_at:G}).execute(),{id:Q.id,organizationId:Q.organizationId,connectionId:Q.connectionId,publisher:Q.publisher??null,eventType:Q.eventType,filter:Q.filter??null,enabled:!0,createdAt:G,updatedAt:G}}async unsubscribe(Q,J){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Q).where("organization_id","=",J).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Q,J){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q);if(J)X=X.where("connection_id","=",J);return(await X.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 getSubscription(Q,J){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.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((X)=>X.or([X("publisher","is",null),X("publisher","=",Q.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Q,J,X){if(J.length===0)return;let G=new Date().toISOString(),Y=X??null,W=J.map(($)=>({id:crypto.randomUUID(),event_id:Q,subscription_id:$,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:Y,created_at:G}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(Q){let J=new Date().toISOString(),X;try{X=(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(($)=>$.or([$("d.next_retry_at","is",null),$("d.next_retry_at","<=",J)])).orderBy("d.created_at","asc").limit(Q)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let Y=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","<=",J)])).orderBy("d.created_at","asc").limit(Q).execute();if(Y.length===0)return[];X=Y.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.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",X).where("d.status","=","processing").execute()).map((Y)=>({delivery:{id:Y.delivery_id,eventId:Y.event_id,subscriptionId:Y.subscription_id,status:Y.delivery_status,attempts:Y.delivery_attempts,lastError:Y.delivery_last_error,deliveredAt:Y.delivered_at,nextRetryAt:Y.delivery_next_retry_at,createdAt:Y.delivery_created_at},event:{id:Y.event_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.event_status,attempts:Y.event_attempts,lastError:Y.event_last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.event_created_at,updatedAt:Y.event_updated_at},subscription:{id:Y.subscription_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.subscription_created_at,updatedAt:Y.subscription_updated_at}}))}async markDeliveriesDelivered(Q){if(Q.length===0)return;let J=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:J}).where("id","in",Q).execute()}async markDeliveriesFailed(Q,J,X=20,G=1000,Y=3600000){if(Q.length===0)return;for(let W of Q){let $=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!$)continue;let K=$.attempts+1;if(K>=X)await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let Z=Math.min(G*Math.pow(2,K-1),Y),H=new Date(Date.now()+Z).toISOString();await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(Q){let J=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Q).execute();if(J.length===0)return;let X=J.every((W)=>W.status==="delivered"),G=J.some((W)=>W.status==="failed"),Y=J.some((W)=>W.status==="pending"||W.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Q).execute();else if(G&&!Y)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,J){let X=await this.db.selectFrom("events").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async cancelEvent(Q,J,X){let G=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Q).where("organization_id","=",J).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((G.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:(G.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Q,J){if(Q.length===0)return;let X=new Date(Date.now()+J).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Q).execute()}async ackDelivery(Q,J,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Q).where("organization_id","=",J).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(($)=>$.exists($.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",J))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(Q);return{success:W}}async syncSubscriptions(Q){let{organizationId:J,connectionId:X,subscriptions:G}=Q,Y=(w,A)=>{return`${w}::${A??""}`},W=await this.listSubscriptions(J,X),$=new Map;for(let w of W)$.set(Y(w.eventType,w.publisher),w);let K=new Map;for(let w of G)K.set(Y(w.eventType,w.publisher),w);let Z=new Date().toISOString(),H=[],q=[],F=[],V=0;for(let[w,A]of K){let P=$.get(w);if(!P)H.push({id:crypto.randomUUID(),organization_id:J,connection_id:X,event_type:A.eventType,publisher:A.publisher??null,filter:A.filter??null,enabled:1,created_at:Z,updated_at:Z});else{let M=P.filter??null,T=A.filter??null;if(M!==T)q.push({id:P.id,filter:T});else V++}}for(let[w,A]of $)if(!K.has(w))F.push(A.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(q.length>0)await Promise.all(q.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:Z}).where("id","=",w.id).execute()));if(F.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",F).execute();let z=H.length,U=q.length,N=F.length,D=await this.listSubscriptions(J,X);return{created:z,updated:U,deleted:N,unchanged:V,subscriptions:D}}}function sY1(Q){return new oY1(Q)}function u5(Q,J,X,G,Y,W,$,K){return u5.fromTZ(u5.tp(Q,J,X,G,Y,W,$),K)}u5.fromTZISO=(Q,J,X)=>u5.fromTZ(bI4(Q,J),X);u5.fromTZ=function(Q,J){let X=new Date(Date.UTC(Q.y,Q.m-1,Q.d,Q.h,Q.i,Q.s)),G=w90(Q.tz,X),Y=new Date(X.getTime()-G),W=w90(Q.tz,Y);if(W-G===0)return Y;{let $=new Date(X.getTime()-W),K=w90(Q.tz,$);if(K-W===0)return $;if(!J&&K-W>0)return $;if(J)throw Error("Invalid date passed to fromTZ()");return Y}};u5.toTZ=function(Q,J){let X=Q.toLocaleString("en-US",{timeZone:J}).replace(/[\u202f]/," "),G=new Date(X);return{y:G.getFullYear(),m:G.getMonth()+1,d:G.getDate(),h:G.getHours(),i:G.getMinutes(),s:G.getSeconds(),tz:J}};u5.tp=(Q,J,X,G,Y,W,$)=>({y:Q,m:J,d:X,h:G,i:Y,s:W,tz:$});function w90(Q,J=new Date){let X=J.toLocaleString("en-US",{timeZone:Q,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],G=J.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${G} GMT`)-Date.parse(`${G} ${X}`)}function bI4(Q,J){let X=new Date(Date.parse(Q));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let G=Q.substring(9);return Q.includes("Z")||G.includes("-")||G.includes("+")?u5.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):u5.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),J)}u5.minitz=u5;var P90=32,gP=31|P90,J71=[1,2,4,8,16],tY1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Q,J){this.pattern=Q,this.timezone=J,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 J=new uX(new Date,this.timezone).getDate(!0);Q[0]=Q[0].replace("?",J.getSeconds().toString()),Q[1]=Q[1].replace("?",J.getMinutes().toString()),Q[2]=Q[2].replace("?",J.getHours().toString()),this.starDOM||(Q[3]=Q[3].replace("?",J.getDate().toString())),Q[4]=Q[4].replace("?",(J.getMonth()+1).toString()),this.starDOW||(Q[5]=Q[5].replace("?",J.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,gP),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Q,J,X,G){let Y=this[Q],W=Q==="day"&&this.lastDayOfMonth;if(J===""&&!W)throw TypeError("CronPattern: configuration entry "+Q+" ("+J+") is empty, check for trailing spaces.");if(J==="*")return Y.fill(G);let $=J.split(",");if($.length>1)for(let K=0;K<$.length;K++)this.partToArray(Q,$[K],X,G);else J.indexOf("-")!==-1&&J.indexOf("/")!==-1?this.handleRangeWithStepping(J,Q,X,G):J.indexOf("-")!==-1?this.handleRange(J,Q,X,G):J.indexOf("/")!==-1?this.handleStepping(J,Q,X,G):J!==""&&this.handleNumber(J,Q,X,G)}throwAtIllegalCharacters(Q){for(let J=0;J<Q.length;J++)if((J===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Q[J]))throw TypeError("CronPattern: configuration entry "+J+" ("+Q[J]+") contains illegal characters.")}handleNumber(Q,J,X,G){let Y=this.extractNth(Q,J),W=parseInt(Y[0],10)+X;if(isNaN(W))throw TypeError("CronPattern: "+J+" is not a number: '"+Q+"'");this.setPart(J,W,Y[1]||G)}setPart(Q,J,X){if(!Object.prototype.hasOwnProperty.call(this,Q))throw TypeError("CronPattern: Invalid part specified: "+Q);if(Q==="dayOfWeek"){if(J===7&&(J=0),J<0||J>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+J);this.setNthWeekdayOfMonth(J,X);return}if(Q==="second"||Q==="minute"){if(J<0||J>=60)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="hour"){if(J<0||J>=24)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="day"){if(J<0||J>=31)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="month"&&(J<0||J>=12))throw RangeError("CronPattern: Invalid value for "+Q+": "+J);this[Q][J]=X}handleRangeWithStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Q+"'");let[,$,K,Z]=W,H=parseInt($,10)+X,q=parseInt(K,10)+X,F=parseInt(Z,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(q))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(F===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(F>this[J].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[J].length+")");if(H>q)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let V=H;V<=q;V+=F)this.setPart(J,V,Y[1]||G)}extractNth(Q,J){let X=Q,G;if(X.includes("#")){if(J!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");G=X.split("#")[1],X=X.split("#")[0]}return[X,G]}handleRange(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Q+"'");let $=parseInt(W[0],10)+X,K=parseInt(W[1],10)+X;if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if($>K)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let Z=$;Z<=K;Z++)this.setPart(J,Z,Y[1]||G)}handleStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Q+"'");W[0]===""&&(W[0]="*");let $=0;W[0]!=="*"&&($=parseInt(W[0],10)+X);let K=parseInt(W[1],10);if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(K===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(K>this[J].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[J].length+")");for(let Z=$;Z<this[J].length;Z+=K)this.setPart(J,Z,Y[1]||G)}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 J=Q.trim().toLowerCase();return J==="@yearly"||J==="@annually"?"0 0 1 1 *":J==="@monthly"?"0 0 1 * *":J==="@weekly"?"0 0 * * 0":J==="@daily"?"0 0 * * *":J==="@hourly"?"0 * * * *":Q}setNthWeekdayOfMonth(Q,J){if(typeof J!="number"&&J==="L")this.dayOfWeek[Q]=this.dayOfWeek[Q]|P90;else if(J===gP)this.dayOfWeek[Q]=gP;else if(J<6&&J>0)this.dayOfWeek[Q]=this.dayOfWeek[Q]|J71[J-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${J}, Type: ${typeof J}`)}},eY1=[31,28,31,30,31,30,31,31,30,31,30,31],SW=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],uX=class Q{tz;ms;second;minute;hour;day;month;year;constructor(J,X){if(this.tz=X,J&&J instanceof Date)if(!isNaN(J))this.fromDate(J);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(J===void 0)this.fromDate(new Date);else if(J&&typeof J=="string")this.fromString(J);else if(J instanceof Q)this.fromCronDate(J);else throw TypeError("CronDate: Invalid type ("+typeof J+") passed to CronDate constructor")}isNthWeekdayOfMonth(J,X,G,Y){let W=new Date(Date.UTC(J,X,G)).getUTCDay(),$=0;for(let K=1;K<=G;K++)new Date(Date.UTC(J,X,K)).getUTCDay()===W&&$++;if(Y&gP&&J71[$-1]&Y)return!0;if(Y&P90){let K=new Date(Date.UTC(J,X+1,0)).getUTCDate();for(let Z=G+1;Z<=K;Z++)if(new Date(Date.UTC(J,X,Z)).getUTCDay()===W)return!1;return!0}return!1}fromDate(J){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes()+this.tz,this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),this.apply();else{let X=u5.toTZ(J,this.tz);this.ms=J.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=J.getMilliseconds(),this.second=J.getSeconds(),this.minute=J.getMinutes(),this.hour=J.getHours(),this.day=J.getDate(),this.month=J.getMonth(),this.year=J.getFullYear()}fromCronDate(J){this.tz=J.tz,this.year=J.year,this.month=J.month,this.day=J.day,this.hour=J.hour,this.minute=J.minute,this.second=J.second,this.ms=J.ms}apply(){if(this.month>11||this.day>eY1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let J=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes(),this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),!0}else return!1}fromString(J){if(typeof this.tz=="number"){let X=u5.fromTZISO(J);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(),this.apply()}else return this.fromDate(u5.fromTZISO(J,this.tz))}findNext(J,X,G,Y){let W=this[X],$;G.lastDayOfMonth&&(this.month!==1?$=eY1[this.month]:$=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let K=!G.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let Z=this[X]+Y;Z<G[X].length;Z++){let H=G[X][Z];if(X==="day"&&G.lastDayOfMonth&&Z-Y==$&&(H=1),X==="day"&&!G.starDOW){let q=G.dayOfWeek[(K+(Z-Y-1))%7];if(q&&q&gP)q=this.isNthWeekdayOfMonth(this.year,this.month,Z-Y,q)?1:0;else if(q)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${q}`);J.legacyMode&&!G.starDOM?H=H||q:H=H&&q}if(H)return this[X]=Z-Y,W!==this[X]?2:1}return 3}recurse(J,X,G){let Y=this.findNext(X,SW[G][0],J,SW[G][2]);if(Y>1){let W=G+1;for(;W<SW.length;)this[SW[W][0]]=-SW[W][2],W++;if(Y===3)return this[SW[G][1]]++,this[SW[G][0]]=-SW[G][2],this.apply(),this.recurse(J,X,0);if(this.apply())return this.recurse(J,X,G-1)}return G+=1,G>=SW.length?this:this.year>=3000?null:this.recurse(J,X,G)}increment(J,X,G){return this.second+=X.interval!==void 0&&X.interval>1&&G?X.interval:1,this.ms=0,this.apply(),this.recurse(J,X,0)}getDate(J){return J||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)):u5.fromTZ(u5.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function xI4(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 uX(Q.startAt,Q.timezone)),Q.stopAt&&(Q.stopAt=new uX(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 xP(Q){return Object.prototype.toString.call(Q)==="[object Function]"||typeof Q=="function"||Q instanceof Function}function gI4(Q){return xP(Q)}function uI4(Q){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Q):Q&&typeof Q.unref<"u"&&Q.unref()}var Q71=30000,w_=[],P_=class{name;options;_states;fn;constructor(Q,J,X){let G,Y;if(xP(J))Y=J;else if(typeof J=="object")G=J;else if(J!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(xP(X))Y=X;else if(typeof X=="object")G=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=G?.name,this.options=xI4(G),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:G?G.maxRuns:void 0,paused:G?G.paused:!1,pattern:new tY1("* * * * *")},Q&&(Q instanceof Date||typeof Q=="string"&&Q.indexOf(":")>0)?this._states.once=new uX(Q,this.options.timezone||this.options.utcOffset):this._states.pattern=new tY1(Q,this.options.timezone),this.name){if(w_.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");w_.push(this)}return Y!==void 0&&gI4(Y)&&(this.fn=Y,this.schedule()),this}nextRun(Q){let J=this._next(Q);return J?J.getDate(!1):null}nextRuns(Q,J){this._states.maxRuns!==void 0&&Q>this._states.maxRuns&&(Q=this._states.maxRuns);let X=[],G=J||this._states.currentRun||void 0;for(;Q--&&(G=this.nextRun(G));)X.push(G);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Q=this.nextRun(this._states.currentRun),J=!this._states.paused,X=this.fn!==void 0,G=!this._states.kill;return J&&X&&G&&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 J=this._next(Q);return J?Q instanceof uX||Q instanceof Date?J.getTime()-Q.getTime():J.getTime()-new uX(Q).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Q=w_.indexOf(this);Q>=0&&w_.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 J=this.msToNext(),X=this.nextRun(this._states.currentRun);return J==null||isNaN(J)||X===null?this:(J>Q71&&(J=Q71),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),J),this._states.currentTimeout&&this.options.unref&&uI4(this._states.currentTimeout),this)}async _trigger(Q){if(this._states.blocking=!0,this._states.currentRun=new uX(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(J){xP(this.options.catch)&&this.options.catch(J,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new uX(Q,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Q){let J=new Date,X=!this._states.paused&&J.getTime()>=Q.getTime(),G=this._states.blocking&&this.options.protect;X&&!G?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&G&&xP(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Q){let J=!!(Q||this._states.currentRun),X=!1;!Q&&this.options.startAt&&this.options.interval&&([Q,J]=this._calculatePreviousRun(Q,J),X=!Q),Q=new uX(Q,this.options.timezone||this.options.utcOffset),this.options.startAt&&Q&&Q.getTime()<this.options.startAt.getTime()&&(Q=this.options.startAt);let G=this._states.once||new uX(Q,this.options.timezone||this.options.utcOffset);return!X&&G!==this._states.once&&(G=G.increment(this._states.pattern,this.options,J)),this._states.once&&this._states.once.getTime()<=Q.getTime()||G===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&G.getTime()>=this.options.stopAt.getTime()?null:G}_calculatePreviousRun(Q,J){let X=new uX(void 0,this.options.timezone||this.options.utcOffset),G=Q;if(this.options.startAt.getTime()<=X.getTime()){G=this.options.startAt;let Y=G.getTime()+this.options.interval*1000;for(;Y<=X.getTime();)G=new uX(G,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),Y=G.getTime()+this.options.interval*1000;J=!0}return G===null&&(G=void 0),[G,J]}};var M_={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};V_();function X71(){return async(Q,J)=>{try{let X=await JZ.create(),G=await dY1(Q,{...X,auth:{...X.auth,user:{id:"notify-worker"}}}),W=await j80.forClient(G).ON_EVENTS({events:J});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(X){let G=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Q}:`,G),{success:!1,error:G}}}}function Y71(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 mI4(Q){let J=new Map;for(let G of Q){let Y=G.subscription.connectionId,W=J.get(Y);if(W){if(W.deliveryIds.push(G.delivery.id),!W.seenEventIds.has(G.event.id))W.seenEventIds.add(G.event.id),W.events.push(Y71(G.event))}else J.set(Y,{connectionId:G.subscription.connectionId,deliveryIds:[G.delivery.id],events:[Y71(G.event)],seenEventIds:new Set([G.event.id])})}let X=new Map;for(let[G,Y]of J)X.set(G,{connectionId:Y.connectionId,deliveryIds:Y.deliveryIds,events:Y.events});return X}class M90{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Q,J){this.storage=Q;this.notifySubscriber=X71(),this.config={...M_,...J}}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 J=mI4(Q),X=new Set;for(let[G,Y]of J){try{let W=await this.notifySubscriber(Y.connectionId,Y.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(Y,W);else if(W.success)await this.storage.markDeliveriesDelivered(Y.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(Y.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(Y.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let $=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${G}:`,$),await this.storage.markDeliveriesFailed(Y.deliveryIds,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of Q)if(Y.deliveryIds.includes(W.delivery.id))X.add(W.event.id)}for(let G of X)try{await this.storage.updateEventStatus(G);let Y=Q.find((W)=>W.event.id===G)?.event;if(Y?.cron)await this.scheduleNextCronDelivery(Y)}catch(Y){console.error(`[EventBus] Failed to update event status ${G}:`,Y)}}async processPerEventResults(Q,J){let X=[],G=new Map,Y=[],W=new Map;for(let $=0;$<Q.events.length;$++){let K=Q.events?.[$];if(!K)continue;let Z=Q.deliveryIds?.[$];if(!Z)continue;W.set(K.id,Z)}for(let $ of Q.events){let K=W.get($.id);if(!K)continue;let Z=J.results?.[$.id];if(Z)if(Z.success)X.push(K);else if(Z.retryAfter&&Z.retryAfter>0){let H=G.get(Z.retryAfter)||[];H.push(K),G.set(Z.retryAfter,H)}else Y.push({deliveryId:K,error:Z.error||"Event processing failed"});else if(J.success)X.push(K);else if(J.retryAfter&&J.retryAfter>0){let H=G.get(J.retryAfter)||[];H.push(K),G.set(J.retryAfter,H)}else Y.push({deliveryId:K,error:J.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[$,K]of G)await this.storage.scheduleRetryWithoutAttemptIncrement(K,$);if(Y.length>0){let $=new Map;for(let{deliveryId:K,error:Z}of Y){let H=$.get(Z)||[];H.push(K),$.set(Z,H)}for(let[K,Z]of $)await this.storage.markDeliveriesFailed(Z,K,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Q){if(!Q.cron)return;try{let X=new P_(Q.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Q.id} has no more runs`);return}let G=X.toISOString(),Y=await this.storage.getMatchingSubscriptions(Q);if(Y.length===0){console.log(`[EventBus] No subscriptions for cron event ${Q.id}, skipping next delivery`);return}await this.storage.createDeliveries(Q.id,Y.map((W)=>W.id),G),console.log(`[EventBus] Scheduled next cron delivery for event ${Q.id} at ${G}`)}catch(J){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Q.id}:`,J)}}}class T90{storage;worker;notifyStrategy;running=!1;constructor(Q){this.storage=Q.storage,this.notifyStrategy=Q.notifyStrategy,this.worker=new M90(this.storage,Q.config)}async publish(Q,J,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let G;if(X.cron)try{let H=new P_(X.cron).nextRun();if(!H)throw Error("Cron expression does not produce a next run time");G=H.toISOString()}catch(Z){throw Error(`Invalid cron expression: ${Z instanceof Error?Z.message:String(Z)}`)}let Y=crypto.randomUUID(),W=new Date().toISOString(),$=await this.storage.publishEvent({id:Y,organizationId:Q,type:X.type,source:J,subject:X.subject,time:W,data:X.data,cron:X.cron}),K=await this.storage.getMatchingSubscriptions($);if(K.length>0){let Z=X.deliverAt??G;if(await this.storage.createDeliveries(Y,K.map((H)=>H.id),Z),this.notifyStrategy&&!Z)await this.notifyStrategy.notify(Y).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return $}async subscribe(Q,J){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Q,connectionId:J.connectionId,publisher:J.publisher,eventType:J.eventType,filter:J.filter})}async unsubscribe(Q,J){return this.storage.unsubscribe(J,Q)}async listSubscriptions(Q,J){return this.storage.listSubscriptions(Q,J)}async getSubscription(Q,J){return this.storage.getSubscription(J,Q)}async getEvent(Q,J){return this.storage.getEvent(J,Q)}async cancelEvent(Q,J,X){return this.storage.cancelEvent(J,Q,X)}async ackEvent(Q,J,X){return this.storage.ackDelivery(J,Q,X)}async syncSubscriptions(Q,J){return this.storage.syncSubscriptions({organizationId:Q,...J})}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 G71(...Q){return{async start(J){await Promise.all(Q.map((X)=>X.start(J)))},async stop(){await Promise.all(Q.map((J)=>J.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(J){await Promise.all(Q.map((X)=>X.notify(J).catch((G)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",G)})))}}}class T_{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 lI4}from"kysely";var gU="mesh_events";class A90{db;pool;listenClient=null;onNotify=null;constructor(Q,J){this.db=Q;this.pool=J}async start(Q){if(this.listenClient)return;this.onNotify=Q;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(J)=>{if(J.channel===gU&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(J)=>{console.error("[PostgresNotify] Connection error:",J),this.cleanup()}),await this.listenClient.query(`LISTEN ${gU}`),console.log("[PostgresNotify] Started LISTEN on",gU)}catch(J){console.error("[PostgresNotify] Failed to start LISTEN:",J),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${gU}`),console.log("[PostgresNotify] Stopped LISTEN on",gU)}catch{}this.cleanup()}}async notify(Q){try{await lI4`SELECT pg_notify(${gU}, ${Q})`.execute(this.db)}catch(J){console.warn("[PostgresNotify] Failed to send NOTIFY:",J)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function W71(Q,J){let X=sY1(Q.db),G=J?.pollIntervalMs??M_.pollIntervalMs,Y=Q.type==="postgres"?G71(new T_(G),new A90(Q.db,Q.pool)):new T_(G);return new T90({storage:X,config:J,notifyStrategy:Y})}var $71={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 K71=new i5;K71.get("/config",async(Q)=>{try{let J=Object.keys(Z9.socialProviders??{}),X=J.length>0,G=J.map((W)=>({name:W,icon:$71[W].icon})),Y={emailAndPassword:{enabled:Z9.emailAndPassword?.enabled??!1},magicLink:{enabled:Z9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:X,providers:G},sso:Z9.ssoConfig?{enabled:!0,providerId:Z9.ssoConfig.providerId}:{enabled:!1}};return Q.json({success:!0,config:Y})}catch(J){let X=J instanceof Error?J.message:"Failed to load auth config";return Q.json({success:!1,error:X},500)}});var Z71=K71;yk();yJ();class uP{proxies=new Map;constructor(){}static async create(Q,J){let X=new uP,G=await Promise.allSettled(Q.map(async({connection:Y,selectedTools:W})=>{try{let $=await J.createMCPProxy(Y);return{connection:Y,proxy:$,selectedTools:W}}catch($){return console.error(`[gateway] Failed to create proxy for connection ${Y.id}:`,$),null}}));for(let Y of G)if(Y.status==="fulfilled"&&Y.value)X.proxies.set(Y.value.connection.id,Y.value);return X}get(Q){return this.proxies.get(Q)}entries(){return this.proxies.entries()}forEach(Q){this.proxies.forEach((J,X)=>Q(J,X))}async mapAsync(Q){let J=[];for(let[X,G]of this.proxies.entries())J.push(Q(G,X));return await Promise.all(J)}async mapSettled(Q){return Promise.allSettled(Array.from(this.proxies.entries()).map(([J,X])=>Q(X,J)))}get size(){return this.proxies.size}}function dI4(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((J)=>J.length>=2)}function pI4(Q,J){let X=0,G=J.name.toLowerCase(),Y=(J.description??"").toLowerCase(),W=J.connectionTitle.toLowerCase();for(let $ of Q){if(G===$)X+=10;else if(G.includes($))X+=3;if(Y.includes($))X+=2;if(W.includes($))X+=1}return X}function cI4(Q,J,X){let G=dI4(Q);if(G.length===0)return J.slice(0,X);return J.map((Y)=>({tool:Y,score:pI4(G,Y)})).filter((Y)=>Y.score>0).sort((Y,W)=>W.score-Y.score).slice(0,X).map((Y)=>Y.tool)}var H71=(Q)=>({tools:Q.tools,callTool:(J,X)=>Q.callTool(J,X)}),XZ={SEARCH:"GATEWAY_SEARCH_TOOLS",DESCRIBE:"GATEWAY_DESCRIBE_TOOLS",CALL:"GATEWAY_CALL_TOOL"};function nI4(Q){let J=Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:"",X=Q.tools.map((G)=>G.name);return[{name:XZ.SEARCH,description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${J} Total tools: ${Q.tools.length}.`,inputSchema:{type:"object",properties:{query:{type:"string",description:"Natural language search query (e.g., 'send email', 'create order')"},limit:{type:"number",description:"Maximum results to return (default: 10)",default:10}},required:["query"]}},{name:XZ.DESCRIBE,description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:{type:"object",properties:{tools:{type:"array",items:{type:"string",enum:X},description:"Array of tool names to get detailed schemas for"}},required:["tools"]}},{name:XZ.CALL,description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:{type:"object",properties:{name:{type:"string",enum:X,description:"The name of the tool to execute"},arguments:{type:"object",description:"Arguments to pass to the tool",additionalProperties:!0}},required:["name"]}}]}var iI4=(Q)=>{let J=new Map(Q.tools.map((G)=>[G.name,G])),X=async(G,Y)=>{switch(G){case XZ.SEARCH:{let W=Y.query??"",$=Y.limit??10,K=cI4(W,Q.tools,$);return{content:[{type:"text",text:JSON.stringify({query:W,results:K.map((Z)=>({name:Z.name,description:Z.description,connection:Z.connectionTitle})),totalAvailable:Q.tools.length},null,2)}]}}case XZ.DESCRIBE:{let W=Y.tools??[];if(W.length===0)return{content:[{type:"text",text:JSON.stringify({error:"No tool names provided"})}],isError:!0};let $=W.map((K)=>J.get(K)).filter((K)=>K!==void 0);return{content:[{type:"text",text:JSON.stringify({tools:$.map((K)=>({name:K.name,description:K.description,connection:K.connectionTitle,inputSchema:K.inputSchema,outputSchema:K.outputSchema})),notFound:W.filter((K)=>!J.has(K))},null,2)}]}}case XZ.CALL:{let W=Y.name,$=Y.arguments??{};if(!W)return{content:[{type:"text",text:JSON.stringify({error:"Tool name is required"})}],isError:!0};if(!J.has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use ${XZ.SEARCH} to find available tools.`}],isError:!0};return Q.callTool(W,$)}default:return{content:[{type:"text",text:`Unknown meta-tool: ${G}. Available: ${Object.values(XZ).join(", ")}`}],isError:!0}}};return{tools:nI4(Q),callTool:X}};function q71(Q){switch(Q){case"smart_tool_selection":return iI4;case"code_execution":return H71;case"passthrough":default:return H71}}class A_{proxies;options;cache;constructor(Q,J){this.proxies=Q;this.options=J;this.cache=XG(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(Z,H)=>{try{let F=(await Z.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>!V.has(z.name))}}else if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>V.has(z.name))}return{connectionId:H,connectionTitle:Z.connection.title,tools:F}}catch(q){return console.error(`[gateway] Failed to list tools for connection ${H}:`,q),null}}),J=new Set,X=[],G=new Map,Y=new Set;for(let Z of Q){if(Z.status!=="fulfilled"||!Z.value)continue;let{connectionId:H,connectionTitle:q,tools:F}=Z.value;Y.add(q);for(let V of F){if(J.has(V.name))continue;J.add(V.name),X.push({...V,connectionId:H,connectionTitle:q}),G.set(V.name,{connectionId:H,originalName:V.name})}}let W=async(Z,H)=>{let q=G.get(Z);if(!q)return{content:[{type:"text",text:`Tool not found: ${Z}`}],isError:!0};let F=this.proxies.get(q.connectionId);if(!F)return{content:[{type:"text",text:`Connection not found for tool: ${Z}`}],isError:!0};return await F.proxy.client.callTool({name:q.originalName,arguments:H})},K=q71(this.options.strategy)({tools:X,callTool:W,categories:Array.from(Y).sort()});return{tools:X,mappings:G,strategyResult:K}}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,J){let X=await this.cache,G=X.mappings.get(Q);if(G){let W=this.proxies.get(G.connectionId);if(W)return W.proxy.callStreamableTool(G.originalName,J)}let Y=await X.strategyResult.callTool(Q,J);return new Response(JSON.stringify(Y),{headers:{"Content-Type":"application/json"}})}}class E_{proxies;cache;constructor(Q){this.proxies=Q;this.cache=XG(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listResources();return{connectionId:W,resources:$.resources}}catch($){return console.error(`[gateway] Failed to list resources for connection ${W}:`,$),{connectionId:W,resources:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,resources:$}=Y.value;for(let K of $){if(J.has(K.uri))continue;J.add(K.uri),X.push(K),G.set(K.uri,W)}}return{resources:X,mappings:G}}async list(){return{resources:(await this.cache).resources}}async read(Q){let X=(await this.cache).mappings.get(Q.uri);if(!X)throw Error(`Resource not found: ${Q.uri}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for resource: ${Q.uri}`);return await G.proxy.client.readResource(Q)}}class j_{proxies;cache;constructor(Q){this.proxies=Q;this.cache=XG(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(X,G)=>{try{let Y=await X.proxy.client.listResourceTemplates();return{connectionId:G,templates:Y.resourceTemplates}}catch(Y){return console.error(`[gateway] Failed to list resource templates for connection ${G}:`,Y),{connectionId:G,templates:[]}}}),J=[];for(let X of Q){if(X.status!=="fulfilled")continue;let{templates:G}=X.value;for(let Y of G)J.push(Y)}return{templates:J}}async list(){return{resourceTemplates:(await this.cache).templates}}}class I_{proxies;cache;constructor(Q){this.proxies=Q;this.cache=XG(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listPrompts();return{connectionId:W,prompts:$.prompts}}catch($){return console.error(`[gateway] Failed to list prompts for connection ${W}:`,$),{connectionId:W,prompts:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,prompts:$}=Y.value;for(let K of $){if(J.has(K.name))continue;J.add(K.name),X.push(K),G.set(K.name,W)}}return{prompts:X,mappings:G}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let X=(await this.cache).mappings.get(Q.name);if(!X)throw Error(`Prompt not found: ${Q.name}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for prompt: ${Q.name}`);return await G.proxy.client.getPrompt(Q)}}W_();var F71=new i5;async function rI4(Q,J){let X=await uP.create(Q.connections,J),G=new A_(X,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),Y=new E_(X),W=new j_(X),$=new I_(X);return{client:{listTools:G.list.bind(G),callTool:G.call.bind(G),listResources:Y.list.bind(Y),readResource:Y.read.bind(Y),listResourceTemplates:W.list.bind(W),listPrompts:$.list.bind($),getPrompt:$.get.bind($)},callStreamableTool:G.callStreamable.bind(G)}}async function aI4(Q,J){let X;if(Q.toolSelectionMode==="exclusion"){let W=(await J.storage.connections.list(Q.organizationId)).filter((K)=>K.status==="active"),$=new Map;for(let K of Q.connections)$.set(K.connectionId,K.selectedTools);X=[];for(let K of W){let Z=$.get(K.id);if(Z===void 0)X.push({connection:K,selectedTools:null});else if(Z===null||Z.length===0);else X.push({connection:K,selectedTools:Z})}}else{let Y=Q.connections.map(($)=>$.connectionId),W=[];for(let $ of Y){let K=await J.storage.connections.findById($);if(K&&K.status==="active")W.push(K)}X=W.map(($)=>{let K=Q.connections.find((Z)=>Z.connectionId===$.id);return{connection:$,selectedTools:K?.selectedTools??null}})}let G={connections:X,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Q.toolSelectionStrategy};return rI4(G,J)}F71.all("/gateway/:gatewayId?",async(Q)=>{let J=Q.req.param("gatewayId"),X=Q.get("meshContext");try{let G=null;if(J)G=await X.storage.gateways.findById(J);else{let Z=Q.req.header("x-org-id"),H=Q.req.header("x-org-slug");if(Z)G=await X.storage.gateways.getDefaultByOrgId(Z);else if(H)G=await X.storage.gateways.getDefaultByOrgSlug(H);else return Q.json({error:"Gateway ID required, or provide x-org-id or x-org-slug header for default gateway"},400)}if(!G){if(J)return Q.json({error:`Gateway not found: ${J}`},404);return Q.json({error:"No default gateway configured for this organization"},404)}if(X.gatewayId=G.id,G.status!=="active")return Q.json({error:`Gateway is inactive: ${G.id}`},503);let Y=await X.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",G.organizationId).executeTakeFirst();if(Y)X.organization={id:Y.id,slug:Y.slug,name:Y.name};let W=await aI4(G,X),$=new tH({name:`mcp-gateway-${G.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),K=new Kq({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await $.connect(K),$.server.setRequestHandler(bK,async(Z)=>{return W.client.listTools()}),$.server.setRequestHandler(xK,async(Z)=>{return await W.client.callTool(Z.params)}),$.server.setRequestHandler(kK,async()=>{return W.client.listResources()}),$.server.setRequestHandler(yK,async(Z)=>{return W.client.readResource(Z.params)}),$.server.setRequestHandler(_K,async()=>{return W.client.listResourceTemplates()}),$.server.setRequestHandler(hK,async()=>{return W.client.listPrompts()}),$.server.setRequestHandler(fK,async(Z)=>{return W.client.getPrompt(Z.params)}),await K.handleMessage(Q.req.raw).then(async(Z)=>{return Z})}catch(G){let Y=G;return console.error("[gateway] Error handling gateway request:",Y),Q.json({error:"Internal server error",message:Y.message},500)}});var V71=F71;z90();var z71=new i5;z71.all("/",async(Q)=>{return V90(Q.get("meshContext")).fetch(Q.req.raw)});var U71=z71;var d71="vercel.ai.error",oI4=Symbol.for(d71),N71,B71,D1=class Q extends(B71=Error,N71=oI4,B71){constructor({name:J,message:X,cause:G}){super(X);this[N71]=!0,this.name=J,this.cause=G}static isInstance(J){return Q.hasMarker(J,d71)}static hasMarker(J,X){let G=Symbol.for(X);return J!=null&&typeof J==="object"&&G in J&&typeof J[G]==="boolean"&&J[G]===!0}},p71="AI_APICallError",c71=`vercel.ai.error.${p71}`,sI4=Symbol.for(c71),O71,D71,H9=class extends(D71=D1,O71=sI4,D71){constructor({message:Q,url:J,requestBodyValues:X,statusCode:G,responseHeaders:Y,responseBody:W,cause:$,isRetryable:K=G!=null&&(G===408||G===409||G===429||G>=500),data:Z}){super({name:p71,message:Q,cause:$});this[O71]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=G,this.responseHeaders=Y,this.responseBody=W,this.isRetryable=K,this.data=Z}static isInstance(Q){return D1.hasMarker(Q,c71)}},n71="AI_EmptyResponseBodyError",i71=`vercel.ai.error.${n71}`,tI4=Symbol.for(i71),L71,w71,r71=class extends(w71=D1,L71=tI4,w71){constructor({message:Q="Empty response body"}={}){super({name:n71,message:Q});this[L71]=!0}static isInstance(Q){return D1.hasMarker(Q,i71)}};function YG(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 a71="AI_InvalidArgumentError",o71=`vercel.ai.error.${a71}`,eI4=Symbol.for(o71),P71,M71,s71=class extends(M71=D1,P71=eI4,M71){constructor({message:Q,cause:J,argument:X}){super({name:a71,message:Q,cause:J});this[P71]=!0,this.argument=X}static isInstance(Q){return D1.hasMarker(Q,o71)}},t71="AI_InvalidPromptError",e71=`vercel.ai.error.${t71}`,QC4=Symbol.for(e71),T71,A71,Hq=class extends(A71=D1,T71=QC4,A71){constructor({prompt:Q,message:J,cause:X}){super({name:t71,message:`Invalid prompt: ${J}`,cause:X});this[T71]=!0,this.prompt=Q}static isInstance(Q){return D1.hasMarker(Q,e71)}},QG1="AI_InvalidResponseDataError",JG1=`vercel.ai.error.${QG1}`,JC4=Symbol.for(JG1),E71,j71,Eb6=class extends(j71=D1,E71=JC4,j71){constructor({data:Q,message:J=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:QG1,message:J});this[E71]=!0,this.data=Q}static isInstance(Q){return D1.hasMarker(Q,JG1)}},XG1="AI_JSONParseError",YG1=`vercel.ai.error.${XG1}`,XC4=Symbol.for(YG1),I71,C71,mP=class extends(C71=D1,I71=XC4,C71){constructor({text:Q,cause:J}){super({name:XG1,message:`JSON parsing failed: Text: ${Q}.
|
|
1068
|
+
`})}}}var LI4=[Z00({organizationCreation:{afterCreate:async(Q)=>{await LY1(Q.organization.id,Q.member.userId)}},ac:B_,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:wY1,resourceNameValidation:(Q)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Q)}}},roles:{user:BI4,admin:OI4,owner:DI4},sendInvitationEmail:EY1}),T00({loginPage:"/login",oidcConfig:{scopes:AY1,metadata:{scopes_supported:AY1},loginPage:"/login"}}),M00({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Q)=>{if(Q.headers?.get("X-MCP-Session-Auth")==="true")return null;let X=Q.headers?.get("Authorization");if(X?.startsWith("Bearer "))return X.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"]}}}),F00({defaultRole:"user",adminRoles:["admin","owner"]}),I00(),U00({jwt:{expirationTime:"5m"}}),rt0(Z9.ssoConfig?PY1(Z9.ssoConfig):void 0),...Z9.magicLinkConfig&&Z9.emailProviders&&Z9.emailProviders.length>0?[j00(H61(Z9.magicLinkConfig,Z9.emailProviders))]:[]],wI4=q10(),PI4=Z61(wI4),RW=Le({baseURL:process.env.BASE_URL||"http://localhost:3000",database:PI4,emailAndPassword:{enabled:!0},...Z9,plugins:LI4,databaseHooks:{user:{create:{after:async(Q)=>{if(Hv.autoCreateOrganizationOnSignup===!1)return;let J=Q.name?Q.name.split(" ")[0]:Q.email.split("@")[0],X=3;for(let G=0;G<X;G++){let Y=`${J} ${zI4()}`,W=VI4(Y);try{await RW.api.createOrganization({body:{name:Y,slug:W,userId:Q.id}});return}catch($){if(!($ instanceof Error&&("body"in $)&&$.body?.code==="ORGANIZATION_ALREADY_EXISTS")||G===X-1){console.error("Failed to create default organization:",$);return}}}}}}}});PJ();import{randomBytes as MI4}from"crypto";var yP=null;function jY1(){if(yP)return yP;let Q=process.env.MESH_JWT_SECRET??Z9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Q)yP=new TextEncoder().encode(Q);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),yP=new Uint8Array(MI4(32));return yP}async function IY1(Q,J="5m"){let X=jY1();return await new mQ(Q).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(J).sign(X)}async function CY1(Q){try{let J=jY1(),{payload:X}=await B8(Q,J);return X}catch{return}}class N90{db;constructor(Q){this.db=Q}async get(Q){let J=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Q).executeTakeFirst();if(!J)return null;return{organizationId:J.organizationId,sidebar_items:J.sidebar_items?typeof J.sidebar_items==="string"?JSON.parse(J.sidebar_items):J.sidebar_items:null,createdAt:J.createdAt,updatedAt:J.updatedAt}}async upsert(Q,J){let X=new Date().toISOString(),G=J?.sidebar_items?JSON.stringify(J.sidebar_items):null;await this.db.insertInto("organization_settings").values({organizationId:Q,sidebar_items:G,createdAt:X,updatedAt:X}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:G?G:void 0,updatedAt:X})).execute();let Y=await this.get(Q);if(!Y)return{organizationId:Q,sidebar_items:J?.sidebar_items??null,createdAt:X,updatedAt:X};return Y}}gH();class RY1 extends Error{constructor(Q){super(Q);this.name="UnauthorizedError"}}class B90 extends Error{constructor(Q){super(Q);this.name="ForbiddenError"}}class xU{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(Q,J,X,G,Y,W=EY.SELF){this.userId=J;this.toolName=X;this.boundAuth=G;this.role=Y;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 RY1("Authentication required. Please provide a valid OAuth token or API key.");let J=Q.length>0?Q:this.toolName?[this.toolName]:[];if(J.length===0)throw new B90("No resources specified for access check");for(let X of J)if(await this.checkResource(X)){this.grant();return}throw new B90(`Access denied to: ${J.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 J={};if(this.connectionId)J[this.connectionId]=[Q];return this.boundAuth.hasPermission(J)}granted(){return this._granted}}class O90{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 QO.startActiveSpan("redactor.redact",(J)=>{try{if(Q===null||Q===void 0)return Q;if(typeof Q==="string")return J.setAttribute("data.type","string"),this.redactString(Q);if(Array.isArray(Q))return J.setAttribute("data.type","array"),J.setAttribute("data.length",Q.length),Q.map((X)=>this.redact(X));if(typeof Q==="object"){J.setAttribute("data.type","object");let X={};for(let[G,Y]of Object.entries(Q)){let W=this.redactString(G);X[W]=this.redact(Y)}return X}return J.setAttribute("data.type",typeof Q),Q}finally{J.end()}})}redactString(Q){return QO.startActiveSpan("redactor.redactString",(J)=>{try{J.setAttribute("text.length",Q.length);let X=Q,G=0;for(let Y of this.patterns){let W=Q.match(Y.regex);if(W)G+=W.length,J.setAttribute(`redaction.${Y.type}.count`,W.length);X=X.replace(Y.regex,`[REDACTED:${Y.type}]`)}return J.setAttribute("redaction.total_count",G),X}finally{J.end()}})}}class D90{db;redactor;constructor(Q){this.db=Q;this.redactor=new O90}async log(Q){await this.logBatch([Q])}async logBatch(Q){if(Q.length===0)return;let J=Q.map((X)=>({...X,input:this.redactor.redact(X.input),output:this.redactor.redact(X.output)}));await this.db.transaction().execute(async(X)=>{await X.insertInto("monitoring_logs").values(J.map((G)=>this.toDbRow(G))).execute()})}async query(Q){let J=this.db.selectFrom("monitoring_logs").selectAll(),X=this.db.selectFrom("monitoring_logs").select((K)=>K.fn.count("id").as("count"));if(Q.organizationId)J=J.where("organization_id","=",Q.organizationId),X=X.where("organization_id","=",Q.organizationId);if(Q.connectionId)J=J.where("connection_id","=",Q.connectionId),X=X.where("connection_id","=",Q.connectionId);if(Q.gatewayId)J=J.where("gateway_id","=",Q.gatewayId),X=X.where("gateway_id","=",Q.gatewayId);if(Q.toolName)J=J.where("tool_name","=",Q.toolName),X=X.where("tool_name","=",Q.toolName);if(Q.isError!==void 0)J=J.where("is_error","=",Q.isError?1:0),X=X.where("is_error","=",Q.isError?1:0);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString()),X=X.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString()),X=X.where("timestamp","<=",Q.endDate.toISOString());if(J=J.orderBy("timestamp","desc"),Q.limit)J=J.limit(Q.limit);if(Q.offset)J=J.offset(Q.offset);let[G,Y]=await Promise.all([J.execute(),X.executeTakeFirst()]),W=Number(Y?.count||0);return{logs:G.map((K)=>this.fromDbRow(K)),total:W}}async getStats(Q){let J=this.db.selectFrom("monitoring_logs").where("organization_id","=",Q.organizationId);if(Q.startDate)J=J.where("timestamp",">=",Q.startDate.toISOString());if(Q.endDate)J=J.where("timestamp","<=",Q.endDate.toISOString());let X=await J.select([($)=>$.fn.count("id").as("total_count"),($)=>$.fn.sum($.ref("is_error")).as("error_count"),($)=>$.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),G=Number(X?.total_count||0),Y=Number(X?.error_count||0),W=Number(X?.avg_duration||0);return{totalCalls:G,errorRate:G>0?Y/G:0,avgDurationMs:W}}toDbRow(Q){return{id:Q.id||a7("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}}fromDbRow(Q){let J=typeof Q.input==="string"?JSON.parse(Q.input):Q.input,X=typeof Q.output==="string"?JSON.parse(Q.output):Q.output,G=typeof Q.timestamp==="string"?new Date(Q.timestamp):Q.timestamp;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,connectionTitle:Q.connection_title,toolName:Q.tool_name,input:J,output:X,isError:Q.is_error===1,errorMessage:Q.error_message,durationMs:Q.duration_ms,timestamp:G,userId:Q.user_id,requestId:Q.request_id,userAgent:Q.user_agent,gatewayId:Q.gateway_id}}}gH();_80();function SY1(Q){let J=null;return()=>{if(J)return J;return J=Q().catch((X)=>{throw J=null,X}),J}}class vY1{factory;promise=null;constructor(Q){this.factory=Q}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Q,J){return this.getOrCreatePromise().then(Q,J)}catch(Q){return this.getOrCreatePromise().catch(Q)}finally(Q){return this.getOrCreatePromise().finally(Q)}}function XG(Q){return new vY1(Q)}Kk();QP();yk();yJ();W_();var O_=new i5;async function kY1(Q,J){return(await J.storage.connections.findById(Q))?.connection_url??null}async function D_(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=new URL(Q);G.pathname=`${X}/.well-known/oauth-protected-resource`;let Y=await fetch(G.toString(),{method:"GET",headers:{Accept:"application/json"}});if(Y.ok)return Y;if(Y.status!==404&&Y.status!==401)return Y;let W=new URL(Q);if(W.pathname=`/.well-known/oauth-protected-resource${X}`,Y=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y.status!==404&&Y.status!==401)return Y;let $=new URL(Q);return $.pathname="/.well-known/oauth-protected-resource",Y=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),Y}async function TI4(Q,J){let X=await kY1(Q,J);if(!X)return null;try{let G=await D_(X);if(!G.ok)return null;return(await G.json()).authorization_servers?.[0]??null}catch{return null}}async function _Y1(Q){let J=Q.get("meshContext");if(!J)J=await JZ.create(Q.req.raw),Q.set("meshContext",J);return J}async function yY1({error:Q,reqUrl:J,connectionId:X,connectionUrl:G,headers:Y}){if(!(Q.status===401||Q.message?.includes("401")||Q.message?.toLowerCase().includes("unauthorized")))return null;if(await fetch(G,{method:"POST",headers:{...Y,"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"}}})}).then((K)=>K.headers.has("WWW-Authenticate")).catch(()=>!1))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${J.origin}/mcp/${X}/.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 L_=(Q)=>{if(!(Q.hostname==="localhost"||Q.hostname==="127.0.0.1"))Q.protocol="https:";return Q},hY1=async(Q)=>{let J=Q.req.param("connectionId"),X=await _Y1(Q),G=await kY1(J,X);if(!G)return Q.json({error:"Connection not found"},404);try{let Y=await D_(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),$=L_(new URL(Q.req.url)),K=`${$.origin}/mcp/${J}`,Z=`${$.origin}/oauth-proxy/${J}`,H={...W,resource:K,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",W),Q.json({error:"Failed to proxy OAuth metadata",message:W.message},502)}};O_.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Q)=>hY1(Q));O_.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Q)=>hY1(Q));async function L90(Q){let X=new URL(Q).pathname;if(X.endsWith("/"))X=X.slice(0,-1);let G=X!==""&&X!=="/",Y=[];if(G){let $=new URL(Q);$.pathname=`/.well-known/oauth-authorization-server${X}`,Y.push($);let K=new URL(Q);K.pathname=`/.well-known/openid-configuration${X}`,Y.push(K);let Z=new URL(Q);Z.pathname=`${X}/.well-known/openid-configuration`,Y.push(Z)}else{let $=new URL(Q);$.pathname="/.well-known/oauth-authorization-server",Y.push($);let K=new URL(Q);K.pathname="/.well-known/openid-configuration",Y.push(K)}let W=null;for(let $ of Y){if(W=await fetch($.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}O_.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=await _Y1(Q),G=await TI4(J,X);if(!G)return Q.json({error:"Connection not found or no auth server"},404);try{let Y=await L90(G);if(!Y.ok)return new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:{"Content-Type":"application/json"}});let W=await Y.json(),K=`${L_(new URL(Q.req.url)).origin}/oauth-proxy/${J}`,Z={...W,authorization_endpoint:W.authorization_endpoint?`${K}/authorize`:void 0,token_endpoint:W.token_endpoint?`${K}/token`:void 0,registration_endpoint:W.registration_endpoint?`${K}/register`:void 0};return new Response(JSON.stringify(Z),{status:200,headers:{"Content-Type":"application/json"}})}catch(Y){let W=Y;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 fY1=O_;function AI4(Q){if(!Q.isError)return;let J=Q.content;if(!Array.isArray(J))return;for(let X of J)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function bY1(Q){if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q,X=J.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return J}return{value:Q}}async function EI4(Q,J){let X=Q.body;if(!X)return{text:"",truncated:!1};let G=X.getReader(),Y=new TextDecoder,W=!1,$=0,K=[];try{while(!0){let{value:Z,done:H}=await G.read();if(H)break;if(Z){if($+=Z.byteLength,$>J){W=!0;let q=J-($-Z.byteLength);if(q>0)K.push(Y.decode(Z.slice(0,q),{stream:!0}));break}K.push(Y.decode(Z,{stream:!0}))}}}finally{G.releaseLock()}return K.push(Y.decode()),{text:K.join(""),truncated:W}}async function hP(Q){let{ctx:J,enabled:X}=Q,G=Q.organizationId??J.organization?.id;if(!X||!G)return;await J.storage.monitoring.log({organizationId:G,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:J.auth.user?.id||J.auth.apiKey?.userId||null,requestId:J.metadata.requestId,userAgent:J.metadata.userAgent,gatewayId:J.gatewayId})}function xY1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=Date.now()-K;return await hP({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:bY1(Z),isError:Boolean(Z.isError),errorMessage:AI4(Z),durationMs:H}),Z}catch(Z){let H=Z,q=Date.now()-K;throw await hP({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}function gY1(Q){let{ctx:J,enabled:X,connectionId:G,connectionTitle:Y}=Q;return async(W,$)=>{let K=Date.now();try{let Z=await $(),H=J.organization?.id;if(X&&H){let q=Z.clone();(async()=>{try{let{text:F,truncated:V}=await EI4(q,262144),z=Date.now()-K,U=q.headers.get("content-type")??"",N=F;if(U.includes("application/json"))try{N=F.length?JSON.parse(F):null}catch{N=F}let D=Z.status>=400,w=D&&N&&typeof N==="object"&&"error"in N?N.error:void 0,A=typeof w==="string"&&w?w:D&&typeof N==="string"&&N.trim()?N.slice(0,500):D?`HTTP ${Z.status} ${Z.statusText}`.trim():V?"Response body truncated to 262144 bytes":void 0;await hP({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:bY1(N),isError:D,errorMessage:A,durationMs:z})}catch(F){let V=Date.now()-K;await hP({ctx:J,enabled:X,organizationId:H,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${F.message}`,durationMs:V})}})()}return Z}catch(Z){let H=Z,q=Date.now()-K;throw await hP({ctx:J,enabled:X,connectionId:G,connectionTitle:Y,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:q}),Z}}}var uY1=new i5;function jI4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new xU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return{content:[{type:"text",text:`Authorization failed: ${Y.message}`}],isError:!0}}}}function II4(Q,J){return async(X,G)=>{try{let Y=X.params.name;return await new xU(Q.authInstance,Q.auth.user?.id??Q.auth.apiKey?.userId,Y,Q.boundAuth,Q.auth.user?.role,J).check(Y),await G()}catch(Y){return new Response(JSON.stringify({error:`Authorization failed: ${Y.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function mY1(Q,J,{superUser:X}){let G=typeof Q==="string"?await J.storage.connections.findById(Q,J.organization?.id):Q;if(!G)throw Error("Connection not found");let Y=G?.id;if(J.organization&&G.organization_id!==J.organization.id)throw Error("Connection does not belong to the active organization");if(J.organization??={id:G.organization_id},G.status!=="active")throw Error(`Connection inactive: ${G.status}`);let W,$=J.auth.user?.connectionId,K=SY1(async()=>{let y=k80(G.configuration_state,G.configuration_scopes),f=J.auth.user?.id??J.auth.apiKey?.userId;if(!f){console.error("User ID required to issue configuration token");return}try{W=await IY1({sub:f,user:{id:f},metadata:{state:G.configuration_state??void 0,meshUrl:process.env.MESH_URL??J.baseUrl,connectionId:Y,organizationId:J.organization?.id},permissions:y})}catch(m){console.error("Failed to issue configuration token:",m)}}),Z=async()=>{await K();let y={...$?{"x-caller-id":$}:{}};if(G.connection_token)y.Authorization=`Bearer ${G.connection_token}`;if(W)y["x-mesh-token"]=W;if(G.connection_headers)Object.assign(y,G.connection_headers);return y},H=async()=>{let y=await Z(),f=new MW(new URL(G.connection_url),{requestInit:{headers:y}}),m=new oH({name:"mcp-mesh-proxy",version:"1.0.0"});return await m.connect(f),m},q=X?async(y,f)=>await f():jI4(J,Y),F=X?async(y,f)=>await f():II4(J,Y),V={enabled:y01().enabled,connectionId:Y,connectionTitle:G.title,ctx:J},z=xY1(V),U=gY1(V),N=VP(z,q),D=VP(U,F),w=async(y)=>{return N(y,async()=>{let f=await H(),m=Date.now();return await J.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":Y,"tool.name":y.params.name}},async(b)=>{try{let v=await f.callTool(y.params),x=Date.now()-m;return J.meter.createHistogram("connection.proxy.duration").record(x,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),J.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":Y,"tool.name":y.params.name,status:"success"}),b.end(),v}catch(v){let x=v,Q0=Date.now()-m;throw J.meter.createHistogram("connection.proxy.duration").record(Q0,{"connection.id":Y,"tool.name":y.params.name,status:"error"}),J.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":Y,"tool.name":y.params.name,error:x.message}),b.recordException(x),b.end(),v}finally{await f.close()}})})};return{fetch:async(y)=>{let f=new URL(y.url),m;try{m=await H()}catch(x){let Q0=await yY1({error:x,reqUrl:f,connectionId:Y,connectionUrl:G.connection_url,headers:await Z()});if(Q0)return Q0;throw x}let b=new tH({name:"mcp-mesh",version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),v=new Kq({enableJsonResponse:y.headers.get("Accept")?.includes("application/json")??!1});return await b.connect(v),b.server.setRequestHandler(bK,async(x)=>{return await m.listTools()}),b.server.setRequestHandler(xK,w),b.server.setRequestHandler(kK,async()=>{if(m.getServerCapabilities()?.resources)return await m.listResources();return{resources:[]}}),b.server.setRequestHandler(yK,async(x)=>{return await m.readResource(x.params)}),b.server.setRequestHandler(_K,async()=>{if(m.getServerCapabilities()?.resourceTemplates)return await m.listResourceTemplates();return{resourceTemplates:[]}}),b.server.setRequestHandler(hK,async()=>{if(m.getServerCapabilities()?.prompts)return await m.listPrompts();return{prompts:[]}}),b.server.setRequestHandler(fK,async(x)=>{return await m.getPrompt(x.params)}),await v.handleMessage(y)},client:{callTool:(y)=>{return w({method:"tools/call",params:y})},listTools:async()=>{if(G.tools&&G.tools.length>0)return{tools:G.tools.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))};return await(await H()).listTools()},listResources:async()=>{return await(await H()).listResources()},readResource:async(y)=>{return await(await H()).readResource(y)},listResourceTemplates:async()=>{return await(await H()).listResourceTemplates()},listPrompts:async()=>{return await(await H()).listPrompts()},getPrompt:async(y)=>{return await(await H()).getPrompt(y)}},callStreamableTool:async(y,f)=>{let m={method:"tools/call",params:{name:y,arguments:f}};return D(m,async()=>{let b=await Z(),v=new URL(G.connection_url);return v.pathname=v.pathname.replace(/\/$/,"")+`/call-tool/${m.params.name}`,await J.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":Y,"tool.name":m.params.name}},async(x)=>{let Q0=Date.now();try{let c=await fetch(v.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(m.params.arguments),headers:{...b,"Content-Type":"application/json"}}),G0=Date.now()-Q0;return J.meter.createHistogram("connection.proxy.streamable.duration").record(G0,{"connection.id":Y,"tool.name":m.params.name,status:c.ok?"success":"error"}),J.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":Y,"tool.name":m.params.name,status:c.ok?"success":"error"}),x.end(),c}catch(c){let G0=c,U0=Date.now()-Q0;throw J.meter.createHistogram("connection.proxy.streamable.duration").record(U0,{"connection.id":Y,"tool.name":m.params.name,status:"error"}),J.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":Y,"tool.name":m.params.name,error:G0.message}),x.recordException(G0),x.end(),c}})})}}}async function lY1(Q,J){return mY1(Q,J,{superUser:!1})}async function dY1(Q,J){return mY1(Q,J,{superUser:!0})}uY1.all("/:connectionId",async(Q)=>{let J=Q.req.param("connectionId"),X=Q.get("meshContext");try{return await(await X.createMCPProxy(J)).fetch(Q.req.raw)}catch(G){let Y=G;if(Y.message.includes("not found"))return Q.json({error:Y.message},404);if(Y.message.includes("does not belong to the active organization"))return Q.json({error:"Connection not found"},404);if(Y.message.includes("inactive"))return Q.json({error:Y.message},503);return Q.json({error:"Internal server error",message:Y.message},500)}});var pY1=uY1;function CI4(Q,J){for(let[X,G]of Object.entries(J)){let Y=Q[X];if(!Y||Y.length===0){let W=Q["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let $ of G)if(!W.includes($))return!1;continue}if(Y.includes("*"))continue;for(let W of G)if(!Y.includes(W))return!1}return!0}function RI4(Q){let{auth:J,headers:X,role:G,permissions:Y,userId:W}=Q,$=J.api.hasPermission;return{hasPermission:async(K)=>{if(G&&U90.includes(G))return!0;if(Y)return CI4(Y,K);if(!$)return console.error("[Auth] hasPermission API not available"),!1;try{if((await $({headers:X,body:{permission:K}}))?.success===!0)return!0;let H={};for(let F of Object.keys(K))H[F]=["*"];return(await $({headers:X,body:{permission:H}}))?.success===!0}catch(Z){return console.error("[Auth] Permission check failed:",Z),!1}},organization:{create:async(K)=>{return J.api.createOrganization({headers:X,body:K})},update:async(K)=>{return J.api.updateOrganization({headers:X,body:K})},delete:async(K)=>{await J.api.deleteOrganization({headers:X,body:{organizationId:K}})},get:async(K)=>{return J.api.getFullOrganization({headers:X,query:K?{organizationId:K}:void 0})},list:async(K)=>{return J.api.listOrganizations({headers:X,query:K?{userId:K}:void 0})},addMember:async(K)=>{return J.api.addMember({headers:X,body:K})},removeMember:async(K)=>{await J.api.removeMember({headers:X,body:K})},listMembers:async(K)=>{return J.api.listMembers({headers:X,query:K?{organizationId:K.organizationId,limit:K.limit,offset:K.offset}:void 0})},updateMemberRole:async(K)=>{return J.api.updateMemberRole({headers:X,body:K})}},apiKey:{create:async(K)=>{return J.api.createApiKey({body:{...K,userId:W}})},list:async()=>{return J.api.listApiKeys({headers:X})},update:async(K)=>{return J.api.updateApiKey({body:{...K,userId:W}})},delete:async(K)=>{await J.api.deleteApiKey({headers:X,body:{keyId:K}})}}}}async function SI4(Q,J,X){if(U90.includes(X))return;let G=await Q.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",J).where("role","=",X).executeTakeFirst();if(!G?.permission)return;try{return JSON.parse(G.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function vI4(Q,J,X){let G=Q.headers.get("Authorization");try{let Y=new Headers(Q.headers);Y.set("X-MCP-Session-Auth","true");let W=await J.api.getMcpSession({headers:Y});if(W){let $=W.userId,K=await X.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(),Z=K?.role,H=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,q;if(K&&Z)q=await SI4(X,K.organizationId,Z);return{user:{id:$,role:Z},role:Z,permissions:q,organization:H}}}catch(Y){console.error("[Auth] OAuth session check failed:",Y)}if(G?.startsWith("Bearer ")){let Y=G.replace("Bearer ","").trim();try{let W=await CY1(Y);if(W)return{user:{id:W.sub,connectionId:W.metadata?.connectionId},permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}catch{}try{let W=await J.api.verifyApiKey({body:{key:Y}});if(W?.valid&&W.key){let $=W.key.metadata?.organization,K=W.key.permissions;return{apiKeyId:W.key.id,user:{id:W.key.userId},permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let Y=await J.api.getSession({headers:Q.headers});if(Y){let W,$;if(Y.session.activeOrganizationId){let K=await J.api.getFullOrganization({headers:Q.headers}).catch(()=>null);if(K)W={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((H)=>H.userId===Y.user.id)?.role;else W={id:Y.session.activeOrganizationId,slug:"",name:""}}return{user:{id:Y.user.id,email:Y.user.email,role:$},role:$,organization:W}}}catch(Y){console.error("[Auth] Session check failed:",Y)}return{user:void 0}}var cY1,JZ={set:(Q)=>{cY1=Q},create:async(Q)=>{return await cY1(Q)}};function nY1(Q){let J=new _w(Q.encryption.key),X={connections:new yw(Q.db,J),organizationSettings:new N90(Q.db),monitoring:new D90(Q.db),gateways:new hw(Q.db)};return async(G)=>{let Y=G?.headers.get("x-caller-id")??void 0,W=G?await vI4(G,Q.auth,Q.db):{user:void 0},$=RI4({auth:Q.auth,headers:G?.headers??new Headers,role:W.role,permissions:W.permissions,userId:W.user?.id}),K={user:W.user};if(W.apiKeyId)K.apiKey={id:W.apiKeyId,name:"",userId:""};let Z=W.organization,H=G?new URL(G.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${H.protocol}//${H.host}`,F=new xU(Q.auth,K.user?.id,void 0,$,W.role,EY.SELF),V={auth:K,connectionId:Y,organization:Z,storage:X,vault:J,authInstance:Q.auth,boundAuth:$,access:F,db:Q.db,tracer:Q.observability.tracer,meter:Q.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:G?.headers.get("x-mesh-client")||G?.headers.get("User-Agent")||void 0,ipAddress:(G?.headers.get("CF-Connecting-IP")||G?.headers.get("X-Forwarded-For"))??void 0},eventBus:Q.eventBus,createMCPProxy:async(z)=>{return await lY1(z,V)}};return V}}var fP={HEALTH:"/health",METRICS:"/metrics"},bP={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known"},kI4=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/;function iY1(Q){return Q===fP.HEALTH||Q===fP.METRICS||Q.startsWith(bP.WELL_KNOWN)}function _I4(Q){return Q.startsWith(bP.API)}function yI4(Q){return Q==="/mcp"||Q.startsWith(bP.MCP)}function hI4(Q){return Q.startsWith(bP.OAUTH_PROXY)}function fI4(Q){return kI4.test(Q)}function rY1(Q){return _I4(Q)||yI4(Q)||hI4(Q)||iY1(Q)}function aY1(Q){return Q==="/"||Q.startsWith(bP.API_AUTH)||iY1(Q)||fI4(Q)}class oY1{db;constructor(Q){this.db=Q}async publishEvent(Q){let J=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:J,updated_at:J}).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:J,updatedAt:J}}async subscribe(Q){let J=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q.organizationId).where("connection_id","=",Q.connectionId).where("event_type","=",Q.eventType);if(Q.publisher)J=J.where("publisher","=",Q.publisher);else J=J.where("publisher","is",null);if(Q.filter)J=J.where("filter","=",Q.filter);else J=J.where("filter","is",null);let X=await J.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let G=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:G,updated_at:G}).execute(),{id:Q.id,organizationId:Q.organizationId,connectionId:Q.connectionId,publisher:Q.publisher??null,eventType:Q.eventType,filter:Q.filter??null,enabled:!0,createdAt:G,updatedAt:G}}async unsubscribe(Q,J){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Q).where("organization_id","=",J).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Q,J){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Q);if(J)X=X.where("connection_id","=",J);return(await X.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 getSubscription(Q,J){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.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((X)=>X.or([X("publisher","is",null),X("publisher","=",Q.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Q,J,X){if(J.length===0)return;let G=new Date().toISOString(),Y=X??null,W=J.map(($)=>({id:crypto.randomUUID(),event_id:Q,subscription_id:$,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:Y,created_at:G}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(Q){let J=new Date().toISOString(),X;try{X=(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(($)=>$.or([$("d.next_retry_at","is",null),$("d.next_retry_at","<=",J)])).orderBy("d.created_at","asc").limit(Q)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let Y=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","<=",J)])).orderBy("d.created_at","asc").limit(Q).execute();if(Y.length===0)return[];X=Y.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.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",X).where("d.status","=","processing").execute()).map((Y)=>({delivery:{id:Y.delivery_id,eventId:Y.event_id,subscriptionId:Y.subscription_id,status:Y.delivery_status,attempts:Y.delivery_attempts,lastError:Y.delivery_last_error,deliveredAt:Y.delivered_at,nextRetryAt:Y.delivery_next_retry_at,createdAt:Y.delivery_created_at},event:{id:Y.event_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.event_status,attempts:Y.event_attempts,lastError:Y.event_last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.event_created_at,updatedAt:Y.event_updated_at},subscription:{id:Y.subscription_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.subscription_created_at,updatedAt:Y.subscription_updated_at}}))}async markDeliveriesDelivered(Q){if(Q.length===0)return;let J=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:J}).where("id","in",Q).execute()}async markDeliveriesFailed(Q,J,X=20,G=1000,Y=3600000){if(Q.length===0)return;for(let W of Q){let $=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!$)continue;let K=$.attempts+1;if(K>=X)await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let Z=Math.min(G*Math.pow(2,K-1),Y),H=new Date(Date.now()+Z).toISOString();await this.db.updateTable("event_deliveries").set({attempts:K,last_error:J,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(Q){let J=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Q).execute();if(J.length===0)return;let X=J.every((W)=>W.status==="delivered"),G=J.some((W)=>W.status==="failed"),Y=J.some((W)=>W.status==="pending"||W.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Q).execute();else if(G&&!Y)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,J){let X=await this.db.selectFrom("events").selectAll().where("id","=",Q).where("organization_id","=",J).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async cancelEvent(Q,J,X){let G=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Q).where("organization_id","=",J).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((G.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:(G.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Q,J){if(Q.length===0)return;let X=new Date(Date.now()+J).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Q).execute()}async ackDelivery(Q,J,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Q).where("organization_id","=",J).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(($)=>$.exists($.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",J))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(Q);return{success:W}}async syncSubscriptions(Q){let{organizationId:J,connectionId:X,subscriptions:G}=Q,Y=(w,A)=>{return`${w}::${A??""}`},W=await this.listSubscriptions(J,X),$=new Map;for(let w of W)$.set(Y(w.eventType,w.publisher),w);let K=new Map;for(let w of G)K.set(Y(w.eventType,w.publisher),w);let Z=new Date().toISOString(),H=[],q=[],F=[],V=0;for(let[w,A]of K){let P=$.get(w);if(!P)H.push({id:crypto.randomUUID(),organization_id:J,connection_id:X,event_type:A.eventType,publisher:A.publisher??null,filter:A.filter??null,enabled:1,created_at:Z,updated_at:Z});else{let M=P.filter??null,T=A.filter??null;if(M!==T)q.push({id:P.id,filter:T});else V++}}for(let[w,A]of $)if(!K.has(w))F.push(A.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(q.length>0)await Promise.all(q.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:Z}).where("id","=",w.id).execute()));if(F.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",F).execute();let z=H.length,U=q.length,N=F.length,D=await this.listSubscriptions(J,X);return{created:z,updated:U,deleted:N,unchanged:V,subscriptions:D}}}function sY1(Q){return new oY1(Q)}function u5(Q,J,X,G,Y,W,$,K){return u5.fromTZ(u5.tp(Q,J,X,G,Y,W,$),K)}u5.fromTZISO=(Q,J,X)=>u5.fromTZ(bI4(Q,J),X);u5.fromTZ=function(Q,J){let X=new Date(Date.UTC(Q.y,Q.m-1,Q.d,Q.h,Q.i,Q.s)),G=w90(Q.tz,X),Y=new Date(X.getTime()-G),W=w90(Q.tz,Y);if(W-G===0)return Y;{let $=new Date(X.getTime()-W),K=w90(Q.tz,$);if(K-W===0)return $;if(!J&&K-W>0)return $;if(J)throw Error("Invalid date passed to fromTZ()");return Y}};u5.toTZ=function(Q,J){let X=Q.toLocaleString("en-US",{timeZone:J}).replace(/[\u202f]/," "),G=new Date(X);return{y:G.getFullYear(),m:G.getMonth()+1,d:G.getDate(),h:G.getHours(),i:G.getMinutes(),s:G.getSeconds(),tz:J}};u5.tp=(Q,J,X,G,Y,W,$)=>({y:Q,m:J,d:X,h:G,i:Y,s:W,tz:$});function w90(Q,J=new Date){let X=J.toLocaleString("en-US",{timeZone:Q,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],G=J.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${G} GMT`)-Date.parse(`${G} ${X}`)}function bI4(Q,J){let X=new Date(Date.parse(Q));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let G=Q.substring(9);return Q.includes("Z")||G.includes("-")||G.includes("+")?u5.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):u5.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),J)}u5.minitz=u5;var P90=32,gP=31|P90,J71=[1,2,4,8,16],tY1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Q,J){this.pattern=Q,this.timezone=J,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 J=new uX(new Date,this.timezone).getDate(!0);Q[0]=Q[0].replace("?",J.getSeconds().toString()),Q[1]=Q[1].replace("?",J.getMinutes().toString()),Q[2]=Q[2].replace("?",J.getHours().toString()),this.starDOM||(Q[3]=Q[3].replace("?",J.getDate().toString())),Q[4]=Q[4].replace("?",(J.getMonth()+1).toString()),this.starDOW||(Q[5]=Q[5].replace("?",J.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,gP),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Q,J,X,G){let Y=this[Q],W=Q==="day"&&this.lastDayOfMonth;if(J===""&&!W)throw TypeError("CronPattern: configuration entry "+Q+" ("+J+") is empty, check for trailing spaces.");if(J==="*")return Y.fill(G);let $=J.split(",");if($.length>1)for(let K=0;K<$.length;K++)this.partToArray(Q,$[K],X,G);else J.indexOf("-")!==-1&&J.indexOf("/")!==-1?this.handleRangeWithStepping(J,Q,X,G):J.indexOf("-")!==-1?this.handleRange(J,Q,X,G):J.indexOf("/")!==-1?this.handleStepping(J,Q,X,G):J!==""&&this.handleNumber(J,Q,X,G)}throwAtIllegalCharacters(Q){for(let J=0;J<Q.length;J++)if((J===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Q[J]))throw TypeError("CronPattern: configuration entry "+J+" ("+Q[J]+") contains illegal characters.")}handleNumber(Q,J,X,G){let Y=this.extractNth(Q,J),W=parseInt(Y[0],10)+X;if(isNaN(W))throw TypeError("CronPattern: "+J+" is not a number: '"+Q+"'");this.setPart(J,W,Y[1]||G)}setPart(Q,J,X){if(!Object.prototype.hasOwnProperty.call(this,Q))throw TypeError("CronPattern: Invalid part specified: "+Q);if(Q==="dayOfWeek"){if(J===7&&(J=0),J<0||J>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+J);this.setNthWeekdayOfMonth(J,X);return}if(Q==="second"||Q==="minute"){if(J<0||J>=60)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="hour"){if(J<0||J>=24)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="day"){if(J<0||J>=31)throw RangeError("CronPattern: Invalid value for "+Q+": "+J)}else if(Q==="month"&&(J<0||J>=12))throw RangeError("CronPattern: Invalid value for "+Q+": "+J);this[Q][J]=X}handleRangeWithStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Q+"'");let[,$,K,Z]=W,H=parseInt($,10)+X,q=parseInt(K,10)+X,F=parseInt(Z,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(q))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(F===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(F>this[J].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[J].length+")");if(H>q)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let V=H;V<=q;V+=F)this.setPart(J,V,Y[1]||G)}extractNth(Q,J){let X=Q,G;if(X.includes("#")){if(J!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");G=X.split("#")[1],X=X.split("#")[0]}return[X,G]}handleRange(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Q+"'");let $=parseInt(W[0],10)+X,K=parseInt(W[1],10)+X;if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if($>K)throw TypeError("CronPattern: From value is larger than to value: '"+Q+"'");for(let Z=$;Z<=K;Z++)this.setPart(J,Z,Y[1]||G)}handleStepping(Q,J,X,G){let Y=this.extractNth(Q,J),W=Y[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Q+"'");W[0]===""&&(W[0]="*");let $=0;W[0]!=="*"&&($=parseInt(W[0],10)+X);let K=parseInt(W[1],10);if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(K===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(K>this[J].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[J].length+")");for(let Z=$;Z<this[J].length;Z+=K)this.setPart(J,Z,Y[1]||G)}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 J=Q.trim().toLowerCase();return J==="@yearly"||J==="@annually"?"0 0 1 1 *":J==="@monthly"?"0 0 1 * *":J==="@weekly"?"0 0 * * 0":J==="@daily"?"0 0 * * *":J==="@hourly"?"0 * * * *":Q}setNthWeekdayOfMonth(Q,J){if(typeof J!="number"&&J==="L")this.dayOfWeek[Q]=this.dayOfWeek[Q]|P90;else if(J===gP)this.dayOfWeek[Q]=gP;else if(J<6&&J>0)this.dayOfWeek[Q]=this.dayOfWeek[Q]|J71[J-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${J}, Type: ${typeof J}`)}},eY1=[31,28,31,30,31,30,31,31,30,31,30,31],SW=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],uX=class Q{tz;ms;second;minute;hour;day;month;year;constructor(J,X){if(this.tz=X,J&&J instanceof Date)if(!isNaN(J))this.fromDate(J);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(J===void 0)this.fromDate(new Date);else if(J&&typeof J=="string")this.fromString(J);else if(J instanceof Q)this.fromCronDate(J);else throw TypeError("CronDate: Invalid type ("+typeof J+") passed to CronDate constructor")}isNthWeekdayOfMonth(J,X,G,Y){let W=new Date(Date.UTC(J,X,G)).getUTCDay(),$=0;for(let K=1;K<=G;K++)new Date(Date.UTC(J,X,K)).getUTCDay()===W&&$++;if(Y&gP&&J71[$-1]&Y)return!0;if(Y&P90){let K=new Date(Date.UTC(J,X+1,0)).getUTCDate();for(let Z=G+1;Z<=K;Z++)if(new Date(Date.UTC(J,X,Z)).getUTCDay()===W)return!1;return!0}return!1}fromDate(J){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes()+this.tz,this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),this.apply();else{let X=u5.toTZ(J,this.tz);this.ms=J.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=J.getMilliseconds(),this.second=J.getSeconds(),this.minute=J.getMinutes(),this.hour=J.getHours(),this.day=J.getDate(),this.month=J.getMonth(),this.year=J.getFullYear()}fromCronDate(J){this.tz=J.tz,this.year=J.year,this.month=J.month,this.day=J.day,this.hour=J.hour,this.minute=J.minute,this.second=J.second,this.ms=J.ms}apply(){if(this.month>11||this.day>eY1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let J=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=J.getUTCMilliseconds(),this.second=J.getUTCSeconds(),this.minute=J.getUTCMinutes(),this.hour=J.getUTCHours(),this.day=J.getUTCDate(),this.month=J.getUTCMonth(),this.year=J.getUTCFullYear(),!0}else return!1}fromString(J){if(typeof this.tz=="number"){let X=u5.fromTZISO(J);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(),this.apply()}else return this.fromDate(u5.fromTZISO(J,this.tz))}findNext(J,X,G,Y){let W=this[X],$;G.lastDayOfMonth&&(this.month!==1?$=eY1[this.month]:$=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let K=!G.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let Z=this[X]+Y;Z<G[X].length;Z++){let H=G[X][Z];if(X==="day"&&G.lastDayOfMonth&&Z-Y==$&&(H=1),X==="day"&&!G.starDOW){let q=G.dayOfWeek[(K+(Z-Y-1))%7];if(q&&q&gP)q=this.isNthWeekdayOfMonth(this.year,this.month,Z-Y,q)?1:0;else if(q)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${q}`);J.legacyMode&&!G.starDOM?H=H||q:H=H&&q}if(H)return this[X]=Z-Y,W!==this[X]?2:1}return 3}recurse(J,X,G){let Y=this.findNext(X,SW[G][0],J,SW[G][2]);if(Y>1){let W=G+1;for(;W<SW.length;)this[SW[W][0]]=-SW[W][2],W++;if(Y===3)return this[SW[G][1]]++,this[SW[G][0]]=-SW[G][2],this.apply(),this.recurse(J,X,0);if(this.apply())return this.recurse(J,X,G-1)}return G+=1,G>=SW.length?this:this.year>=3000?null:this.recurse(J,X,G)}increment(J,X,G){return this.second+=X.interval!==void 0&&X.interval>1&&G?X.interval:1,this.ms=0,this.apply(),this.recurse(J,X,0)}getDate(J){return J||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)):u5.fromTZ(u5.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function xI4(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 uX(Q.startAt,Q.timezone)),Q.stopAt&&(Q.stopAt=new uX(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 xP(Q){return Object.prototype.toString.call(Q)==="[object Function]"||typeof Q=="function"||Q instanceof Function}function gI4(Q){return xP(Q)}function uI4(Q){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Q):Q&&typeof Q.unref<"u"&&Q.unref()}var Q71=30000,w_=[],P_=class{name;options;_states;fn;constructor(Q,J,X){let G,Y;if(xP(J))Y=J;else if(typeof J=="object")G=J;else if(J!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(xP(X))Y=X;else if(typeof X=="object")G=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=G?.name,this.options=xI4(G),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:G?G.maxRuns:void 0,paused:G?G.paused:!1,pattern:new tY1("* * * * *")},Q&&(Q instanceof Date||typeof Q=="string"&&Q.indexOf(":")>0)?this._states.once=new uX(Q,this.options.timezone||this.options.utcOffset):this._states.pattern=new tY1(Q,this.options.timezone),this.name){if(w_.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");w_.push(this)}return Y!==void 0&&gI4(Y)&&(this.fn=Y,this.schedule()),this}nextRun(Q){let J=this._next(Q);return J?J.getDate(!1):null}nextRuns(Q,J){this._states.maxRuns!==void 0&&Q>this._states.maxRuns&&(Q=this._states.maxRuns);let X=[],G=J||this._states.currentRun||void 0;for(;Q--&&(G=this.nextRun(G));)X.push(G);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Q=this.nextRun(this._states.currentRun),J=!this._states.paused,X=this.fn!==void 0,G=!this._states.kill;return J&&X&&G&&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 J=this._next(Q);return J?Q instanceof uX||Q instanceof Date?J.getTime()-Q.getTime():J.getTime()-new uX(Q).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Q=w_.indexOf(this);Q>=0&&w_.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 J=this.msToNext(),X=this.nextRun(this._states.currentRun);return J==null||isNaN(J)||X===null?this:(J>Q71&&(J=Q71),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),J),this._states.currentTimeout&&this.options.unref&&uI4(this._states.currentTimeout),this)}async _trigger(Q){if(this._states.blocking=!0,this._states.currentRun=new uX(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(J){xP(this.options.catch)&&this.options.catch(J,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new uX(Q,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Q){let J=new Date,X=!this._states.paused&&J.getTime()>=Q.getTime(),G=this._states.blocking&&this.options.protect;X&&!G?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&G&&xP(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Q){let J=!!(Q||this._states.currentRun),X=!1;!Q&&this.options.startAt&&this.options.interval&&([Q,J]=this._calculatePreviousRun(Q,J),X=!Q),Q=new uX(Q,this.options.timezone||this.options.utcOffset),this.options.startAt&&Q&&Q.getTime()<this.options.startAt.getTime()&&(Q=this.options.startAt);let G=this._states.once||new uX(Q,this.options.timezone||this.options.utcOffset);return!X&&G!==this._states.once&&(G=G.increment(this._states.pattern,this.options,J)),this._states.once&&this._states.once.getTime()<=Q.getTime()||G===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&G.getTime()>=this.options.stopAt.getTime()?null:G}_calculatePreviousRun(Q,J){let X=new uX(void 0,this.options.timezone||this.options.utcOffset),G=Q;if(this.options.startAt.getTime()<=X.getTime()){G=this.options.startAt;let Y=G.getTime()+this.options.interval*1000;for(;Y<=X.getTime();)G=new uX(G,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),Y=G.getTime()+this.options.interval*1000;J=!0}return G===null&&(G=void 0),[G,J]}};var M_={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};V_();function X71(){return async(Q,J)=>{try{let X=await JZ.create(),G=await dY1(Q,{...X,auth:{...X.auth,user:{id:"notify-worker"}}}),W=await j80.forClient(G).ON_EVENTS({events:J});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(X){let G=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Q}:`,G),{success:!1,error:G}}}}function Y71(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 mI4(Q){let J=new Map;for(let G of Q){let Y=G.subscription.connectionId,W=J.get(Y);if(W){if(W.deliveryIds.push(G.delivery.id),!W.seenEventIds.has(G.event.id))W.seenEventIds.add(G.event.id),W.events.push(Y71(G.event))}else J.set(Y,{connectionId:G.subscription.connectionId,deliveryIds:[G.delivery.id],events:[Y71(G.event)],seenEventIds:new Set([G.event.id])})}let X=new Map;for(let[G,Y]of J)X.set(G,{connectionId:Y.connectionId,deliveryIds:Y.deliveryIds,events:Y.events});return X}class M90{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Q,J){this.storage=Q;this.notifySubscriber=X71(),this.config={...M_,...J}}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 J=mI4(Q),X=new Set;for(let[G,Y]of J){try{let W=await this.notifySubscriber(Y.connectionId,Y.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(Y,W);else if(W.success)await this.storage.markDeliveriesDelivered(Y.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(Y.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(Y.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let $=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${G}:`,$),await this.storage.markDeliveriesFailed(Y.deliveryIds,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of Q)if(Y.deliveryIds.includes(W.delivery.id))X.add(W.event.id)}for(let G of X)try{await this.storage.updateEventStatus(G);let Y=Q.find((W)=>W.event.id===G)?.event;if(Y?.cron)await this.scheduleNextCronDelivery(Y)}catch(Y){console.error(`[EventBus] Failed to update event status ${G}:`,Y)}}async processPerEventResults(Q,J){let X=[],G=new Map,Y=[],W=new Map;for(let $=0;$<Q.events.length;$++){let K=Q.events?.[$];if(!K)continue;let Z=Q.deliveryIds?.[$];if(!Z)continue;W.set(K.id,Z)}for(let $ of Q.events){let K=W.get($.id);if(!K)continue;let Z=J.results?.[$.id];if(Z)if(Z.success)X.push(K);else if(Z.retryAfter&&Z.retryAfter>0){let H=G.get(Z.retryAfter)||[];H.push(K),G.set(Z.retryAfter,H)}else Y.push({deliveryId:K,error:Z.error||"Event processing failed"});else if(J.success)X.push(K);else if(J.retryAfter&&J.retryAfter>0){let H=G.get(J.retryAfter)||[];H.push(K),G.set(J.retryAfter,H)}else Y.push({deliveryId:K,error:J.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[$,K]of G)await this.storage.scheduleRetryWithoutAttemptIncrement(K,$);if(Y.length>0){let $=new Map;for(let{deliveryId:K,error:Z}of Y){let H=$.get(Z)||[];H.push(K),$.set(Z,H)}for(let[K,Z]of $)await this.storage.markDeliveriesFailed(Z,K,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Q){if(!Q.cron)return;try{let X=new P_(Q.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Q.id} has no more runs`);return}let G=X.toISOString(),Y=await this.storage.getMatchingSubscriptions(Q);if(Y.length===0){console.log(`[EventBus] No subscriptions for cron event ${Q.id}, skipping next delivery`);return}await this.storage.createDeliveries(Q.id,Y.map((W)=>W.id),G),console.log(`[EventBus] Scheduled next cron delivery for event ${Q.id} at ${G}`)}catch(J){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Q.id}:`,J)}}}class T90{storage;worker;notifyStrategy;running=!1;constructor(Q){this.storage=Q.storage,this.notifyStrategy=Q.notifyStrategy,this.worker=new M90(this.storage,Q.config)}async publish(Q,J,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let G;if(X.cron)try{let H=new P_(X.cron).nextRun();if(!H)throw Error("Cron expression does not produce a next run time");G=H.toISOString()}catch(Z){throw Error(`Invalid cron expression: ${Z instanceof Error?Z.message:String(Z)}`)}let Y=crypto.randomUUID(),W=new Date().toISOString(),$=await this.storage.publishEvent({id:Y,organizationId:Q,type:X.type,source:J,subject:X.subject,time:W,data:X.data,cron:X.cron}),K=await this.storage.getMatchingSubscriptions($);if(K.length>0){let Z=X.deliverAt??G;if(await this.storage.createDeliveries(Y,K.map((H)=>H.id),Z),this.notifyStrategy&&!Z)await this.notifyStrategy.notify(Y).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return $}async subscribe(Q,J){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Q,connectionId:J.connectionId,publisher:J.publisher,eventType:J.eventType,filter:J.filter})}async unsubscribe(Q,J){return this.storage.unsubscribe(J,Q)}async listSubscriptions(Q,J){return this.storage.listSubscriptions(Q,J)}async getSubscription(Q,J){return this.storage.getSubscription(J,Q)}async getEvent(Q,J){return this.storage.getEvent(J,Q)}async cancelEvent(Q,J,X){return this.storage.cancelEvent(J,Q,X)}async ackEvent(Q,J,X){return this.storage.ackDelivery(J,Q,X)}async syncSubscriptions(Q,J){return this.storage.syncSubscriptions({organizationId:Q,...J})}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 G71(...Q){return{async start(J){await Promise.all(Q.map((X)=>X.start(J)))},async stop(){await Promise.all(Q.map((J)=>J.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(J){await Promise.all(Q.map((X)=>X.notify(J).catch((G)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",G)})))}}}class T_{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 lI4}from"kysely";var gU="mesh_events";class A90{db;pool;listenClient=null;onNotify=null;constructor(Q,J){this.db=Q;this.pool=J}async start(Q){if(this.listenClient)return;this.onNotify=Q;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(J)=>{if(J.channel===gU&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(J)=>{console.error("[PostgresNotify] Connection error:",J),this.cleanup()}),await this.listenClient.query(`LISTEN ${gU}`),console.log("[PostgresNotify] Started LISTEN on",gU)}catch(J){console.error("[PostgresNotify] Failed to start LISTEN:",J),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${gU}`),console.log("[PostgresNotify] Stopped LISTEN on",gU)}catch{}this.cleanup()}}async notify(Q){try{await lI4`SELECT pg_notify(${gU}, ${Q})`.execute(this.db)}catch(J){console.warn("[PostgresNotify] Failed to send NOTIFY:",J)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function W71(Q,J){let X=sY1(Q.db),G=J?.pollIntervalMs??M_.pollIntervalMs,Y=Q.type==="postgres"?G71(new T_(G),new A90(Q.db,Q.pool)):new T_(G);return new T90({storage:X,config:J,notifyStrategy:Y})}var $71={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 K71=new i5;K71.get("/config",async(Q)=>{try{let J=Object.keys(Z9.socialProviders??{}),X=J.length>0,G=J.map((W)=>({name:W,icon:$71[W].icon})),Y={emailAndPassword:{enabled:Z9.emailAndPassword?.enabled??!1},magicLink:{enabled:Z9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:X,providers:G},sso:Z9.ssoConfig?{enabled:!0,providerId:Z9.ssoConfig.providerId}:{enabled:!1}};return Q.json({success:!0,config:Y})}catch(J){let X=J instanceof Error?J.message:"Failed to load auth config";return Q.json({success:!1,error:X},500)}});var Z71=K71;yk();yJ();class uP{proxies=new Map;constructor(){}static async create(Q,J){let X=new uP,G=await Promise.allSettled(Q.map(async({connection:Y,selectedTools:W})=>{try{let $=await J.createMCPProxy(Y);return{connection:Y,proxy:$,selectedTools:W}}catch($){return console.error(`[gateway] Failed to create proxy for connection ${Y.id}:`,$),null}}));for(let Y of G)if(Y.status==="fulfilled"&&Y.value)X.proxies.set(Y.value.connection.id,Y.value);return X}get(Q){return this.proxies.get(Q)}entries(){return this.proxies.entries()}forEach(Q){this.proxies.forEach((J,X)=>Q(J,X))}async mapAsync(Q){let J=[];for(let[X,G]of this.proxies.entries())J.push(Q(G,X));return await Promise.all(J)}async mapSettled(Q){return Promise.allSettled(Array.from(this.proxies.entries()).map(([J,X])=>Q(X,J)))}get size(){return this.proxies.size}}function dI4(Q){return Q.toLowerCase().split(/[\s_\-./]+/).filter((J)=>J.length>=2)}function pI4(Q,J){let X=0,G=J.name.toLowerCase(),Y=(J.description??"").toLowerCase(),W=J.connectionTitle.toLowerCase();for(let $ of Q){if(G===$)X+=10;else if(G.includes($))X+=3;if(Y.includes($))X+=2;if(W.includes($))X+=1}return X}function cI4(Q,J,X){let G=dI4(Q);if(G.length===0)return J.slice(0,X);return J.map((Y)=>({tool:Y,score:pI4(G,Y)})).filter((Y)=>Y.score>0).sort((Y,W)=>W.score-Y.score).slice(0,X).map((Y)=>Y.tool)}var H71=(Q)=>({tools:Q.tools,callTool:(J,X)=>Q.callTool(J,X)}),XZ={SEARCH:"GATEWAY_SEARCH_TOOLS",DESCRIBE:"GATEWAY_DESCRIBE_TOOLS",CALL:"GATEWAY_CALL_TOOL"};function nI4(Q){let J=Q.categories.length>0?` Available categories: ${Q.categories.join(", ")}.`:"",X=Q.tools.map((G)=>G.name);return[{name:XZ.SEARCH,description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas.${J} Total tools: ${Q.tools.length}.`,inputSchema:{type:"object",properties:{query:{type:"string",description:"Natural language search query (e.g., 'send email', 'create order')"},limit:{type:"number",description:"Maximum results to return (default: 10)",default:10}},required:["query"]}},{name:XZ.DESCRIBE,description:"Get detailed schemas for specific tools. Call after searching to get full input/output schemas.",inputSchema:{type:"object",properties:{tools:{type:"array",items:{type:"string",enum:X},description:"Array of tool names to get detailed schemas for"}},required:["tools"]}},{name:XZ.CALL,description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:{type:"object",properties:{name:{type:"string",enum:X,description:"The name of the tool to execute"},arguments:{type:"object",description:"Arguments to pass to the tool",additionalProperties:!0}},required:["name"]}}]}var iI4=(Q)=>{let J=new Map(Q.tools.map((G)=>[G.name,G])),X=async(G,Y)=>{switch(G){case XZ.SEARCH:{let W=Y.query??"",$=Y.limit??10,K=cI4(W,Q.tools,$);return{content:[{type:"text",text:JSON.stringify({query:W,results:K.map((Z)=>({name:Z.name,description:Z.description,connection:Z.connectionTitle})),totalAvailable:Q.tools.length},null,2)}]}}case XZ.DESCRIBE:{let W=Y.tools??[];if(W.length===0)return{content:[{type:"text",text:JSON.stringify({error:"No tool names provided"})}],isError:!0};let $=W.map((K)=>J.get(K)).filter((K)=>K!==void 0);return{content:[{type:"text",text:JSON.stringify({tools:$.map((K)=>({name:K.name,description:K.description,connection:K.connectionTitle,inputSchema:K.inputSchema,outputSchema:K.outputSchema})),notFound:W.filter((K)=>!J.has(K))},null,2)}]}}case XZ.CALL:{let W=Y.name,$=Y.arguments??{};if(!W)return{content:[{type:"text",text:JSON.stringify({error:"Tool name is required"})}],isError:!0};if(!J.has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use ${XZ.SEARCH} to find available tools.`}],isError:!0};return Q.callTool(W,$)}default:return{content:[{type:"text",text:`Unknown meta-tool: ${G}. Available: ${Object.values(XZ).join(", ")}`}],isError:!0}}};return{tools:nI4(Q),callTool:X}};function q71(Q){switch(Q){case"smart_tool_selection":return iI4;case"code_execution":return H71;case"passthrough":default:return H71}}class A_{proxies;options;cache;constructor(Q,J){this.proxies=Q;this.options=J;this.cache=XG(()=>this.loadTools())}async loadTools(){let Q=await this.proxies.mapSettled(async(Z,H)=>{try{let F=(await Z.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>!V.has(z.name))}}else if(Z.selectedTools&&Z.selectedTools.length>0){let V=new Set(Z.selectedTools);F=F.filter((z)=>V.has(z.name))}return{connectionId:H,connectionTitle:Z.connection.title,tools:F}}catch(q){return console.error(`[gateway] Failed to list tools for connection ${H}:`,q),null}}),J=new Set,X=[],G=new Map,Y=new Set;for(let Z of Q){if(Z.status!=="fulfilled"||!Z.value)continue;let{connectionId:H,connectionTitle:q,tools:F}=Z.value;Y.add(q);for(let V of F){if(J.has(V.name))continue;J.add(V.name),X.push({...V,connectionId:H,connectionTitle:q}),G.set(V.name,{connectionId:H,originalName:V.name})}}let W=async(Z,H)=>{let q=G.get(Z);if(!q)return{content:[{type:"text",text:`Tool not found: ${Z}`}],isError:!0};let F=this.proxies.get(q.connectionId);if(!F)return{content:[{type:"text",text:`Connection not found for tool: ${Z}`}],isError:!0};return await F.proxy.client.callTool({name:q.originalName,arguments:H})},K=q71(this.options.strategy)({tools:X,callTool:W,categories:Array.from(Y).sort()});return{tools:X,mappings:G,strategyResult:K}}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,J){let X=await this.cache,G=X.mappings.get(Q);if(G){let W=this.proxies.get(G.connectionId);if(W)return W.proxy.callStreamableTool(G.originalName,J)}let Y=await X.strategyResult.callTool(Q,J);return new Response(JSON.stringify(Y),{headers:{"Content-Type":"application/json"}})}}class E_{proxies;cache;constructor(Q){this.proxies=Q;this.cache=XG(()=>this.loadResources())}async loadResources(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listResources();return{connectionId:W,resources:$.resources}}catch($){return console.error(`[gateway] Failed to list resources for connection ${W}:`,$),{connectionId:W,resources:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,resources:$}=Y.value;for(let K of $){if(J.has(K.uri))continue;J.add(K.uri),X.push(K),G.set(K.uri,W)}}return{resources:X,mappings:G}}async list(){return{resources:(await this.cache).resources}}async read(Q){let X=(await this.cache).mappings.get(Q.uri);if(!X)throw Error(`Resource not found: ${Q.uri}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for resource: ${Q.uri}`);return await G.proxy.client.readResource(Q)}}class j_{proxies;cache;constructor(Q){this.proxies=Q;this.cache=XG(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let Q=await this.proxies.mapSettled(async(X,G)=>{try{let Y=await X.proxy.client.listResourceTemplates();return{connectionId:G,templates:Y.resourceTemplates}}catch(Y){return console.error(`[gateway] Failed to list resource templates for connection ${G}:`,Y),{connectionId:G,templates:[]}}}),J=[];for(let X of Q){if(X.status!=="fulfilled")continue;let{templates:G}=X.value;for(let Y of G)J.push(Y)}return{templates:J}}async list(){return{resourceTemplates:(await this.cache).templates}}}class I_{proxies;cache;constructor(Q){this.proxies=Q;this.cache=XG(()=>this.loadPrompts())}async loadPrompts(){let Q=await this.proxies.mapSettled(async(Y,W)=>{try{let $=await Y.proxy.client.listPrompts();return{connectionId:W,prompts:$.prompts}}catch($){return console.error(`[gateway] Failed to list prompts for connection ${W}:`,$),{connectionId:W,prompts:[]}}}),J=new Set,X=[],G=new Map;for(let Y of Q){if(Y.status!=="fulfilled")continue;let{connectionId:W,prompts:$}=Y.value;for(let K of $){if(J.has(K.name))continue;J.add(K.name),X.push(K),G.set(K.name,W)}}return{prompts:X,mappings:G}}async list(){return{prompts:(await this.cache).prompts}}async get(Q){let X=(await this.cache).mappings.get(Q.name);if(!X)throw Error(`Prompt not found: ${Q.name}`);let G=this.proxies.get(X);if(!G)throw Error(`Connection not found for prompt: ${Q.name}`);return await G.proxy.client.getPrompt(Q)}}W_();var F71=new i5;async function rI4(Q,J){let X=await uP.create(Q.connections,J),G=new A_(X,{selectionMode:Q.toolSelectionMode,strategy:Q.toolSelectionStrategy}),Y=new E_(X),W=new j_(X),$=new I_(X);return{client:{listTools:G.list.bind(G),callTool:G.call.bind(G),listResources:Y.list.bind(Y),readResource:Y.read.bind(Y),listResourceTemplates:W.list.bind(W),listPrompts:$.list.bind($),getPrompt:$.get.bind($)},callStreamableTool:G.callStreamable.bind(G)}}async function aI4(Q,J){let X;if(Q.toolSelectionMode==="exclusion"){let W=(await J.storage.connections.list(Q.organizationId)).filter((K)=>K.status==="active"),$=new Map;for(let K of Q.connections)$.set(K.connectionId,K.selectedTools);X=[];for(let K of W){let Z=$.get(K.id);if(Z===void 0)X.push({connection:K,selectedTools:null});else if(Z===null||Z.length===0);else X.push({connection:K,selectedTools:Z})}}else{let Y=Q.connections.map(($)=>$.connectionId),W=[];for(let $ of Y){let K=await J.storage.connections.findById($);if(K&&K.status==="active")W.push(K)}X=W.map(($)=>{let K=Q.connections.find((Z)=>Z.connectionId===$.id);return{connection:$,selectedTools:K?.selectedTools??null}})}let G={connections:X,toolSelectionMode:Q.toolSelectionMode,toolSelectionStrategy:Q.toolSelectionStrategy};return rI4(G,J)}F71.all("/gateway/:gatewayId?",async(Q)=>{let J=Q.req.param("gatewayId"),X=Q.get("meshContext");try{let G=null;if(J)G=await X.storage.gateways.findById(J);else{let Z=Q.req.header("x-org-id"),H=Q.req.header("x-org-slug");if(Z)G=await X.storage.gateways.getDefaultByOrgId(Z);else if(H)G=await X.storage.gateways.getDefaultByOrgSlug(H);else return Q.json({error:"Gateway ID required, or provide x-org-id or x-org-slug header for default gateway"},400)}if(!G){if(J)return Q.json({error:`Gateway not found: ${J}`},404);return Q.json({error:"No default gateway configured for this organization"},404)}if(X.gatewayId=G.id,G.status!=="active")return Q.json({error:`Gateway is inactive: ${G.id}`},503);let Y=await X.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",G.organizationId).executeTakeFirst();if(Y)X.organization={id:Y.id,slug:Y.slug,name:Y.name};let W=await aI4(G,X),$=new tH({name:`mcp-gateway-${G.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),K=new Kq({enableJsonResponse:Q.req.header("Accept")?.includes("application/json")??!1});return await $.connect(K),$.server.setRequestHandler(bK,async(Z)=>{return W.client.listTools()}),$.server.setRequestHandler(xK,async(Z)=>{return await W.client.callTool(Z.params)}),$.server.setRequestHandler(kK,async()=>{return W.client.listResources()}),$.server.setRequestHandler(yK,async(Z)=>{return W.client.readResource(Z.params)}),$.server.setRequestHandler(_K,async()=>{return W.client.listResourceTemplates()}),$.server.setRequestHandler(hK,async()=>{return W.client.listPrompts()}),$.server.setRequestHandler(fK,async(Z)=>{return W.client.getPrompt(Z.params)}),await K.handleMessage(Q.req.raw).then(async(Z)=>{return Z})}catch(G){let Y=G;return console.error("[gateway] Error handling gateway request:",Y),Q.json({error:"Internal server error",message:Y.message},500)}});var V71=F71;z90();var z71=new i5;z71.all("/",async(Q)=>{return V90(Q.get("meshContext")).fetch(Q.req.raw)});var U71=z71;var d71="vercel.ai.error",oI4=Symbol.for(d71),N71,B71,D1=class Q extends(B71=Error,N71=oI4,B71){constructor({name:J,message:X,cause:G}){super(X);this[N71]=!0,this.name=J,this.cause=G}static isInstance(J){return Q.hasMarker(J,d71)}static hasMarker(J,X){let G=Symbol.for(X);return J!=null&&typeof J==="object"&&G in J&&typeof J[G]==="boolean"&&J[G]===!0}},p71="AI_APICallError",c71=`vercel.ai.error.${p71}`,sI4=Symbol.for(c71),O71,D71,H9=class extends(D71=D1,O71=sI4,D71){constructor({message:Q,url:J,requestBodyValues:X,statusCode:G,responseHeaders:Y,responseBody:W,cause:$,isRetryable:K=G!=null&&(G===408||G===409||G===429||G>=500),data:Z}){super({name:p71,message:Q,cause:$});this[O71]=!0,this.url=J,this.requestBodyValues=X,this.statusCode=G,this.responseHeaders=Y,this.responseBody=W,this.isRetryable=K,this.data=Z}static isInstance(Q){return D1.hasMarker(Q,c71)}},n71="AI_EmptyResponseBodyError",i71=`vercel.ai.error.${n71}`,tI4=Symbol.for(i71),L71,w71,r71=class extends(w71=D1,L71=tI4,w71){constructor({message:Q="Empty response body"}={}){super({name:n71,message:Q});this[L71]=!0}static isInstance(Q){return D1.hasMarker(Q,i71)}};function YG(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 a71="AI_InvalidArgumentError",o71=`vercel.ai.error.${a71}`,eI4=Symbol.for(o71),P71,M71,s71=class extends(M71=D1,P71=eI4,M71){constructor({message:Q,cause:J,argument:X}){super({name:a71,message:Q,cause:J});this[P71]=!0,this.argument=X}static isInstance(Q){return D1.hasMarker(Q,o71)}},t71="AI_InvalidPromptError",e71=`vercel.ai.error.${t71}`,QC4=Symbol.for(e71),T71,A71,Hq=class extends(A71=D1,T71=QC4,A71){constructor({prompt:Q,message:J,cause:X}){super({name:t71,message:`Invalid prompt: ${J}`,cause:X});this[T71]=!0,this.prompt=Q}static isInstance(Q){return D1.hasMarker(Q,e71)}},QG1="AI_InvalidResponseDataError",JG1=`vercel.ai.error.${QG1}`,JC4=Symbol.for(JG1),E71,j71,Eb6=class extends(j71=D1,E71=JC4,j71){constructor({data:Q,message:J=`Invalid response data: ${JSON.stringify(Q)}.`}){super({name:QG1,message:J});this[E71]=!0,this.data=Q}static isInstance(Q){return D1.hasMarker(Q,JG1)}},XG1="AI_JSONParseError",YG1=`vercel.ai.error.${XG1}`,XC4=Symbol.for(YG1),I71,C71,mP=class extends(C71=D1,I71=XC4,C71){constructor({text:Q,cause:J}){super({name:XG1,message:`JSON parsing failed: Text: ${Q}.
|
|
1069
1069
|
Error message: ${YG(J)}`,cause:J});this[I71]=!0,this.text=Q}static isInstance(Q){return D1.hasMarker(Q,YG1)}},GG1="AI_LoadAPIKeyError",WG1=`vercel.ai.error.${GG1}`,YC4=Symbol.for(WG1),R71,S71,jb6=class extends(S71=D1,R71=YC4,S71){constructor({message:Q}){super({name:GG1,message:Q});this[R71]=!0}static isInstance(Q){return D1.hasMarker(Q,WG1)}},$G1="AI_LoadSettingError",KG1=`vercel.ai.error.${$G1}`,GC4=Symbol.for(KG1),v71,k71,Ib6=class extends(k71=D1,v71=GC4,k71){constructor({message:Q}){super({name:$G1,message:Q});this[v71]=!0}static isInstance(Q){return D1.hasMarker(Q,KG1)}},ZG1="AI_NoContentGeneratedError",HG1=`vercel.ai.error.${ZG1}`,WC4=Symbol.for(HG1),_71,y71,Cb6=class extends(y71=D1,_71=WC4,y71){constructor({message:Q="No content generated."}={}){super({name:ZG1,message:Q});this[_71]=!0}static isInstance(Q){return D1.hasMarker(Q,HG1)}},qG1="AI_NoSuchModelError",FG1=`vercel.ai.error.${qG1}`,$C4=Symbol.for(FG1),h71,f71,Rb6=class extends(f71=D1,h71=$C4,f71){constructor({errorName:Q=qG1,modelId:J,modelType:X,message:G=`No such ${X}: ${J}`}){super({name:Q,message:G});this[h71]=!0,this.modelId=J,this.modelType=X}static isInstance(Q){return D1.hasMarker(Q,FG1)}},VG1="AI_TooManyEmbeddingValuesForCallError",zG1=`vercel.ai.error.${VG1}`,KC4=Symbol.for(zG1),b71,x71,Sb6=class extends(x71=D1,b71=KC4,x71){constructor(Q){super({name:VG1,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[b71]=!0,this.provider=Q.provider,this.modelId=Q.modelId,this.maxEmbeddingsPerCall=Q.maxEmbeddingsPerCall,this.values=Q.values}static isInstance(Q){return D1.hasMarker(Q,zG1)}},UG1="AI_TypeValidationError",NG1=`vercel.ai.error.${UG1}`,ZC4=Symbol.for(NG1),g71,u71,bY=class Q extends(u71=D1,g71=ZC4,u71){constructor({value:J,cause:X}){super({name:UG1,message:`Type validation failed: Value: ${JSON.stringify(J)}.
|
|
1070
1070
|
Error message: ${YG(X)}`,cause:X});this[g71]=!0,this.value=J}static isInstance(J){return D1.hasMarker(J,NG1)}static wrap({value:J,cause:X}){return Q.isInstance(X)&&X.value===J?X:new Q({value:J,cause:X})}},BG1="AI_UnsupportedFunctionalityError",OG1=`vercel.ai.error.${BG1}`,HC4=Symbol.for(OG1),m71,l71,vb6=class extends(l71=D1,m71=HC4,l71){constructor({functionality:Q,message:J=`'${Q}' functionality not supported.`}){super({name:BG1,message:J});this[m71]=!0,this.functionality=Q}static isInstance(Q){return D1.hasMarker(Q,OG1)}};var I={};_6(I,{xid:()=>HS4,void:()=>SS4,uuidv7:()=>XS4,uuidv6:()=>JS4,uuidv4:()=>QS4,uuid:()=>eR4,url:()=>YS4,uppercase:()=>qM,unknown:()=>Ly,union:()=>jy,undefined:()=>CS4,ulid:()=>ZS4,uint64:()=>jS4,uint32:()=>TS4,tuple:()=>bS4,trim:()=>BM,treeifyError:()=>b90,transform:()=>pX0,toUpperCase:()=>DM,toLowerCase:()=>OM,toJSONSchema:()=>wM,templateLiteral:()=>nS4,symbol:()=>IS4,superRefine:()=>kW1,success:()=>pS4,stringbool:()=>oS4,stringFormat:()=>LS4,string:()=>LX0,strictObject:()=>yS4,startsWith:()=>VM,size:()=>KM,setErrorMap:()=>Qv4,set:()=>uS4,safeParseAsync:()=>PM,safeParse:()=>DX0,registry:()=>p_,regexes:()=>zq,regex:()=>ZM,refine:()=>vW1,record:()=>KW1,readonly:()=>EW1,property:()=>YX0,promise:()=>iS4,prettifyError:()=>x90,preprocess:()=>tS4,prefault:()=>DW1,positive:()=>eJ0,pipe:()=>My,partialRecord:()=>xS4,parseAsync:()=>OX0,parse:()=>BX0,overwrite:()=>hW,optional:()=>wy,object:()=>_S4,number:()=>nG1,nullish:()=>dS4,nullable:()=>Py,null:()=>sG1,normalize:()=>NM,nonpositive:()=>JX0,nonoptional:()=>LW1,nonnegative:()=>XX0,never:()=>Ty,negative:()=>QX0,nativeEnum:()=>mS4,nanoid:()=>WS4,nan:()=>cS4,multipleOf:()=>Bq,minSize:()=>Oq,minLength:()=>GZ,mime:()=>UM,maxSize:()=>nU,maxLength:()=>iU,map:()=>gS4,lte:()=>mX,lt:()=>_W,lowercase:()=>HM,looseObject:()=>hS4,locales:()=>GM,literal:()=>VW1,length:()=>rU,lazy:()=>CW1,ksuid:()=>qS4,keyof:()=>kS4,jwt:()=>DS4,json:()=>sS4,iso:()=>Oy,ipv6:()=>VS4,ipv4:()=>FS4,intersection:()=>WW1,int64:()=>ES4,int32:()=>MS4,int:()=>wX0,instanceof:()=>aS4,includes:()=>FM,guid:()=>tR4,gte:()=>JJ,gt:()=>yW,globalRegistry:()=>GG,getErrorMap:()=>Jv4,function:()=>FX0,formatError:()=>tP,float64:()=>PS4,float32:()=>wS4,flattenError:()=>sP,file:()=>lS4,enum:()=>qW1,endsWith:()=>zM,emoji:()=>GS4,email:()=>sR4,e164:()=>OS4,discriminatedUnion:()=>fS4,date:()=>vS4,custom:()=>rS4,cuid2:()=>KS4,cuid:()=>$S4,core:()=>fW,config:()=>B9,coerce:()=>rX0,clone:()=>fJ,cidrv6:()=>US4,cidrv4:()=>zS4,check:()=>SW1,catch:()=>MW1,boolean:()=>iG1,bigint:()=>AS4,base64url:()=>BS4,base64:()=>NS4,array:()=>uX0,any:()=>RS4,_default:()=>BW1,_ZodString:()=>PX0,ZodXID:()=>RX0,ZodVoid:()=>JW1,ZodUnknown:()=>eG1,ZodUnion:()=>mX0,ZodUndefined:()=>aG1,ZodUUID:()=>bW,ZodURL:()=>TX0,ZodULID:()=>CX0,ZodType:()=>I4,ZodTuple:()=>$W1,ZodTransform:()=>dX0,ZodTemplateLiteral:()=>jW1,ZodSymbol:()=>rG1,ZodSuccess:()=>wW1,ZodStringFormat:()=>F8,ZodString:()=>TM,ZodSet:()=>HW1,ZodRecord:()=>lX0,ZodRealError:()=>aU,ZodReadonly:()=>AW1,ZodPromise:()=>RW1,ZodPrefault:()=>OW1,ZodPipe:()=>iX0,ZodOptional:()=>cX0,ZodObject:()=>Ey,ZodNumberFormat:()=>oU,ZodNumber:()=>AM,ZodNullable:()=>UW1,ZodNull:()=>oG1,ZodNonOptional:()=>nX0,ZodNever:()=>QW1,ZodNanoID:()=>EX0,ZodNaN:()=>TW1,ZodMap:()=>ZW1,ZodLiteral:()=>FW1,ZodLazy:()=>IW1,ZodKSUID:()=>SX0,ZodJWT:()=>xX0,ZodIssueCode:()=>eS4,ZodIntersection:()=>GW1,ZodISOTime:()=>Ny,ZodISODuration:()=>By,ZodISODateTime:()=>zy,ZodISODate:()=>Uy,ZodIPv6:()=>kX0,ZodIPv4:()=>vX0,ZodGUID:()=>Dy,ZodFile:()=>zW1,ZodError:()=>aR4,ZodEnum:()=>MM,ZodEmoji:()=>AX0,ZodEmail:()=>MX0,ZodE164:()=>bX0,ZodDiscriminatedUnion:()=>YW1,ZodDefault:()=>NW1,ZodDate:()=>Ay,ZodCustomStringFormat:()=>cG1,ZodCustom:()=>Iy,ZodCatch:()=>PW1,ZodCUID2:()=>IX0,ZodCUID:()=>jX0,ZodCIDRv6:()=>yX0,ZodCIDRv4:()=>_X0,ZodBoolean:()=>EM,ZodBigIntFormat:()=>gX0,ZodBigInt:()=>jM,ZodBase64URL:()=>fX0,ZodBase64:()=>hX0,ZodArray:()=>XW1,ZodAny:()=>tG1,TimePrecision:()=>jJ0,NEVER:()=>E90,$output:()=>MJ0,$input:()=>TJ0,$brand:()=>j90});var fW={};_6(fW,{version:()=>y50,util:()=>H1,treeifyError:()=>b90,toJSONSchema:()=>wM,toDotPath:()=>wG1,safeParseAsync:()=>u90,safeParse:()=>g90,registry:()=>p_,regexes:()=>zq,prettifyError:()=>x90,parseAsync:()=>k_,parse:()=>S_,locales:()=>GM,isValidJWT:()=>xG1,isValidBase64URL:()=>bG1,isValidBase64:()=>JQ0,globalRegistry:()=>GG,globalConfig:()=>lP,function:()=>FX0,formatError:()=>tP,flattenError:()=>sP,config:()=>B9,clone:()=>fJ,_xid:()=>Xy,_void:()=>aJ0,_uuidv7:()=>a_,_uuidv6:()=>r_,_uuidv4:()=>i_,_uuid:()=>n_,_url:()=>o_,_uppercase:()=>qM,_unknown:()=>cU,_union:()=>IR4,_undefined:()=>cJ0,_ulid:()=>Jy,_uint64:()=>dJ0,_uint32:()=>bJ0,_tuple:()=>GX0,_trim:()=>BM,_transform:()=>fR4,_toUpperCase:()=>DM,_toLowerCase:()=>OM,_templateLiteral:()=>cR4,_symbol:()=>pJ0,_success:()=>mR4,_stringbool:()=>ZX0,_stringFormat:()=>HX0,_string:()=>AJ0,_startsWith:()=>VM,_size:()=>KM,_set:()=>kR4,_safeParseAsync:()=>y_,_safeParse:()=>__,_regex:()=>ZM,_refine:()=>KX0,_record:()=>SR4,_readonly:()=>pR4,_property:()=>YX0,_promise:()=>iR4,_positive:()=>eJ0,_pipe:()=>dR4,_parseAsync:()=>v_,_parse:()=>R_,_overwrite:()=>hW,_optional:()=>bR4,_number:()=>vJ0,_nullable:()=>xR4,_null:()=>nJ0,_normalize:()=>NM,_nonpositive:()=>JX0,_nonoptional:()=>uR4,_nonnegative:()=>XX0,_never:()=>rJ0,_negative:()=>QX0,_nativeEnum:()=>yR4,_nanoid:()=>t_,_nan:()=>tJ0,_multipleOf:()=>Bq,_minSize:()=>Oq,_minLength:()=>GZ,_min:()=>JJ,_mime:()=>UM,_maxSize:()=>nU,_maxLength:()=>iU,_max:()=>mX,_map:()=>vR4,_lte:()=>mX,_lt:()=>_W,_lowercase:()=>HM,_literal:()=>hR4,_length:()=>rU,_lazy:()=>nR4,_ksuid:()=>Yy,_jwt:()=>Fy,_isoTime:()=>RJ0,_isoDuration:()=>SJ0,_isoDateTime:()=>IJ0,_isoDate:()=>CJ0,_ipv6:()=>Wy,_ipv4:()=>Gy,_intersection:()=>RR4,_int64:()=>lJ0,_int32:()=>fJ0,_int:()=>_J0,_includes:()=>FM,_guid:()=>$M,_gte:()=>JJ,_gt:()=>yW,_float64:()=>hJ0,_float32:()=>yJ0,_file:()=>WX0,_enum:()=>_R4,_endsWith:()=>zM,_emoji:()=>s_,_email:()=>c_,_e164:()=>qy,_discriminatedUnion:()=>CR4,_default:()=>gR4,_date:()=>oJ0,_custom:()=>$X0,_cuid2:()=>Qy,_cuid:()=>e_,_coercedString:()=>EJ0,_coercedNumber:()=>kJ0,_coercedDate:()=>sJ0,_coercedBoolean:()=>gJ0,_coercedBigint:()=>mJ0,_cidrv6:()=>Ky,_cidrv4:()=>$y,_catch:()=>lR4,_boolean:()=>xJ0,_bigint:()=>uJ0,_base64url:()=>Hy,_base64:()=>Zy,_array:()=>LM,_any:()=>iJ0,TimePrecision:()=>jJ0,NEVER:()=>E90,JSONSchemaGenerator:()=>Vy,JSONSchema:()=>lG1,Doc:()=>x_,$output:()=>MJ0,$input:()=>TJ0,$constructor:()=>T0,$brand:()=>j90,$ZodXID:()=>c50,$ZodVoid:()=>UQ0,$ZodUnknown:()=>pU,$ZodUnion:()=>d_,$ZodUndefined:()=>qQ0,$ZodUUID:()=>b50,$ZodURL:()=>g50,$ZodULID:()=>p50,$ZodType:()=>Z4,$ZodTuple:()=>Nq,$ZodTransform:()=>JM,$ZodTemplateLiteral:()=>yQ0,$ZodSymbol:()=>HQ0,$ZodSuccess:()=>SQ0,$ZodStringFormat:()=>$8,$ZodString:()=>Uq,$ZodSet:()=>PQ0,$ZodRegistry:()=>WM,$ZodRecord:()=>LQ0,$ZodRealError:()=>lU,$ZodReadonly:()=>_Q0,$ZodPromise:()=>hQ0,$ZodPrefault:()=>CQ0,$ZodPipe:()=>XM,$ZodOptional:()=>EQ0,$ZodObject:()=>BQ0,$ZodNumberFormat:()=>KQ0,$ZodNumber:()=>m_,$ZodNullable:()=>jQ0,$ZodNull:()=>FQ0,$ZodNonOptional:()=>RQ0,$ZodNever:()=>zQ0,$ZodNanoID:()=>m50,$ZodNaN:()=>kQ0,$ZodMap:()=>wQ0,$ZodLiteral:()=>TQ0,$ZodLazy:()=>fQ0,$ZodKSUID:()=>n50,$ZodJWT:()=>WQ0,$ZodIntersection:()=>DQ0,$ZodISOTime:()=>a50,$ZodISODuration:()=>o50,$ZodISODateTime:()=>i50,$ZodISODate:()=>r50,$ZodIPv6:()=>t50,$ZodIPv4:()=>s50,$ZodGUID:()=>f50,$ZodFunction:()=>qX0,$ZodFile:()=>AQ0,$ZodError:()=>oP,$ZodEnum:()=>MQ0,$ZodEmoji:()=>u50,$ZodEmail:()=>x50,$ZodE164:()=>GQ0,$ZodDiscriminatedUnion:()=>OQ0,$ZodDefault:()=>IQ0,$ZodDate:()=>NQ0,$ZodCustomStringFormat:()=>$Q0,$ZodCustom:()=>bQ0,$ZodCheckUpperCase:()=>I50,$ZodCheckStringFormat:()=>dU,$ZodCheckStartsWith:()=>R50,$ZodCheckSizeEquals:()=>P50,$ZodCheckRegex:()=>E50,$ZodCheckProperty:()=>v50,$ZodCheckOverwrite:()=>_50,$ZodCheckNumberFormat:()=>O50,$ZodCheckMultipleOf:()=>B50,$ZodCheckMinSize:()=>w50,$ZodCheckMinLength:()=>T50,$ZodCheckMimeType:()=>k50,$ZodCheckMaxSize:()=>L50,$ZodCheckMaxLength:()=>M50,$ZodCheckLowerCase:()=>j50,$ZodCheckLessThan:()=>f_,$ZodCheckLengthEquals:()=>A50,$ZodCheckIncludes:()=>C50,$ZodCheckGreaterThan:()=>b_,$ZodCheckEndsWith:()=>S50,$ZodCheckBigIntFormat:()=>D50,$ZodCheck:()=>l8,$ZodCatch:()=>vQ0,$ZodCUID2:()=>d50,$ZodCUID:()=>l50,$ZodCIDRv6:()=>QQ0,$ZodCIDRv4:()=>e50,$ZodBoolean:()=>eP,$ZodBigIntFormat:()=>ZQ0,$ZodBigInt:()=>l_,$ZodBase64URL:()=>YQ0,$ZodBase64:()=>XQ0,$ZodAsyncError:()=>vW,$ZodArray:()=>QM,$ZodAny:()=>VQ0});var E90=Object.freeze({status:"aborted"});function T0(Q,J,X){function G(K,Z){var H;Object.defineProperty(K,"_zod",{value:K._zod??{},enumerable:!1}),(H=K._zod).traits??(H.traits=new Set),K._zod.traits.add(Q),J(K,Z);for(let q in $.prototype)if(!(q in K))Object.defineProperty(K,q,{value:$.prototype[q].bind(K)});K._zod.constr=$,K._zod.def=Z}let Y=X?.Parent??Object;class W extends Y{}Object.defineProperty(W,"name",{value:Q});function $(K){var Z;let H=X?.Parent?new W:this;G(H,K),(Z=H._zod).deferred??(Z.deferred=[]);for(let q of H._zod.deferred)q();return H}return Object.defineProperty($,"init",{value:G}),Object.defineProperty($,Symbol.hasInstance,{value:(K)=>{if(X?.Parent&&K instanceof X.Parent)return!0;return K?._zod?.traits?.has(Q)}}),Object.defineProperty($,"name",{value:Q}),$}var j90=Symbol("zod_brand");class vW extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}var lP={};function B9(Q){if(Q)Object.assign(lP,Q);return lP}var H1={};_6(H1,{unwrapMessage:()=>dP,stringifyPrimitive:()=>Z1,required:()=>jC4,randomString:()=>OC4,propertyKeyTypes:()=>iP,promiseAllObject:()=>BC4,primitiveTypes:()=>k90,prefixIssues:()=>QJ,pick:()=>PC4,partial:()=>EC4,optionalKeys:()=>_90,omit:()=>MC4,numKeys:()=>DC4,nullish:()=>YZ,normalizeParams:()=>W1,merge:()=>AC4,jsonStringifyReplacer:()=>C90,joinValues:()=>g0,issue:()=>f90,isPlainObject:()=>mU,isObject:()=>uU,getSizableOrigin:()=>rP,getParsedType:()=>LC4,getLengthableOrigin:()=>aP,getEnumValues:()=>pP,getElementAtPath:()=>NC4,floatSafeRemainder:()=>R90,finalizeIssue:()=>bJ,extend:()=>TC4,escapeRegex:()=>kW,esc:()=>qq,defineLazy:()=>T6,createTransparentProxy:()=>wC4,clone:()=>fJ,cleanRegex:()=>nP,cleanEnum:()=>IC4,captureStackTrace:()=>C_,cached:()=>cP,assignProp:()=>S90,assertNotEqual:()=>FC4,assertNever:()=>zC4,assertIs:()=>VC4,assertEqual:()=>qC4,assert:()=>UC4,allowsEval:()=>v90,aborted:()=>Fq,NUMBER_FORMAT_RANGES:()=>y90,Class:()=>DG1,BIGINT_FORMAT_RANGES:()=>h90});function qC4(Q){return Q}function FC4(Q){return Q}function VC4(Q){}function zC4(Q){throw Error()}function UC4(Q){}function pP(Q){let J=Object.values(Q).filter((G)=>typeof G==="number");return Object.entries(Q).filter(([G,Y])=>J.indexOf(+G)===-1).map(([G,Y])=>Y)}function g0(Q,J="|"){return Q.map((X)=>Z1(X)).join(J)}function C90(Q,J){if(typeof J==="bigint")return J.toString();return J}function cP(Q){return{get value(){{let X=Q();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function YZ(Q){return Q===null||Q===void 0}function nP(Q){let J=Q.startsWith("^")?1:0,X=Q.endsWith("$")?Q.length-1:Q.length;return Q.slice(J,X)}function R90(Q,J){let X=(Q.toString().split(".")[1]||"").length,G=(J.toString().split(".")[1]||"").length,Y=X>G?X:G,W=Number.parseInt(Q.toFixed(Y).replace(".","")),$=Number.parseInt(J.toFixed(Y).replace(".",""));return W%$/10**Y}function T6(Q,J,X){Object.defineProperty(Q,J,{get(){{let Y=X();return Q[J]=Y,Y}throw Error("cached value already set")},set(Y){Object.defineProperty(Q,J,{value:Y})},configurable:!0})}function S90(Q,J,X){Object.defineProperty(Q,J,{value:X,writable:!0,enumerable:!0,configurable:!0})}function NC4(Q,J){if(!J)return Q;return J.reduce((X,G)=>X?.[G],Q)}function BC4(Q){let J=Object.keys(Q),X=J.map((G)=>Q[G]);return Promise.all(X).then((G)=>{let Y={};for(let W=0;W<J.length;W++)Y[J[W]]=G[W];return Y})}function OC4(Q=10){let X="";for(let G=0;G<Q;G++)X+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return X}function qq(Q){return JSON.stringify(Q)}var C_=Error.captureStackTrace?Error.captureStackTrace:(...Q)=>{};function uU(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}var v90=cP(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Q){return!1}});function mU(Q){if(uU(Q)===!1)return!1;let J=Q.constructor;if(J===void 0)return!0;let X=J.prototype;if(uU(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}function DC4(Q){let J=0;for(let X in Q)if(Object.prototype.hasOwnProperty.call(Q,X))J++;return J}var LC4=(Q)=>{let J=typeof Q;switch(J){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Q)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return"promise";if(typeof Map<"u"&&Q instanceof Map)return"map";if(typeof Set<"u"&&Q instanceof Set)return"set";if(typeof Date<"u"&&Q instanceof Date)return"date";if(typeof File<"u"&&Q instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${J}`)}},iP=new Set(["string","number","symbol"]),k90=new Set(["string","number","bigint","boolean","symbol","undefined"]);function kW(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fJ(Q,J,X){let G=new Q._zod.constr(J??Q._zod.def);if(!J||X?.parent)G._zod.parent=Q;return G}function W1(Q){let J=Q;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function wC4(Q){let J;return new Proxy({},{get(X,G,Y){return J??(J=Q()),Reflect.get(J,G,Y)},set(X,G,Y,W){return J??(J=Q()),Reflect.set(J,G,Y,W)},has(X,G){return J??(J=Q()),Reflect.has(J,G)},deleteProperty(X,G){return J??(J=Q()),Reflect.deleteProperty(J,G)},ownKeys(X){return J??(J=Q()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(X,G){return J??(J=Q()),Reflect.getOwnPropertyDescriptor(J,G)},defineProperty(X,G,Y){return J??(J=Q()),Reflect.defineProperty(J,G,Y)}})}function Z1(Q){if(typeof Q==="bigint")return Q.toString()+"n";if(typeof Q==="string")return`"${Q}"`;return`${Q}`}function _90(Q){return Object.keys(Q).filter((J)=>{return Q[J]._zod.optin==="optional"&&Q[J]._zod.optout==="optional"})}var y90={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},h90={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function PC4(Q,J){let X={},G=Q._zod.def;for(let Y in J){if(!(Y in G.shape))throw Error(`Unrecognized key: "${Y}"`);if(!J[Y])continue;X[Y]=G.shape[Y]}return fJ(Q,{...Q._zod.def,shape:X,checks:[]})}function MC4(Q,J){let X={...Q._zod.def.shape},G=Q._zod.def;for(let Y in J){if(!(Y in G.shape))throw Error(`Unrecognized key: "${Y}"`);if(!J[Y])continue;delete X[Y]}return fJ(Q,{...Q._zod.def,shape:X,checks:[]})}function TC4(Q,J){if(!mU(J))throw Error("Invalid input to extend: expected a plain object");let X={...Q._zod.def,get shape(){let G={...Q._zod.def.shape,...J};return S90(this,"shape",G),G},checks:[]};return fJ(Q,X)}function AC4(Q,J){return fJ(Q,{...Q._zod.def,get shape(){let X={...Q._zod.def.shape,...J._zod.def.shape};return S90(this,"shape",X),X},catchall:J._zod.def.catchall,checks:[]})}function EC4(Q,J,X){let G=J._zod.def.shape,Y={...G};if(X)for(let W in X){if(!(W in G))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;Y[W]=Q?new Q({type:"optional",innerType:G[W]}):G[W]}else for(let W in G)Y[W]=Q?new Q({type:"optional",innerType:G[W]}):G[W];return fJ(J,{...J._zod.def,shape:Y,checks:[]})}function jC4(Q,J,X){let G=J._zod.def.shape,Y={...G};if(X)for(let W in X){if(!(W in Y))throw Error(`Unrecognized key: "${W}"`);if(!X[W])continue;Y[W]=new Q({type:"nonoptional",innerType:G[W]})}else for(let W in G)Y[W]=new Q({type:"nonoptional",innerType:G[W]});return fJ(J,{...J._zod.def,shape:Y,checks:[]})}function Fq(Q,J=0){for(let X=J;X<Q.issues.length;X++)if(Q.issues[X]?.continue!==!0)return!0;return!1}function QJ(Q,J){return J.map((X)=>{var G;return(G=X).path??(G.path=[]),X.path.unshift(Q),X})}function dP(Q){return typeof Q==="string"?Q:Q?.message}function bJ(Q,J,X){let G={...Q,path:Q.path??[]};if(!Q.message){let Y=dP(Q.inst?._zod.def?.error?.(Q))??dP(J?.error?.(Q))??dP(X.customError?.(Q))??dP(X.localeError?.(Q))??"Invalid input";G.message=Y}if(delete G.inst,delete G.continue,!J?.reportInput)delete G.input;return G}function rP(Q){if(Q instanceof Set)return"set";if(Q instanceof Map)return"map";if(Q instanceof File)return"file";return"unknown"}function aP(Q){if(Array.isArray(Q))return"array";if(typeof Q==="string")return"string";return"unknown"}function f90(...Q){let[J,X,G]=Q;if(typeof J==="string")return{message:J,code:"custom",input:X,inst:G};return{...J}}function IC4(Q){return Object.entries(Q).filter(([J,X])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}class DG1{constructor(...Q){}}var LG1=(Q,J)=>{Q.name="$ZodError",Object.defineProperty(Q,"_zod",{value:Q._zod,enumerable:!1}),Object.defineProperty(Q,"issues",{value:J,enumerable:!1}),Object.defineProperty(Q,"message",{get(){return JSON.stringify(J,C90,2)},enumerable:!0}),Object.defineProperty(Q,"toString",{value:()=>Q.message,enumerable:!1})},oP=T0("$ZodError",LG1),lU=T0("$ZodError",LG1,{Parent:Error});function sP(Q,J=(X)=>X.message){let X={},G=[];for(let Y of Q.issues)if(Y.path.length>0)X[Y.path[0]]=X[Y.path[0]]||[],X[Y.path[0]].push(J(Y));else G.push(J(Y));return{formErrors:G,fieldErrors:X}}function tP(Q,J){let X=J||function(W){return W.message},G={_errors:[]},Y=(W)=>{for(let $ of W.issues)if($.code==="invalid_union"&&$.errors.length)$.errors.map((K)=>Y({issues:K}));else if($.code==="invalid_key")Y({issues:$.issues});else if($.code==="invalid_element")Y({issues:$.issues});else if($.path.length===0)G._errors.push(X($));else{let K=G,Z=0;while(Z<$.path.length){let H=$.path[Z];if(Z!==$.path.length-1)K[H]=K[H]||{_errors:[]};else K[H]=K[H]||{_errors:[]},K[H]._errors.push(X($));K=K[H],Z++}}};return Y(Q),G}function b90(Q,J){let X=J||function(W){return W.message},G={errors:[]},Y=(W,$=[])=>{var K,Z;for(let H of W.issues)if(H.code==="invalid_union"&&H.errors.length)H.errors.map((q)=>Y({issues:q},H.path));else if(H.code==="invalid_key")Y({issues:H.issues},H.path);else if(H.code==="invalid_element")Y({issues:H.issues},H.path);else{let q=[...$,...H.path];if(q.length===0){G.errors.push(X(H));continue}let F=G,V=0;while(V<q.length){let z=q[V],U=V===q.length-1;if(typeof z==="string")F.properties??(F.properties={}),(K=F.properties)[z]??(K[z]={errors:[]}),F=F.properties[z];else F.items??(F.items=[]),(Z=F.items)[z]??(Z[z]={errors:[]}),F=F.items[z];if(U)F.errors.push(X(H));V++}}};return Y(Q),G}function wG1(Q){let J=[];for(let X of Q)if(typeof X==="number")J.push(`[${X}]`);else if(typeof X==="symbol")J.push(`[${JSON.stringify(String(X))}]`);else if(/[^\w$]/.test(X))J.push(`[${JSON.stringify(X)}]`);else{if(J.length)J.push(".");J.push(X)}return J.join("")}function x90(Q){let J=[],X=[...Q.issues].sort((G,Y)=>G.path.length-Y.path.length);for(let G of X)if(J.push(`\u2716 ${G.message}`),G.path?.length)J.push(` \u2192 at ${wG1(G.path)}`);return J.join(`
|
|
1071
1071
|
`)}var R_=(Q)=>(J,X,G,Y)=>{let W=G?Object.assign(G,{async:!1}):{async:!1},$=J._zod.run({value:X,issues:[]},W);if($ instanceof Promise)throw new vW;if($.issues.length){let K=new(Y?.Err??Q)($.issues.map((Z)=>bJ(Z,W,B9())));throw C_(K,Y?.callee),K}return $.value},S_=R_(lU),v_=(Q)=>async(J,X,G,Y)=>{let W=G?Object.assign(G,{async:!0}):{async:!0},$=J._zod.run({value:X,issues:[]},W);if($ instanceof Promise)$=await $;if($.issues.length){let K=new(Y?.Err??Q)($.issues.map((Z)=>bJ(Z,W,B9())));throw C_(K,Y?.callee),K}return $.value},k_=v_(lU),__=(Q)=>(J,X,G)=>{let Y=G?{...G,async:!1}:{async:!1},W=J._zod.run({value:X,issues:[]},Y);if(W instanceof Promise)throw new vW;return W.issues.length?{success:!1,error:new(Q??oP)(W.issues.map(($)=>bJ($,Y,B9())))}:{success:!0,data:W.value}},g90=__(lU),y_=(Q)=>async(J,X,G)=>{let Y=G?Object.assign(G,{async:!0}):{async:!0},W=J._zod.run({value:X,issues:[]},Y);if(W instanceof Promise)W=await W;return W.issues.length?{success:!1,error:new Q(W.issues.map(($)=>bJ($,Y,B9())))}:{success:!0,data:W.value}},u90=y_(lU);var zq={};_6(zq,{xid:()=>p90,uuid7:()=>kC4,uuid6:()=>vC4,uuid4:()=>SC4,uuid:()=>Vq,uppercase:()=>N50,unicodeEmail:()=>hC4,undefined:()=>z50,ulid:()=>d90,time:()=>W50,string:()=>K50,rfc5322Email:()=>yC4,number:()=>q50,null:()=>V50,nanoid:()=>n90,lowercase:()=>U50,ksuid:()=>c90,ipv6:()=>t90,ipv4:()=>s90,integer:()=>H50,html5Email:()=>_C4,hostname:()=>X50,guid:()=>r90,extendedDuration:()=>RC4,emoji:()=>o90,email:()=>a90,e164:()=>Y50,duration:()=>i90,domain:()=>xC4,datetime:()=>$50,date:()=>G50,cuid2:()=>l90,cuid:()=>m90,cidrv6:()=>Q50,cidrv4:()=>e90,browserEmail:()=>fC4,boolean:()=>F50,bigint:()=>Z50,base64url:()=>h_,base64:()=>J50,_emoji:()=>bC4});var m90=/^[cC][^\s-]{8,}$/,l90=/^[0-9a-z]+$/,d90=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,p90=/^[0-9a-vA-V]{20}$/,c90=/^[A-Za-z0-9]{27}$/,n90=/^[a-zA-Z0-9_-]{21}$/,i90=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,RC4=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,r90=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Vq=(Q)=>{if(!Q)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Q}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},SC4=Vq(4),vC4=Vq(6),kC4=Vq(7),a90=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_C4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,yC4=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,hC4=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,fC4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,bC4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function o90(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var s90=/^(?:(?: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])$/,t90=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,e90=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Q50=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,J50=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,h_=/^[A-Za-z0-9_-]*$/,X50=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,xC4=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Y50=/^\+(?:[0-9]){6,14}[0-9]$/,PG1="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",G50=new RegExp(`^${PG1}$`);function MG1(Q){return typeof Q.precision==="number"?Q.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Q.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${Q.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function W50(Q){return new RegExp(`^${MG1(Q)}$`)}function $50(Q){let J=MG1({precision:Q.precision}),X=["Z"];if(Q.local)X.push("");if(Q.offset)X.push("([+-]\\d{2}:\\d{2})");let G=`${J}(?:${X.join("|")})`;return new RegExp(`^${PG1}T(?:${G})$`)}var K50=(Q)=>{let J=Q?`[\\s\\S]{${Q?.minimum??0},${Q?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)},Z50=/^\d+n?$/,H50=/^\d+$/,q50=/^-?\d+(?:\.\d+)?/i,F50=/true|false/i,V50=/null/i;var z50=/undefined/i;var U50=/^[^A-Z]*$/,N50=/^[^a-z]*$/;var l8=T0("$ZodCheck",(Q,J)=>{var X;Q._zod??(Q._zod={}),Q._zod.def=J,(X=Q._zod).onattach??(X.onattach=[])}),AG1={number:"number",bigint:"bigint",object:"date"},f_=T0("$ZodCheckLessThan",(Q,J)=>{l8.init(Q,J);let X=AG1[typeof J.value];Q._zod.onattach.push((G)=>{let Y=G._zod.bag,W=(J.inclusive?Y.maximum:Y.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<W)if(J.inclusive)Y.maximum=J.value;else Y.exclusiveMaximum=J.value}),Q._zod.check=(G)=>{if(J.inclusive?G.value<=J.value:G.value<J.value)return;G.issues.push({origin:X,code:"too_big",maximum:J.value,input:G.value,inclusive:J.inclusive,inst:Q,continue:!J.abort})}}),b_=T0("$ZodCheckGreaterThan",(Q,J)=>{l8.init(Q,J);let X=AG1[typeof J.value];Q._zod.onattach.push((G)=>{let Y=G._zod.bag,W=(J.inclusive?Y.minimum:Y.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>W)if(J.inclusive)Y.minimum=J.value;else Y.exclusiveMinimum=J.value}),Q._zod.check=(G)=>{if(J.inclusive?G.value>=J.value:G.value>J.value)return;G.issues.push({origin:X,code:"too_small",minimum:J.value,input:G.value,inclusive:J.inclusive,inst:Q,continue:!J.abort})}}),B50=T0("$ZodCheckMultipleOf",(Q,J)=>{l8.init(Q,J),Q._zod.onattach.push((X)=>{var G;(G=X._zod.bag).multipleOf??(G.multipleOf=J.value)}),Q._zod.check=(X)=>{if(typeof X.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof X.value==="bigint"?X.value%J.value===BigInt(0):R90(X.value,J.value)===0)return;X.issues.push({origin:typeof X.value,code:"not_multiple_of",divisor:J.value,input:X.value,inst:Q,continue:!J.abort})}}),O50=T0("$ZodCheckNumberFormat",(Q,J)=>{l8.init(Q,J),J.format=J.format||"float64";let X=J.format?.includes("int"),G=X?"int":"number",[Y,W]=y90[J.format];Q._zod.onattach.push(($)=>{let K=$._zod.bag;if(K.format=J.format,K.minimum=Y,K.maximum=W,X)K.pattern=H50}),Q._zod.check=($)=>{let K=$.value;if(X){if(!Number.isInteger(K)){$.issues.push({expected:G,format:J.format,code:"invalid_type",input:K,inst:Q});return}if(!Number.isSafeInteger(K)){if(K>0)$.issues.push({input:K,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:G,continue:!J.abort});else $.issues.push({input:K,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:G,continue:!J.abort});return}}if(K<Y)$.issues.push({origin:"number",input:K,code:"too_small",minimum:Y,inclusive:!0,inst:Q,continue:!J.abort});if(K>W)$.issues.push({origin:"number",input:K,code:"too_big",maximum:W,inst:Q})}}),D50=T0("$ZodCheckBigIntFormat",(Q,J)=>{l8.init(Q,J);let[X,G]=h90[J.format];Q._zod.onattach.push((Y)=>{let W=Y._zod.bag;W.format=J.format,W.minimum=X,W.maximum=G}),Q._zod.check=(Y)=>{let W=Y.value;if(W<X)Y.issues.push({origin:"bigint",input:W,code:"too_small",minimum:X,inclusive:!0,inst:Q,continue:!J.abort});if(W>G)Y.issues.push({origin:"bigint",input:W,code:"too_big",maximum:G,inst:Q})}}),L50=T0("$ZodCheckMaxSize",(Q,J)=>{var X;l8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!YZ(Y)&&Y.size!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<Y)G._zod.bag.maximum=J.maximum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.size<=J.maximum)return;G.issues.push({origin:rP(Y),code:"too_big",maximum:J.maximum,input:Y,inst:Q,continue:!J.abort})}}),w50=T0("$ZodCheckMinSize",(Q,J)=>{var X;l8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!YZ(Y)&&Y.size!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>Y)G._zod.bag.minimum=J.minimum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.size>=J.minimum)return;G.issues.push({origin:rP(Y),code:"too_small",minimum:J.minimum,input:Y,inst:Q,continue:!J.abort})}}),P50=T0("$ZodCheckSizeEquals",(Q,J)=>{var X;l8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!YZ(Y)&&Y.size!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.minimum=J.size,Y.maximum=J.size,Y.size=J.size}),Q._zod.check=(G)=>{let Y=G.value,W=Y.size;if(W===J.size)return;let $=W>J.size;G.issues.push({origin:rP(Y),...$?{code:"too_big",maximum:J.size}:{code:"too_small",minimum:J.size},inclusive:!0,exact:!0,input:G.value,inst:Q,continue:!J.abort})}}),M50=T0("$ZodCheckMaxLength",(Q,J)=>{var X;l8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!YZ(Y)&&Y.length!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<Y)G._zod.bag.maximum=J.maximum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.length<=J.maximum)return;let $=aP(Y);G.issues.push({origin:$,code:"too_big",maximum:J.maximum,inclusive:!0,input:Y,inst:Q,continue:!J.abort})}}),T50=T0("$ZodCheckMinLength",(Q,J)=>{var X;l8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!YZ(Y)&&Y.length!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>Y)G._zod.bag.minimum=J.minimum}),Q._zod.check=(G)=>{let Y=G.value;if(Y.length>=J.minimum)return;let $=aP(Y);G.issues.push({origin:$,code:"too_small",minimum:J.minimum,inclusive:!0,input:Y,inst:Q,continue:!J.abort})}}),A50=T0("$ZodCheckLengthEquals",(Q,J)=>{var X;l8.init(Q,J),(X=Q._zod.def).when??(X.when=(G)=>{let Y=G.value;return!YZ(Y)&&Y.length!==void 0}),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.minimum=J.length,Y.maximum=J.length,Y.length=J.length}),Q._zod.check=(G)=>{let Y=G.value,W=Y.length;if(W===J.length)return;let $=aP(Y),K=W>J.length;G.issues.push({origin:$,...K?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:G.value,inst:Q,continue:!J.abort})}}),dU=T0("$ZodCheckStringFormat",(Q,J)=>{var X,G;if(l8.init(Q,J),Q._zod.onattach.push((Y)=>{let W=Y._zod.bag;if(W.format=J.format,J.pattern)W.patterns??(W.patterns=new Set),W.patterns.add(J.pattern)}),J.pattern)(X=Q._zod).check??(X.check=(Y)=>{if(J.pattern.lastIndex=0,J.pattern.test(Y.value))return;Y.issues.push({origin:"string",code:"invalid_format",format:J.format,input:Y.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Q,continue:!J.abort})});else(G=Q._zod).check??(G.check=()=>{})}),E50=T0("$ZodCheckRegex",(Q,J)=>{dU.init(Q,J),Q._zod.check=(X)=>{if(J.pattern.lastIndex=0,J.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:J.pattern.toString(),inst:Q,continue:!J.abort})}}),j50=T0("$ZodCheckLowerCase",(Q,J)=>{J.pattern??(J.pattern=U50),dU.init(Q,J)}),I50=T0("$ZodCheckUpperCase",(Q,J)=>{J.pattern??(J.pattern=N50),dU.init(Q,J)}),C50=T0("$ZodCheckIncludes",(Q,J)=>{l8.init(Q,J);let X=kW(J.includes),G=new RegExp(typeof J.position==="number"?`^.{${J.position}}${X}`:X);J.pattern=G,Q._zod.onattach.push((Y)=>{let W=Y._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(G)}),Q._zod.check=(Y)=>{if(Y.value.includes(J.includes,J.position))return;Y.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:Y.value,inst:Q,continue:!J.abort})}}),R50=T0("$ZodCheckStartsWith",(Q,J)=>{l8.init(Q,J);let X=new RegExp(`^${kW(J.prefix)}.*`);J.pattern??(J.pattern=X),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.patterns??(Y.patterns=new Set),Y.patterns.add(X)}),Q._zod.check=(G)=>{if(G.value.startsWith(J.prefix))return;G.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:G.value,inst:Q,continue:!J.abort})}}),S50=T0("$ZodCheckEndsWith",(Q,J)=>{l8.init(Q,J);let X=new RegExp(`.*${kW(J.suffix)}$`);J.pattern??(J.pattern=X),Q._zod.onattach.push((G)=>{let Y=G._zod.bag;Y.patterns??(Y.patterns=new Set),Y.patterns.add(X)}),Q._zod.check=(G)=>{if(G.value.endsWith(J.suffix))return;G.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:G.value,inst:Q,continue:!J.abort})}});function TG1(Q,J,X){if(Q.issues.length)J.issues.push(...QJ(X,Q.issues))}var v50=T0("$ZodCheckProperty",(Q,J)=>{l8.init(Q,J),Q._zod.check=(X)=>{let G=J.schema._zod.run({value:X.value[J.property],issues:[]},{});if(G instanceof Promise)return G.then((Y)=>TG1(Y,X,J.property));TG1(G,X,J.property);return}}),k50=T0("$ZodCheckMimeType",(Q,J)=>{l8.init(Q,J);let X=new Set(J.mime);Q._zod.onattach.push((G)=>{G._zod.bag.mime=J.mime}),Q._zod.check=(G)=>{if(X.has(G.value.type))return;G.issues.push({code:"invalid_value",values:J.mime,input:G.value.type,inst:Q})}}),_50=T0("$ZodCheckOverwrite",(Q,J)=>{l8.init(Q,J),Q._zod.check=(X)=>{X.value=J.tx(X.value)}});class x_{constructor(Q=[]){if(this.content=[],this.indent=0,this)this.args=Q}indented(Q){this.indent+=1,Q(this),this.indent-=1}write(Q){if(typeof Q==="function"){Q(this,{execution:"sync"}),Q(this,{execution:"async"});return}let X=Q.split(`
|