@zuplo/runtime 7.13.8 → 7.13.10

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.
@@ -259,7 +259,7 @@ data:
259
259
 
260
260
  `,t.enqueue(e.encode(r)),!0}catch(r){return this.onerror?.(r),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,e){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!ep(t.headers.get("content-type")))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let o=t,r;if(e?.parsedBody===void 0)try{let R=await H4(t,this._maxRequestBodySize);if(R.tooLarge){let C=z4(this._maxRequestBodySize);return this.onerror?.(new Error(C)),this.createJsonErrorResponse(413,-32e3,C)}r=JSON.parse(R.text)}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else r=e.parsedBody;if(Array.isArray(r)&&r.length>Gw)return this.onerror?.(new Error(`Invalid Request: Batch must not exceed ${Gw} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${Gw} messages`);let s;try{s=Array.isArray(r)?r.map(R=>wi.parse(R)):[wi.parse(r)]}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let a=s.some(R=>Qd(R));if(a){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(s.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!a){let R=this.validateSession(t);if(R)return R;let C=this.validateProtocolVersion(t);if(C)return C}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let c;try{c=await this._checkScopeChallenge(s,e?.authInfo)}catch(R){return this.onerror?.(R),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(c)return c;if(!s.some(R=>_r(R))){for(let R of s)this.onmessage?.(R,{authInfo:e?.authInfo,request:o});return new Response(null,{status:202})}let u=crypto.randomUUID(),l=s.find(R=>Qd(R)),d=l?l.params.protocolVersion:t.headers.get("mcp-protocol-version")??bh;if(this._enableJsonResponse)return new Promise(R=>{this._streamMapping.set(u,{resolveJson:R,cleanup:i(()=>{this._streamMapping.delete(u)},"cleanup")});for(let C of s)_r(C)&&this._requestToStreamMapping.set(C.id,u);for(let C of s)this.onmessage?.(C,{authInfo:e?.authInfo,request:o})});let p=new TextEncoder,f,h,y=new ReadableStream({start:i(R=>{f=R},"start"),cancel:i(()=>{h!==void 0&&clearInterval(h),this._streamMapping.get(u)?.controller===f&&this._streamMapping.delete(u)},"cancel")}),S={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};this.sessionId!==void 0&&(S["mcp-session-id"]=this.sessionId);for(let R of s)_r(R)&&(this._streamMapping.set(u,{controller:f,encoder:p,cleanup:i(()=>{h!==void 0&&clearInterval(h),this._streamMapping.delete(u);try{f.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(R.id,u));await this.writePrimingEvent(f,p,u,d);for(let R of s){let C,T;_r(R)&&this._eventStore&&this.supportsEmptySSEData(d)&&(C=i(()=>{this.closeSSEStream(R.id)},"closeSSEStream"),T=i(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(R,{authInfo:e?.authInfo,request:o,closeSSEStream:C,closeStandaloneSSEStream:T})}return this._streamMapping.get(u)?.controller===f&&(h=this.startKeepAlive(f,p)),new Response(y,{status:200,headers:S})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let e=this.validateSession(t);if(e)return e;let n=this.validateProtocolVersion(t);if(n)return n;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let e=t.headers.get("mcp-session-id");if(!e)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(e!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let e=t.headers.get("mcp-protocol-version");if(e!==null&&!this._supportedProtocolVersions.includes(e)){let n=`Bad Request: Unsupported protocol version: ${e} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(400,-32e3,n)}}async close(){if(!this._closed){this._closed=!0;for(let{cleanup:t}of this._streamMapping.values())t();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(t){let e=this._requestToStreamMapping.get(t);if(!e)return;let n=this._streamMapping.get(e);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,e){let n=e?.relatedRequestId;if((Rc(t)||Yd(t))&&(n=t.id),n===void 0){if(Rc(t)||Yd(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let s;this._eventStore&&(s=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&(s===void 0||!a.replayedEventIds?.has(s))&&this.writeSSEEvent(a.controller,a.encoder,t,s);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let r=this._streamMapping.get(o);if(!this._enableJsonResponse){let s;this._eventStore&&(s=await this._eventStore.storeEvent(o,t),r=this._streamMapping.get(o)),r?.controller&&r?.encoder&&(s===void 0||!r.replayedEventIds?.has(s))&&this.writeSSEEvent(r.controller,r.encoder,t,s)}if(Rc(t)||Yd(t)){this._requestResponseMap.set(n,t);let s=[...this._requestToStreamMapping.entries()].filter(([a,c])=>c===o).map(([a])=>a);if(s.every(a=>this._requestResponseMap.has(a))){if(!r){if(this._enableJsonResponse)throw new Error(`No connection established for request ID: ${String(n)}`);if(!this._eventStore){this.onerror?.(new Error(`Response for request ID ${String(n)} is undeliverable: per-request stream is disconnected and no eventStore is configured`));for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}if(this._enableJsonResponse&&r.resolveJson){let a={"Content-Type":"application/json"};this.sessionId!==void 0&&(a["mcp-session-id"]=this.sessionId);let c=s.map(u=>this._requestResponseMap.get(u));c.length===1?r.resolveJson(Response.json(c[0],{status:200,headers:a})):r.resolveJson(Response.json(c,{status:200,headers:a})),r.cleanup()}else r.cleanup();for(let a of s)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a)}}}};var F4="mcp-protocol-version",G4="unknown",B4=new Set([...jo,"2026-07-28"]),Z4="io.modelcontextprotocol/protocolVersion";function np(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(np,"isRecord");function Bw(t){return typeof t=="string"&&t!==""?t:void 0}i(Bw,"nonEmptyString");function V4(t){if(!np(t)||!np(t.params))return;let{params:e}=t,n=np(e._meta)?Bw(e._meta[Z4]):void 0;return n!==void 0?n:t.method==="initialize"?Bw(e.protocolVersion):void 0}i(V4,"versionFromMessage");function Is(t,e){try{let n=Bw(t?.get(F4));if(n!==void 0)return n;let o=Array.isArray(e)?e:[e];for(let r of o){let s=V4(r);if(s!==void 0)return s}}catch{}}i(Is,"resolveMcpProtocolVersion");function oM(t){if(t!==void 0)return B4.has(t)?t:G4}i(oM,"analyticsProtocolVersion");var Zw="unsupported_protocol_version";async function rM(t){if(t.status!==400)return!1;try{let e=await t.clone().json(),n=np(e)?e.error:void 0,o=np(n)?n.message:void 0;return typeof o=="string"&&/^(Bad Request: )?Unsupported protocol version/.test(o)}catch{return!1}}i(rM,"isUnsupportedProtocolVersionResponse");var iM=2,Vw=4,sM=24,aM=16,Jw=512,J4=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,K4=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,W4=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,Y4=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,Q4=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,X4=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function cM(t){let e=t.route;return e&&typeof e=="object"?e:void 0}i(cM,"readRoute");function eK(t){let e=cM(t)?.path;return typeof e=="string"&&e.length>0?e:void 0}i(eK,"readRoutePath");function tK(t){let e=cM(t)?.raw;if(typeof e!="function")return;let n=e();if(!n||typeof n!="object")return;let o=n.operationId;return typeof o=="string"&&o.length>0?o:void 0}i(tK,"readRouteOperationId");function uM(t){if(!(t===void 0||!Number.isFinite(t)||t<100))return`${Math.trunc(t/100)}xx`}i(uM,"deriveStatusClass");function lM(t,e){if(!(!t&&!e))return t==="user"?e==="user-oauth"?"upstream_user_attributed":"gateway_user_attributed_only":t==="shared"?"shared_upstream_identity":t==="none"?"machine_identity":"unknown"}i(lM,"deriveOriginAttributionMode");function dM(t){if(!t)return;let e=t.toLowerCase();return e.includes("desktop")||e.includes("claude")||e.includes("chatgpt")?"desktop":e.includes("vscode")||e.includes("cursor")||e.includes("zed")||e.includes("jetbrains")||e.includes("ide")?"ide":e.includes("extension")?"extension":e.includes("agent")||e.includes("bot")||e.includes("worker")||e.includes("service")?"service":"unknown"}i(dM,"deriveClientKind");function pM(t,e){return e==="success"?"none":t===N.MCP_REQUEST_RECEIVED||t===N.MCP_REQUEST_REJECTED||t===N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===N.MCP_INITIALIZE_NEGOTIATED?"routing":t.startsWith("mcp_capability_")?"upstream":t===N.MCP_REQUEST_COMPLETED?"egress":"none"}i(pM,"deriveFailureStage");function mM(t,e){return e==="success"?"none":e==="application_error"?"mcp_application":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===N.MCP_CAPABILITY_FAILED||t===N.MCP_CAPABILITY_CONNECT_REQUIRED?"upstream":t===N.MCP_REQUEST_REJECTED||t===N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}i(mM,"deriveFailureOrigin");function fM(t,e){return e==="success"?"none":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR||t===N.MCP_REQUEST_REJECTED?"protocol":"none"}i(fM,"deriveReasonClass");function nK(t){return t.length<=Jw?t:`${t.slice(0,Jw)}...`}i(nK,"truncateAnalyticsString");function oK(t){return nK(t.replace(K4,"$1[REDACTED]$3").replace(Y4,"$1$2[REDACTED]").replace(W4,"$1$2[REDACTED]").replace(Q4,"Bearer [REDACTED]").replace(X4,"Basic [REDACTED]"))}i(oK,"redactAnalyticsString");function hM(t,e){if(t!==void 0){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return oK(t);if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(Array.isArray(t))return e>=Vw?"[DEPTH_LIMIT]":t.slice(0,aM).map(n=>hM(n,e+1)).filter(n=>n!==void 0);if(typeof t=="object")return t instanceof Date?t.toISOString():e>=Vw?"[DEPTH_LIMIT]":Kw(t,e+1)}}i(hM,"sanitizeAnalyticsValue");function Kw(t,e=0){if(!t)return;let n={};for(let[o,r]of Object.entries(t).slice(0,sM)){if(J4.test(o)){n[o]="[REDACTED]";continue}let s=hM(r,e);s!==void 0&&(n[o]=s)}return Object.keys(n).length===0?void 0:n}i(Kw,"sanitizeMcpAnalyticsAttributes");function Ae(t){return t===void 0?null:t}i(Ae,"nullable");function rK(t){let e=t.environment;return e&&typeof e=="object"&&typeof e.name=="string"?e.name:null}i(rK,"readEnvironment");function iK(t){let e=t.requestId;return typeof e=="string"&&e.length>0?e:null}i(iK,"readRequestId");function sK(t){if(t===void 0)return null;try{return JSON.stringify(t)}catch{return null}}i(sK,"attributesToJsonString");function Ww(t,e){let n=Kw(e.attributes),o=iK(t),r=e.ownerMode??null,s=e.upstreamAuthMode??null,a=e.clientKind??dM(e.clientName)??null,c=lM(r??void 0,s??void 0)??null,u=uM(e.httpStatusCode)??null,l=e.reasonClass??fM(e.eventType,e.outcome),d=e.failureOrigin??mM(e.eventType,e.outcome),p=e.failureStage??pM(e.eventType,e.outcome);return{schemaVersion:iM,outcome:e.outcome,subjectId:Ae(e.subjectId),environment:rK(t),traceId:e.traceId??o,spanId:Ae(e.spanId),parentEventId:Ae(e.parentEventId),mcpSessionId:Ae(e.mcpSessionId),routeSurface:Ae(e.routeSurface),routePath:e.routePath??eK(t)??null,operationId:e.operationId??tK(t)??null,virtualServerName:Ae(e.virtualServerName),virtualServerTitle:Ae(e.virtualServerTitle),upstreamServerName:Ae(e.upstreamServerName),upstreamServerTitle:Ae(e.upstreamServerTitle),upstreamBindingId:Ae(e.upstreamBindingId),clientName:Ae(e.clientName),clientTitle:Ae(e.clientTitle),clientVersion:Ae(e.clientVersion),clientKind:a,authProfileId:Ae(e.authProfileId),upstreamAuthMode:s,ownerMode:r,authMethod:Ae(e.authMethod),originAttributionMode:c,apiKeySub:Ae(e.apiKeySub),httpMethod:Ae(e.httpMethod),httpStatusCode:Ae(e.httpStatusCode),statusClass:u,mcpMethod:Ae(e.mcpMethod),mcpProtocolVersion:Ae(oM(e.mcpProtocolVersion)),mcpStatus:Ae(e.mcpStatus),mcpErrorType:Ae(e.mcpErrorType),applicationError:Ae(e.applicationError),applicationErrorCode:Ae(e.applicationErrorCode),toolResultIsError:Ae(e.toolResultIsError),transport:Ae(e.transport),sessionId:Ae(e.sessionId),capabilityType:Ae(e.capabilityType),capabilityName:Ae(e.capabilityName),capabilityTitle:Ae(e.capabilityTitle),upstreamCapabilityName:Ae(e.upstreamCapabilityName),upstreamCapabilityTitle:Ae(e.upstreamCapabilityTitle),capabilitySchemaHash:Ae(e.capabilitySchemaHash),toolPath:Ae(e.toolPath),toolMethod:Ae(e.toolMethod),toolOperationId:Ae(e.toolOperationId),resourceUri:Ae(e.resourceUri),resourceMimeType:Ae(e.resourceMimeType),policyId:Ae(e.policyId),policyAction:Ae(e.policyAction),guardrailType:Ae(e.guardrailType),guardrailDirection:Ae(e.guardrailDirection),guardrailFindingCount:Ae(e.guardrailFindingCount),redactionCount:Ae(e.redactionCount),requestMutated:Ae(e.requestMutated),responseMutated:Ae(e.responseMutated),latencyMs:Ae(e.latencyMs),gatewayLatencyMs:Ae(e.gatewayLatencyMs),upstreamLatencyMs:Ae(e.upstreamLatencyMs),authLatencyMs:Ae(e.authLatencyMs),policyLatencyMs:Ae(e.policyLatencyMs),requestBytes:Ae(e.requestBytes),responseBytes:Ae(e.responseBytes),estimatedInputTokens:Ae(e.estimatedInputTokens),estimatedOutputTokens:Ae(e.estimatedOutputTokens),estimatedContextTokens:Ae(e.estimatedContextTokens),contextPressureBucket:Ae(e.contextPressureBucket),responseMimeTypes:Ae(e.responseMimeTypes),base64Suspected:Ae(e.base64Suspected),truncated:Ae(e.truncated),isLargePayloadRequest:Ae(e.isLargePayloadRequest),isLargePayloadResponse:Ae(e.isLargePayloadResponse),payloadCaptureMode:Ae(e.payloadCaptureMode),reasonCode:Ae(e.reasonCode),reasonClass:l,errorType:e.errorType??e.reasonCode??null,failureOrigin:d,failureStage:p,errorCode:Ae(e.errorCode),customMetadataJson:Ae(e.customMetadataJson),attributesJson:sK(n)}}i(Ww,"buildMcpAnalyticsMetadata");function gM(t,e){try{t.analyticsContext.addAnalyticsEvent(e.value??1,e.eventType,Ww(t,e),e.unit)}catch(n){t.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:n instanceof Error?n.name:"unknown"})}}i(gM,"emitMcpAnalyticsEvent");import{AsyncLocalStorage as aK}from"node:async_hooks";var yM=new aK;function bM(t,e){return yM.run(t,e)}i(bM,"runWithAdvertisedMcpToolName");function RM(){return yM.getStore()}i(RM,"getAdvertisedMcpToolName");function ag(t,e){if(!t||typeof t!="object")return;let n=t[e];return typeof n=="string"?n:void 0}i(ag,"readStringProperty");function wM(t){let e=ag(t,"method");if(!e)return;let n=t&&typeof t=="object"?t.params:void 0;switch(e){case"tools/call":return{eventType:N.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"tool",capabilityName:ag(n,"name"),mcpMethod:"tools/call"};case"prompts/get":return{eventType:N.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"prompt",capabilityName:ag(n,"name"),mcpMethod:"prompts/get"};case"resources/read":{let o=ag(n,"uri");return{eventType:N.MCP_CAPABILITY_INVOKED,outcome:"success",capabilityType:"resource",capabilityName:o,resourceUri:o,mcpMethod:"resources/read"}}default:return}}i(wM,"buildCapabilityInvokedAnalyticsInput");var zn=class{constructor(e,n){this.schemaSource=e;this.validateFn=n}schemaSource;validateFn;static{i(this,"CustomValidator")}schemaValue;get schema(){let e=this.schemaValue??(typeof this.schemaSource=="function"?this.schemaSource():this.schemaSource);return this.schemaValue=e,e}validate(e){return this.validateFn(e)}};var cK="Zuplo's MCP server doesn't support elicitation",cg=class{static{i(this,"UnsupportedElicitationValidator")}getValidator(e){throw new Error(cK)}};var uK=2,lK="__zuploMcpTools";function Yw(){let e=ot.instance?.schemaValidator?.[lK];if(typeof e!="function")return;let n=e();return n?.version===uK?n:void 0}i(Yw,"generatedModule");function TM(t,e,n){let o=JSON.stringify([t,e,n??""]);return Yw()?.tools[o]}i(TM,"getGeneratedToolSchemas");function IM(t,e){let n=JSON.stringify([t,e]);return Yw()?.prompts?.[n]}i(IM,"getGeneratedPromptSchemas");function EM(){return JE(_.instance.build.COMPATIBILITY_FLAGS)}i(EM,"generatedToolSchemasBySpec");function PM(t){return bm(Yw()?.defs,t)}i(PM,"getGeneratedSchemaAssembler");var SM=i((t,e,n)=>()=>e.assemble(t,n),"lazySchema");function dK(t){return t.split("/").slice(1).map(e=>e.replaceAll("~1","/").replaceAll("~0","~")).join(".")}i(dK,"dottedPath");function pK(t){return(t??[]).map(e=>{let n=dK(e.instancePath),o=e.keyword==="additionalProperties"||e.keyword==="unevaluatedProperties"?e.params?.additionalProperty??e.params?.unevaluatedProperty:void 0,r=`${e.message??`failed ${e.keyword}`}${typeof o=="string"?` (${o})`:""}`;return n===""?r:`${n}: ${r}`})}i(pK,"describeValidationErrors");var mK=20,CM=4096,vM=i(t=>`\u2026and ${t} more ${t===1?"error":"errors"}`,"moreErrors");function AM(t){let e=t??[],n=pK(e.slice(0,mK)),o=[],r=0;for(let s of n){let a=o.length===0?0:2,c=e.length-o.length-1,u=c>0?2+vM(c).length:0;if(r+a+s.length+u<=CM){o.push(s),r+=a+s.length;continue}if(o.length===0){let l=Math.max(1,CM-u-1),d=/[\uD800-\uDBFF]/.test(s.charAt(l-1))?l-1:l;o.push(`${s.slice(0,d)}\u2026`)}break}return o.length<e.length&&o.push(vM(e.length-o.length)),o}i(AM,"summarizeValidationErrors");var ug=i((t,e,n="")=>{let o;try{o=t(e)}catch(s){let a="the tool's input schema could not be evaluated";return{success:!1,data:null,errorMessage:a,errorData:{errors:[a]},internalError:s}}if(o)return{success:!0,data:e,errorData:null};let r=AM(t.errors?.map(s=>({...s,instancePath:`${n}${s.instancePath}`})));return{success:!1,data:null,errorMessage:r.join("; "),errorData:{errors:r}}},"runValidator"),fK=i(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isRecord");function kM(t){return new zn({},e=>ug(t.validate,e))}i(kM,"createGeneratedPromptValidator");function _M(t,e,n=bm(void 0,"inline")){let o=new zn(SM(t.input,n,"input"),p=>ug(t.input.validate,p));if(!e)return{validator:o};let r=t.flat;if(!r)return{validator:o,flatRefusal:t.flatRefusal??`the build resolved this tool's toolInputStyle to "nested", so it has no flat schema. Set toolInputStyle to the literal "flat" (not $env()) in the handler options or the tool's x-zuplo-route.mcp to flatten it.`};let s=new Map;for(let p of r.components)for(let f of p.keys)s.set(f,p.component);let a=new Set(r.components.map(p=>p.component)),c=new Set([...a].filter(p=>!s.has(p))),u=i((p,f)=>p.length>0&&p.every(h=>f.has(h)),"allIn"),l=i(p=>{let f=ug(r.validate,p);if(!f.success)return f;let h=f.data,y=Object.keys(h).filter(R=>!s.has(R)),S=Object.create(null);for(let R of r.components){if(R.mode==="wrapped"){Object.hasOwn(h,R.component)&&(S[R.component]=h[R.component]);continue}let C=R.mode==="spread"?[...R.keys,...y]:R.keys,T=Object.create(null);for(let I of C)Object.hasOwn(h,I)&&(T[I]=h[I]);S[R.component]=T}if(r.validateBody){let R=ug(r.validateBody,S.body,"/body");if(!R.success)return R}return{success:!0,data:S,errorData:null}},"validateFlat");return{validator:new zn(SM(r,n,"flat"),p=>{let f=fK(p)?Object.keys(p):[],h=i(S=>!S.success&&S.internalError!==void 0,"threw");if(u(f,c)){let S=o.validate(p);if(S.success||h(S))return S;let R=l(p);return R.success||h(R)?R:S}let y=l(p);if(!y.success&&!h(y)&&u(f,a)){let S=o.validate(p);if(S.success||h(S))return S}return y}),...t.flatNotes&&{flatNotes:t.flatNotes}}}i(_M,"createGeneratedToolValidator");function xM(t,e=bm(void 0,"inline")){let n=t.output;if(!n)return;let o;return{schema:i(()=>{if(!o){let r=e.assemble(n,"output");o=n.objectRoot&&r.type===void 0?{type:"object",...r}:r,e.mode==="defs"&&o.type!=="object"&&(o=VE(o))}return o},"schema"),validate:i((r,s)=>{try{if(n.validate(r))return}catch(a){return s?.(a),"the tool's output schema could not be evaluated"}return AM(n.validate.errors).join("; ")},"validate"),objectRoot:n.objectRoot}}i(xM,"createGeneratedOutput");function OM(t,e){let n=t.virtualServerName??e;return n===void 0?t:{...t,virtualServerName:n}}i(OM,"injectMcpServerName");import{AsyncLocalStorage as hK}from"node:async_hooks";var lg=new hK;function MM(t,e,n){return lg.run({zuploContext:t,requestData:e},n)}i(MM,"runWithInvokeContext");function Qw(){return lg.getStore()?.requestData.headers??{}}i(Qw,"getInvokeHeaders");function wc(){let t=lg.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}i(wc,"getInvokeContext");function LM(){return lg.getStore()?.requestData.user?.sub}i(LM,"getInvokeSubjectId");var UM="2026-07-28";function Xw(t){return t!==null&&t>=UM?-32602:-32002}i(Xw,"resourceNotFoundCode");var eS=200,qM=64,dg=1024,gK=new Set(["\r",`
261
261
  `,"\u2028","\u2029"]),NM=new Set([" "," "]);function pg(t){let e=[],n=!1;for(let o of t){if(gK.has(o)){for(;e.length>0&&NM.has(e[e.length-1]);)e.pop();n=!0;continue}if(n){if(NM.has(o))continue;e.length>0&&e.push(" "),n=!1}e.push(o)}return e.join("")}i(pg,"singleLine");function Sc(t,e){if(t.length<=e)return t;let n="";for(let o of t){if(n.length+o.length+1>e)break;n+=o}return`${n}\u2026`}i(Sc,"truncate");function mg(t){return Sc(pg(t),qM)}i(mg,"echo");var nS=Se.InvalidRequest,DM=Se.InvalidParams,yK=Se.ParseError;function uo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(uo,"isPlainObject");function jM(t){return typeof t=="string"||typeof t=="number"&&Number.isSafeInteger(t)}i(jM,"isRequestId");function bK(t){try{return Uw(t),!0}catch{return!1}}i(bK,"isJsonRpcMessage");function RK(t){return uo(t)?t.jsonrpc!=="2.0"?'jsonrpc must be "2.0"':!("method"in t)&&!("result"in t)&&!("error"in t)?"missing method":"method"in t&&typeof t.method!="string"?"method must be a string":"id"in t&&!jM(t.id)?"id must be a string or an integer":"params"in t&&!uo(t.params)?"params must be an object":"not a valid JSON-RPC 2.0 message":"expected a JSON-RPC message object"}i(RK,"invalidMessageReason");function wK(t){let e=Sc(pg(t.message),eS);return e===t.message?t:{...t,message:e,...t.data===void 0&&{data:{message:Sc(t.message,dg)}}}}i(wK,"conciseError");function HM(t){if(!uo(t)||!uo(t.error)||typeof t.error.code!="number"||typeof t.error.message!="string")return t;let e=t.error,n=wK(e);return n===e?t:{...t,error:n}}i(HM,"conciseMessage");function $M(t,e){if(bK(t))return;let n=e===void 0?"":`batch member ${e}: `,o={jsonrpc:"2.0",error:{code:nS,message:`Invalid Request: ${n}${RK(t)}`}},r=FM(t);return r!==void 0&&(o.id=r),o}i($M,"invalidMessageError");function FM(t){return uo(t)&&jM(t.id)?t.id:void 0}i(FM,"requestIdOf");function op(t,e,n){let o=new Headers(n);return o.set("Content-Type","application/json"),o.delete("content-length"),new Response(JSON.stringify(t),{status:e,headers:o})}i(op,"jsonResponse");function tS(t,e,n,o){let r={jsonrpc:"2.0",error:{code:e,message:n}};return o!==void 0&&(r.id=o),op(r,t)}i(tS,"errorResponse");function GM(t){let e=t.headers.get("accept");return t.method==="POST"&&e!==null&&e.includes("application/json")&&e.includes("text/event-stream")&&ep(t.headers.get("content-type")??void 0)}i(GM,"transportReadsBody");var SK="2025-06-18";function CK(t){return t!==null&&jo.includes(t)&&t>=SK}i(CK,"rejectsBatches");function BM(t,e){let n=t.headers.get("mcp-protocol-version");if(!(!Array.isArray(e)||!CK(n)||!GM(t)))return tS(400,nS,`Invalid Request: protocol version ${n} does not support JSON-RPC batches`,void 0)}i(BM,"refuseBatch");var vK={jsonrpc:"2.0",id:0,method:"ping"},TK=100;function IK(t,e){let n=t.headers.get("mcp-protocol-version");return n!==null&&!jo.includes(n)&&e.length>TK&&!e.some(Qd)}i(IK,"capHidesVersionError");async function ZM(t,e){if(!GM(t))return Cc(await e());let n;try{n=await t.clone().text()}catch{return Cc(await e())}let o;try{o=JSON.parse(n)}catch{return tS(400,yK,"Parse error: Invalid JSON",void 0)}if(!Array.isArray(o)){let c=$M(o);return c?op(c,400):Cc(await e())}if(o.length===0)return tS(400,nS,"Invalid Request: empty batch",void 0);let r=o.map((c,u)=>$M(c,u)),s=o.filter((c,u)=>r[u]===void 0);if(IK(t,s))return Cc(await e([vK]));if(s.length===o.length)return Cc(await e());if(s.length===0)return op(r,400);let a=await Cc(await e(s));return EK(o,r,a)}i(ZM,"handleWithSpecErrors");async function EK(t,e,n){let o=[];if(n.status===200){let a;try{a=await n.clone().json()}catch{return n}o=Array.isArray(a)?a:[a]}else if(n.status!==202)return n;let r=new Map;for(let a of o)uo(a)&&r.set(a.id,a);let s=[];for(let[a,c]of t.entries()){let u=e[a];if(u){s.push(u);continue}let l=FM(c);l!==void 0&&r.has(l)&&(s.push(r.get(l)),r.delete(l))}return s.push(...r.values()),op(s,200,n.headers)}i(EK,"mergeBatchAnswers");async function Cc(t){if(t.status<400||!ep(t.headers.get("content-type")??void 0))return t;let e;try{e=await t.clone().json()}catch{return t}if(!uo(e)||!("error"in e))return t;let n=HM(e);if(n===e&&e.id!==null)return t;let{id:o,...r}=n;return op(o==null?r:{...r,id:o},t.status,t.headers)}i(Cc,"normalizeTransportResponse");function Es(t,e,n,o=!1){let r=t[e];if(!(typeof r=="string"||o&&r===void 0))return[n,"a string"]}i(Es,"stringField");var PK=["experimental","sampling","elicitation","roots","tasks"];function AK(t){let e=Es(t,"protocolVersion","params.protocolVersion");if(e)return e;let n=t.capabilities;if(!uo(n))return["params.capabilities","an object"];for(let r of PK)if(r in n&&!uo(n[r]))return[`params.capabilities.${r}`,"an object"];let o=t.clientInfo;return uo(o)?Es(o,"name","params.clientInfo.name")??Es(o,"version","params.clientInfo.version")??Es(o,"title","params.clientInfo.title",!0):["params.clientInfo","an object"]}i(AK,"initializeIssue");function zM(t,e){let n=t.arguments;if(n!==void 0){if(!uo(n))return["params.arguments",e?"an object of strings":"an object"];if(e&&Object.values(n).some(o=>typeof o!="string"))return["params.arguments","an object of strings"]}}i(zM,"argumentsIssue");function kK(t,e){switch(t){case"initialize":case"tools/call":case"prompts/get":case"resources/read":break;default:return}if(e===void 0)return["params","an object"];switch(t){case"initialize":return AK(e);case"tools/call":return Es(e,"name","params.name")??zM(e,!1);case"prompts/get":return Es(e,"name","params.name")??zM(e,!0);default:return Es(e,"uri","params.uri")}}i(kK,"paramIssue");var _K=new Set(["tools/list","prompts/list","resources/list","resources/templates/list"]);function xK(t,e){let{id:n,method:o}=t,r=uo(t.params)?t.params:void 0,s=i((c,u,l)=>({jsonrpc:"2.0",id:n,error:{code:c,message:u,...l!==void 0&&{data:l}}}),"fail"),a=kK(o,r);if(a){let[c,u]=a;return s(DM,`Invalid params for ${o}: ${c} must be ${u}`)}if(_K.has(o)&&r!==void 0&&"cursor"in r)return s(DM,`Invalid params for ${o}: params.cursor is not a cursor this server issued`);if(o==="resources/read"){let c=r?.uri;if(typeof c=="string"&&!e.hasResource(c))return s(Xw(e.protocolVersion),"Resource not found",{uri:Sc(c,dg)})}}i(xK,"checkRequest");function VM(t,e){let n=t.send.bind(t);t.send=(r,s)=>n(HM(r),s);let o=t.onmessage;t.onmessage=(r,s)=>{let a=_r(r)?xK(r,e):void 0;if(a===void 0){o?.(r,s);return}t.send(a).catch(c=>{t.onerror?.(c instanceof Error?c:new Error("Failed to send an error response",{cause:c}))})}}i(VM,"refuseInvalidRequests");var fg=class t{static{i(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>m.email()],["uri",()=>m.url()],["url",()=>m.url()],["date",()=>m.iso.date()],["date-time",()=>m.iso.datetime()],["time",()=>m.iso.time()],["ipv4",()=>m.ipv4()],["ipv6",()=>m.ipv6()],["uuid",()=>m.guid()],["int32",()=>m.int32()],["int64",()=>m.int64()],["float",()=>m.number()],["double",()=>m.number()]]);static get(e){return t.formatter.get(e)}static register(e,n){t.formatter.set(e,n)}},rp=class t{static{i(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,n){let o={path:[],definitions:{},visitedRefs:new Set,...n};return t.transpileSchema(e,o)}static transpileSchema(e,n){if(!e)return m.unknown();try{if("$ref"in e)return t.resolveReference(e.$ref,n);if(e.allOf)return t.transpileAllOf(e.allOf,n);if(e.oneOf)return t.transpileOneOf(e.oneOf,n);if(e.anyOf)return t.transpileAnyOf(e.anyOf,n);if(e.not)return t.transpileNot(e.not,n);let o=t.transpileByType(e,n);return o=t.applyCommonModifiers(o,e),o}catch(o){let r=n.path.join(".");throw new Error(`Failed to transpile schema at path "${r}": ${o.message}`)}}static transpileByType(e,n){let o=e.type;!o&&e.properties&&(o="object");let r=t.typeTranspilers.get(o||"unknown");return r?r(e,n):m.unknown()}static transpileString(e,n){if(e.enum)return m.enum(e.enum);let o=e.format?fg.get(e.format):null,r=o?o():m.string();if(r instanceof m.ZodString){let s=r;return e.minLength!==void 0&&(s=s.min(e.minLength)),e.maxLength!==void 0&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),s}else e.minLength||e.maxLength||e.pattern;return r}static applyNumericConstraints(e,n,o){let r=e;if(n.minimum!==void 0&&(r=r.min(n.minimum)),n.maximum!==void 0&&(r=r.max(n.maximum)),n.exclusiveMinimum!==void 0){let s;if(typeof n.exclusiveMinimum=="number")s=n.exclusiveMinimum;else if(n.minimum!==void 0)s=n.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${o.path.join(".")}"`);r=r.gt(s)}if(n.exclusiveMaximum!==void 0){let s;if(typeof n.exclusiveMaximum=="number")s=n.exclusiveMaximum;else if(n.maximum!==void 0)s=n.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${o.path.join(".")}"`);r=r.lt(s)}return r}static transpileNumber(e,n){let o=m.number();return t.applyNumericConstraints(o,{...e,type:"number"},n)}static transpileInteger(e,n){let o=m.int();return t.applyNumericConstraints(o,{...e,type:"number"},n)}static transpileBoolean(e,n){return m.boolean()}static transpileArray(e,n){let o=e.items?t.transpileSchema(e.items,{...n,path:[...n.path,"items"]}):m.unknown(),r=m.array(o);return e.minItems!==void 0&&(r=r.min(e.minItems)),e.maxItems!==void 0&&(r=r.max(e.maxItems)),e.uniqueItems&&(r=r.refine(s=>new Set(s).size===s.length,{message:"Array must contain unique items"})),r}static transpileObject(e,n){let o;if(e.properties){let r={},s=new Set(e.required||[]);for(let[c,u]of Object.entries(e.properties)){let l={...n,path:[...n.path,c]},d=t.transpileSchema(u,l);s.has(c)||(d=d.optional()),r[c]=d}let a=m.object(r);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),o=a}else if(e.additionalProperties===!1)o=m.object({}).strict();else if(typeof e.additionalProperties=="object"){let r=t.transpileSchema(e.additionalProperties,n);o=m.record(m.string(),r)}else o=m.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(o=o.refine(r=>{let s=Object.keys(r).length;return!(e.minProperties!==void 0&&s<e.minProperties||e.maxProperties!==void 0&&s>e.maxProperties)},{message:t.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),o}static buildPropertyCountErrorMessage(e,n){return e!==void 0&&n!==void 0?`Object must have between ${e} and ${n} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${n} properties`}static transpileNull(e,n){return m.null()}static transpileAllOf(e,n){let o=e.map((a,c)=>t.transpileSchema(a,{...n,path:[...n.path,`allOf[${c}]`]}));if(o.length===0)return m.unknown();let r=o.reduce((a,c)=>a.and(c)),s=e.filter(a=>a?.additionalProperties===!1).map(a=>Object.keys(a.properties??{}));return s.length===0?r:r.superRefine((a,c)=>{if(!(typeof a!="object"||a===null||Array.isArray(a)))for(let u of s){let l=Object.keys(a).filter(d=>!u.includes(d));l.length>0&&c.addIssue({code:"custom",message:`Unrecognized key(s) in object: ${l.map(d=>`'${d}'`).join(", ")}`})}})}static transpileOneOf(e,n){let o=e.map((r,s)=>t.transpileSchema(r,{...n,path:[...n.path,`oneOf[${s}]`]}));return o.length===0?m.never():o.length===1?o[0]:m.union(o)}static transpileAnyOf(e,n){return t.transpileOneOf(e,n)}static transpileNot(e,n){let o=t.transpileSchema(e,{...n,path:[...n.path,"not"]});return m.unknown().refine(r=>!o.safeParse(r).success,{message:"Value must not match the schema"})}static resolveReference(e,n){if(n.visitedRefs?.has(e))return m.lazy(()=>t.resolveReference(e,n));n.visitedRefs?.add(e);let o=e.split("/");if(o[0]==="#"&&o[1]==="definitions"&&n.definitions){let r=n.definitions[o[2]];if(r)return t.transpileSchema(r,n)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,n){let o=e;return n.nullable&&(o=o.nullable()),n.default!==void 0&&(o=o.default(n.default)),n.description&&(o=o.describe(n.description)),n.examples&&n.examples.length>0&&(o=o.meta({examples:n.examples})),o}static registerTypeTranspiler(e,n){t.typeTranspilers.set(e,n)}static registerFormatSchema(e,n){fg.register(e,n)}};var ip=class{constructor(e,n){this.routeData=e;this.contentType=n}routeData;contentType;static{i(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let n=e.content[this.contentType].schema;return n?rp.run(n):null}},hg=class{constructor(e){this.parameters=e}parameters;static{i(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let n of this.parameters)e[n.name]=this.buildParameterSchema(n);return m.object(e)}buildParameterSchema(e){let n;e.schema?n=rp.run(e.schema):n=m.string(),e.required||(n=n.optional()),e.description&&(n=n.describe(e.description));let o=[];if(e.schema?.example!==void 0&&o.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&o.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?o.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(r=>{r?.value!==void 0&&o.push(r.value)})),e.example!==void 0&&o.push(e.example),o.length>0){let r=[...new Set(o.map(s=>JSON.stringify(s)))].map(s=>JSON.parse(s));n=n.meta({examples:r})}return n}};function oS(t){return m.toJSONSchema(t,{override:i(({jsonSchema:e})=>{Array.isArray(e.allOf)&&(e.allOf=[...e.allOf])},"override")})}i(oS,"toLegacyJsonSchema");var Ps={error:i(t=>t.input===void 0?"Missing required field":void 0,"error")},rS=i((t,e)=>{let n={};for(let o of e)o in t&&(n[o]=t[o]);return n},"pick"),sp=class t{static{i(this,"LegacyValidatorBuilder")}root=null;components={};flatInput=!1;refusals=[];notes=[];static withRoot(e){let n=new t;return n.root=e,n}withFlatInput(e=!0){return this.flatInput=e,this}get flattenRefusals(){return this.refusals}get flattenNotes(){return this.notes}withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){if(this.root)return this.buildFromSchema(this.root);if(Object.keys(this.components).length>0){if(this.flatInput){let e=this.buildFlattened();if(e)return e}return this.buildFromComponents()}return this.buildEmptyValidator()}buildFromSchema(e){let n=oS(e);return new zn(n,o=>{let r=e.safeParse(o,Ps);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:m.prettifyError(r.error),errorData:m.treeifyError(r.error)}})}buildFromComponents(){let e=m.strictObject(this.components),n=oS(e);return new zn(n,o=>{let r=e.safeParse(o,Ps);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:m.prettifyError(r.error),errorData:m.treeifyError(r.error)}})}buildFlattened(){let e=oS(m.strictObject(this.components)),n=WE(e,Object.keys(this.components));if(!n.ok){this.refusals.push(n.reason);return}this.notes.push(...n.warnings);let o,r=i(()=>(o||(o=this.buildFromComponents()),o),"legacy"),s=new Set(Object.keys(this.components)),a=new Set([...s].filter(f=>!n.routes.has(f))),c=i((f,h)=>f.length>0&&f.every(y=>h.has(y)),"allIn"),u=m.looseObject({}),l=m.strictObject({}),d=new Map;for(let f of n.components)f.mode==="wrapped"&&d.set(f.component,m.object({[f.component]:this.components[f.component]}));let p=i(f=>{let y=Object.keys(f).filter(P=>!n.routes.has(P)),S=[],R=[],C={},T={},I=i(P=>{S.push(m.prettifyError(P));let A=m.treeifyError(P);R.push(...A.errors??[]),Object.assign(C,A.properties??{})},"collect");for(let P of n.components){let A=d.get(P.component);if(A){let $=A.safeParse(rS(f,P.keys),Ps);$.success?Object.assign(T,$.data):I($.error);continue}let M=rS(f,P.mode==="spread"?[...P.keys,...y]:P.keys),z=this.components[P.component].safeParse(M,Ps);z.success?T[P.component]=z.data:I(z.error)}if(!n.spread&&y.length>0){let P=l.safeParse(rS(f,y),Ps);P.success||I(P.error)}return S.length>0?{success:!1,data:null,errorMessage:S.join(`
262
- `),errorData:{errors:R,...Object.keys(C).length>0&&{properties:C}}}:{success:!0,data:T,errorData:null}},"validateFlat");return new zn(n.schema,f=>{let h=u.safeParse(f,Ps);if(!h.success)return{success:!1,data:null,errorMessage:m.prettifyError(h.error),errorData:m.treeifyError(h.error)};let y=f,S=Object.keys(y);if(c(S,a)){let C=r().validate(y);if(C.success)return C;let T=p(y);return T.success?T:C}let R=p(y);if(R.success)return R;if(c(S,s)){let C=r().validate(y);if(C.success)return C}return R})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1},n=m.strictObject({});return new zn(e,o=>{let r=n.safeParse(o,Ps);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:m.prettifyError(r.error),errorData:m.treeifyError(r.error)}})}},iS=i((t,e)=>new hg(t.filter(n=>n.in===e)),"parameterBuilder");function JM(t,e,n="nested"){let o=new sp().withFlatInput(n==="flat"),r=t.raw()?.parameters||[];return e&&o.withBody(new ip(t,e).build()),o.withQueryParams(iS(r,"query").build()),o.withPathParams(iS(r,"path").build()),o.withHeaders(iS(r,"header").build()),o}i(JM,"createLegacyToolValidatorBuilder");function KM(t){return t.raw()?.requestBody?.content?.["application/json"]?sp.withRoot(new ip(t,"application/json").build()):new sp}i(KM,"createLegacyPromptValidatorBuilder");function WM(t){let e=KM(t).build();return{validator:e,arguments:KE(e.schema)}}i(WM,"buildLegacyPromptSchemas");function QM(t){return t!==void 0&&t.type!=="object"}i(QM,"hasNonObjectOutputRoot");function XM(t,e,n){try{let o=t.raw(),r=o?.responses;if(!r){e.warn("No responses found in OpenAPI spec for outputSchema",{path:t.path,operationId:o?.operationId});return}for(let s of Object.keys(r))if(s.startsWith("2")){let c=r[s]?.content;if(c){for(let u of["application/json","application/json; charset=utf-8"])if(c[u]?.schema){let l=c[u].schema;return n&&e.debug("Output schema extracted successfully",{path:t.path,operationId:o?.operationId,statusCode:s,contentType:u,schemaKeys:l&&typeof l=="object"?Object.keys(l).join(", "):"none"}),l}}}n&&e.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:t.path,operationId:o?.operationId,statusCodes:Object.keys(r).join(", ")});return}catch(o){e.warn("Failed to extract outputSchema",{path:t.path,operationId:t.raw()?.operationId,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0});return}}i(XM,"extractLegacyOutputSchema");var YM;function e0(t){try{YM??=new Ts({draft:"2020-12",shortcircuit:!1});let e=YM.getValidator(t);return{validate:i(n=>{try{let o=e(n);return o.valid?void 0:o.errorMessage}catch(o){return o instanceof Error?o.message:String(o)}},"validate")}}catch(e){return{unbuildableReason:e instanceof Error?e.message:String(e)}}}i(e0,"buildLegacyOutputSchemaValidator");function t0({name:t,routeData:e,method:n,contentType:o,includeOutputSchema:r,toolInputStyle:s,log:a,debugMode:c}){let u=OK(e,o,s,a,c);if(!u){a.warn("MCP tool skipped: could not build parameter validator",{toolName:t,method:n.toUpperCase(),path:e.path,operationId:e.raw()?.operationId,suggestion:"Check the OpenAPI parameter and request body definitions for this route."});return}let l=r?XM(e,a,c):void 0,d=l?e0(l):void 0;d?.unbuildableReason&&a.warn("MCP outputSchema conformance check unavailable",{toolName:t,method:n.toUpperCase(),path:e.path,operationId:e.raw()?.operationId,reason:d.unbuildableReason});let p=d?.unbuildableReason?void 0:l;return{validator:u,...p&&{outputSchema:i(()=>p,"outputSchema")},...d?.validate&&{validateStructuredContent:d.validate},nonObjectOutputRoot:QM(p)}}i(t0,"buildLegacyToolSchemas");function OK(t,e,n,o,r){try{let s=JM(t,e,n),a=s.build();for(let c of s.flattenRefusals)o.warn("MCP tool input schema left nested",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId,reason:c});if(r){for(let c of s.flattenNotes)o.debug("MCP tool request body left nested",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId,reason:c});o.debug("MCP validator built successfully",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId})}return a}catch(s){o.warn("MCP validator build failed",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId,error:s instanceof Error?s.message:String(s)});return}}i(OK,"buildValidator");var n0="2025-03-26",vc="2025-06-18",gg="2025-11-25",MK=n0,o0={annotations:n0,title:vc,outputSchema:vc,icons:gg,execution:gg},r0={title:vc,icons:gg},LK={icons:gg},NK={lastModified:vc},UK=vc,qK=vc;function i0(t){return t??MK}i(i0,"requestProtocolVersion");function yg(t,e,n){let o;for(let[r,s]of Object.entries(e))n<s&&r in t&&(o??={...t},delete o[r]);return o??t}i(yg,"omitNewerFields");function s0(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(s0,"isPlainObject");function a0(t,e){let n=t;if(s0(n.annotations)){let o=yg(n.annotations,NK,e);o!==n.annotations&&(n={...n,annotations:o})}if(n.type!=="resource_link")return n;if(e<UK){let{annotations:o,_meta:r}=n;return{type:"text",text:JSON.stringify(t),...o!==void 0&&{annotations:o},...r!==void 0&&{_meta:r}}}return yg(n,LK,e)}i(a0,"projectContentBlock");function DK(t,e){let n;for(let[o,r]of t.entries()){let s=a0(r,e);s!==r&&(n??=t.slice(),n[o]=s)}return n??t}i(DK,"projectContent");function c0(t,e){let n=Array.isArray(t.content)?DK(t.content,e):t.content;if(e>=qK||!("structuredContent"in t))return n===t.content?t:{...t,content:n};let{structuredContent:o,...r}=t,s=Array.isArray(t.content)&&t.content.some(a=>a.type==="text");return o===void 0||s?{...r,content:n}:{...r,content:[...n??[],{type:"text",text:JSON.stringify(o)}]}}i(c0,"projectCallToolResultForVersion");function u0(t,e){let n;for(let[o,r]of t.entries()){if(!s0(r.content))continue;let s=a0(r.content,e);s!==r.content&&(n??=t.slice(),n[o]={...r,content:s})}return n??t}i(u0,"projectPromptMessagesForVersion");var $K="2025-11-25";function l0(t){return t!==null&&t>=$K}i(l0,"shouldReturnToolInputErrorsAsResults");function d0(t,e,n,o,r){let s=t.validator.validate(n);if(s.success)return{valid:!0,data:s.data};s.internalError!==void 0&&r?.(s.internalError);let a=s.errorMessage?`Invalid arguments for tool '${e}': ${s.errorMessage}`:`Invalid arguments for tool '${e}'`;if(o)return{valid:!1,result:{content:[{type:"text",text:a}],isError:!0},...s.internalError!==void 0&&{internalError:s.internalError}};throw new Je(Se.InvalidParams,a,s.errorData)}i(d0,"validateToolArguments");function sS(t,e,n){if(t===void 0)return e;if(t==="flat"||t==="nested")return t;throw new Error(`MCP tool configuration error: invalid toolInputStyle ${JSON.stringify(t)} on operation "${n}". Use "flat" or "nested".`)}i(sS,"resolveToolInputStyle");var aS=["text","image","audio","resource_link","resource"],zK={text:Tr,image:Ir,audio:Er,resource_link:gs,resource:hs},p0=m.custom(t=>t!==null&&typeof t=="object"&&!Array.isArray(t)),jK=m.looseObject({content:m.array(m.unknown()).optional(),structuredContent:p0.optional(),_meta:p0.optional()});function h0(t,e,n){return e.isError===!0?e:t.projectCallToolResult(e,n)}i(h0,"projectToolResult");var m0=120;function As(t){let e;try{e=JSON.stringify(t)??String(t)}catch{e=Object.prototype.toString.call(t)}return e.length>m0?`${e.slice(0,m0)}\u2026`:e}i(As,"describeValue");function Tc(t){return t===null?"null":Array.isArray(t)?"array":typeof t}i(Tc,"describeKind");function ap(t){return`MCP tool '${t.toolName}' (${t.method.toUpperCase()} ${t.path})`}i(ap,"toolLabel");function cS(t,e){return t!==null&&typeof t=="object"&&e in t?{present:!0,value:t[e]}:{present:!1,value:void 0}}i(cS,"readField");function HK(t,e,n){let o=n.issues[0]?.path[0],r=ap(t);switch(o){case"content":{let{value:s}=cS(e,"content");return`${r}: \`setRawCallToolResult({ content })\` must be an array of content blocks, got ${As(s)} (${Tc(s)}). Each block is an object with a \`type\` discriminator, e.g. { type: "text", text: "..." }.`}case"structuredContent":{let{value:s}=cS(e,"structuredContent");return`${r}: \`setRawCallToolResult({ structuredContent })\` must be a JSON object, got ${As(s)} (${Tc(s)}). The MCP 2025-11-25 wire format rejects arrays and scalars here \u2014 wrap the value in an object, e.g. { result: [...] }.`}case"_meta":{let{value:s}=cS(e,"_meta");return`${r}: \`setRawCallToolResult({ _meta })\` must be a JSON object, got ${As(s)} (${Tc(s)}). MCP reserves \`_meta\` for metadata key/value pairs.`}default:return`${r}: setRawCallToolResult() takes an object with optional \`content\`, \`structuredContent\`, and \`_meta\` fields, got ${As(e)} (${Tc(e)}).`}}i(HK,"envelopeFailureMessage");function FK(t,e,n){let o=ap(t);if(n===null||typeof n!="object"||Array.isArray(n)){let a=typeof n=="string"?` Use \`{ type: "text", text: ${As(n)} }\`.`:"";return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} is ${As(n)} (${Tc(n)}), not a content block object. Every block needs a \`type\` discriminator so MCP clients know how to render it.${a}`}}let r=n.type;if(typeof r!="string")return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} has \`type\` ${As(r)} (${Tc(r)}) \u2014 the \`type\` discriminator must be a string naming the block kind, one of: ${aS.join(", ")}.`};if(!aS.includes(r))return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} has unsupported \`type\` "${r}". The MCP 2025-11-25 wire format this server negotiates accepts only: ${aS.join(", ")}.`};let s=zK[r].safeParse(n);if(!s.success){let a=s.error.issues.slice(0,3).map(c=>{let u=c.path.join(".");return u?`${u}: ${c.message}`:c.message}).join("; ");return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} (type "${r}") is not a valid MCP content block: ${a}.`}}return{ok:!0,block:s.data}}i(FK,"validateContentBlock");function f0(t,e,n){let o=ap(t),r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null){let s=n.constructor?.name??"custom class";return`${o}: \`setRawCallToolResult({ ${e} })\` must be a plain JSON object, got an instance of ${s}. Only plain objects serialize to a JSON object on the wire \u2014 return a literal object instead, e.g. { ... }.`}try{JSON.stringify(n)}catch(s){return`${o}: \`setRawCallToolResult({ ${e} })\` could not be serialized to JSON: ${s instanceof Error?s.message:String(s)}. Remove circular references and BigInt values \u2014 the wire format is JSON.`}}i(f0,"serializabilityViolation");function bg(t){let{target:e,defaults:n,override:o,validateStructuredContent:r,enforceOutputSchema:s,nonObjectOutputRoot:a=!1}=t,c;if(o!==void 0){let f=jK.safeParse(o);if(!f.success)return{ok:!1,message:HK(e,o,f.error)};c=f.data}let u;if(c?.content!==void 0){u=[];for(let[f,h]of c.content.entries()){let y=FK(e,f,h);if(!y.ok)return{ok:!1,message:y.message};u.push(y.block)}}if(c?.structuredContent!==void 0){let f=f0(e,"structuredContent",c.structuredContent);if(f!==void 0)return{ok:!1,message:f}}if(c?._meta!==void 0){let f=f0(e,"_meta",c._meta);if(f!==void 0)return{ok:!1,message:f}}let l=u??n.content,d=c?.structuredContent??n.structuredContent,p=c?._meta??{};if(s&&r){if(d===void 0)return{ok:!1,message:`${ap(e)}: this tool advertises an outputSchema, so MCP clients require a \`structuredContent\` result, but the downstream response body was not JSON of the kind the schema describes. Return a JSON body that matches the route's OpenAPI 2xx response schema`+(a?".":", or set a JSON object explicitly with `setRawCallToolResult({ structuredContent })`.")};let f=r(d);if(f!==void 0)return{ok:!1,message:`${ap(e)}: structuredContent does not conform to the tool's advertised outputSchema: ${f}. MCP clients reject results that violate the schema published in tools/list. Fix the route's response `+(a?"":"(or the setRawCallToolResult override) ")+"to match the schema, or correct the route's OpenAPI 2xx response schema."}}return{ok:!0,result:{content:l,...d!==void 0&&{structuredContent:d},isError:n.isError,_meta:p}}}i(bg,"buildCallToolResult");function g0(){return{}}i(g0,"buildToolsCapability");var uS={path:["simple","label","matrix"],query:["form","spaceDelimited","pipeDelimited","deepObject"],header:["simple"]},GK=/[A-Za-z0-9\-._~]/,BK=new Set(":/?@!$'()*,;".split("")),ZK=/^[0-9A-Fa-f]{2}$/,VK=new TextEncoder;function JK(t){let e="";for(let n of VK.encode(t))e+=`%${n.toString(16).toUpperCase().padStart(2,"0")}`;return e}i(JK,"percentEncodeChar");function Go(t,e=!1){let n="",o=Array.from(t);for(let r=0;r<o.length;r++){let s=o[r];GK.test(s)||e&&BK.has(s)||e&&s==="%"&&r+2<o.length&&ZK.test(o[r+1]+o[r+2])?n+=s:n+=JK(s)}return n}i(Go,"percentEncode");function xr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(xr,"isPlainObject");function Ic(t){return typeof t=="string"?t:typeof t=="object"&&t!==null?JSON.stringify(t):String(t)}i(Ic,"scalarText");function wg(t){return Array.isArray(t)?t.filter(e=>e!=null):xr(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null)):t}i(wg,"dropNulls");function lS(t){return Array.isArray(t)?t.length===0:xr(t)?Object.keys(t).length===0:!1}i(lS,"isEmptyCollection");function ks(t){return t.content!==void 0&&t.content!==null&&Object.keys(t.content).length>0}i(ks,"hasContent");function KK(t){return Object.entries(t.content??{})[0]}i(KK,"contentEntry");function WK(t){let e=t.split(";")[0].trim().toLowerCase();return e==="application/json"||e.endsWith("+json")}i(WK,"isJsonMediaType");function YK(t){if(t.schema!==void 0||!ks(t))return;let e=KK(t);if(!e||!WK(e[0]))return;let n=e[1]?.schema;return xr(n)?n:void 0}i(YK,"contentParameterSchema");function y0(t){return t==="query"?"form":"simple"}i(y0,"defaultStyle");function b0(t){return t==="form"}i(b0,"defaultExplode");function Sg(t,e){let n=t.in,o=t.style??y0(n),r=t.explode??b0(o),s=uS[n]?.includes(o)??!1,a=Array.isArray(e)||xr(e);if(s&&o==="deepObject"&&!xr(e)&&(s=!1),s&&(o==="spaceDelimited"||o==="pipeDelimited")&&(!a||r)&&(s=!1),s)return{style:o,explode:r};let c=y0(n);return{style:c,explode:b0(c),unsupportedStyle:o}}i(Sg,"resolveStyle");function QK(t){if(t.style===void 0||ks(t)||!Object.hasOwn(uS,t.in))return;let e=t.in,n=t.style;if(!uS[e].includes(n))return n;let o=XK(t);if(n==="deepObject")return o&&!o.includes("object")?n:void 0;if(n==="spaceDelimited"||n==="pipeDelimited")return t.explode===!0||o&&!o.includes("array")&&!o.includes("object")?n:void 0}i(QK,"findUnsupportedStyle");function w0(t,e,n){if(!n)return[];e=up(e);let o=[];for(let r of e){let s=QK(r);s!==void 0&&o.push({operationId:t,parameter:r.name,in:r.in,style:s})}return o}i(w0,"unsupportedStyleWarnings");function XK(t){let e=t.schema?.type;if(typeof e=="string")return[e];if(Array.isArray(e))return e.filter(n=>typeof n=="string")}i(XK,"schemaTypes");function dS(t,e,n){return n&&YK(t)!==void 0?JSON.stringify(e):typeof e=="string"?e:String(e)}i(dS,"contentText");function Cg(t){return t==null}i(Cg,"isEmpty");function S0(t,e,n=!0){if(Cg(e))return;if(ks(t))return Go(dS(t,e,n));let o=wg(e);if(lS(o))return"";let{style:r,explode:s}=Sg(t,o),a=Go(t.name),c=i(d=>r==="label"?Go(d).replaceAll(".","%2E"):Go(d),"encodeText"),u=i(d=>c(Ic(d)),"enc");if(Array.isArray(o)){let d=o.map(u);switch(r){case"label":return d.map(p=>`.${p}`).join("");case"matrix":return s?d.map(p=>`;${a}=${p}`).join(""):`;${a}=${d.join(",")}`;default:return d.join(",")}}if(xr(o)){let d=Object.entries(o),p=d.flatMap(([h,y])=>[c(h),u(y)]),f=d.map(([h,y])=>`${c(h)}=${u(y)}`);switch(r){case"label":return s?f.map(h=>`.${h}`).join(""):p.map(h=>`.${h}`).join("");case"matrix":return s?f.map(h=>`;${h}`).join(""):`;${a}=${p.join(",")}`;default:return(s?f:p).join(",")}}let l=u(o);switch(r){case"label":return`.${l}`;case"matrix":return l===""?`;${a}`:`;${a}=${l}`;default:return l}}i(S0,"serializePathParameter");function C0(t,e,n=!0,o=[]){if(Cg(e))return[];let r=Go(t.name),s=!ks(t)&&t.allowReserved===!0,a=i(p=>Go(Ic(p),s),"enc");if(ks(t))return[`${r}=${Go(dS(t,e,n))}`];let c=wg(e);if(lS(c))return[];let{style:u,explode:l}=Sg(t,c),d=i(p=>u==="form"&&!l?a(p).replaceAll(",","%2C"):a(p),"encItem");if(Array.isArray(c)){let p=c.map(d);return u==="spaceDelimited"?[`${r}=${p.join("%20")}`]:u==="pipeDelimited"?[`${r}=${p.join("|")}`]:l?p.map(f=>`${r}=${f}`):[`${r}=${p.join(",")}`]}if(xr(c)){let p=Object.entries(c);if(u==="deepObject")return p.map(([h,y])=>`${r}[${Go(h)}]=${a(y)}`);let f=p.flatMap(([h,y])=>[Go(h),d(y)]);return u==="spaceDelimited"?[`${r}=${f.join("%20")}`]:u==="pipeDelimited"?[`${r}=${f.join("|")}`]:l?(tW(t,Object.keys(c),o),p.map(([h,y])=>`${Go(h)}=${a(y)}`)):[`${r}=${f.join(",")}`]}return[`${r}=${a(c)}`]}i(C0,"serializeQueryParameter");var Si=class extends Error{static{i(this,"InvalidQueryKeyError")}constructor(e,n,o){super(`query parameter '${e}' has the key ${JSON.stringify(n)}, ${o}`),this.name="InvalidQueryKeyError"}},eW=/^[A-Za-z0-9\-._~]+$/;function v0(t,e){if(t.in!=="query"||ks(t)||Cg(e))return[];let n=wg(e);if(!xr(n))return[];let{style:o,explode:r}=Sg(t,n);return o==="form"&&r?Object.keys(n):[]}i(v0,"explodedQueryNames");function tW(t,e,n){let o=[t.name,...n];for(let r of e){if(!eW.test(r))throw new Si(t.name,r,"which is sent as a query name and may hold only the characters A-Z a-z 0-9 - . _ ~");let s=r.toLowerCase(),a=o.find(c=>c.toLowerCase()===s);if(a!==void 0)throw new Si(t.name,r,`which is sent as a query name and is the name of the declared query parameter '${a}'`)}}i(tW,"assertExplodedQueryNames");var Ec=class extends Error{static{i(this,"InvalidHeaderValueError")}constructor(e,n="a CR, LF or NUL character"){super(`header parameter '${e}' has a value that contains ${n}`),this.name="InvalidHeaderValueError"}},Pc=class extends Error{static{i(this,"InvalidTextValueError")}constructor(e,n){super(`${e} parameter '${n}' has a value that contains a lone surrogate, which is not valid text`),this.name="InvalidTextValueError"}},R0=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;function Rg(t){return typeof t=="string"?R0.test(t):Array.isArray(t)?t.some(Rg):typeof t=="object"&&t!==null?Object.entries(t).some(([e,n])=>R0.test(e)||Rg(n)):!1}i(Rg,"hasLoneSurrogate");var nW=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,cp=class extends Error{static{i(this,"InvalidHeaderNameError")}constructor(e){super(`header parameter '${e}' is not a valid header name (RFC 7230 token)`),this.name="InvalidHeaderNameError"}};function T0(t,e){let n=String(e);if(/[\r\n\0]/.test(n))throw new Ec(t);try{new Headers().set(t,n)}catch(o){throw o instanceof TypeError?new Ec(t,"a character this runtime's headers can't carry (such as one above U+00FF)"):o}}i(T0,"assertSendableHeaderValue");function oW(t){if(!nW.test(t))throw new cp(t)}i(oW,"assertHeaderName");var Bo=class extends Error{static{i(this,"InvalidPathValueError")}constructor(e,n,o){super(o===void 0?`path parameter '${e}' is written as the dot segment '${n}', which a URL parser removes from the path`:`path parameter '${e}' builds the path '${n}', ${o}`),this.name="InvalidPathValueError"}};function pS(t){return/^(\.|%2e){1,2}$/i.test(t)}i(pS,"isDotSegment");function I0(t,e,n=!0){if(Cg(e))return;let o;if(ks(t))o=dS(t,e,n);else{let r=wg(e);if(lS(r))return;let{explode:s}=Sg(t,r);if(Array.isArray(r))o=r.map(Ic).join(",");else if(xr(r)){let a=Object.entries(r);o=s?a.map(([c,u])=>`${c}=${Ic(u)}`).join(","):a.flatMap(([c,u])=>[c,Ic(u)]).join(",")}else o=Ic(r)}return T0(t.name,o),o}i(I0,"serializeHeaderParameter");function up(t){let e=new Map;for(let n of t){let o=n.in==="header"?n.name.toLowerCase():n.name;e.set(`${n.in}\0${o}`,n)}return[...e.values()]}i(up,"effectiveParameters");function E0(t,e,n,o=!0){let r={};if(!e)return r;let s=n?up(t):t;for(let[a,c]of Object.entries(e)){oW(a);let u=a.toLowerCase(),l=n?s.find(p=>p.in==="header"&&p.name.toLowerCase()===u):void 0;if(!l){T0(a,c),r[u]=c;continue}let d=I0(l,c,o);d!==void 0&&(r[u]=d)}return r}i(E0,"serializeHeaderArguments");function P0(t,e){let n=[];if(!e)return n;let o=up(t);for(let[r,s]of Object.entries(e)){let a=r.toLowerCase(),c=o.find(u=>u.in==="header"&&u.name.toLowerCase()===a);c&&I0(c,s)===void 0&&n.push(a)}return n}i(P0,"omittedHeaderArguments");var A0="(?<!(?<!\\\\)(?:\\\\\\\\)*\\\\):",k0={"\\":"/","?":"%3F","#":"%23"};function rW(t){return t.replace(/\\(.)/gs,(e,n)=>Object.hasOwn(k0,n)?k0[n]:e)}i(rW,"encodeReservedEscapes");function _0(t){return t.replace(/\\(.)/gs,(e,n)=>n==="\\"?"/":e)}i(_0,"readEscapedBackslashes");var vg=class{constructor(e,n=!1,o=!0,r=[]){this.serializeByStyle=n;this.contentSchemaAdvertised=o;this.declaredQueryNames=r;e=rW(e),this.pattern=new URLPattern({pathname:e});let s=new RegExp(`${A0}(\\w+)(\\([^)]*\\))?[*+?]?`,"g"),a;for(;(a=s.exec(e))!==null;)this.expectedPathParams.add(a[1])}serializeByStyle;contentSchemaAdvertised;declaredQueryNames;static{i(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;styledPathParams={};queryPairs=[];explodedNames=new Map;addParameter(e,n,o){let r=this.getParameterValue(e,n,o);if(r!=null){if((e.in==="path"||e.in==="query")&&Rg(r))throw new Pc(e.in,e.name);switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new v(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.serializeByStyle?this.styledPathParams[e.name]=S0(e,r,this.contentSchemaAdvertised)??"":this.addPathParameter(e.name,r);break;case"query":this.serializeByStyle?(this.queryPairs.push(...C0(e,r,this.contentSchemaAdvertised,this.declaredQueryNames)),this.claimExplodedNames(e,r)):this.addQueryParameter(e.name,r);break;default:break}}}claimExplodedNames(e,n){for(let o of v0(e,n)){let r=o.toLowerCase(),s=this.explodedNames.get(r);if(s!==void 0&&s!==e.name)throw new Si(e.name,o,`which is sent as a query name and is also a key of query parameter '${s}'`);this.explodedNames.set(r,e.name)}}getParameterValue(e,n,o){switch(e.in){case"path":return n?.[e.name];case"query":return o?.[e.name];default:return}}addPathParameter(e,n){this.pathParams[e]=String(n)}addQueryParameter(e,n){Array.isArray(n)?n.forEach(o=>{o!=null&&this.searchParams.append(e,String(o))}):typeof n=="object"&&n!==null?this.searchParams.append(e,JSON.stringify(n)):this.searchParams.append(e,String(n))}toString(){let e=[...this.expectedPathParams].filter(u=>!this.seenPathParams.has(u));if(e.length>0)throw new v(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let n=i((u,l)=>this.serializeByStyle?Object.hasOwn(this.styledPathParams,l)?this.styledPathParams[l]:u:this.pathParams[l]?encodeURIComponent(this.pathParams[l]):u,"substitute"),o=new RegExp(`${A0}(\\w+)(\\([^)]*\\))?([*+?])?`,"g");this.assertNoDotSegments(n,o);let r=this.pattern.pathname,s=r.replace(o,n),a=this.cleanupUrlPatternSyntax(s);this.assertFinalPath(a,r,n,o);let c=this.serializeByStyle?this.queryPairs.join("&"):this.searchParams.toString();return c?`${a}?${c}`:a}assertNoDotSegments(e,n){let o=this.pattern.pathname.replace(/\{\/\}[?*+]?/g,"");for(let r of o.split("/")){let s=[...r.matchAll(n)].map(c=>c[1]);if(s.length===0)continue;let a=r.replace(n,e);if(pS(a))throw new Bo(s[0],a)}}assertFinalPath(e,n,o,r){let s=i((f,h)=>{let y=[...n.matchAll(r)].map(R=>({name:R[1],written:o(R[0],R[1]),index:R.index??0})).filter(({written:R,index:C})=>h(R,C)).map(({name:R})=>R),S=[...new Set(y.length>0?y:this.expectedPathParams)];return new Bo(S.join(", ")||"path",e,f)},"fail"),a=n.indexOf("/",1),c=i(f=>a===-1||f<a,"inFirstSegment");if(e.includes("\\"))throw s("which holds a backslash that a URL parser reads as '/'",f=>f.includes("\\"));if(/[?#]/.test(e))throw s("which holds a '?' or '#' that a URL parser ends the path at",f=>/[?#]/.test(f));if(e.startsWith("//"))throw s("which starts with '//' that a URL parser reads as a host (an empty value in the first segment)",(f,h)=>f===""&&c(h));let u=e.startsWith("/")?e:`/${e}`,l=u.split("/"),d=l.find(pS);if(d!==void 0)throw new Bo("path",d);let p=new URL(u,"http://localhost");if(p.search!==""||p.hash!==""||p.pathname.split("/").length!==l.length)throw s("which a URL parser resolves to a different route",()=>!1)}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/(:\w+\([^)]*\))|\\(.)/gs,(n,o,r)=>o??r)}};var Tg=class{constructor(e,n=!1,o=!0){this.routeData=e;this.serializeByStyle=n;this.contentSchemaAdvertised=o}routeData;serializeByStyle;contentSchemaAdvertised;static{i(this,"McpUrlBuilder")}build(e,n){let o=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,r=this.routeData.raw()?.parameters||[],s=this.serializeByStyle?up(r):r,a=new vg(o,this.serializeByStyle,this.contentSchemaAdvertised,s.filter(c=>c.in==="query").map(c=>c.name));for(let c of s)a.addParameter(c,e,n);return a.toString()}},x0=new WeakMap;function Ig(t,e,n){let o=x0.get(t);o||(o=new URLPattern({pathname:_0(t.pathPattern||t.path)}),x0.set(t,o));let{pathname:r}=new URL(e,"http://localhost"),s=o.exec({pathname:r});if(s)return s.pathname.groups;let a=Object.keys(n??{}),c=a.find(u=>n?.[u]==="")??(a.join(", ")||"path");throw new Bo(c,r,"which the tool's route does not match")}i(Ig,"matchToolRoute");var iW={error:i(t=>t.input===void 0?"Missing required field":void 0,"error")};function O0(){let t={type:"object",properties:{},required:[],additionalProperties:!1},e=m.strictObject({});return new zn(t,n=>{let o=e.safeParse(n,iW);return o.success?{success:!0,data:o.data,errorData:null}:{success:!1,data:null,errorMessage:m.prettifyError(o.error),errorData:m.treeifyError(o.error)}})}i(O0,"createEmptyValidator");var M0=new WeakMap,L0=new WeakSet;function mS(t,e=!1){let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"&&!Array.isArray(n)||e?n:void 0}i(mS,"parseStructuredContent");function sW(t){let e=t.headers.get("accept");if(!e)return t;let n=e.replace(/application\/json/gi,"application/json").replace(/text\/event-stream/gi,"text/event-stream").replace(/(^|[ ,;])event-stream($|[ ,;])/i,"$1text/event-stream$2");if(!n.includes("text/event-stream")){if(!n.includes("application/json"))return t;n=`${n}, text/event-stream`}if(n===e)return t;let o=new Request(t,{headers:new Headers(t.headers)});return o.headers.set("accept",n),o}i(sW,"normalizeLegacyAcceptHeader");var Eg=class t{static{i(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:n,key:o}){let r=e.debugMode??!1,s=t.instances.get(o);if(s)r&&n.log.debug("MCP Server warm reuse",{routeKey:o});else{let a=Date.now();if(s=new t(e,n),s.registerFromOperations(s.opts.operations??[]),s.registerToolsFromFileSources(s.opts.files??[]),s.registerPromptsFromFileSources(s.opts.prompts??[]),s.registerResourcesFromFileSources(s.opts.resources??[]),s.logMissingGeneratedPromptSchemas(),_.instance.build.COMPATIBILITY_FLAGS.sanitizeMcpToolNames&&s.advertiseSanitizedToolNames(),s.logMissingGeneratedSchemas(),t.instances.set(o,s),r){let c=s.tools.size,u=s.prompts.size,l=s.resources.size,d=Date.now()-a;n.log.debug("MCP Server cold start",{routeKey:o,toolCount:c,promptCount:u,resourceCount:l,totalElapsedMs:d,debugMode:r,includeOutputSchema:s.includeOutputSchema,includeStructuredContent:s.includeStructuredContent})}}return s}opts;context;serverName;serverDisplayName;registeredToolNames;registeredPromptNames;registeredResourceNames;tools=new Map;toolRegistrations=[];toolsWithoutGeneratedSchemas=[];styleWarnedRoutes=new WeakSet;prompts=new Map;promptsWithoutGeneratedSchemas=[];resources=new Map;includeOutputSchema;includeStructuredContent;debugMode;toolInputStyle;schemaRefs;toolSchemasBySpec;jsonSchemaValidator=new cg;constructor(e,n){if(this.debugMode=e.debugMode??!1,this.context=n,this.opts=e,this.serverName=e.name??n.route?.path??void 0,this.serverDisplayName=e.name??"Zuplo MCP Server",this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.toolInputStyle=e.toolInputStyle??"nested",this.toolSchemasBySpec=EM(),this.toolSchemasBySpec&&e.schemaRefs!==void 0&&e.schemaRefs!=="inline"&&e.schemaRefs!=="defs")throw new Error(`MCP server configuration error: invalid schemaRefs ${JSON.stringify(e.schemaRefs)} on route "${n.route?.path??"(unknown)"}". Use "inline" or "defs".`);this.schemaRefs=e.schemaRefs??"inline",this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}missingGeneratedSchemasMessage(){let e=[...new Set(this.toolsWithoutGeneratedSchemas)];if(e.length===0)return;let n=e.slice(0,5).join(", "),o=e.length>5?` and ${e.length-5} more`:"";return`The build generated no schemas for some MCP tools: $env() in the handler options, or a handler not exported as "mcpServerHandler". Tools (${e.length}): ${n}${o}`}logMissingGeneratedPromptSchemas(){let e=[...new Set(this.promptsWithoutGeneratedSchemas)];if(e.length===0)return;let n=e.slice(0,5).join(", "),o=e.length>5?` and ${e.length-5} more`:"";this.context.log.error(`The build generated no arguments for some MCP prompts: $env() in the handler options, or a handler not exported as "mcpServerHandler". Prompts (${e.length}): ${n}${o}`,{promptNames:e,route:this.context.route?.path})}logMissingGeneratedSchemas(){let e=this.missingGeneratedSchemasMessage();e&&this.context.log.error(e,{toolNames:[...new Set(this.toolsWithoutGeneratedSchemas)],route:this.context.route?.path})}emitEvent(e,n){let o=n.capabilityType==="tool"?RM():void 0,r=OM(o===void 0?n:{...n,capabilityName:o},this.serverName),s=r.subjectId??LM(),a=r.mcpProtocolVersion??M0.get(e);gM(e,{...r,...s===void 0?{}:{subjectId:s},...a===void 0?{}:{mcpProtocolVersion:a}})}async handleRequest(e,n){let o=Date.now(),r=e.headers.get("mcp-session-id")??e.headers.get("Mcp-Session-Id")??null,s=e.user?.sub;try{let a=await e.clone().json().catch(()=>({})),c=typeof a?.method=="string"?a.method:null,u=Is(e.headers,a);u!==void 0&&M0.set(n,u),c==="tools/call"&&(n.custom.mcpCallToolRequest=a),this.emitEvent(n,{eventType:N.MCP_REQUEST_RECEIVED,outcome:"success",mcpMethod:c??void 0,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s}),s!==void 0&&this.emitEvent(n,{eventType:N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s});let l=wM(a);l&&this.emitEvent(n,{...l,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0});try{it.getContextExtensions(n).addHandlerResponseHook(C=>{let T=Date.now()-o;this.emitEvent(n,{eventType:N.MCP_REQUEST_COMPLETED,outcome:C.status>=400?"failure":"success",mcpMethod:c??void 0,httpMethod:e.method,httpStatusCode:C.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:T,subjectId:s,...L0.has(n)?{reasonClass:"protocol",reasonCode:Zw}:{}})})}catch{}if(this.debugMode)switch(n.log.debug("MCP Server request start",{method:a.method,requestId:a.id,routePath:n.route?.path}),a.method){case"tools/list":n.log.debug("MCP Server list tools request",{toolCount:this.tools.size,toolNames:Array.from(this.tools.keys())});break;case"prompts/list":n.log.debug("MCP Server list prompts request",{promptCount:this.prompts.size,promptNames:Array.from(this.prompts.keys())});break;case"resources/list":n.log.debug("MCP Server list resources request",{resourceCount:this.resources.size,resourceNames:Array.from(this.resources.keys())});break}let d=new Fw({name:this.serverDisplayName,version:this.opts.version??"0.0.0"},{jsonSchemaValidator:this.jsonSchemaValidator,capabilities:{tools:g0(),prompts:{},resources:{}}});this.wireRequestHandlers(d,n,e.headers.get("mcp-protocol-version"));let p=new nM({enableJsonResponse:!0,maxRequestBodySize:Number.MAX_SAFE_INTEGER});await d.connect(p);let f=sW(e),h=BM(f,a),y;h?y=h:(VM(p,{protocolVersion:e.headers.get("mcp-protocol-version"),hasResource:i(C=>Array.from(this.resources.values()).some(T=>T.uri===C),"hasResource")}),y=await ZM(f,C=>p.handleRequest(f,C===void 0?void 0:{parsedBody:C})));let S=Date.now()-o;await rM(y)&&(L0.add(n),this.emitEvent(n,{eventType:N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:c??void 0,httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,reasonClass:"protocol",reasonCode:Zw,subjectId:s}));let R=y.status>=200&&y.status<300;switch(a.method){case"initialize":{let C=a?.params?.clientInfo,T=typeof C?.name=="string"?C.name:void 0,I=typeof C?.title=="string"?C.title:void 0,P=typeof C?.version=="string"?C.version:void 0,A=a?.params?.protocolVersion,M=typeof A=="string"&&A!==""?A:u;this.emitEvent(n,{eventType:N.MCP_INITIALIZE_NEGOTIATED,outcome:R?"success":"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:T,clientTitle:I,clientVersion:P,mcpProtocolVersion:M,latencyMs:S}),R||this.emitEvent(n,{eventType:N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:T,clientVersion:P,mcpProtocolVersion:M,reasonClass:"client",reasonCode:"initialize_failed",attributes:{feature:"initialize"}});break}case"tools/list":this.emitEvent(n,{eventType:N.MCP_CAPABILITY_LISTED,outcome:R?"success":"failure",capabilityType:"tool",mcpMethod:"tools/list",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:S});break;case"resources/list":this.emitEvent(n,{eventType:N.MCP_CAPABILITY_LISTED,outcome:R?"success":"failure",capabilityType:"resource",mcpMethod:"resources/list",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:S});break;case"prompts/list":this.emitEvent(n,{eventType:N.MCP_CAPABILITY_LISTED,outcome:R?"success":"failure",capabilityType:"prompt",mcpMethod:"prompts/list",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:S});break}if(this.debugMode){let C=await y.clone().json().catch(()=>({}));n.log.debug("MCP Server response complete",{status:y.status,requestMethod:a.method,requestId:a.id,totalElapsedMs:S,respData:C})}return y}catch(a){let c=Date.now()-o;return n.log.error("MCP server internal error",{elapsedMs:c,err:a}),new Response("Internal error",{status:500})}}wireRequestHandlers(e,n,o){let r=_.instance.build.COMPATIBILITY_FLAGS.omitMcpFieldsNewerThanNegotiatedVersion?i0(o):void 0,s=i((c,u)=>r===void 0?c:yg(c,u,r),"forVersion"),a=i(c=>r===void 0?c:c0(c,r),"toolResultForVersion");e.setRequestHandler("tools/list",async()=>({tools:Array.from(this.tools.entries()).map(([c,u])=>({name:c,description:u.description,inputSchema:u.validator.schema,...u.outputSchema&&{outputSchema:u.outputSchema()},...u.annotations&&{annotations:u.annotations},...u._meta&&{_meta:u._meta}})).map(c=>s(c,o0))})),e.setRequestHandler("tools/call",async c=>{let u=c.params.name,l=this.tools.get(u);if(!l)throw new Je(Se.InvalidParams,`Tool "${mg(u)}" not found`);let d=c.params.arguments??{},p=i(h=>this.emitEvent(n,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:u,mcpMethod:"tools/call",transport:"http",reasonCode:h?"route_configuration_error":"invalid_arguments",reasonClass:h?"config":"client",...h&&{failureOrigin:"config",errorType:h.error instanceof Error?h.error.name:"unknown"}}),"failed"),f=d0(l,u,d,l0(o),h=>{n.log.error("MCP tool input validator threw",{toolName:u,err:h}),p({error:h})});if(!f.valid)return f.internalError===void 0&&p(),a(f.result);try{let h=i(()=>l.handler(f.data,c.params._meta),"call"),y=await(_.instance.build.COMPATIBILITY_FLAGS.sanitizeMcpToolNames?bM(u,h):h());return a(h0(e,y,l.outputSchema?.()))}catch(h){return a({content:[{type:"text",text:h instanceof Error?h.message:"Tool execution error"}],isError:!0})}}),e.setRequestHandler("prompts/list",async()=>({prompts:Array.from(this.prompts.entries()).map(([c,u])=>({name:c,description:u.description,arguments:u.arguments}))})),e.setRequestHandler("prompts/get",async c=>{let u=c.params.name,l=this.prompts.get(u);if(!l)throw new Je(Se.InvalidParams,`Prompt "${mg(u)}" not found`);let d=c.params.arguments??{},p=l.validator.validate(d);if(!p.success)throw new Je(Se.InvalidParams,p.errorMessage?`Invalid arguments for prompt '${u}': ${p.errorMessage}`:`Invalid arguments for prompt '${u}'`,p.errorData);try{let f=await l.generator(p.data);return{...l.description!==void 0&&{description:l.description},messages:r===void 0?f:u0(f,r)}}catch(f){throw new Je(Se.InternalError,f instanceof Error?f.message:"Prompt generation error")}}),e.setRequestHandler("resources/list",async()=>({resources:Array.from(this.resources.entries()).map(([c,u])=>({name:c,uri:u.uri,...u.metadata.title!==void 0&&{title:u.metadata.title},...u.metadata.description!==void 0&&{description:u.metadata.description},...u.metadata.mimeType!==void 0&&{mimeType:u.metadata.mimeType},...u.metadata._meta!==void 0&&{_meta:u.metadata._meta}})).map(c=>s(c,r0))})),e.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:[]})),e.setRequestHandler("resources/read",async c=>{let u=c.params.uri,l=Array.from(this.resources.values()).find(d=>d.uri===u);if(!l)throw new Wd(u);try{return await l.reader()}catch(d){throw new Je(Se.InternalError,d instanceof Error?d.message:"Resource read error")}})}addToolInternal(e){let n={description:e.description,validator:e.validator,...e.outputSchema&&{outputSchema:e.outputSchema},...e.annotations&&{annotations:e.annotations},...e._meta&&{_meta:e._meta},handler:e.handler};this.tools.set(e.name,n),this.toolRegistrations.push([e.name,n])}advertiseSanitizedToolNames(){let e=YE(this.toolRegistrations.map(([n])=>n));this.tools.clear(),this.toolRegistrations.forEach(([,n],o)=>{this.tools.set(e[o],n)})}addPromptInternal(e){this.prompts.set(e.name,{description:e.description,arguments:e.arguments,validator:e.validator,generator:e.generator})}addResourceInternal(e,n,o,r){this.resources.set(e,{uri:n,metadata:o,reader:r})}generatePromptDescriptionFromSpec(e){let n=e.raw();return n?.description?n.description:n?.summary?n.summary:`Generate content for operation for ${e.path}`}static getOperationsMetadataForFile(e){let{routes:n}=ot.instance.routeData,o=n.filter(s=>s.metadata?.filepath===e);if(o.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let r=new Map;for(let s of o){let a=s?.raw().operationId;if(a){r.set(a,{routeConfig:s});let c=s?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],p=c["x-zuplo-mcp-resource"],f=c["x-zuplo-route"]?.mcp;(u||l||d||p||f)&&r.set(a,{routeConfig:s,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:p||void 0,routeMcpExtension:f||void 0})}}return r}registerFromOperations(e){let n=new Map;for(let o of e){let r=n.get(o.file)??[];r.push(o.id),n.set(o.file,r)}for(let[o,r]of n.entries()){let s=t.getOperationsMetadataForFile(o);for(let a of r){let c=s.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${o}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let n of e){let o=t.getOperationsMetadataForFile(n.path),r=new Set;for(let s of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${s}" from file: "${n.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(s);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${s}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??s;if(r.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);r.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:s});continue}this.registerPromptForOperation(l,d,c,s)}}}generatedPromptSchemas(e,n,o){let r=IM(n.metadata?.filepath??"",o);if(!r){this.promptsWithoutGeneratedSchemas.push(e);return}return{validator:kM(r),arguments:r.arguments}}registerPromptForOperation(e,n,o,r){try{if(o.handler?.export==="mcpServerHandler")return;let s=this.toolSchemasBySpec?this.generatedPromptSchemas(e,o,r):WM(o);if(!s)return;this.addPromptInternal({name:e,description:n,arguments:s.arguments,validator:s.validator,generator:i(async a=>{let c=wc(),u=Date.now();try{this.debugMode&&c.log.debug("MCP prompt invoked",{promptName:e,operationId:o.raw()?.operationId,path:o.path,args:a});let l=this.buildToolUrl(o,{body:a}),d=this.buildToolRequest("POST","application/json",{body:a});this.debugMode&&c.log.debug("MCP prompt downstream call",{promptName:e,url:l,method:"POST",bodyPreview:a});let p=Date.now(),f=await c.invokeRoute(l,d),h=Date.now()-p,y=await f.json();if(!f.ok)throw new Error(`Route returned ${f.status}: ${y}`);let S;try{if(S=y.messages||y,!Array.isArray(S))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(C){throw new Error(`Invalid JSON response or missing messages array: ${C instanceof Error?C.message:String(C)}`)}let R=Date.now()-u;return this.debugMode&&c.log.debug("MCP prompt response complete",{promptName:e,operationId:o.raw()?.operationId,status:f.status,elapsedMs:R,downstreamElapsedMs:h,messageCount:S.length}),this.emitEvent(c,{eventType:N.MCP_CAPABILITY_COMPLETED,outcome:"success",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:R}),S}catch(l){let d=Date.now()-u,p=l instanceof Error?`${l.name}: ${l.message}`:String(l);throw c.log.error("MCP prompt invocation failed",{promptName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:d,err:l}),this.emitEvent(c,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:d,reasonCode:"gateway_error",reasonClass:"upstream",errorType:l instanceof Error?l.name:"unknown"}),new Error(`MCP prompt invocation failed for prompt '${e}': ${p}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:r,path:o.path})}catch(s){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:r,error:s instanceof Error?s.message:String(s)}),new Error(`Failed to register prompt "${e}" for operation "${r}": ${s instanceof Error?s.message:String(s)}`)}}registerResourcesFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${s}" from file: "${o.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${s}" in file ${o.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:s});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${s}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${s}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${s}" uses ${d} method. Resources are read-only and must use GET method only.`);let p=u?.name?.trim()||s.trim()||"";if(!p)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${s}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(n.has(p))throw new Error(`MCP Resource configuration error: Duplicate resource name "${p}". Resource names must be unique across all configured resources.`);n.add(p);let f=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${p}`,h=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,y=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,h,f,c,s,y)}}}registerResourceForOperation(e,n,o,r,s,a,c){try{if(r.handler?.export==="mcpServerHandler")return;this.addResourceInternal(e,n,{title:e,description:o,mimeType:a,...c&&{_meta:c}},async()=>{let u=wc(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,uri:n});let d=this.buildToolUrl(r,{}),p=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let f=Date.now(),h=await u.invokeRoute(d,p),y=Date.now()-f,S=await h.text(),R=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:r.raw()?.operationId,status:h.status,elapsedMs:R,downstreamElapsedMs:y,declaredMimeType:a,contentLength:S.length}),this.emitEvent(u,{eventType:h.ok?N.MCP_CAPABILITY_COMPLETED:N.MCP_CAPABILITY_FAILED,outcome:h.ok?"success":"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:R,...h.ok?{}:{errorCode:h.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),{contents:[{uri:n,mimeType:a,text:S,...c&&{_meta:c}}]}}catch(d){let p=Date.now()-l,f=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,elapsedMs:p,err:d}),this.emitEvent(u,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:p,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP resource call failed for resource '${e}': ${f}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:s,path:r.path,uri:n,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:s,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${s}": ${u instanceof Error?u.message:String(u)}`)}}resolveIncludeStructuredContent({includeOutputSchema:e,includeStructuredContent:n,routeConfig:o,operationId:r}){return e&&!n?(this.context.log.warn("MCP includeOutputSchema implies includeStructuredContent; enabling it",{path:o.path,operationId:r,override:"includeStructuredContent: true"}),!0):n}registerTool(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredToolNames.has(s))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${n}". The tool name "${s}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${n}".`);this.registeredToolNames.add(s);let a=o?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${s}`,c=o?.includeOutputSchema??this.includeOutputSchema??!1,u=this.resolveIncludeStructuredContent({includeOutputSchema:c,includeStructuredContent:o?.includeStructuredContent??this.includeStructuredContent??!1,routeConfig:e,operationId:n}),l=sS(o?.toolInputStyle,this.toolInputStyle,n);if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${n}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,operationId:n,method:e.methods[0],name:s,description:a,includeOutputSchema:c,includeStructuredContent:u,toolInputStyle:l,annotations:o?.annotations,_meta:o?._meta})}registerPrompt(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredPromptNames.has(s))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${s}" for operation ID "${n}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(s);let a=o?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(s,a,e,n)}registerResource(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:n});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${n}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${n}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let s=e.methods[0].toUpperCase();if(s!=="GET")throw new Error(`MCP Resource configuration error: Operation "${n}" uses ${s} method. Resources are read-only and must use GET method only.`);let a=o?.name?.trim()||n;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=o?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=o?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=o?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,n,l,o?._meta)}registerToolsFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);this.debugMode&&this.context.log.debug("Processing file source",{path:o.path,operationIds:o.operationIds,availableOperationIds:Array.from(r.keys())});for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${s}" from file: "${o.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${s}" not found in OpenAPI spec at ${o.path}. Available operation IDs: ${Array.from(r.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:s,path:o.path});continue}let c=a.toolExtension?.name?.trim()??s,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${s}" in file "${o.path}"`);if(n.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${s}".`);n.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=this.resolveIncludeStructuredContent({includeOutputSchema:l,includeStructuredContent:a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1,routeConfig:a.routeConfig,operationId:s}),p=sS(a.toolExtension?.toolInputStyle,this.toolInputStyle,s);if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${s}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(s,a.routeConfig,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,operationId:s,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d,toolInputStyle:p})}}}registerGraphQLTools(e,n,o){let r=o?.introspectionTool?.name?.trim()||`${e}_introspect`,s=o?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(r))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${r}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(s))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${s}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(r),this.registeredToolNames.add(s);let a=o?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=o?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=n.path,l=O0();this.addToolInternal({name:r,description:a,validator:l,handler:i(async()=>{let p=wc(),f=Date.now();try{this.debugMode&&p.log.debug("MCP GraphQL introspection tool invoked",{toolName:r,operationId:e,path:u});let h=df(),y=this.buildToolUrl(n,{}),S=this.buildToolRequest("POST","application/json",{body:{query:h}});hf(S,{route:n,params:Ig(n,y,void 0)});let R=Date.now(),C=await p.invokeRoute(y,S),T=Date.now()-R,I=await C.text(),P=Date.now()-f;this.debugMode&&(C.ok?p.log.debug("MCP GraphQL introspection tool ok response",{toolName:r,operationId:e,status:C.status,elapsedMs:P,downstreamElapsedMs:T}):p.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:r,operationId:e,status:C.status,elapsedMs:P,downstreamElapsedMs:T,response:I}));let A=mS(I);this.debugMode&&A===void 0&&p.log.debug("MCP GraphQL introspection structuredContent skipped (non-object)",{toolName:r,bodyPreview:I.slice(0,200)});let M=p.custom.mcpCallToolResponse;delete p.custom.mcpCallToolResponse;let z=bg({target:{toolName:r,method:"POST",path:u},defaults:{content:[{type:"text",text:I}],structuredContent:A,isError:!C.ok},override:M,enforceOutputSchema:!1});return z.ok?z.result:(p.log.error("MCP tool result rejected",{toolName:r,operationId:e,path:u,reason:z.message}),{content:[{type:"text",text:z.message}],isError:!0,_meta:{}})}catch(h){let y=Date.now()-f,S=h instanceof Error?`${h.name}: ${h.message}`:String(h);throw p.log.error("MCP GraphQL introspection tool invocation failed",{toolName:r,operationId:e,path:u,elapsedMs:y,err:h}),new Error(`MCP GraphQL introspection tool call failed for '${r}': ${S}`)}},"handler")});let d={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.addToolInternal({name:s,description:c,validator:new zn(d,p=>typeof p=="object"&&p!==null&&"query"in p&&typeof p?.query=="string"?{success:!0,data:p,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:i(async p=>{let f=wc(),h=Date.now();try{this.debugMode&&f.log.debug("MCP GraphQL execute tool invoked",{toolName:s,operationId:e,path:u,queryPreview:p.query.substring(0,100)});let y=this.buildToolUrl(n,{}),S={query:p.query};p.variables&&(S.variables=p.variables);let R=this.buildToolRequest("POST","application/json",{body:S});hf(R,{route:n,params:Ig(n,y,void 0)});let C=Date.now(),T=await f.invokeRoute(y,R),I=Date.now()-C,P=await T.text(),A=Date.now()-h;this.debugMode&&(T.ok?f.log.debug("MCP GraphQL execute tool ok response",{toolName:s,operationId:e,status:T.status,elapsedMs:A,downstreamElapsedMs:I}):f.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:s,operationId:e,status:T.status,elapsedMs:A,downstreamElapsedMs:I,response:P}));let M=mS(P);this.debugMode&&M===void 0&&f.log.debug("MCP GraphQL execute structuredContent skipped (non-object)",{toolName:s,bodyPreview:P.slice(0,200)});let z=f.custom.mcpCallToolResponse;delete f.custom.mcpCallToolResponse;let $=bg({target:{toolName:s,method:"POST",path:u},defaults:{content:[{type:"text",text:P}],structuredContent:M,isError:!T.ok},override:z,enforceOutputSchema:!1});return $.ok?$.result:(f.log.error("MCP tool result rejected",{toolName:s,operationId:e,path:u,reason:$.message}),{content:[{type:"text",text:$.message}],isError:!0,_meta:{}})}catch(y){let S=Date.now()-h,R=y instanceof Error?`${y.name}: ${y.message}`:String(y);throw f.log.error("MCP GraphQL execute tool invocation failed",{toolName:s,operationId:e,path:u,elapsedMs:S,err:y}),new Error(`MCP GraphQL execute tool call failed for '${s}': ${R}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:r,executeToolName:s,path:u})}registerToolsForMethod({routeData:e,operationId:n,method:o,name:r,description:s,includeOutputSchema:a,includeStructuredContent:c,toolInputStyle:u,annotations:l,_meta:d}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let p of Object.keys(e.raw().requestBody?.content)){let h=Object.keys(e.raw().requestBody?.content).length>1?`${r}_${p.replace(/[^\w]/g,"_")}`:r;this.registerGenericToolSpec({name:h,description:s,routeData:e,operationId:n,method:o,contentType:p,includeOutputSchema:a,includeStructuredContent:c,toolInputStyle:u,annotations:l,_meta:d})}else this.registerGenericToolSpec({name:r,description:s,routeData:e,operationId:n,method:o,contentType:null,includeOutputSchema:a,includeStructuredContent:c,toolInputStyle:u,annotations:l,_meta:d})}registerGenericToolSpec({name:e,description:n,routeData:o,operationId:r,method:s,contentType:a,includeOutputSchema:c,includeStructuredContent:u,toolInputStyle:l,annotations:d,_meta:p}){let f=this.toolSchemasBySpec?this.generatedToolSchemas({name:e,routeData:o,operationId:r,method:s,contentType:a,includeOutputSchema:c,toolInputStyle:l}):t0({name:e,routeData:o,method:s,contentType:a,includeOutputSchema:c,toolInputStyle:l,log:this.context.log,debugMode:this.debugMode});if(!f)return;this.warnUnsupportedParameterStyles(o);let{validator:h,outputSchema:y,validateStructuredContent:S,nonObjectOutputRoot:R}=f;try{this.addToolInternal({name:e,description:n,validator:h,...y&&{outputSchema:y},...d&&{annotations:d},...p&&{_meta:p},handler:i(async(C,T)=>{let I=wc(),P=Date.now();try{this.debugMode&&I.log.debug("MCP tool invoked",{toolName:e,operationId:o.raw()?.operationId,method:s,path:o.path,args:C});let A=this.buildToolUrl(o,C),M=Ig(o,A,C.pathParams),z=this.buildToolRequest(s,a,C,o);hf(z,{route:o,params:M}),this.debugMode&&I.log.debug("MCP tool downstream call",{toolName:e,url:A,method:s,headers:z.headers?Object.keys(z.headers).join(", "):"",bodyPreview:C.body});let $=Date.now(),F=await I.invokeRoute(A,z),K=Date.now()-$,se=await F.text(),ce=u?mS(se,R):void 0;this.debugMode&&u&&ce===void 0&&I.log.debug("MCP tool structuredContent skipped (unparseable, or non-object without a non-object outputSchema)",{toolName:e,bodyPreview:se.slice(0,200)});let we=Date.now()-P;this.debugMode&&(F.ok?I.log.debug("MCP tool ok response",{toolName:e,operationId:o.raw()?.operationId,status:F.status,elapsedMs:we,downstreamElapsedMs:K}):I.log.debug("MCP tool 'isError' response",{toolName:e,operationId:o.raw()?.operationId,status:F.status,elapsedMs:we,downstreamElapsedMs:K,response:se}));let B=I.custom.mcpCallToolResponse;delete I.custom.mcpCallToolResponse;let te=bg({target:{toolName:e,method:s,path:o.path},defaults:{content:[{type:"text",text:se}],structuredContent:F.ok?ce:void 0,isError:!F.ok},override:B,validateStructuredContent:S&&(X=>S(X,re=>I.log.error("MCP tool output validator threw",{toolName:e,err:re}))),enforceOutputSchema:F.ok,nonObjectOutputRoot:R});return te.ok?(this.emitEvent(I,{eventType:F.ok?N.MCP_CAPABILITY_COMPLETED:N.MCP_CAPABILITY_FAILED,outcome:F.ok?"success":"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:s,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:Date.now()-P,...F.ok?{}:{errorCode:F.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),te.result):(I.log.error("MCP tool result rejected",{toolName:e,operationId:o.raw()?.operationId,method:s,path:o.path,reason:te.message}),this.emitEvent(I,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:s,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:Date.now()-P,reasonCode:"invalid_tool_result",reasonClass:"config"}),{content:[{type:"text",text:te.message}],isError:!0,_meta:{}})}catch(A){return this.toolInvocationFailure(I,A,{toolName:e,operationId:o.raw()?.operationId,method:s,path:o.path,elapsedMs:Date.now()-P})}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:s.toUpperCase(),path:o.path,operationId:r,contentType:a||"none",includeOutputSchema:c,includeStructuredContent:u,hasValidator:!!h,hasOutputSchema:!!y})}catch(C){throw new Error(`Failed to add tool ${s} ${o.path}`,C)}}generatedToolSchemas({name:e,routeData:n,operationId:o,method:r,contentType:s,includeOutputSchema:a,toolInputStyle:c}){let u=TM(n.metadata?.filepath??"",o,s);if(!u){this.toolsWithoutGeneratedSchemas.push(e);return}let l=PM(this.schemaRefs),{validator:d,flatRefusal:p,flatNotes:f}=_M(u,c==="flat",l);if(p&&this.context.log.warn("MCP tool input schema left nested",{method:r.toUpperCase(),path:n.path,contentType:s||"none",operationId:o,reason:p}),this.debugMode)for(let y of f??[])this.context.log.debug("MCP tool request body left nested",{method:r.toUpperCase(),path:n.path,contentType:s||"none",operationId:o,reason:y});let h=a?xM(u,l):void 0;return{validator:d,...h&&{outputSchema:h.schema,validateStructuredContent:h.validate},nonObjectOutputRoot:h!==void 0&&!h.objectRoot}}warnUnsupportedParameterStyles(e){if(!this.styleWarnedRoutes.has(e)){this.styleWarnedRoutes.add(e);for(let n of w0(e.raw()?.operationId,e.raw()?.parameters??[],_.instance.build.COMPATIBILITY_FLAGS.serializeMcpParametersByStyle))this.context.log.warn("MCP tool parameter style not supported for value; using default",n)}}toolInvocationFailure(e,n,o){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n),s=n instanceof Bo||n instanceof Si||n instanceof Pc||n instanceof cp||n instanceof Ec;return s?e.log.debug("MCP tool call refused: unsendable argument value",{...o,err:n}):e.log.error("MCP server tool invocation failed",{...o,err:n}),this.emitEvent(e,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:o.toolName,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:o.method,toolOperationId:o.operationId??"unknown",latencyMs:o.elapsedMs,reasonCode:s?"invalid_arguments":"gateway_error",reasonClass:s?"client":"upstream",errorType:n instanceof Error?n.name:"unknown"}),{content:[{type:"text",text:`MCP tool call failed for tool '${o.toolName}': ${r}`}],isError:!0}}buildToolUrl(e,n){return new Tg(e,_.instance.build.COMPATIBILITY_FLAGS.serializeMcpParametersByStyle,this.toolSchemasBySpec).build(n.pathParams,n.queryParams)}buildToolRequest(e,n,o,r){let s=this.buildToolHeaders(e,n,o,r?.raw()?.parameters),a={method:e,headers:s};return this.shouldIncludeBody(e,n,o)&&(a.body=this.serializeBody(o.body,n)),a}buildToolHeaders(e,n,o,r=[]){let s={...Qw()};if(delete s["content-type"],o.headers){let a=_.instance.build.COMPATIBILITY_FLAGS.serializeMcpParametersByStyle;if(a){let c=new Set(P0(r,o.headers));for(let u of Object.keys(s))c.has(u.toLowerCase())&&delete s[u]}Object.assign(s,E0(r,o.headers,a,this.toolSchemasBySpec))}return n&&o.body!==void 0&&(s["content-type"]=n),this.isBodyMethod(e||"")&&o.body!==void 0&&!s["content-type"]&&(s["content-type"]="application/json"),s}shouldIncludeBody(e,n,o){return o.body===void 0?!1:this.isBodyMethod(e)?!0:n!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,n){return JSON.stringify(e)}};async function N0(t,e){if(pe("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new v(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let n={};t.headers.forEach((a,c)=>{n[c]=a});let o=e.route?.handler?.options??{},r=e.route?.path??"unknown-route",s=await Eg.getInstance({opts:o,context:e,key:r});return MM(e,{headers:n,user:t.user},()=>s.handleRequest(t,e))}i(N0,"mcpServerHandler");jt("mcp-server",N0);var aW=[502,503,504];function Pg(t){if(t!=null){if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new v(`The 'requestTimeoutSeconds' handler option must be a positive number of seconds. Received: ${String(t)}. Remove the option to disable the request timeout.`);return AbortSignal.timeout(t*1e3)}}i(Pg,"getRequestTimeoutSignal");function Or(t){if(typeof t!="object"||t===null)return!1;let e=t.name;return e==="TimeoutError"||e==="AbortError"}i(Or,"isRequestTimeoutError");async function Ac(t,e){if(aW.includes(t.status)){let n=de.getLogger(e),r=await t.clone().text(),s={};for(let[a,c]of t.headers)s[a]=c;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:r,headers:s})}}i(Ac,"logBadGatewayResponses");var fS;function kc(t){if(fS===void 0){let n=_.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),fS=n}return t.log[fS]}i(kc,"getHandlerUserLogFunction");async function U0(t,e){pe("handler.open-api");let n=_.instance.build.BUILD_ID,{buildAssetsUrl:o}=_.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new v("Open API Spec Handler must have 'openApiFilePath' specified");let a=uW(s);if(!a.isValid)throw new v(a.error);let c=cW(_.instance);if(c){let{label:f,reason:h,environment:y}=c;return G.notImplemented(t,e,{detail:`The 'openApiSpecHandler' route cannot serve '${s}' in ${f}. The handler reads the OpenAPI file from the build assets that are published when a project is deployed, and ${h}. Deploy this project to a preview or production environment to use this route. While developing, read the file from your '/config' directory instead.`,openApiFilePath:s,environment:y})}let u=`${o}/${n}${s.substring(1)}`,l=await V.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(l.status!==200)return G.notFound(t,e,{detail:`The OpenAPI file '${s}' was not published with this deployment's build assets. Check that the file exists in your '/config' directory, then redeploy the project.`,openApiFilePath:s});let d={"content-type":"application/json",vary:"Accept-Encoding"};_.instance.isDeno||(d["content-encoding"]=l.headers.get("content-encoding")||"");let p=new Response(l.body,{headers:d,status:l.status,statusText:l.statusText});return Ac(p,e),p}i(U0,"openApiSpecHandler");function cW(t){if(t.isWorkingCopy)return{label:"a working copy",reason:"working copy deployments do not publish build assets",environment:"working-copy"};if(t.isLocalDevelopment)return{label:"local development",reason:"`zuplo dev` does not publish build assets",environment:"local-development"}}i(cW,"getUnsupportedEnvironment");var uW=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");jt("open-api",U0);async function q0(t,e){pe("handler.redirect");let n=e.route.handler.options;if(!n.location)throw new v("Redirect Handler must have 'location' specified");let o=n.status??302;return new Response(null,{status:o,headers:{location:n.location}})}i(q0,"redirectHandler");jt("redirect",q0);async function D0(t){if(pe("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new v("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=vm(t.params.path),n=new Headers(t.headers);return n.set("Authorization",`Bearer ${_.instance.authApiJWT}`),V.fetch(e,{method:t.method,headers:n,body:t.body})}i(D0,"zuploServiceProxy");jt("service-proxy",D0);function lW(t,e){let n=t.endsWith("/"),o=e.startsWith("/");return n&&o?`${t.substring(0,t.length-1)}${e}`:!n&&!o?`${t}/${e}`:`${t}${e}`}i(lW,"join");async function $0(t,e){pe("handler.url-forward");let n=kc(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s;if(_.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=o.followRedirects===!0?"follow":"manual":typeof o.followRedirects<"u"&&pe("handler.url-forward.follow-redirects"),!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new v("Invalid options for this route");let a=_c(e),c=new URL(t.url),u=o.__rewriteFunction(t,a),l=lW(u,c.pathname),d=r?`${l}${c.search}`:l.toString(),p=Date.now();n(`URL Forwarding to '${d}'`);let f=t.body;if(s==="follow"&&t.body)try{f=await t.arrayBuffer()}catch(R){throw new Error(`Failed to buffer request body for redirect handling: ${R}`)}let h=Pg(o.requestTimeoutSeconds),y;try{y=await fetch(d,{method:t.method,body:f,headers:da(t.headers),redirect:s,signal:h,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0})}catch(R){if(h&&Or(R)){let C=Date.now()-p;return n(`URL Forward to '${d}' timed out after ${C}ms (requestTimeoutSeconds: ${o.requestTimeoutSeconds})`),G.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${o.requestTimeoutSeconds} seconds.`})}throw R}let S=Date.now()-p;return n(`URL Forward received response ${y.status} - ${y.statusText} in ${S}ms`),Ac(y,e),y}i($0,"urlForwardHandler");jt("url-forward",$0);var dW=i((t,e)=>{let n=new URL(t),o=new URL(e);for(let[r,s]of o.searchParams.entries())n.searchParams.append(r,s);return n.toString()},"addQuery");async function z0(t,e){return pW(t,e)}i(z0,"urlRewriteHandler");async function pW(t,e,n){pe("handler.url-rewrite");let o=kc(e),r=e.route.handler.options,s=r.forwardSearch!==!1,a=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new v("Invalid options for this route");let c=_c(e),u=r.__rewriteFunction(t,c),l=s?dW(u,t.url):u,d=Pg(r.requestTimeoutSeconds);n?.(d);let p=Date.now();o(`URL Rewriting to '${l}'`);let f;try{f=await fetch(l.toString(),{method:t.method,body:t.body,headers:da(t.headers),redirect:a?"follow":"manual",signal:d,zuplo:r.mtlsCertificate?{mtlsCertificate:r.mtlsCertificate}:void 0})}catch(y){if(d&&Or(y)){let S=Date.now()-p;return o(`URL Rewrite to '${l}' timed out after ${S}ms (requestTimeoutSeconds: ${r.requestTimeoutSeconds})`),G.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${r.requestTimeoutSeconds} seconds.`})}throw y}let h=Date.now()-p;return o(`URL Rewrite received response ${f.status} - ${f.statusText} in ${h}ms`),Ac(f,e),f}i(pW,"rewriteUrlAndFetch");jt("url-rewrite",z0);var hS=i((t,e)=>t.map((o,r)=>{let s;if(typeof o.module=="object"&&(s=o.module[o.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${r+1}, export name: ${o.export}`;throw new v(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions"),j0=i(t=>{let e;if(typeof t.module=="object"&&(e=t.module[t.export]),!e||typeof e!="function")throw new v(`WebSocketOnOpenHook - Websocket onOpen hook must be a valid function (export name: ${t.export})`);return e},"getWebSocketOnOpenHook"),gS=i(async(t,e,n,o,r,s)=>{let a=t.data;if(s&&s.length>0){let c=[...s];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,n,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function mW(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}i(mW,"createDeferred");var H0=1,Z0=4096,V0=16*1024*1024,bS=1011,fW=`WebSocket connection closed with code ${bS}: more than ${Z0} frames or ${V0/1024/1024} MiB were waiting to be sent to the client. Make the outbound message policies faster, or have the upstream send less.`,hW=new Set([1004,1005,1006,1015]),F0=123;function G0(t){return typeof t=="string"?t.length*2:t instanceof Blob?t.size:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:0}i(G0,"frameSize");function gW(t){return typeof t=="string"||t instanceof Blob?t:t instanceof ArrayBuffer?t.slice(0):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():`${t}`}i(gW,"captureFrame");function yW(t,e){if(t!==void 0&&(!Number.isInteger(t)||t<1e3||t>4999||hW.has(t)))throw new DOMException(`The close code must be an integer from 1000 to 4999 other than 1004, 1005, 1006 or 1015, but was ${t}.`,"InvalidAccessError");if(e===void 0)return{code:t};let n=`${e}`;if(new TextEncoder().encode(n).byteLength>F0)throw new DOMException(`The close reason may not be longer than ${F0} bytes.`,"SyntaxError");return{code:t,reason:n}}i(yW,"captureCloseArgs");function B0(t,e,n){let o=Object.getOwnPropertyDescriptor(t,e);return t[e]=n,()=>{o?Object.defineProperty(t,e,o):Reflect.deleteProperty(t,e)}}i(B0,"overrideProperty");var RS=class{static{i(this,"DenoClientLeg")}#e;#t;#o;#n;#i;#r=[];#s=0;#a=0;#c;#l=[];#p=!1;#d=!1;#u="holding";#f="";constructor(e,n,o,r,s){this.#e=e,this.#t=n,this.#o=o,this.#n=r,this.#i=s,e.addEventListener("message",this.#y),e.addEventListener("close",this.#b),e.addEventListener("error",this.#R)}attach(e){this.#c=e,this.#l=[B0(e,"send",n=>{let o=gW(n);this.#m({kind:"send",data:o,size:G0(o)},!0)}),B0(e,"close",(n,o)=>{this.#m({kind:"close",...yW(n,o)},!0)})],e.addEventListener("open",this.#w),e.addEventListener("close",this.#S)}release(){this.#p=!0,this.#C()}fail(e){this.#u==="failed"||this.#u==="disposed"||(this.#u="failed",this.#f=e,this.#g(),this.#I(),this.#e.close(),this.#c?.readyState===H0&&this.#T(bS,e))}dispose(){this.#u!=="disposed"&&(this.#u="disposed",this.#g(),this.#I(),this.#h(),this.#c?.removeEventListener("open",this.#w),this.#c?.removeEventListener("close",this.#S),this.#e.close())}#y=i(e=>{this.#m({kind:"relay",event:e,size:G0(e.data)})},"#onUpstreamMessage");#b=i(()=>{this.#m({kind:"close"})},"#onUpstreamClose");#R=i(()=>{this.#c&&(this.#i(),this.#m({kind:"close"}))},"#onUpstreamError");#w=i(()=>{if(this.#u==="failed"){this.#T(bS,this.#f);return}this.#C()},"#onClientOpen");#S=i(()=>{this.dispose()},"#onClientClose");#m(e,n=!1){if(!(this.#u!=="holding"&&this.#u!=="relaying")){if(e.kind!=="close"){if(this.#r.length>0&&(this.#r.length>=Z0||this.#a+e.size>V0)){this.#o.log.error(fW),this.fail("Relay queue full");return}this.#a+=e.size}n?this.#r.splice(this.#s++,0,e):this.#r.push(e),this.#v()}}#C(){this.#u!=="holding"||!this.#p||this.#c?.readyState!==H0||(this.#u="relaying",this.#s=0,this.#h(),this.#v())}#v(){if(this.#u!=="relaying"||this.#d)return;let e=this.#E().catch(n=>this.#o.log.error(n));this.#d&&this.#o.waitUntil(e)}async#E(){this.#d=!0;try{for(;this.#u==="relaying";){let e=this.#r.shift();if(!e)return;if(e.kind==="close"){this.#u="closed",this.#g(),this.#c?.close(e.code,e.reason);return}this.#a-=e.size;let n=e.kind==="send"?e.data:e.event.data;if(e.kind==="relay"&&this.#n.length>0){try{n=await gS(e.event,this.#e,this.#c,this.#t,this.#o,this.#n)}catch(o){this.#o.log.error(o);continue}if(this.#u!=="relaying")return;if(n===void 0)continue}try{this.#c?.send(n)}catch(o){this.#o.log.error(o)}}}finally{this.#d=!1}}#T(e,n){this.#h(),this.#c?.close(e,n)}#h(){for(let e of this.#l.splice(0))e()}#g(){this.#r.length=0,this.#a=0,this.#s=0}#I(){this.#e.removeEventListener("message",this.#y),this.#e.removeEventListener("close",this.#b),this.#e.removeEventListener("error",this.#R)}};async function bW(t,e,n,o){n(`Attempting WebSocket connection to '${e}'`);let r=new WebSocket(e),s=o(r);await new Promise((l,d)=>{let p=i(()=>{h(),n("WebSocket connection established with upstream"),l()},"onOpen"),f=i(y=>{h(),n(`WebSocket connection error: ${y}`),d(new Error("Upstream open failed"))},"onErr"),h=i(()=>{r.removeEventListener("open",p),r.removeEventListener("error",f)},"cleanup");r.addEventListener("open",p),r.addEventListener("error",f)}).catch(l=>{throw s.dispose(),new Error(`Failed to open outgoing socket: ${l.message}`)});let a;try{a=globalThis.Deno.upgradeWebSocket(t)}catch(l){throw s.dispose(),l}let{socket:c,response:u}=a;return s.attach(c),{clientSocket:c,outgoingSocket:r,response:u,clientLeg:s}}i(bW,"getDenoClientAndServerSockets");function RW(t){return t>=400&&t<600}i(RW,"isUpstreamHttpErrorStatus");async function wW(t,e,n,o){n(`Attempting WebSocket connection to '${e}'`);let r=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(r.status!==101||!r.webSocket)return n(`WebSocket upgrade failed: ${r.status} ${r.statusText}`),{ok:!1,response:r};if(n(`WebSocket connected, received response ${r.status} - ${r.statusText}`),o)return{ok:!0,passthrough:!0,response:new Response(null,{status:101,webSocket:r.webSocket})};let s=new WebSocketPair,[a,c]=Object.values(s);r.webSocket.accept(),c.accept();let u=new Response(null,{status:101,webSocket:a});return{ok:!0,passthrough:!1,clientSocket:a,outgoingSocket:r.webSocket,serverSocket:c,response:u}}i(wW,"getCfClientAndServerSockets");function wS(t,e,n,o,r){if(t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",()=>{n.log.error("WebSocket passthrough error",{direction:o}),e.close()}),r===void 0){t.addEventListener("message",s=>{e.send(s.data)});return}t.addEventListener("message",s=>{n.waitUntil(r.then(()=>e.send(s.data)).catch(n.log.error))})}i(wS,"wireUpPassthroughDirection");function SW(t,e,n,o){wS(t,e,n,"incoming",o),wS(e,t,n,"outgoing",o)}i(SW,"wireUpPassthrough");function yS(t,e,n,o,r,s,a){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",()=>{o.log.error("WebSocket pipeline error",{direction:s}),e.close()}),t.addEventListener("message",c=>{try{let l=i(async d=>{await a;let p=await gS(d,t,e,n,o,r);p!==void 0&&e.send(p)},"innerPipeline")(c).catch(o.log.error);o.waitUntil(l)}catch(u){o.log.error(u)}})}i(yS,"wireUpListeners");async function SS(t,e){pe("handler.websocket-pipeline");let n=e.route.handler.options,o=kc(e);if(!n||!n.rewritePattern)throw new v("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=t.headers.get("Upgrade");if(!r||r!=="websocket")return G.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new v("Invalid options for this route");let s=_c(e),a=n.__rewriteFunction(t,s),c=n.policies?.inbound?hS(n.policies.inbound,"inbound"):[],u=n.policies?.outbound?hS(n.policies.outbound,"outbound"):[],l=n.onOpen?j0(n.onOpen):void 0,d=c.length>0||u.length>0,p=d||l!==void 0,f,h,y,S;if(_.instance.isDeno){let C=t.originalRequest??it.findContextExtensions(e)?.originalRequest;if(!C)throw new Error("Original websocket request is not available");let T=e.incomingRequestProperties;T instanceof Ca&&T.detachFromRequest();let I=await bW(C,a,o,P=>new RS(P,t,e,u,()=>d?e.log.error("WebSocket pipeline error",{direction:"outbound"}):e.log.error("WebSocket passthrough error",{direction:"outgoing"})));f=I.clientSocket,h=I.outgoingSocket,y=I.response,S=I.clientLeg}else{a=a.replace(/^(ws)/,"http");let C=await wW(t,a,o,!p);if(!C.ok){let T=C.response;if(RW(T.status))return T;let I=await T.text(),P=`WebSocket connection error - ${T.status}: ${T.statusText}`,A=`${P}, content: '${I}'`;return e.log.warn({outgoingUrl:a,status:T.status},P),G.badGateway(t,e,{detail:A})}if(C.passthrough)return C.response;f=C.serverSocket,h=C.outgoingSocket,y=C.response}let R=mW();if(R.promise.catch(()=>{}),S?d?yS(f,h,t,e,c,"inbound",R.promise):wS(f,h,e,"incoming",l?R.promise:void 0):d?(yS(f,h,t,e,c,"inbound",R.promise),yS(h,f,t,e,u,"outbound",R.promise)):SW(f,h,e,l?R.promise:void 0),l)try{await l(h,f,t,e),R.resolve()}catch(C){R.reject(C);let T=new v("WebSocket onOpen hook failed",{cause:C});if(S)return e.log.error(T),S.fail("onOpen hook failed"),y;try{f.close(1011,"onOpen hook failed")}catch{}try{h.close(1011,"onOpen hook failed")}catch{}throw T}else R.resolve();return S?.release(),y}i(SS,"webSocketPipelineHandler");jt("websocket-pipeline",SS);var CW=SS;var CS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"AWSLoggingPlugin")}getTransport(){return new vS(this.options)}},vS=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new Be({name:"aws-log-transport",msDelay:10,dispatchFunction:i(async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n});o.ok||await Ve({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await Ve({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}},"dispatchFunction")});constructor({accessKeyId:e,logStreamName:n,logGroupName:o,secretAccessKey:r,region:s,fields:a}){pe("logging.aws"),this.awsClient=new ym({accessKeyId:e,secretAccessKey:r,service:"logs",region:s}),this.logGroupName=o,this.logStreamName=n,this.region=s,this.environmentType=_.instance.loggingEnvironmentType,this.environmentStage=_.instance.loggingEnvironmentStage,this.environment=_.instance.deploymentName,this.fields=a??{}}log(e,n){e.messages.forEach(o=>{let r={timestamp:Date.now(),message:JSON.stringify(Object.assign({data:Vn(o),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields,n.properties??{}))};this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var TS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new IS(this.options)}},IS=class{static{i(this,"DynaTraceTransport")}constructor(e){pe("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#n=_.instance.loggingEnvironmentType,this.#i=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#r=e.fields??{}}#e;#t;#o;#n;#i;#r;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:Vn(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#o,"custom.environmentStage":this.#i,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#r,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let n=await V.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});n.ok||await Ve({level:"error",messages:[`Failed to send logs to Dynatrace: ${n.status} - ${n.statusText}`]},n)}catch{await Ve({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"dyna-trace-log-transport",msDelay:10,dispatchFunction:this.#s})};var ES=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"LokiLoggingPlugin")}getTransport(){return new AS(this.options)}},PS=class{static{i(this,"LokiStream")}constructor(e,n,o,r,s,a){this.level=e,this.environment=n,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function vW(t,e){return btoa(`${t}:${e}`)}i(vW,"createBasicDigest");var AS=class{static{i(this,"LokiTransport")}constructor(e){pe("logging.loki"),this.#o=e.url,this.#n=vW(e.username,e.password),this.#r=_.instance.loggingEnvironmentType,this.#s=_.instance.loggingEnvironmentStage,this.#i=_.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#o;#n;#i;#r;#s;#a;log(e,n){let o=new PS(e.level,this.#i,this.#r,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s=Object.assign({stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Vn(r),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a,n.properties??{});this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#c=i(e=>{let n={streams:[]};return e.forEach(o=>{let r=n.streams.find(s=>s.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},n.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),n},"#convertToLokiStreamsBatch");#l=i(async e=>{if(e.length===0)return;let n=this.#c(e);try{let o=await V.fetch(this.#o,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#n}`}});o.ok||await Ve({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await Ve({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"loki-log-transport",msDelay:10,dispatchFunction:this.#l})};var kS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new _S(this.options)}},_S=class{static{i(this,"NewRelicTransport")}constructor(e){pe("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#n=_.instance.loggingEnvironmentType,this.#i=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#r=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#o;#n;#i;#r;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({message:Vn(o),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#i,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#r,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let n=await V.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});n.ok||await Ve({level:"error",messages:[`Failed to send logs to New Relic: ${n.status} - ${n.statusText}`]},n)}catch{await Ve({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"new-relic-log-transport",msDelay:10,dispatchFunction:this.#a})};var xS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"SplunkLoggingPlugin")}getTransport(){return new OS(this.options)}},OS=class{static{i(this,"SplunkTransport")}constructor(e){pe("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#n=_.instance.loggingEnvironmentType,this.#i=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#r=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#c=e.host??"zuplo-api",this.#l=e.channel}#e;#t;#o;#n;#i;#r;#s;#a;#c;#l;log(e,n){e.messages.forEach(o=>{let s={event:{message:Vn(o),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#i,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#r,...n.properties??{}},sourcetype:this.#a,host:this.#c,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#p=i(async e=>{if(e.length!==0)try{for(let n of e){let o={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#l&&(o["X-Splunk-Request-Channel"]=this.#l);let r=await V.fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:o});if(!r.ok){let s=await r.text();await Ve({level:"error",messages:[`Failed to send logs to Splunk: ${r.status} - ${r.statusText}`,`Response: ${s}`]},r)}}}catch(n){await Ve({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${n instanceof Error?n.message:String(n)}`]})}},"#dispatchFunction");batcher=new Be({name:"splunk-log-transport",msDelay:10,dispatchFunction:this.#p})};var MS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new LS(this.options)}},LS=class{static{i(this,"SumoLogicTransport")}constructor(e){pe("logging.sumologic"),this.#e=e.url,this.#i=e.category,this.#r=e.name,this.#o=_.instance.loggingEnvironmentType,this.#n=_.instance.loggingEnvironmentStage,this.#t=_.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#o;#n;#i;#r;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:Vn(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#o,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId},this.#s,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let n=e.map(r=>JSON.stringify(r)).join(`
262
+ `),errorData:{errors:R,...Object.keys(C).length>0&&{properties:C}}}:{success:!0,data:T,errorData:null}},"validateFlat");return new zn(n.schema,f=>{let h=u.safeParse(f,Ps);if(!h.success)return{success:!1,data:null,errorMessage:m.prettifyError(h.error),errorData:m.treeifyError(h.error)};let y=f,S=Object.keys(y);if(c(S,a)){let C=r().validate(y);if(C.success)return C;let T=p(y);return T.success?T:C}let R=p(y);if(R.success)return R;if(c(S,s)){let C=r().validate(y);if(C.success)return C}return R})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1},n=m.strictObject({});return new zn(e,o=>{let r=n.safeParse(o,Ps);return r.success?{success:!0,data:r.data,errorData:null}:{success:!1,data:null,errorMessage:m.prettifyError(r.error),errorData:m.treeifyError(r.error)}})}},iS=i((t,e)=>new hg(t.filter(n=>n.in===e)),"parameterBuilder");function JM(t,e,n="nested"){let o=new sp().withFlatInput(n==="flat"),r=t.raw()?.parameters||[];return e&&o.withBody(new ip(t,e).build()),o.withQueryParams(iS(r,"query").build()),o.withPathParams(iS(r,"path").build()),o.withHeaders(iS(r,"header").build()),o}i(JM,"createLegacyToolValidatorBuilder");function KM(t){return t.raw()?.requestBody?.content?.["application/json"]?sp.withRoot(new ip(t,"application/json").build()):new sp}i(KM,"createLegacyPromptValidatorBuilder");function WM(t){let e=KM(t).build();return{validator:e,arguments:KE(e.schema)}}i(WM,"buildLegacyPromptSchemas");function QM(t){return t!==void 0&&t.type!=="object"}i(QM,"hasNonObjectOutputRoot");function XM(t,e,n){try{let o=t.raw(),r=o?.responses;if(!r){e.warn("No responses found in OpenAPI spec for outputSchema",{path:t.path,operationId:o?.operationId});return}for(let s of Object.keys(r))if(s.startsWith("2")){let c=r[s]?.content;if(c){for(let u of["application/json","application/json; charset=utf-8"])if(c[u]?.schema){let l=c[u].schema;return n&&e.debug("Output schema extracted successfully",{path:t.path,operationId:o?.operationId,statusCode:s,contentType:u,schemaKeys:l&&typeof l=="object"?Object.keys(l).join(", "):"none"}),l}}}n&&e.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:t.path,operationId:o?.operationId,statusCodes:Object.keys(r).join(", ")});return}catch(o){e.warn("Failed to extract outputSchema",{path:t.path,operationId:t.raw()?.operationId,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0});return}}i(XM,"extractLegacyOutputSchema");var YM;function e0(t){try{YM??=new Ts({draft:"2020-12",shortcircuit:!1});let e=YM.getValidator(t);return{validate:i(n=>{try{let o=e(n);return o.valid?void 0:o.errorMessage}catch(o){return o instanceof Error?o.message:String(o)}},"validate")}}catch(e){return{unbuildableReason:e instanceof Error?e.message:String(e)}}}i(e0,"buildLegacyOutputSchemaValidator");function t0({name:t,routeData:e,method:n,contentType:o,includeOutputSchema:r,toolInputStyle:s,log:a,debugMode:c}){let u=OK(e,o,s,a,c);if(!u){a.warn("MCP tool skipped: could not build parameter validator",{toolName:t,method:n.toUpperCase(),path:e.path,operationId:e.raw()?.operationId,suggestion:"Check the OpenAPI parameter and request body definitions for this route."});return}let l=r?XM(e,a,c):void 0,d=l?e0(l):void 0;d?.unbuildableReason&&a.warn("MCP outputSchema conformance check unavailable",{toolName:t,method:n.toUpperCase(),path:e.path,operationId:e.raw()?.operationId,reason:d.unbuildableReason});let p=d?.unbuildableReason?void 0:l;return{validator:u,...p&&{outputSchema:i(()=>p,"outputSchema")},...d?.validate&&{validateStructuredContent:d.validate},nonObjectOutputRoot:QM(p)}}i(t0,"buildLegacyToolSchemas");function OK(t,e,n,o,r){try{let s=JM(t,e,n),a=s.build();for(let c of s.flattenRefusals)o.warn("MCP tool input schema left nested",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId,reason:c});if(r){for(let c of s.flattenNotes)o.debug("MCP tool request body left nested",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId,reason:c});o.debug("MCP validator built successfully",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId})}return a}catch(s){o.warn("MCP validator build failed",{method:t.methods?.[0],path:t.path,contentType:e||"none",operationId:t.raw()?.operationId,error:s instanceof Error?s.message:String(s)});return}}i(OK,"buildValidator");var n0="2025-03-26",vc="2025-06-18",gg="2025-11-25",MK=n0,o0={annotations:n0,title:vc,outputSchema:vc,icons:gg,execution:gg},r0={title:vc,icons:gg},LK={icons:gg},NK={lastModified:vc},UK=vc,qK=vc;function i0(t){return t??MK}i(i0,"requestProtocolVersion");function yg(t,e,n){let o;for(let[r,s]of Object.entries(e))n<s&&r in t&&(o??={...t},delete o[r]);return o??t}i(yg,"omitNewerFields");function s0(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(s0,"isPlainObject");function a0(t,e){let n=t;if(s0(n.annotations)){let o=yg(n.annotations,NK,e);o!==n.annotations&&(n={...n,annotations:o})}if(n.type!=="resource_link")return n;if(e<UK){let{annotations:o,_meta:r}=n;return{type:"text",text:JSON.stringify(t),...o!==void 0&&{annotations:o},...r!==void 0&&{_meta:r}}}return yg(n,LK,e)}i(a0,"projectContentBlock");function DK(t,e){let n;for(let[o,r]of t.entries()){let s=a0(r,e);s!==r&&(n??=t.slice(),n[o]=s)}return n??t}i(DK,"projectContent");function c0(t,e){let n=Array.isArray(t.content)?DK(t.content,e):t.content;if(e>=qK||!("structuredContent"in t))return n===t.content?t:{...t,content:n};let{structuredContent:o,...r}=t,s=Array.isArray(t.content)&&t.content.some(a=>a.type==="text");return o===void 0||s?{...r,content:n}:{...r,content:[...n??[],{type:"text",text:JSON.stringify(o)}]}}i(c0,"projectCallToolResultForVersion");function u0(t,e){let n;for(let[o,r]of t.entries()){if(!s0(r.content))continue;let s=a0(r.content,e);s!==r.content&&(n??=t.slice(),n[o]={...r,content:s})}return n??t}i(u0,"projectPromptMessagesForVersion");var $K="2025-11-25";function l0(t){return t!==null&&t>=$K}i(l0,"shouldReturnToolInputErrorsAsResults");function d0(t,e,n,o,r){let s=t.validator.validate(n);if(s.success)return{valid:!0,data:s.data};s.internalError!==void 0&&r?.(s.internalError);let a=s.errorMessage?`Invalid arguments for tool '${e}': ${s.errorMessage}`:`Invalid arguments for tool '${e}'`;if(o)return{valid:!1,result:{content:[{type:"text",text:a}],isError:!0},...s.internalError!==void 0&&{internalError:s.internalError}};throw new Je(Se.InvalidParams,a,s.errorData)}i(d0,"validateToolArguments");function sS(t,e,n){if(t===void 0)return e;if(t==="flat"||t==="nested")return t;throw new Error(`MCP tool configuration error: invalid toolInputStyle ${JSON.stringify(t)} on operation "${n}". Use "flat" or "nested".`)}i(sS,"resolveToolInputStyle");var aS=["text","image","audio","resource_link","resource"],zK={text:Tr,image:Ir,audio:Er,resource_link:gs,resource:hs},p0=m.custom(t=>t!==null&&typeof t=="object"&&!Array.isArray(t)),jK=m.looseObject({content:m.array(m.unknown()).optional(),structuredContent:p0.optional(),_meta:p0.optional()});function h0(t,e,n){return e.isError===!0?e:t.projectCallToolResult(e,n)}i(h0,"projectToolResult");var m0=120;function As(t){let e;try{e=JSON.stringify(t)??String(t)}catch{e=Object.prototype.toString.call(t)}return e.length>m0?`${e.slice(0,m0)}\u2026`:e}i(As,"describeValue");function Tc(t){return t===null?"null":Array.isArray(t)?"array":typeof t}i(Tc,"describeKind");function ap(t){return`MCP tool '${t.toolName}' (${t.method.toUpperCase()} ${t.path})`}i(ap,"toolLabel");function cS(t,e){return t!==null&&typeof t=="object"&&e in t?{present:!0,value:t[e]}:{present:!1,value:void 0}}i(cS,"readField");function HK(t,e,n){let o=n.issues[0]?.path[0],r=ap(t);switch(o){case"content":{let{value:s}=cS(e,"content");return`${r}: \`setRawCallToolResult({ content })\` must be an array of content blocks, got ${As(s)} (${Tc(s)}). Each block is an object with a \`type\` discriminator, e.g. { type: "text", text: "..." }.`}case"structuredContent":{let{value:s}=cS(e,"structuredContent");return`${r}: \`setRawCallToolResult({ structuredContent })\` must be a JSON object, got ${As(s)} (${Tc(s)}). The MCP 2025-11-25 wire format rejects arrays and scalars here \u2014 wrap the value in an object, e.g. { result: [...] }.`}case"_meta":{let{value:s}=cS(e,"_meta");return`${r}: \`setRawCallToolResult({ _meta })\` must be a JSON object, got ${As(s)} (${Tc(s)}). MCP reserves \`_meta\` for metadata key/value pairs.`}default:return`${r}: setRawCallToolResult() takes an object with optional \`content\`, \`structuredContent\`, and \`_meta\` fields, got ${As(e)} (${Tc(e)}).`}}i(HK,"envelopeFailureMessage");function FK(t,e,n){let o=ap(t);if(n===null||typeof n!="object"||Array.isArray(n)){let a=typeof n=="string"?` Use \`{ type: "text", text: ${As(n)} }\`.`:"";return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} is ${As(n)} (${Tc(n)}), not a content block object. Every block needs a \`type\` discriminator so MCP clients know how to render it.${a}`}}let r=n.type;if(typeof r!="string")return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} has \`type\` ${As(r)} (${Tc(r)}) \u2014 the \`type\` discriminator must be a string naming the block kind, one of: ${aS.join(", ")}.`};if(!aS.includes(r))return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} has unsupported \`type\` "${r}". The MCP 2025-11-25 wire format this server negotiates accepts only: ${aS.join(", ")}.`};let s=zK[r].safeParse(n);if(!s.success){let a=s.error.issues.slice(0,3).map(c=>{let u=c.path.join(".");return u?`${u}: ${c.message}`:c.message}).join("; ");return{ok:!1,message:`${o}: \`setRawCallToolResult({ content })\` block at index ${e} (type "${r}") is not a valid MCP content block: ${a}.`}}return{ok:!0,block:s.data}}i(FK,"validateContentBlock");function f0(t,e,n){let o=ap(t),r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null){let s=n.constructor?.name??"custom class";return`${o}: \`setRawCallToolResult({ ${e} })\` must be a plain JSON object, got an instance of ${s}. Only plain objects serialize to a JSON object on the wire \u2014 return a literal object instead, e.g. { ... }.`}try{JSON.stringify(n)}catch(s){return`${o}: \`setRawCallToolResult({ ${e} })\` could not be serialized to JSON: ${s instanceof Error?s.message:String(s)}. Remove circular references and BigInt values \u2014 the wire format is JSON.`}}i(f0,"serializabilityViolation");function bg(t){let{target:e,defaults:n,override:o,validateStructuredContent:r,enforceOutputSchema:s,nonObjectOutputRoot:a=!1}=t,c;if(o!==void 0){let f=jK.safeParse(o);if(!f.success)return{ok:!1,message:HK(e,o,f.error)};c=f.data}let u;if(c?.content!==void 0){u=[];for(let[f,h]of c.content.entries()){let y=FK(e,f,h);if(!y.ok)return{ok:!1,message:y.message};u.push(y.block)}}if(c?.structuredContent!==void 0){let f=f0(e,"structuredContent",c.structuredContent);if(f!==void 0)return{ok:!1,message:f}}if(c?._meta!==void 0){let f=f0(e,"_meta",c._meta);if(f!==void 0)return{ok:!1,message:f}}let l=u??n.content,d=c?.structuredContent??n.structuredContent,p=c?._meta??{};if(s&&r){if(d===void 0)return{ok:!1,message:`${ap(e)}: this tool advertises an outputSchema, so MCP clients require a \`structuredContent\` result, but the downstream response body was not JSON of the kind the schema describes. Return a JSON body that matches the route's OpenAPI 2xx response schema`+(a?".":", or set a JSON object explicitly with `setRawCallToolResult({ structuredContent })`.")};let f=r(d);if(f!==void 0)return{ok:!1,message:`${ap(e)}: structuredContent does not conform to the tool's advertised outputSchema: ${f}. MCP clients reject results that violate the schema published in tools/list. Fix the route's response `+(a?"":"(or the setRawCallToolResult override) ")+"to match the schema, or correct the route's OpenAPI 2xx response schema."}}return{ok:!0,result:{content:l,...d!==void 0&&{structuredContent:d},isError:n.isError,_meta:p}}}i(bg,"buildCallToolResult");function g0(){return{}}i(g0,"buildToolsCapability");var uS={path:["simple","label","matrix"],query:["form","spaceDelimited","pipeDelimited","deepObject"],header:["simple"]},GK=/[A-Za-z0-9\-._~]/,BK=new Set(":/?@!$'()*,;".split("")),ZK=/^[0-9A-Fa-f]{2}$/,VK=new TextEncoder;function JK(t){let e="";for(let n of VK.encode(t))e+=`%${n.toString(16).toUpperCase().padStart(2,"0")}`;return e}i(JK,"percentEncodeChar");function Go(t,e=!1){let n="",o=Array.from(t);for(let r=0;r<o.length;r++){let s=o[r];GK.test(s)||e&&BK.has(s)||e&&s==="%"&&r+2<o.length&&ZK.test(o[r+1]+o[r+2])?n+=s:n+=JK(s)}return n}i(Go,"percentEncode");function xr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(xr,"isPlainObject");function Ic(t){return typeof t=="string"?t:typeof t=="object"&&t!==null?JSON.stringify(t):String(t)}i(Ic,"scalarText");function wg(t){return Array.isArray(t)?t.filter(e=>e!=null):xr(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null)):t}i(wg,"dropNulls");function lS(t){return Array.isArray(t)?t.length===0:xr(t)?Object.keys(t).length===0:!1}i(lS,"isEmptyCollection");function ks(t){return t.content!==void 0&&t.content!==null&&Object.keys(t.content).length>0}i(ks,"hasContent");function KK(t){return Object.entries(t.content??{})[0]}i(KK,"contentEntry");function WK(t){let e=t.split(";")[0].trim().toLowerCase();return e==="application/json"||e.endsWith("+json")}i(WK,"isJsonMediaType");function YK(t){if(t.schema!==void 0||!ks(t))return;let e=KK(t);if(!e||!WK(e[0]))return;let n=e[1]?.schema;return xr(n)?n:void 0}i(YK,"contentParameterSchema");function y0(t){return t==="query"?"form":"simple"}i(y0,"defaultStyle");function b0(t){return t==="form"}i(b0,"defaultExplode");function Sg(t,e){let n=t.in,o=t.style??y0(n),r=t.explode??b0(o),s=uS[n]?.includes(o)??!1,a=Array.isArray(e)||xr(e);if(s&&o==="deepObject"&&!xr(e)&&(s=!1),s&&(o==="spaceDelimited"||o==="pipeDelimited")&&(!a||r)&&(s=!1),s)return{style:o,explode:r};let c=y0(n);return{style:c,explode:b0(c),unsupportedStyle:o}}i(Sg,"resolveStyle");function QK(t){if(t.style===void 0||ks(t)||!Object.hasOwn(uS,t.in))return;let e=t.in,n=t.style;if(!uS[e].includes(n))return n;let o=XK(t);if(n==="deepObject")return o&&!o.includes("object")?n:void 0;if(n==="spaceDelimited"||n==="pipeDelimited")return t.explode===!0||o&&!o.includes("array")&&!o.includes("object")?n:void 0}i(QK,"findUnsupportedStyle");function w0(t,e,n){if(!n)return[];e=up(e);let o=[];for(let r of e){let s=QK(r);s!==void 0&&o.push({operationId:t,parameter:r.name,in:r.in,style:s})}return o}i(w0,"unsupportedStyleWarnings");function XK(t){let e=t.schema?.type;if(typeof e=="string")return[e];if(Array.isArray(e))return e.filter(n=>typeof n=="string")}i(XK,"schemaTypes");function dS(t,e,n){return n&&YK(t)!==void 0?JSON.stringify(e):typeof e=="string"?e:String(e)}i(dS,"contentText");function Cg(t){return t==null}i(Cg,"isEmpty");function S0(t,e,n=!0){if(Cg(e))return;if(ks(t))return Go(dS(t,e,n));let o=wg(e);if(lS(o))return"";let{style:r,explode:s}=Sg(t,o),a=Go(t.name),c=i(d=>r==="label"?Go(d).replaceAll(".","%2E"):Go(d),"encodeText"),u=i(d=>c(Ic(d)),"enc");if(Array.isArray(o)){let d=o.map(u);switch(r){case"label":return d.map(p=>`.${p}`).join("");case"matrix":return s?d.map(p=>`;${a}=${p}`).join(""):`;${a}=${d.join(",")}`;default:return d.join(",")}}if(xr(o)){let d=Object.entries(o),p=d.flatMap(([h,y])=>[c(h),u(y)]),f=d.map(([h,y])=>`${c(h)}=${u(y)}`);switch(r){case"label":return s?f.map(h=>`.${h}`).join(""):p.map(h=>`.${h}`).join("");case"matrix":return s?f.map(h=>`;${h}`).join(""):`;${a}=${p.join(",")}`;default:return(s?f:p).join(",")}}let l=u(o);switch(r){case"label":return`.${l}`;case"matrix":return l===""?`;${a}`:`;${a}=${l}`;default:return l}}i(S0,"serializePathParameter");function C0(t,e,n=!0,o=[]){if(Cg(e))return[];let r=Go(t.name),s=!ks(t)&&t.allowReserved===!0,a=i(p=>Go(Ic(p),s),"enc");if(ks(t))return[`${r}=${Go(dS(t,e,n))}`];let c=wg(e);if(lS(c))return[];let{style:u,explode:l}=Sg(t,c),d=i(p=>u==="form"&&!l?a(p).replaceAll(",","%2C"):a(p),"encItem");if(Array.isArray(c)){let p=c.map(d);return u==="spaceDelimited"?[`${r}=${p.join("%20")}`]:u==="pipeDelimited"?[`${r}=${p.join("|")}`]:l?p.map(f=>`${r}=${f}`):[`${r}=${p.join(",")}`]}if(xr(c)){let p=Object.entries(c);if(u==="deepObject")return p.map(([h,y])=>`${r}[${Go(h)}]=${a(y)}`);let f=p.flatMap(([h,y])=>[Go(h),d(y)]);return u==="spaceDelimited"?[`${r}=${f.join("%20")}`]:u==="pipeDelimited"?[`${r}=${f.join("|")}`]:l?(tW(t,Object.keys(c),o),p.map(([h,y])=>`${Go(h)}=${a(y)}`)):[`${r}=${f.join(",")}`]}return[`${r}=${a(c)}`]}i(C0,"serializeQueryParameter");var Si=class extends Error{static{i(this,"InvalidQueryKeyError")}constructor(e,n,o){super(`query parameter '${e}' has the key ${JSON.stringify(n)}, ${o}`),this.name="InvalidQueryKeyError"}},eW=/^[A-Za-z0-9\-._~]+$/;function v0(t,e){if(t.in!=="query"||ks(t)||Cg(e))return[];let n=wg(e);if(!xr(n))return[];let{style:o,explode:r}=Sg(t,n);return o==="form"&&r?Object.keys(n):[]}i(v0,"explodedQueryNames");function tW(t,e,n){let o=[t.name,...n];for(let r of e){if(!eW.test(r))throw new Si(t.name,r,"which is sent as a query name and may hold only the characters A-Z a-z 0-9 - . _ ~");let s=r.toLowerCase(),a=o.find(c=>c.toLowerCase()===s);if(a!==void 0)throw new Si(t.name,r,`which is sent as a query name and is the name of the declared query parameter '${a}'`)}}i(tW,"assertExplodedQueryNames");var Ec=class extends Error{static{i(this,"InvalidHeaderValueError")}constructor(e,n="a CR, LF or NUL character"){super(`header parameter '${e}' has a value that contains ${n}`),this.name="InvalidHeaderValueError"}},Pc=class extends Error{static{i(this,"InvalidTextValueError")}constructor(e,n){super(`${e} parameter '${n}' has a value that contains a lone surrogate, which is not valid text`),this.name="InvalidTextValueError"}},R0=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;function Rg(t){return typeof t=="string"?R0.test(t):Array.isArray(t)?t.some(Rg):typeof t=="object"&&t!==null?Object.entries(t).some(([e,n])=>R0.test(e)||Rg(n)):!1}i(Rg,"hasLoneSurrogate");var nW=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,cp=class extends Error{static{i(this,"InvalidHeaderNameError")}constructor(e){super(`header parameter '${e}' is not a valid header name (RFC 7230 token)`),this.name="InvalidHeaderNameError"}};function T0(t,e){let n=String(e);if(/[\r\n\0]/.test(n))throw new Ec(t);try{new Headers().set(t,n)}catch(o){throw o instanceof TypeError?new Ec(t,"a character this runtime's headers can't carry (such as one above U+00FF)"):o}}i(T0,"assertSendableHeaderValue");function oW(t){if(!nW.test(t))throw new cp(t)}i(oW,"assertHeaderName");var Bo=class extends Error{static{i(this,"InvalidPathValueError")}constructor(e,n,o){super(o===void 0?`path parameter '${e}' is written as the dot segment '${n}', which a URL parser removes from the path`:`path parameter '${e}' builds the path '${n}', ${o}`),this.name="InvalidPathValueError"}};function pS(t){return/^(\.|%2e){1,2}$/i.test(t)}i(pS,"isDotSegment");function I0(t,e,n=!0){if(Cg(e))return;let o;if(ks(t))o=dS(t,e,n);else{let r=wg(e);if(lS(r))return;let{explode:s}=Sg(t,r);if(Array.isArray(r))o=r.map(Ic).join(",");else if(xr(r)){let a=Object.entries(r);o=s?a.map(([c,u])=>`${c}=${Ic(u)}`).join(","):a.flatMap(([c,u])=>[c,Ic(u)]).join(",")}else o=Ic(r)}return T0(t.name,o),o}i(I0,"serializeHeaderParameter");function up(t){let e=new Map;for(let n of t){let o=n.in==="header"?n.name.toLowerCase():n.name;e.set(`${n.in}\0${o}`,n)}return[...e.values()]}i(up,"effectiveParameters");function E0(t,e,n,o=!0){let r={};if(!e)return r;let s=n?up(t):t;for(let[a,c]of Object.entries(e)){oW(a);let u=a.toLowerCase(),l=n?s.find(p=>p.in==="header"&&p.name.toLowerCase()===u):void 0;if(!l){T0(a,c),r[u]=c;continue}let d=I0(l,c,o);d!==void 0&&(r[u]=d)}return r}i(E0,"serializeHeaderArguments");function P0(t,e){let n=[];if(!e)return n;let o=up(t);for(let[r,s]of Object.entries(e)){let a=r.toLowerCase(),c=o.find(u=>u.in==="header"&&u.name.toLowerCase()===a);c&&I0(c,s)===void 0&&n.push(a)}return n}i(P0,"omittedHeaderArguments");var A0="(?<!(?<!\\\\)(?:\\\\\\\\)*\\\\):",k0={"\\":"/","?":"%3F","#":"%23"};function rW(t){return t.replace(/\\(.)/gs,(e,n)=>Object.hasOwn(k0,n)?k0[n]:e)}i(rW,"encodeReservedEscapes");function _0(t){return t.replace(/\\(.)/gs,(e,n)=>n==="\\"?"/":e)}i(_0,"readEscapedBackslashes");var vg=class{constructor(e,n=!1,o=!0,r=[]){this.serializeByStyle=n;this.contentSchemaAdvertised=o;this.declaredQueryNames=r;e=rW(e),this.pattern=new URLPattern({pathname:e});let s=new RegExp(`${A0}(\\w+)(\\([^)]*\\))?[*+?]?`,"g"),a;for(;(a=s.exec(e))!==null;)this.expectedPathParams.add(a[1])}serializeByStyle;contentSchemaAdvertised;declaredQueryNames;static{i(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;styledPathParams={};queryPairs=[];explodedNames=new Map;addParameter(e,n,o){let r=this.getParameterValue(e,n,o);if(r!=null){if((e.in==="path"||e.in==="query")&&Rg(r))throw new Pc(e.in,e.name);switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new v(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.serializeByStyle?this.styledPathParams[e.name]=S0(e,r,this.contentSchemaAdvertised)??"":this.addPathParameter(e.name,r);break;case"query":this.serializeByStyle?(this.queryPairs.push(...C0(e,r,this.contentSchemaAdvertised,this.declaredQueryNames)),this.claimExplodedNames(e,r)):this.addQueryParameter(e.name,r);break;default:break}}}claimExplodedNames(e,n){for(let o of v0(e,n)){let r=o.toLowerCase(),s=this.explodedNames.get(r);if(s!==void 0&&s!==e.name)throw new Si(e.name,o,`which is sent as a query name and is also a key of query parameter '${s}'`);this.explodedNames.set(r,e.name)}}getParameterValue(e,n,o){switch(e.in){case"path":return n?.[e.name];case"query":return o?.[e.name];default:return}}addPathParameter(e,n){this.pathParams[e]=String(n)}addQueryParameter(e,n){Array.isArray(n)?n.forEach(o=>{o!=null&&this.searchParams.append(e,String(o))}):typeof n=="object"&&n!==null?this.searchParams.append(e,JSON.stringify(n)):this.searchParams.append(e,String(n))}toString(){let e=[...this.expectedPathParams].filter(u=>!this.seenPathParams.has(u));if(e.length>0)throw new v(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let n=i((u,l)=>this.serializeByStyle?Object.hasOwn(this.styledPathParams,l)?this.styledPathParams[l]:u:this.pathParams[l]?encodeURIComponent(this.pathParams[l]):u,"substitute"),o=new RegExp(`${A0}(\\w+)(\\([^)]*\\))?([*+?])?`,"g");this.assertNoDotSegments(n,o);let r=this.pattern.pathname,s=r.replace(o,n),a=this.cleanupUrlPatternSyntax(s);this.assertFinalPath(a,r,n,o);let c=this.serializeByStyle?this.queryPairs.join("&"):this.searchParams.toString();return c?`${a}?${c}`:a}assertNoDotSegments(e,n){let o=this.pattern.pathname.replace(/\{\/\}[?*+]?/g,"");for(let r of o.split("/")){let s=[...r.matchAll(n)].map(c=>c[1]);if(s.length===0)continue;let a=r.replace(n,e);if(pS(a))throw new Bo(s[0],a)}}assertFinalPath(e,n,o,r){let s=i((f,h)=>{let y=[...n.matchAll(r)].map(R=>({name:R[1],written:o(R[0],R[1]),index:R.index??0})).filter(({written:R,index:C})=>h(R,C)).map(({name:R})=>R),S=[...new Set(y.length>0?y:this.expectedPathParams)];return new Bo(S.join(", ")||"path",e,f)},"fail"),a=n.indexOf("/",1),c=i(f=>a===-1||f<a,"inFirstSegment");if(e.includes("\\"))throw s("which holds a backslash that a URL parser reads as '/'",f=>f.includes("\\"));if(/[?#]/.test(e))throw s("which holds a '?' or '#' that a URL parser ends the path at",f=>/[?#]/.test(f));if(e.startsWith("//"))throw s("which starts with '//' that a URL parser reads as a host (an empty value in the first segment)",(f,h)=>f===""&&c(h));let u=e.startsWith("/")?e:`/${e}`,l=u.split("/"),d=l.find(pS);if(d!==void 0)throw new Bo("path",d);let p=new URL(u,"http://localhost");if(p.search!==""||p.hash!==""||p.pathname.split("/").length!==l.length)throw s("which a URL parser resolves to a different route",()=>!1)}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/(:\w+\([^)]*\))|\\(.)/gs,(n,o,r)=>o??r)}};var Tg=class{constructor(e,n=!1,o=!0){this.routeData=e;this.serializeByStyle=n;this.contentSchemaAdvertised=o}routeData;serializeByStyle;contentSchemaAdvertised;static{i(this,"McpUrlBuilder")}build(e,n){let o=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,r=this.routeData.raw()?.parameters||[],s=this.serializeByStyle?up(r):r,a=new vg(o,this.serializeByStyle,this.contentSchemaAdvertised,s.filter(c=>c.in==="query").map(c=>c.name));for(let c of s)a.addParameter(c,e,n);return a.toString()}},x0=new WeakMap;function Ig(t,e,n){let o=x0.get(t);o||(o=new URLPattern({pathname:_0(t.pathPattern||t.path)}),x0.set(t,o));let{pathname:r}=new URL(e,"http://localhost"),s=o.exec({pathname:r});if(s)return s.pathname.groups;let a=Object.keys(n??{}),c=a.find(u=>n?.[u]==="")??(a.join(", ")||"path");throw new Bo(c,r,"which the tool's route does not match")}i(Ig,"matchToolRoute");var iW={error:i(t=>t.input===void 0?"Missing required field":void 0,"error")};function O0(){let t={type:"object",properties:{},required:[],additionalProperties:!1},e=m.strictObject({});return new zn(t,n=>{let o=e.safeParse(n,iW);return o.success?{success:!0,data:o.data,errorData:null}:{success:!1,data:null,errorMessage:m.prettifyError(o.error),errorData:m.treeifyError(o.error)}})}i(O0,"createEmptyValidator");var M0=new WeakMap,L0=new WeakSet;function mS(t,e=!1){let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"&&!Array.isArray(n)||e?n:void 0}i(mS,"parseStructuredContent");function sW(t){let e=t.headers.get("accept");if(!e)return t;let n=e.replace(/application\/json/gi,"application/json").replace(/text\/event-stream/gi,"text/event-stream").replace(/(^|[ ,;])event-stream($|[ ,;])/i,"$1text/event-stream$2");if(!n.includes("text/event-stream")){if(!n.includes("application/json"))return t;n=`${n}, text/event-stream`}if(n===e)return t;let o=new Request(t,{headers:new Headers(t.headers)});return o.headers.set("accept",n),o}i(sW,"normalizeLegacyAcceptHeader");var Eg=class t{static{i(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:n,key:o}){let r=e.debugMode??!1,s=t.instances.get(o);if(s)r&&n.log.debug("MCP Server warm reuse",{routeKey:o});else{let a=Date.now();if(s=new t(e,n),s.registerFromOperations(s.opts.operations??[]),s.registerToolsFromFileSources(s.opts.files??[]),s.registerPromptsFromFileSources(s.opts.prompts??[]),s.registerResourcesFromFileSources(s.opts.resources??[]),s.logMissingGeneratedPromptSchemas(),_.instance.build.COMPATIBILITY_FLAGS.sanitizeMcpToolNames&&s.advertiseSanitizedToolNames(),s.logMissingGeneratedSchemas(),t.instances.set(o,s),r){let c=s.tools.size,u=s.prompts.size,l=s.resources.size,d=Date.now()-a;n.log.debug("MCP Server cold start",{routeKey:o,toolCount:c,promptCount:u,resourceCount:l,totalElapsedMs:d,debugMode:r,includeOutputSchema:s.includeOutputSchema,includeStructuredContent:s.includeStructuredContent})}}return s}opts;context;serverName;serverDisplayName;registeredToolNames;registeredPromptNames;registeredResourceNames;tools=new Map;toolRegistrations=[];toolsWithoutGeneratedSchemas=[];styleWarnedRoutes=new WeakSet;prompts=new Map;promptsWithoutGeneratedSchemas=[];resources=new Map;includeOutputSchema;includeStructuredContent;debugMode;toolInputStyle;schemaRefs;toolSchemasBySpec;jsonSchemaValidator=new cg;constructor(e,n){if(this.debugMode=e.debugMode??!1,this.context=n,this.opts=e,this.serverName=e.name??n.route?.path??void 0,this.serverDisplayName=e.name??"Zuplo MCP Server",this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.toolInputStyle=e.toolInputStyle??"nested",this.toolSchemasBySpec=EM(),this.toolSchemasBySpec&&e.schemaRefs!==void 0&&e.schemaRefs!=="inline"&&e.schemaRefs!=="defs")throw new Error(`MCP server configuration error: invalid schemaRefs ${JSON.stringify(e.schemaRefs)} on route "${n.route?.path??"(unknown)"}". Use "inline" or "defs".`);this.schemaRefs=e.schemaRefs??"inline",this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}missingGeneratedSchemasMessage(){let e=[...new Set(this.toolsWithoutGeneratedSchemas)];if(e.length===0)return;let n=e.slice(0,5).join(", "),o=e.length>5?` and ${e.length-5} more`:"";return`The build generated no schemas for some MCP tools: $env() in the handler options, or a handler not exported as "mcpServerHandler". Tools (${e.length}): ${n}${o}`}logMissingGeneratedPromptSchemas(){let e=[...new Set(this.promptsWithoutGeneratedSchemas)];if(e.length===0)return;let n=e.slice(0,5).join(", "),o=e.length>5?` and ${e.length-5} more`:"";this.context.log.error(`The build generated no arguments for some MCP prompts: $env() in the handler options, or a handler not exported as "mcpServerHandler". Prompts (${e.length}): ${n}${o}`,{promptNames:e,route:this.context.route?.path})}logMissingGeneratedSchemas(){let e=this.missingGeneratedSchemasMessage();e&&this.context.log.error(e,{toolNames:[...new Set(this.toolsWithoutGeneratedSchemas)],route:this.context.route?.path})}emitEvent(e,n){let o=n.capabilityType==="tool"?RM():void 0,r=OM(o===void 0?n:{...n,capabilityName:o},this.serverName),s=r.subjectId??LM(),a=r.mcpProtocolVersion??M0.get(e);gM(e,{...r,...s===void 0?{}:{subjectId:s},...a===void 0?{}:{mcpProtocolVersion:a}})}async handleRequest(e,n){let o=Date.now(),r=e.headers.get("mcp-session-id")??e.headers.get("Mcp-Session-Id")??null,s=e.user?.sub;try{let a=await e.clone().json().catch(()=>({})),c=typeof a?.method=="string"?a.method:null,u=Is(e.headers,a);u!==void 0&&M0.set(n,u),c==="tools/call"&&(n.custom.mcpCallToolRequest=a),this.emitEvent(n,{eventType:N.MCP_REQUEST_RECEIVED,outcome:"success",mcpMethod:c??void 0,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s}),s!==void 0&&this.emitEvent(n,{eventType:N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,subjectId:s});let l=wM(a);l&&this.emitEvent(n,{...l,httpMethod:e.method,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0});try{it.getContextExtensions(n).addHandlerResponseHook(C=>{let T=Date.now()-o;this.emitEvent(n,{eventType:N.MCP_REQUEST_COMPLETED,outcome:C.status>=400?"failure":"success",mcpMethod:c??void 0,httpMethod:e.method,httpStatusCode:C.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:T,subjectId:s,...L0.has(n)?{reasonClass:"protocol",reasonCode:Zw}:{}})})}catch{}if(this.debugMode)switch(n.log.debug("MCP Server request start",{method:a.method,requestId:a.id,routePath:n.route?.path}),a.method){case"tools/list":n.log.debug("MCP Server list tools request",{toolCount:this.tools.size,toolNames:Array.from(this.tools.keys())});break;case"prompts/list":n.log.debug("MCP Server list prompts request",{promptCount:this.prompts.size,promptNames:Array.from(this.prompts.keys())});break;case"resources/list":n.log.debug("MCP Server list resources request",{resourceCount:this.resources.size,resourceNames:Array.from(this.resources.keys())});break}let d=new Fw({name:this.serverDisplayName,version:this.opts.version??"0.0.0"},{jsonSchemaValidator:this.jsonSchemaValidator,capabilities:{tools:g0(),prompts:{},resources:{}}});this.wireRequestHandlers(d,n,e.headers.get("mcp-protocol-version"));let p=new nM({enableJsonResponse:!0,maxRequestBodySize:Number.MAX_SAFE_INTEGER});await d.connect(p);let f=sW(e),h=BM(f,a),y;h?y=h:(VM(p,{protocolVersion:e.headers.get("mcp-protocol-version"),hasResource:i(C=>Array.from(this.resources.values()).some(T=>T.uri===C),"hasResource")}),y=await ZM(f,C=>p.handleRequest(f,C===void 0?void 0:{parsedBody:C})));let S=Date.now()-o;await rM(y)&&(L0.add(n),this.emitEvent(n,{eventType:N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:c??void 0,httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,reasonClass:"protocol",reasonCode:Zw,subjectId:s}));let R=y.status>=200&&y.status<300;switch(a.method){case"initialize":{let C=a?.params?.clientInfo,T=typeof C?.name=="string"?C.name:void 0,I=typeof C?.title=="string"?C.title:void 0,P=typeof C?.version=="string"?C.version:void 0,A=a?.params?.protocolVersion,M=typeof A=="string"&&A!==""?A:u;this.emitEvent(n,{eventType:N.MCP_INITIALIZE_NEGOTIATED,outcome:R?"success":"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:T,clientTitle:I,clientVersion:P,mcpProtocolVersion:M,latencyMs:S}),R||this.emitEvent(n,{eventType:N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,clientName:T,clientVersion:P,mcpProtocolVersion:M,reasonClass:"client",reasonCode:"initialize_failed",attributes:{feature:"initialize"}});break}case"tools/list":this.emitEvent(n,{eventType:N.MCP_CAPABILITY_LISTED,outcome:R?"success":"failure",capabilityType:"tool",mcpMethod:"tools/list",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:S});break;case"resources/list":this.emitEvent(n,{eventType:N.MCP_CAPABILITY_LISTED,outcome:R?"success":"failure",capabilityType:"resource",mcpMethod:"resources/list",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:S});break;case"prompts/list":this.emitEvent(n,{eventType:N.MCP_CAPABILITY_LISTED,outcome:R?"success":"failure",capabilityType:"prompt",mcpMethod:"prompts/list",httpMethod:e.method,httpStatusCode:y.status,transport:"http",sessionId:r??void 0,mcpSessionId:r??void 0,latencyMs:S});break}if(this.debugMode){let C=await y.clone().json().catch(()=>({}));n.log.debug("MCP Server response complete",{status:y.status,requestMethod:a.method,requestId:a.id,totalElapsedMs:S,respData:C})}return y}catch(a){let c=Date.now()-o;return n.log.error("MCP server internal error",{elapsedMs:c,err:a}),new Response("Internal error",{status:500})}}wireRequestHandlers(e,n,o){let r=_.instance.build.COMPATIBILITY_FLAGS.omitMcpFieldsNewerThanNegotiatedVersion?i0(o):void 0,s=i((c,u)=>r===void 0?c:yg(c,u,r),"forVersion"),a=i(c=>r===void 0?c:c0(c,r),"toolResultForVersion");e.setRequestHandler("tools/list",async()=>({tools:Array.from(this.tools.entries()).map(([c,u])=>({name:c,description:u.description,inputSchema:u.validator.schema,...u.outputSchema&&{outputSchema:u.outputSchema()},...u.annotations&&{annotations:u.annotations},...u._meta&&{_meta:u._meta}})).map(c=>s(c,o0))})),e.setRequestHandler("tools/call",async c=>{let u=c.params.name,l=this.tools.get(u);if(!l)throw new Je(Se.InvalidParams,`Tool "${mg(u)}" not found`);let d=c.params.arguments??{},p=i(h=>this.emitEvent(n,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:u,mcpMethod:"tools/call",transport:"http",reasonCode:h?"route_configuration_error":"invalid_arguments",reasonClass:h?"config":"client",...h&&{failureOrigin:"config",errorType:h.error instanceof Error?h.error.name:"unknown"}}),"failed"),f=d0(l,u,d,l0(o),h=>{n.log.error("MCP tool input validator threw",{toolName:u,err:h}),p({error:h})});if(!f.valid)return f.internalError===void 0&&p(),a(f.result);try{let h=i(()=>l.handler(f.data,c.params._meta),"call"),y=await(_.instance.build.COMPATIBILITY_FLAGS.sanitizeMcpToolNames?bM(u,h):h());return a(h0(e,y,l.outputSchema?.()))}catch(h){return a({content:[{type:"text",text:h instanceof Error?h.message:"Tool execution error"}],isError:!0})}}),e.setRequestHandler("prompts/list",async()=>({prompts:Array.from(this.prompts.entries()).map(([c,u])=>({name:c,description:u.description,arguments:u.arguments}))})),e.setRequestHandler("prompts/get",async c=>{let u=c.params.name,l=this.prompts.get(u);if(!l)throw new Je(Se.InvalidParams,`Prompt "${mg(u)}" not found`);let d=c.params.arguments??{},p=l.validator.validate(d);if(!p.success)throw new Je(Se.InvalidParams,p.errorMessage?`Invalid arguments for prompt '${u}': ${p.errorMessage}`:`Invalid arguments for prompt '${u}'`,p.errorData);try{let f=await l.generator(p.data);return{...l.description!==void 0&&{description:l.description},messages:r===void 0?f:u0(f,r)}}catch(f){throw new Je(Se.InternalError,f instanceof Error?f.message:"Prompt generation error")}}),e.setRequestHandler("resources/list",async()=>({resources:Array.from(this.resources.entries()).map(([c,u])=>({name:c,uri:u.uri,...u.metadata.title!==void 0&&{title:u.metadata.title},...u.metadata.description!==void 0&&{description:u.metadata.description},...u.metadata.mimeType!==void 0&&{mimeType:u.metadata.mimeType},...u.metadata._meta!==void 0&&{_meta:u.metadata._meta}})).map(c=>s(c,r0))})),e.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:[]})),e.setRequestHandler("resources/read",async c=>{let u=c.params.uri,l=Array.from(this.resources.values()).find(d=>d.uri===u);if(!l)throw new Wd(u);try{return await l.reader()}catch(d){throw new Je(Se.InternalError,d instanceof Error?d.message:"Resource read error")}})}addToolInternal(e){let n={description:e.description,validator:e.validator,...e.outputSchema&&{outputSchema:e.outputSchema},...e.annotations&&{annotations:e.annotations},...e._meta&&{_meta:e._meta},handler:e.handler};this.tools.set(e.name,n),this.toolRegistrations.push([e.name,n])}advertiseSanitizedToolNames(){let e=YE(this.toolRegistrations.map(([n])=>n));this.tools.clear(),this.toolRegistrations.forEach(([,n],o)=>{this.tools.set(e[o],n)})}addPromptInternal(e){this.prompts.set(e.name,{description:e.description,arguments:e.arguments,validator:e.validator,generator:e.generator})}addResourceInternal(e,n,o,r){this.resources.set(e,{uri:n,metadata:o,reader:r})}generatePromptDescriptionFromSpec(e){let n=e.raw();return n?.description?n.description:n?.summary?n.summary:`Generate content for operation for ${e.path}`}static getOperationsMetadataForFile(e){let{routes:n}=ot.instance.routeData,o=n.filter(s=>s.metadata?.filepath===e);if(o.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let r=new Map;for(let s of o){let a=s?.raw().operationId;if(a){r.set(a,{routeConfig:s});let c=s?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],p=c["x-zuplo-mcp-resource"],f=c["x-zuplo-route"]?.mcp;(u||l||d||p||f)&&r.set(a,{routeConfig:s,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:p||void 0,routeMcpExtension:f||void 0})}}return r}registerFromOperations(e){let n=new Map;for(let o of e){let r=n.get(o.file)??[];r.push(o.id),n.set(o.file,r)}for(let[o,r]of n.entries()){let s=t.getOperationsMetadataForFile(o);for(let a of r){let c=s.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${o}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let n of e){let o=t.getOperationsMetadataForFile(n.path),r=new Set;for(let s of n.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${s}" from file: "${n.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.get(s);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${s}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??s;if(r.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);r.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:s});continue}this.registerPromptForOperation(l,d,c,s)}}}generatedPromptSchemas(e,n,o){let r=IM(n.metadata?.filepath??"",o);if(!r){this.promptsWithoutGeneratedSchemas.push(e);return}return{validator:kM(r),arguments:r.arguments}}registerPromptForOperation(e,n,o,r){try{if(o.handler?.export==="mcpServerHandler")return;let s=this.toolSchemasBySpec?this.generatedPromptSchemas(e,o,r):WM(o);if(!s)return;this.addPromptInternal({name:e,description:n,arguments:s.arguments,validator:s.validator,generator:i(async a=>{let c=wc(),u=Date.now();try{this.debugMode&&c.log.debug("MCP prompt invoked",{promptName:e,operationId:o.raw()?.operationId,path:o.path,args:a});let l=this.buildToolUrl(o,{body:a}),d=this.buildToolRequest("POST","application/json",{body:a});this.debugMode&&c.log.debug("MCP prompt downstream call",{promptName:e,url:l,method:"POST",bodyPreview:a});let p=Date.now(),f=await c.invokeRoute(l,d),h=Date.now()-p,y=await f.json();if(!f.ok)throw new Error(`Route returned ${f.status}: ${y}`);let S;try{if(S=y.messages||y,!Array.isArray(S))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(C){throw new Error(`Invalid JSON response or missing messages array: ${C instanceof Error?C.message:String(C)}`)}let R=Date.now()-u;return this.debugMode&&c.log.debug("MCP prompt response complete",{promptName:e,operationId:o.raw()?.operationId,status:f.status,elapsedMs:R,downstreamElapsedMs:h,messageCount:S.length}),this.emitEvent(c,{eventType:N.MCP_CAPABILITY_COMPLETED,outcome:"success",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:R}),S}catch(l){let d=Date.now()-u,p=l instanceof Error?`${l.name}: ${l.message}`:String(l);throw c.log.error("MCP prompt invocation failed",{promptName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:d,err:l}),this.emitEvent(c,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:d,reasonCode:"gateway_error",reasonClass:"upstream",errorType:l instanceof Error?l.name:"unknown"}),new Error(`MCP prompt invocation failed for prompt '${e}': ${p}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:r,path:o.path})}catch(s){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:r,error:s instanceof Error?s.message:String(s)}),new Error(`Failed to register prompt "${e}" for operation "${r}": ${s instanceof Error?s.message:String(s)}`)}}registerResourcesFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${s}" from file: "${o.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${s}" in file ${o.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:s});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${s}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${s}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${s}" uses ${d} method. Resources are read-only and must use GET method only.`);let p=u?.name?.trim()||s.trim()||"";if(!p)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${s}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(n.has(p))throw new Error(`MCP Resource configuration error: Duplicate resource name "${p}". Resource names must be unique across all configured resources.`);n.add(p);let f=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${p}`,h=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,y=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,h,f,c,s,y)}}}registerResourceForOperation(e,n,o,r,s,a,c){try{if(r.handler?.export==="mcpServerHandler")return;this.addResourceInternal(e,n,{title:e,description:o,mimeType:a,...c&&{_meta:c}},async()=>{let u=wc(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,uri:n});let d=this.buildToolUrl(r,{}),p=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let f=Date.now(),h=await u.invokeRoute(d,p),y=Date.now()-f,S=await h.text(),R=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:r.raw()?.operationId,status:h.status,elapsedMs:R,downstreamElapsedMs:y,declaredMimeType:a,contentLength:S.length}),this.emitEvent(u,{eventType:h.ok?N.MCP_CAPABILITY_COMPLETED:N.MCP_CAPABILITY_FAILED,outcome:h.ok?"success":"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:R,...h.ok?{}:{errorCode:h.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),{contents:[{uri:n,mimeType:a,text:S,...c&&{_meta:c}}]}}catch(d){let p=Date.now()-l,f=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:r.raw()?.operationId,path:r.path,elapsedMs:p,err:d}),this.emitEvent(u,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"resource",capabilityName:e,resourceUri:n,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:r.path,toolMethod:"GET",toolOperationId:r.raw()?.operationId,latencyMs:p,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP resource call failed for resource '${e}': ${f}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:s,path:r.path,uri:n,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:s,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${s}": ${u instanceof Error?u.message:String(u)}`)}}resolveIncludeStructuredContent({includeOutputSchema:e,includeStructuredContent:n,routeConfig:o,operationId:r}){return e&&!n?(this.context.log.warn("MCP includeOutputSchema implies includeStructuredContent; enabling it",{path:o.path,operationId:r,override:"includeStructuredContent: true"}),!0):n}registerTool(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredToolNames.has(s))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${n}". The tool name "${s}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${n}".`);this.registeredToolNames.add(s);let a=o?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${s}`,c=o?.includeOutputSchema??this.includeOutputSchema??!1,u=this.resolveIncludeStructuredContent({includeOutputSchema:c,includeStructuredContent:o?.includeStructuredContent??this.includeStructuredContent??!1,routeConfig:e,operationId:n}),l=sS(o?.toolInputStyle,this.toolInputStyle,n);if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${n}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,operationId:n,method:e.methods[0],name:s,description:a,includeOutputSchema:c,includeStructuredContent:u,toolInputStyle:l,annotations:o?.annotations,_meta:o?._meta})}registerPrompt(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:n});return}let s=o?.name?.trim()||n;if(this.registeredPromptNames.has(s))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${s}" for operation ID "${n}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(s);let a=o?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(s,a,e,n)}registerResource(e,n,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:n});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${n}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${n}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let s=e.methods[0].toUpperCase();if(s!=="GET")throw new Error(`MCP Resource configuration error: Operation "${n}" uses ${s} method. Resources are read-only and must use GET method only.`);let a=o?.name?.trim()||n;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=o?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=o?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=o?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,n,l,o?._meta)}registerToolsFromFileSources(e){let n=new Set;for(let o of e){let r=t.getOperationsMetadataForFile(o.path);this.debugMode&&this.context.log.debug("Processing file source",{path:o.path,operationIds:o.operationIds,availableOperationIds:Array.from(r.keys())});for(let s of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${s}" from file: "${o.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=r.get(s);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${s}" not found in OpenAPI spec at ${o.path}. Available operation IDs: ${Array.from(r.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:s,path:o.path});continue}let c=a.toolExtension?.name?.trim()??s,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${s}" in file "${o.path}"`);if(n.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${s}".`);n.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=this.resolveIncludeStructuredContent({includeOutputSchema:l,includeStructuredContent:a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1,routeConfig:a.routeConfig,operationId:s}),p=sS(a.toolExtension?.toolInputStyle,this.toolInputStyle,s);if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${s}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(s,a.routeConfig,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,operationId:s,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d,toolInputStyle:p})}}}registerGraphQLTools(e,n,o){let r=o?.introspectionTool?.name?.trim()||`${e}_introspect`,s=o?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(r))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${r}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(s))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${s}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(r),this.registeredToolNames.add(s);let a=o?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=o?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=n.path,l=O0();this.addToolInternal({name:r,description:a,validator:l,handler:i(async()=>{let p=wc(),f=Date.now();try{this.debugMode&&p.log.debug("MCP GraphQL introspection tool invoked",{toolName:r,operationId:e,path:u});let h=df(),y=this.buildToolUrl(n,{}),S=this.buildToolRequest("POST","application/json",{body:{query:h}});hf(S,{route:n,params:Ig(n,y,void 0)});let R=Date.now(),C=await p.invokeRoute(y,S),T=Date.now()-R,I=await C.text(),P=Date.now()-f;this.debugMode&&(C.ok?p.log.debug("MCP GraphQL introspection tool ok response",{toolName:r,operationId:e,status:C.status,elapsedMs:P,downstreamElapsedMs:T}):p.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:r,operationId:e,status:C.status,elapsedMs:P,downstreamElapsedMs:T,response:I}));let A=mS(I);this.debugMode&&A===void 0&&p.log.debug("MCP GraphQL introspection structuredContent skipped (non-object)",{toolName:r,bodyPreview:I.slice(0,200)});let M=p.custom.mcpCallToolResponse;delete p.custom.mcpCallToolResponse;let z=bg({target:{toolName:r,method:"POST",path:u},defaults:{content:[{type:"text",text:I}],structuredContent:A,isError:!C.ok},override:M,enforceOutputSchema:!1});return z.ok?z.result:(p.log.error("MCP tool result rejected",{toolName:r,operationId:e,path:u,reason:z.message}),{content:[{type:"text",text:z.message}],isError:!0,_meta:{}})}catch(h){let y=Date.now()-f,S=h instanceof Error?`${h.name}: ${h.message}`:String(h);throw p.log.error("MCP GraphQL introspection tool invocation failed",{toolName:r,operationId:e,path:u,elapsedMs:y,err:h}),new Error(`MCP GraphQL introspection tool call failed for '${r}': ${S}`)}},"handler")});let d={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.addToolInternal({name:s,description:c,validator:new zn(d,p=>typeof p=="object"&&p!==null&&"query"in p&&typeof p?.query=="string"?{success:!0,data:p,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:i(async p=>{let f=wc(),h=Date.now();try{this.debugMode&&f.log.debug("MCP GraphQL execute tool invoked",{toolName:s,operationId:e,path:u,queryPreview:p.query.substring(0,100)});let y=this.buildToolUrl(n,{}),S={query:p.query};p.variables&&(S.variables=p.variables);let R=this.buildToolRequest("POST","application/json",{body:S});hf(R,{route:n,params:Ig(n,y,void 0)});let C=Date.now(),T=await f.invokeRoute(y,R),I=Date.now()-C,P=await T.text(),A=Date.now()-h;this.debugMode&&(T.ok?f.log.debug("MCP GraphQL execute tool ok response",{toolName:s,operationId:e,status:T.status,elapsedMs:A,downstreamElapsedMs:I}):f.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:s,operationId:e,status:T.status,elapsedMs:A,downstreamElapsedMs:I,response:P}));let M=mS(P);this.debugMode&&M===void 0&&f.log.debug("MCP GraphQL execute structuredContent skipped (non-object)",{toolName:s,bodyPreview:P.slice(0,200)});let z=f.custom.mcpCallToolResponse;delete f.custom.mcpCallToolResponse;let $=bg({target:{toolName:s,method:"POST",path:u},defaults:{content:[{type:"text",text:P}],structuredContent:M,isError:!T.ok},override:z,enforceOutputSchema:!1});return $.ok?$.result:(f.log.error("MCP tool result rejected",{toolName:s,operationId:e,path:u,reason:$.message}),{content:[{type:"text",text:$.message}],isError:!0,_meta:{}})}catch(y){let S=Date.now()-h,R=y instanceof Error?`${y.name}: ${y.message}`:String(y);throw f.log.error("MCP GraphQL execute tool invocation failed",{toolName:s,operationId:e,path:u,elapsedMs:S,err:y}),new Error(`MCP GraphQL execute tool call failed for '${s}': ${R}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:r,executeToolName:s,path:u})}registerToolsForMethod({routeData:e,operationId:n,method:o,name:r,description:s,includeOutputSchema:a,includeStructuredContent:c,toolInputStyle:u,annotations:l,_meta:d}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let p of Object.keys(e.raw().requestBody?.content)){let h=Object.keys(e.raw().requestBody?.content).length>1?`${r}_${p.replace(/[^\w]/g,"_")}`:r;this.registerGenericToolSpec({name:h,description:s,routeData:e,operationId:n,method:o,contentType:p,includeOutputSchema:a,includeStructuredContent:c,toolInputStyle:u,annotations:l,_meta:d})}else this.registerGenericToolSpec({name:r,description:s,routeData:e,operationId:n,method:o,contentType:null,includeOutputSchema:a,includeStructuredContent:c,toolInputStyle:u,annotations:l,_meta:d})}registerGenericToolSpec({name:e,description:n,routeData:o,operationId:r,method:s,contentType:a,includeOutputSchema:c,includeStructuredContent:u,toolInputStyle:l,annotations:d,_meta:p}){let f=this.toolSchemasBySpec?this.generatedToolSchemas({name:e,routeData:o,operationId:r,method:s,contentType:a,includeOutputSchema:c,toolInputStyle:l}):t0({name:e,routeData:o,method:s,contentType:a,includeOutputSchema:c,toolInputStyle:l,log:this.context.log,debugMode:this.debugMode});if(!f)return;this.warnUnsupportedParameterStyles(o);let{validator:h,outputSchema:y,validateStructuredContent:S,nonObjectOutputRoot:R}=f;try{this.addToolInternal({name:e,description:n,validator:h,...y&&{outputSchema:y},...d&&{annotations:d},...p&&{_meta:p},handler:i(async(C,T)=>{let I=wc(),P=Date.now();try{this.debugMode&&I.log.debug("MCP tool invoked",{toolName:e,operationId:o.raw()?.operationId,method:s,path:o.path,args:C});let A=this.buildToolUrl(o,C),M=Ig(o,A,C.pathParams),z=this.buildToolRequest(s,a,C,o);hf(z,{route:o,params:M}),this.debugMode&&I.log.debug("MCP tool downstream call",{toolName:e,url:A,method:s,headers:z.headers?Object.keys(z.headers).join(", "):"",bodyPreview:C.body});let $=Date.now(),F=await I.invokeRoute(A,z),K=Date.now()-$,se=await F.text(),ce=u?mS(se,R):void 0;this.debugMode&&u&&ce===void 0&&I.log.debug("MCP tool structuredContent skipped (unparseable, or non-object without a non-object outputSchema)",{toolName:e,bodyPreview:se.slice(0,200)});let we=Date.now()-P;this.debugMode&&(F.ok?I.log.debug("MCP tool ok response",{toolName:e,operationId:o.raw()?.operationId,status:F.status,elapsedMs:we,downstreamElapsedMs:K}):I.log.debug("MCP tool 'isError' response",{toolName:e,operationId:o.raw()?.operationId,status:F.status,elapsedMs:we,downstreamElapsedMs:K,response:se}));let B=I.custom.mcpCallToolResponse;delete I.custom.mcpCallToolResponse;let te=bg({target:{toolName:e,method:s,path:o.path},defaults:{content:[{type:"text",text:se}],structuredContent:F.ok?ce:void 0,isError:!F.ok},override:B,validateStructuredContent:S&&(X=>S(X,re=>I.log.error("MCP tool output validator threw",{toolName:e,err:re}))),enforceOutputSchema:F.ok,nonObjectOutputRoot:R});return te.ok?(this.emitEvent(I,{eventType:F.ok?N.MCP_CAPABILITY_COMPLETED:N.MCP_CAPABILITY_FAILED,outcome:F.ok?"success":"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:s,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:Date.now()-P,...F.ok?{}:{errorCode:F.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),te.result):(I.log.error("MCP tool result rejected",{toolName:e,operationId:o.raw()?.operationId,method:s,path:o.path,reason:te.message}),this.emitEvent(I,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:s,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:Date.now()-P,reasonCode:"invalid_tool_result",reasonClass:"config"}),{content:[{type:"text",text:te.message}],isError:!0,_meta:{}})}catch(A){return this.toolInvocationFailure(I,A,{toolName:e,operationId:o.raw()?.operationId,method:s,path:o.path,elapsedMs:Date.now()-P})}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:s.toUpperCase(),path:o.path,operationId:r,contentType:a||"none",includeOutputSchema:c,includeStructuredContent:u,hasValidator:!!h,hasOutputSchema:!!y})}catch(C){throw new Error(`Failed to add tool ${s} ${o.path}`,C)}}generatedToolSchemas({name:e,routeData:n,operationId:o,method:r,contentType:s,includeOutputSchema:a,toolInputStyle:c}){let u=TM(n.metadata?.filepath??"",o,s);if(!u){this.toolsWithoutGeneratedSchemas.push(e);return}let l=PM(this.schemaRefs),{validator:d,flatRefusal:p,flatNotes:f}=_M(u,c==="flat",l);if(p&&this.context.log.warn("MCP tool input schema left nested",{method:r.toUpperCase(),path:n.path,contentType:s||"none",operationId:o,reason:p}),this.debugMode)for(let y of f??[])this.context.log.debug("MCP tool request body left nested",{method:r.toUpperCase(),path:n.path,contentType:s||"none",operationId:o,reason:y});let h=a?xM(u,l):void 0;return{validator:d,...h&&{outputSchema:h.schema,validateStructuredContent:h.validate},nonObjectOutputRoot:h!==void 0&&!h.objectRoot}}warnUnsupportedParameterStyles(e){if(!this.styleWarnedRoutes.has(e)){this.styleWarnedRoutes.add(e);for(let n of w0(e.raw()?.operationId,e.raw()?.parameters??[],_.instance.build.COMPATIBILITY_FLAGS.serializeMcpParametersByStyle))this.context.log.warn("MCP tool parameter style not supported for value; using default",n)}}toolInvocationFailure(e,n,o){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n),s=n instanceof Bo||n instanceof Si||n instanceof Pc||n instanceof cp||n instanceof Ec;return s?e.log.debug("MCP tool call refused: unsendable argument value",{...o,err:n}):e.log.error("MCP server tool invocation failed",{...o,err:n}),this.emitEvent(e,{eventType:N.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:o.toolName,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:o.method,toolOperationId:o.operationId??"unknown",latencyMs:o.elapsedMs,reasonCode:s?"invalid_arguments":"gateway_error",reasonClass:s?"client":"upstream",errorType:n instanceof Error?n.name:"unknown"}),{content:[{type:"text",text:`MCP tool call failed for tool '${o.toolName}': ${r}`}],isError:!0}}buildToolUrl(e,n){return new Tg(e,_.instance.build.COMPATIBILITY_FLAGS.serializeMcpParametersByStyle,this.toolSchemasBySpec).build(n.pathParams,n.queryParams)}buildToolRequest(e,n,o,r){let s=this.buildToolHeaders(e,n,o,r?.raw()?.parameters),a={method:e,headers:s};return this.shouldIncludeBody(e,n,o)&&(a.body=this.serializeBody(o.body,n)),a}buildToolHeaders(e,n,o,r=[]){let s={...Qw()};if(delete s["content-type"],o.headers){let a=_.instance.build.COMPATIBILITY_FLAGS.serializeMcpParametersByStyle;if(a){let c=new Set(P0(r,o.headers));for(let u of Object.keys(s))c.has(u.toLowerCase())&&delete s[u]}Object.assign(s,E0(r,o.headers,a,this.toolSchemasBySpec))}return n&&o.body!==void 0&&(s["content-type"]=n),this.isBodyMethod(e||"")&&o.body!==void 0&&!s["content-type"]&&(s["content-type"]="application/json"),s}shouldIncludeBody(e,n,o){return o.body===void 0?!1:this.isBodyMethod(e)?!0:n!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,n){return JSON.stringify(e)}};async function N0(t,e){if(pe("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new v(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let n={};t.headers.forEach((a,c)=>{n[c]=a});let o=e.route?.handler?.options??{},r=e.route?.path??"unknown-route",s=await Eg.getInstance({opts:o,context:e,key:r});return MM(e,{headers:n,user:t.user},()=>s.handleRequest(t,e))}i(N0,"mcpServerHandler");jt("mcp-server",N0);var aW=[502,503,504];function Pg(t){if(t!=null){if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new v(`The 'requestTimeoutSeconds' handler option must be a positive number of seconds. Received: ${String(t)}. Remove the option to disable the request timeout.`);return AbortSignal.timeout(t*1e3)}}i(Pg,"getRequestTimeoutSignal");function Or(t){if(typeof t!="object"||t===null)return!1;let e=t.name;return e==="TimeoutError"||e==="AbortError"}i(Or,"isRequestTimeoutError");async function Ac(t,e){if(aW.includes(t.status)){let n=de.getLogger(e),r=await t.clone().text(),s={};for(let[a,c]of t.headers)s[a]=c;n.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:r,headers:s})}}i(Ac,"logBadGatewayResponses");var fS;function kc(t){if(fS===void 0){let n=_.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(n??"")||(n="debug"),fS=n}return t.log[fS]}i(kc,"getHandlerUserLogFunction");async function U0(t,e){pe("handler.open-api");let n=_.instance.build.BUILD_ID,{buildAssetsUrl:o}=_.instance,r=e.route.handler.options,{openApiFilePath:s}=r;if(!s)throw new v("Open API Spec Handler must have 'openApiFilePath' specified");let a=uW(s);if(!a.isValid)throw new v(a.error);let c=cW(_.instance);if(c){let{label:f,reason:h,environment:y}=c;return G.notImplemented(t,e,{detail:`The 'openApiSpecHandler' route cannot serve '${s}' in ${f}. The handler reads the OpenAPI file from the build assets that are published when a project is deployed, and ${h}. Deploy this project to a preview or production environment to use this route. While developing, read the file from your '/config' directory instead.`,openApiFilePath:s,environment:y})}let u=`${o}/${n}${s.substring(1)}`,l=await V.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(l.status!==200)return G.notFound(t,e,{detail:`The OpenAPI file '${s}' was not published with this deployment's build assets. Check that the file exists in your '/config' directory, then redeploy the project.`,openApiFilePath:s});let d={"content-type":"application/json",vary:"Accept-Encoding"};_.instance.isDeno||(d["content-encoding"]=l.headers.get("content-encoding")||"");let p=new Response(l.body,{headers:d,status:l.status,statusText:l.statusText});return Ac(p,e),p}i(U0,"openApiSpecHandler");function cW(t){if(t.isWorkingCopy)return{label:"a working copy",reason:"working copy deployments do not publish build assets",environment:"working-copy"};if(t.isLocalDevelopment)return{label:"local development",reason:"`zuplo dev` does not publish build assets",environment:"local-development"}}i(cW,"getUnsupportedEnvironment");var uW=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");jt("open-api",U0);async function q0(t,e){pe("handler.redirect");let n=e.route.handler.options;if(!n.location)throw new v("Redirect Handler must have 'location' specified");let o=n.status??302;return new Response(null,{status:o,headers:{location:n.location}})}i(q0,"redirectHandler");jt("redirect",q0);async function D0(t){if(pe("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new v("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=vm(t.params.path),n=new Headers(t.headers);return n.set("Authorization",`Bearer ${_.instance.authApiJWT}`),V.fetch(e,{method:t.method,headers:n,body:t.body})}i(D0,"zuploServiceProxy");jt("service-proxy",D0);function lW(t,e){let n=t.endsWith("/"),o=e.startsWith("/");return n&&o?`${t.substring(0,t.length-1)}${e}`:!n&&!o?`${t}/${e}`:`${t}${e}`}i(lW,"join");async function $0(t,e){pe("handler.url-forward");let n=kc(e),o=e.route.handler.options,r=o.forwardSearch!==!1,s;if(_.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=o.followRedirects===!0?"follow":"manual":typeof o.followRedirects<"u"&&pe("handler.url-forward.follow-redirects"),!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new v("Invalid options for this route");let a=_c(e),c=new URL(t.url),u=o.__rewriteFunction(t,a),l=lW(u,c.pathname),d=r?`${l}${c.search}`:l.toString(),p=Date.now();n(`URL Forwarding to '${d}'`);let f=t.body;if(s==="follow"&&t.body)try{f=await t.arrayBuffer()}catch(R){throw new Error(`Failed to buffer request body for redirect handling: ${R}`)}let h=Pg(o.requestTimeoutSeconds),y;try{y=await fetch(d,{method:t.method,body:f,headers:da(t.headers),redirect:s,signal:h,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0})}catch(R){if(h&&Or(R)){let C=Date.now()-p;return n(`URL Forward to '${d}' timed out after ${C}ms (requestTimeoutSeconds: ${o.requestTimeoutSeconds})`),G.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${o.requestTimeoutSeconds} seconds.`})}throw R}let S=Date.now()-p;return n(`URL Forward received response ${y.status} - ${y.statusText} in ${S}ms`),Ac(y,e),y}i($0,"urlForwardHandler");jt("url-forward",$0);var dW=i((t,e)=>{let n=new URL(t),o=new URL(e);for(let[r,s]of o.searchParams.entries())n.searchParams.append(r,s);return n.toString()},"addQuery");async function z0(t,e){return pW(t,e)}i(z0,"urlRewriteHandler");async function pW(t,e,n){pe("handler.url-rewrite");let o=kc(e),r=e.route.handler.options,s=r.forwardSearch!==!1,a=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new v("Invalid options for this route");let c=_c(e),u=r.__rewriteFunction(t,c),l=s?dW(u,t.url):u,d=Pg(r.requestTimeoutSeconds);n?.(d);let p=Date.now();o(`URL Rewriting to '${l}'`);let f;try{f=await fetch(l.toString(),{method:t.method,body:t.body,headers:da(t.headers),redirect:a?"follow":"manual",signal:d,zuplo:r.mtlsCertificate?{mtlsCertificate:r.mtlsCertificate}:void 0})}catch(y){if(d&&Or(y)){let S=Date.now()-p;return o(`URL Rewrite to '${l}' timed out after ${S}ms (requestTimeoutSeconds: ${r.requestTimeoutSeconds})`),G.gatewayTimeout(t,e,{detail:`The upstream server did not respond within the configured timeout of ${r.requestTimeoutSeconds} seconds.`})}throw y}let h=Date.now()-p;return o(`URL Rewrite received response ${f.status} - ${f.statusText} in ${h}ms`),Ac(f,e),f}i(pW,"rewriteUrlAndFetch");jt("url-rewrite",z0);var hS=i((t,e)=>t.map((o,r)=>{let s;if(typeof o.module=="object"&&(s=o.module[o.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${r+1}, export name: ${o.export}`;throw new v(`${a} - Websocket policy must be a valid function (${c})`)}return s}),"getWebSocketPolicyFunctions"),j0=i(t=>{let e;if(typeof t.module=="object"&&(e=t.module[t.export]),!e||typeof e!="function")throw new v(`WebSocketOnOpenHook - Websocket onOpen hook must be a valid function (export name: ${t.export})`);return e},"getWebSocketOnOpenHook"),gS=i(async(t,e,n,o,r,s)=>{let a=t.data;if(s&&s.length>0){let c=[...s];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,n,e,o,r),a===void 0)return}}return a},"webSocketPolicyProcessor");function mW(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}i(mW,"createDeferred");var H0=1,Z0=4096,V0=16*1024*1024,bS=1011,fW=`WebSocket connection closed with code ${bS}: more than ${Z0} frames or ${V0/1024/1024} MiB were waiting to be sent to the client. Make the outbound message policies faster, or have the upstream send less.`,hW=new Set([1004,1005,1006,1015]),F0=123;function G0(t){return typeof t=="string"?t.length*2:t instanceof Blob?t.size:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:0}i(G0,"frameSize");function gW(t){return typeof t=="string"||t instanceof Blob?t:t instanceof ArrayBuffer?t.slice(0):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():`${t}`}i(gW,"captureFrame");function yW(t,e){if(t!==void 0&&(!Number.isInteger(t)||t<1e3||t>4999||hW.has(t)))throw new DOMException(`The close code must be an integer from 1000 to 4999 other than 1004, 1005, 1006 or 1015, but was ${t}.`,"InvalidAccessError");if(e===void 0)return{code:t};let n=`${e}`;if(new TextEncoder().encode(n).byteLength>F0)throw new DOMException(`The close reason may not be longer than ${F0} bytes.`,"SyntaxError");return{code:t,reason:n}}i(yW,"captureCloseArgs");function B0(t,e,n){let o=Object.getOwnPropertyDescriptor(t,e);return t[e]=n,()=>{o?Object.defineProperty(t,e,o):Reflect.deleteProperty(t,e)}}i(B0,"overrideProperty");var RS=class{static{i(this,"DenoClientLeg")}#e;#t;#o;#n;#i;#r=[];#s=0;#a=0;#c;#l=[];#p=!1;#d=!1;#u="holding";#f="";constructor(e,n,o,r,s){this.#e=e,this.#t=n,this.#o=o,this.#n=r,this.#i=s,e.addEventListener("message",this.#y),e.addEventListener("close",this.#b),e.addEventListener("error",this.#R)}attach(e){this.#c=e,this.#l=[B0(e,"send",n=>{let o=gW(n);this.#m({kind:"send",data:o,size:G0(o)},!0)}),B0(e,"close",(n,o)=>{this.#m({kind:"close",...yW(n,o)},!0)})],e.addEventListener("open",this.#w),e.addEventListener("close",this.#S)}release(){this.#p=!0,this.#C()}fail(e){this.#u==="failed"||this.#u==="disposed"||(this.#u="failed",this.#f=e,this.#g(),this.#I(),this.#e.close(),this.#c?.readyState===H0&&this.#T(bS,e))}dispose(){this.#u!=="disposed"&&(this.#u="disposed",this.#g(),this.#I(),this.#h(),this.#c?.removeEventListener("open",this.#w),this.#c?.removeEventListener("close",this.#S),this.#e.close())}#y=i(e=>{this.#m({kind:"relay",event:e,size:G0(e.data)})},"#onUpstreamMessage");#b=i(()=>{this.#m({kind:"close"})},"#onUpstreamClose");#R=i(()=>{this.#c&&(this.#i(),this.#m({kind:"close"}))},"#onUpstreamError");#w=i(()=>{if(this.#u==="failed"){this.#T(bS,this.#f);return}this.#C()},"#onClientOpen");#S=i(()=>{this.dispose()},"#onClientClose");#m(e,n=!1){if(!(this.#u!=="holding"&&this.#u!=="relaying")){if(e.kind!=="close"){if(this.#r.length>0&&(this.#r.length>=Z0||this.#a+e.size>V0)){this.#o.log.error(fW),this.fail("Relay queue full");return}this.#a+=e.size}n?this.#r.splice(this.#s++,0,e):this.#r.push(e),this.#v()}}#C(){this.#u!=="holding"||!this.#p||this.#c?.readyState!==H0||(this.#u="relaying",this.#s=0,this.#h(),this.#v())}#v(){if(this.#u!=="relaying"||this.#d)return;let e=this.#E().catch(n=>this.#o.log.error(n));this.#d&&this.#o.waitUntil(e)}async#E(){this.#d=!0;try{for(;this.#u==="relaying";){let e=this.#r.shift();if(!e)return;if(e.kind==="close"){this.#u="closed",this.#g(),this.#c?.close(e.code,e.reason);return}this.#a-=e.size;let n=e.kind==="send"?e.data:e.event.data;if(e.kind==="relay"&&this.#n.length>0){try{n=await gS(e.event,this.#e,this.#c,this.#t,this.#o,this.#n)}catch(o){this.#o.log.error(o);continue}if(this.#u!=="relaying")return;if(n===void 0)continue}try{this.#c?.send(n)}catch(o){this.#o.log.error(o)}}}finally{this.#d=!1}}#T(e,n){this.#h(),this.#c?.close(e,n)}#h(){for(let e of this.#l.splice(0))e()}#g(){this.#r.length=0,this.#a=0,this.#s=0}#I(){this.#e.removeEventListener("message",this.#y),this.#e.removeEventListener("close",this.#b),this.#e.removeEventListener("error",this.#R)}};async function bW(t,e,n,o){n(`Attempting WebSocket connection to '${e}'`);let r=new WebSocket(e),s=o(r);await new Promise((l,d)=>{let p=i(()=>{h(),n("WebSocket connection established with upstream"),l()},"onOpen"),f=i(y=>{h();let S="message"in y&&typeof y.message=="string"?y.message:"";n(S?`WebSocket connection error: ${S}`:"WebSocket connection error"),d(new Error("Upstream open failed"))},"onErr"),h=i(()=>{r.removeEventListener("open",p),r.removeEventListener("error",f)},"cleanup");r.addEventListener("open",p),r.addEventListener("error",f)}).catch(l=>{throw s.dispose(),new Error(`Failed to open outgoing socket: ${l.message}`)});let a;try{a=globalThis.Deno.upgradeWebSocket(t)}catch(l){throw s.dispose(),l}let{socket:c,response:u}=a;return s.attach(c),{clientSocket:c,outgoingSocket:r,response:u,clientLeg:s}}i(bW,"getDenoClientAndServerSockets");function RW(t){return t>=400&&t<600}i(RW,"isUpstreamHttpErrorStatus");async function wW(t,e,n,o){n(`Attempting WebSocket connection to '${e}'`);let r=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(r.status!==101||!r.webSocket)return n(`WebSocket upgrade failed: ${r.status} ${r.statusText}`),{ok:!1,response:r};if(n(`WebSocket connected, received response ${r.status} - ${r.statusText}`),o)return{ok:!0,passthrough:!0,response:new Response(null,{status:101,webSocket:r.webSocket})};let s=new WebSocketPair,[a,c]=Object.values(s);r.webSocket.accept(),c.accept();let u=new Response(null,{status:101,webSocket:a});return{ok:!0,passthrough:!1,clientSocket:a,outgoingSocket:r.webSocket,serverSocket:c,response:u}}i(wW,"getCfClientAndServerSockets");function wS(t,e,n,o,r){if(t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",()=>{n.log.error("WebSocket passthrough error",{direction:o}),e.close()}),r===void 0){t.addEventListener("message",s=>{e.send(s.data)});return}t.addEventListener("message",s=>{n.waitUntil(r.then(()=>e.send(s.data)).catch(n.log.error))})}i(wS,"wireUpPassthroughDirection");function SW(t,e,n,o){wS(t,e,n,"incoming",o),wS(e,t,n,"outgoing",o)}i(SW,"wireUpPassthrough");function yS(t,e,n,o,r,s,a){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",()=>{o.log.error("WebSocket pipeline error",{direction:s}),e.close()}),t.addEventListener("message",c=>{try{let l=i(async d=>{await a;let p=await gS(d,t,e,n,o,r);p!==void 0&&e.send(p)},"innerPipeline")(c).catch(o.log.error);o.waitUntil(l)}catch(u){o.log.error(u)}})}i(yS,"wireUpListeners");async function SS(t,e){pe("handler.websocket-pipeline");let n=e.route.handler.options,o=kc(e);if(!n||!n.rewritePattern)throw new v("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let r=t.headers.get("Upgrade");if(!r||r!=="websocket")return G.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!n||typeof n.__rewriteFunction!="function")throw new v("Invalid options for this route");let s=_c(e),a=n.__rewriteFunction(t,s),c=n.policies?.inbound?hS(n.policies.inbound,"inbound"):[],u=n.policies?.outbound?hS(n.policies.outbound,"outbound"):[],l=n.onOpen?j0(n.onOpen):void 0,d=c.length>0||u.length>0,p=d||l!==void 0,f,h,y,S;if(_.instance.isDeno){let C=t.originalRequest??it.findContextExtensions(e)?.originalRequest;if(!C)throw new Error("Original websocket request is not available");let T=e.incomingRequestProperties;T instanceof Ca&&T.detachFromRequest();let I=await bW(C,a,o,P=>new RS(P,t,e,u,()=>d?e.log.error("WebSocket pipeline error",{direction:"outbound"}):e.log.error("WebSocket passthrough error",{direction:"outgoing"})));f=I.clientSocket,h=I.outgoingSocket,y=I.response,S=I.clientLeg}else{a=a.replace(/^(ws)/,"http");let C=await wW(t,a,o,!p);if(!C.ok){let T=C.response;if(RW(T.status))return T;let I=await T.text(),P=`WebSocket connection error - ${T.status}: ${T.statusText}`,A=`${P}, content: '${I}'`;return e.log.warn({outgoingUrl:a,status:T.status},P),G.badGateway(t,e,{detail:A})}if(C.passthrough)return C.response;f=C.serverSocket,h=C.outgoingSocket,y=C.response}let R=mW();if(R.promise.catch(()=>{}),S?d?yS(f,h,t,e,c,"inbound",R.promise):wS(f,h,e,"incoming",l?R.promise:void 0):d?(yS(f,h,t,e,c,"inbound",R.promise),yS(h,f,t,e,u,"outbound",R.promise)):SW(f,h,e,l?R.promise:void 0),l)try{await l(h,f,t,e),R.resolve()}catch(C){R.reject(C);let T=new v("WebSocket onOpen hook failed",{cause:C});if(S)return e.log.error(T),S.fail("onOpen hook failed"),y;try{f.close(1011,"onOpen hook failed")}catch{}try{h.close(1011,"onOpen hook failed")}catch{}throw T}else R.resolve();return S?.release(),y}i(SS,"webSocketPipelineHandler");jt("websocket-pipeline",SS);var CW=SS;var CS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"AWSLoggingPlugin")}getTransport(){return new vS(this.options)}},vS=class{static{i(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new Be({name:"aws-log-transport",msDelay:10,dispatchFunction:i(async e=>{if(e.length===0)return;let n=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:n});o.ok||await Ve({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await Ve({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}},"dispatchFunction")});constructor({accessKeyId:e,logStreamName:n,logGroupName:o,secretAccessKey:r,region:s,fields:a}){pe("logging.aws"),this.awsClient=new ym({accessKeyId:e,secretAccessKey:r,service:"logs",region:s}),this.logGroupName=o,this.logStreamName=n,this.region=s,this.environmentType=_.instance.loggingEnvironmentType,this.environmentStage=_.instance.loggingEnvironmentStage,this.environment=_.instance.deploymentName,this.fields=a??{}}log(e,n){e.messages.forEach(o=>{let r={timestamp:Date.now(),message:JSON.stringify(Object.assign({data:Vn(o),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields,n.properties??{}))};this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}};var TS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"DynaTraceLoggingPlugin")}getTransport(){return new IS(this.options)}},IS=class{static{i(this,"DynaTraceTransport")}constructor(e){pe("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#n=_.instance.loggingEnvironmentType,this.#i=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#r=e.fields??{}}#e;#t;#o;#n;#i;#r;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:Vn(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#o,"custom.environmentStage":this.#i,"custom.environmentType":this.#n,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#r,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#s=i(async e=>{if(e.length!==0)try{let n=await V.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});n.ok||await Ve({level:"error",messages:[`Failed to send logs to Dynatrace: ${n.status} - ${n.statusText}`]},n)}catch{await Ve({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"dyna-trace-log-transport",msDelay:10,dispatchFunction:this.#s})};var ES=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"LokiLoggingPlugin")}getTransport(){return new AS(this.options)}},PS=class{static{i(this,"LokiStream")}constructor(e,n,o,r,s,a){this.level=e,this.environment=n,this.environmentType=o,this.environmentStage=r,this.requestId=a,this.job=s}job;level;environment;environmentType;environmentStage;requestId;equals=i(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function vW(t,e){return btoa(`${t}:${e}`)}i(vW,"createBasicDigest");var AS=class{static{i(this,"LokiTransport")}constructor(e){pe("logging.loki"),this.#o=e.url,this.#n=vW(e.username,e.password),this.#r=_.instance.loggingEnvironmentType,this.#s=_.instance.loggingEnvironmentStage,this.#i=_.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#o;#n;#i;#r;#s;#a;log(e,n){let o=new PS(e.level,this.#i,this.#r,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(r=>{let s=Object.assign({stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:Vn(r),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a,n.properties??{});this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#c=i(e=>{let n={streams:[]};return e.forEach(o=>{let r=n.streams.find(s=>s.stream.equals(o.stream));r||(r={stream:o.stream,values:[]},n.streams.push(r)),r.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),n},"#convertToLokiStreamsBatch");#l=i(async e=>{if(e.length===0)return;let n=this.#c(e);try{let o=await V.fetch(this.#o,{method:"POST",body:JSON.stringify(n),headers:{"content-type":"application/json",authorization:`Basic ${this.#n}`}});o.ok||await Ve({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await Ve({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"loki-log-transport",msDelay:10,dispatchFunction:this.#l})};var kS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"NewRelicLoggingPlugin")}getTransport(){return new _S(this.options)}},_S=class{static{i(this,"NewRelicTransport")}constructor(e){pe("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#n=_.instance.loggingEnvironmentType,this.#i=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#r=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#o;#n;#i;#r;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({message:Vn(o),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#i,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#r,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length!==0)try{let n=await V.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});n.ok||await Ve({level:"error",messages:[`Failed to send logs to New Relic: ${n.status} - ${n.statusText}`]},n)}catch{await Ve({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"new-relic-log-transport",msDelay:10,dispatchFunction:this.#a})};var xS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"SplunkLoggingPlugin")}getTransport(){return new OS(this.options)}},OS=class{static{i(this,"SplunkTransport")}constructor(e){pe("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#n=_.instance.loggingEnvironmentType,this.#i=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#r=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#c=e.host??"zuplo-api",this.#l=e.channel}#e;#t;#o;#n;#i;#r;#s;#a;#c;#l;log(e,n){e.messages.forEach(o=>{let s={event:{message:Vn(o),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#o,environment_stage:this.#i,environment_type:this.#n,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#r,...n.properties??{}},sourcetype:this.#a,host:this.#c,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(s)}),n.waitUntil(this.batcher.waitUntilFlushed())}#p=i(async e=>{if(e.length!==0)try{for(let n of e){let o={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#l&&(o["X-Splunk-Request-Channel"]=this.#l);let r=await V.fetch(this.#e,{method:"POST",body:JSON.stringify(n),headers:o});if(!r.ok){let s=await r.text();await Ve({level:"error",messages:[`Failed to send logs to Splunk: ${r.status} - ${r.statusText}`,`Response: ${s}`]},r)}}}catch(n){await Ve({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${n instanceof Error?n.message:String(n)}`]})}},"#dispatchFunction");batcher=new Be({name:"splunk-log-transport",msDelay:10,dispatchFunction:this.#p})};var MS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"SumoLogicLoggingPlugin")}getTransport(){return new LS(this.options)}},LS=class{static{i(this,"SumoLogicTransport")}constructor(e){pe("logging.sumologic"),this.#e=e.url,this.#i=e.category,this.#r=e.name,this.#o=_.instance.loggingEnvironmentType,this.#n=_.instance.loggingEnvironmentStage,this.#t=_.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#o;#n;#i;#r;#s;log(e,n){e.messages.forEach(o=>{let r=Object.assign({timestamp:new Date().toISOString(),message:Vn(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#o,environmentStage:this.#n,rayId:e.rayId===null?void 0:e.rayId},this.#s,n.properties??{});this.batcher.enqueue(r)}),n.waitUntil(this.batcher.waitUntilFlushed())}#a=i(async e=>{if(e.length===0)return;let n=e.map(r=>JSON.stringify(r)).join(`
263
263
  `),o=new Headers({"content-type":"application/json; charset=utf-8"});this.#r&&o.set("X-Sumo-Name",this.#r),this.#i&&o.set("X-Sumo-Category",this.#i);try{let r=await V.fetch(this.#e,{method:"POST",body:n,headers:o});r.ok||await Ve({level:"error",messages:[`Failed to send logs to Sumologic: ${r.status} - ${r.statusText}`]},r)}catch{await Ve({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"sumo-logic-log-transport",msDelay:10,dispatchFunction:this.#a})};var TW="d3a5b78f823648f5b1df4fe269d41172",NS=class extends Ot{constructor(n){super();this.options=n}options;static{i(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new US(this.options)}},US=class{static{i(this,"VMWareLogInsightTransport")}constructor(e){pe("logging.vmware-loginsight");let n;try{n=new URL(e.url),n.pathname==="/"&&(n.pathname=`/api/v1/events/ingest/${e.agentId??TW}`)}catch{throw new v(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=n.toString(),this.#n=_.instance.loggingEnvironmentType,this.#i=_.instance.loggingEnvironmentStage,this.#o=_.instance.deploymentName,this.#r=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([o,r])=>({name:o,content:r})))}#e;#t;#o;#n;#i;#r;#s;log(e,n){let o=this.buildEntry(e,n);this.batcher.enqueue(o),n.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,n){let o=$P(e.messages);this.#t?.forEach(s=>{o=o.replaceAll(s[0],s[1])});let r={timestamp:Date.now(),text:o,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#n},{name:"environment_stage",content:this.#i},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&r.fields.push({name:"request_ray_id",content:e.rayId}),this.#o&&r.fields.push({name:"environment",content:this.#o}),this.#s&&r.fields.push(...this.#s),n.properties&&Object.entries(n.properties).forEach(([s,a])=>{let c=km(a);c&&r.fields.push({name:s,content:c})}),n.custom&&Object.entries(n.custom).forEach(([s,a])=>{let c=km(a);c&&r.fields.push({name:s,content:c})}),this.#r&&(r=this.#r(r)),r}#a=i(async e=>{if(e.length!==0)try{let n=await V.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});n.ok||await Ve({level:"error",messages:[`Failed to send logs to Log Insight: ${n.status} - ${n.statusText}`]},n)}catch{await Ve({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new Be({name:"vmware-log-insights-log-transport",msDelay:10,dispatchFunction:this.#a})};var qS=class{static{i(this,"ZuploMcpSdk")}context;constructor(e){this.context=e}getRawCallToolRequest(){let e=null;return this.context.custom.mcpCallToolRequest&&(e=this.context.custom.mcpCallToolRequest),this.context.parentContext?.custom.mcpCallToolRequest&&(e=this.context.parentContext.custom.mcpCallToolRequest),e}setRawCallToolResult(e){if(this.context.parentContext?.custom.mcpCallToolRequest){this.context.parentContext.custom.mcpCallToolResponse=e;return}this.context.custom.mcpCallToolResponse=e}};var $S=new he(Symbol("datadog-metrics-context")),IW={tags:[]},J0="https://api.datadoghq.com",kg="/api/v2/series",Ag="/api/v1/distribution_points",EW=`${J0}${kg}`,PW=`${J0}${Ag}`,AW=".v2",kW="zuplo.request.latency",_W="zuplo.request.content_length",xW="zuplo.response.content_length",DS=i((t,e)=>e?`${t}${AW}`:t,"getMetricNameForMode"),OW=i((t,e)=>{try{let n=new URL(t);return n.pathname.replace(/\/+$/,"")===""?(n.pathname=e,n.search="",n.toString()):t}catch{return t}},"normalizeDatadogApiUrl"),MW=i(t=>{try{let e=new URL(t),n=e.pathname.replace(/\/+$/,"");if(n==="")return e.pathname=Ag,e.search="",e.toString();if(n.endsWith(kg)){let o=n.length-kg.length;return e.pathname=n.slice(0,o)+Ag,e.search="",e.toString()}return e.pathname=Ag,e.search="",e.toString()}catch{}return PW},"getDefaultDistributionUrl"),LW=i(t=>[...t].sort(),"normalizeTagsForGrouping"),zS=class extends so{constructor(n){super();this.options=n;pe("metrics.datadog")}options;static{i(this,"DataDogMetricsPlugin")}#e;getTransport(){return this.#e??=new jS(this.options),this.#e}static setContext(n,o){let r=$S.get(n);r||(r=IW);let s=Object.assign({...r},o);$S.set(n,s)}},jS=class{static{i(this,"DataDogMetricsTransport")}#e;#t;#o;#n;#i;#r;#s;#a=void 0;#c=void 0;constructor(e){this.#e=e.apiKey,this.#t=OW(e.url??EW,kg),this.#o=MW(this.#t),this.#s=e.metricMode==="distributionMode",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#r=e.include??{},this.#i=e.tags??[]}#l(e){return this.#a===void 0&&(this.#a=new Be({name:"data-dog-metrics-transport",msDelay:10,dispatchFunction:this.dispatchSeriesFunction,systemLogger:de.getLogger(e)})),this.#a}#p(e){return this.#c===void 0&&(this.#c=new Be({name:"data-dog-metrics-distribution-transport",msDelay:10,dispatchFunction:this.dispatchDistributionFunction,systemLogger:de.getLogger(e)})),this.#c}#d(e,n,o,r,s){this.#p(e).enqueue({metric:n,timestamp:o,value:r,tags:s})}pushMetrics(e,n){let o=Math.floor(e.timestamp.getTime()/1e3),r=DS(kW,this.#s),s=DS(_W,this.#s),a=DS(xW,this.#s),c=this.#i.concat($S.get(n)?.tags??[]);if(this.#r.country&&c.push(`country:${e.country}`),this.#r.httpMethod&&c.push(`httpMethod:${e.method}`),this.#r.statusCode&&c.push(`statusCode:${e.statusCode}`),this.#r.path){let u=e.systemRouteName||e.routePath;c.push(`path:${u}`)}this.#n.latency&&(this.#s?this.#d(n,r,o,e.durationMs,c):this.#l(n).enqueue({metric:r,type:3,points:[{timestamp:o,value:e.durationMs}],tags:c})),this.#n.requestContentLength&&e.requestContentLength&&(this.#s?this.#d(n,s,o,e.requestContentLength,c):this.#l(n).enqueue({metric:s,type:3,points:[{timestamp:o,value:e.requestContentLength}],tags:c})),this.#n.responseContentLength&&e.responseContentLength&&(this.#s?this.#d(n,a,o,e.responseContentLength,c):this.#l(n).enqueue({metric:a,type:3,points:[{timestamp:o,value:e.responseContentLength}],tags:c})),this.#a&&n.waitUntil(this.#a.waitUntilFlushed()),this.#c&&n.waitUntil(this.#c.waitUntilFlushed())}dispatchSeriesFunction=i(async e=>{if(e.length!==0)try{let n=JSON.stringify({series:e}),o=await V.fetch(this.#t,{method:"POST",body:n,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});o.ok||await Ve({level:"error",messages:["Failed to send metrics to DataDog."]},o)}catch{await Ve({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchSeriesFunction");dispatchDistributionFunction=i(async e=>{if(e.length!==0)try{let n=new Map;e.forEach(s=>{let a=LW(s.tags),c=`${s.metric}:${s.timestamp}:${JSON.stringify(a)}`,u=n.get(c);if(u){u.points[0][1].push(s.value);return}n.set(c,{metric:s.metric,points:[[s.timestamp,[s.value]]],tags:a})});let o=JSON.stringify({series:[...n.values()]}),r=await V.fetch(this.#o,{method:"POST",body:o,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await Ve({level:"error",messages:["Failed to send latency distributions to DataDog."]},r)}catch{await Ve({level:"error",messages:["Failed to connect to DataDog metrics distribution service. Check that the URL is correct."]})}},"dispatchDistributionFunction")};var HS=new he(Symbol("dynatrace-metrics-context")),NW={dimensions:[]},FS=class extends so{constructor(n){super();this.options=n;pe("metrics.dynatrace")}options;static{i(this,"DynatraceMetricsPlugin")}#e;getTransport(){return this.#e??=new GS(this.options),this.#e}static setContext(n,o){let r=HS.get(n);r||(r=NW);let s=Object.assign({...r},o);HS.set(n,s)}},GS=class{static{i(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#o;#n=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,n){this.#n===void 0&&(this.#n=new Be({name:"dynatrace-metrics-transport",msDelay:10,dispatchFunction:this.dispatchFunction,systemLogger:de.getLogger(n)}));let o=Math.floor(e.timestamp.getTime()),r=this.dimensions.concat(HS.get(n)?.dimensions??[]);if(this.#o.country&&r.push(`country="${e.country}"`),this.#o.httpMethod&&r.push(`http_method="${e.method}"`),this.#o.statusCode&&r.push(`status_code="${e.statusCode}"`),this.#o.path){let a=e.systemRouteName||e.routePath;r.push(`path="${a}"`)}let s=r.join(",");this.#t.latency&&this.#n.enqueue(`zuplo.request.latency,${s} ${e.durationMs} ${o}`),this.#t.requestContentLength&&e.requestContentLength&&this.#n.enqueue(`zuplo.request.content_length,${s} ${e.requestContentLength} ${o}`),this.#t.responseContentLength&&e.responseContentLength&&this.#n.enqueue(`zuplo.response.content_length,${s} ${e.responseContentLength} ${o}`),n.waitUntil(this.#n.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let n=e.join(`
264
264
  `),o=await V.fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});o.ok||await Ve({level:"error",messages:["Failed to send metrics to Dynatrace."]},o)}catch{await Ve({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var BS=new he(Symbol("new-relic-metrics-context")),UW={attributes:{}},ZS=class extends so{constructor(n){super();this.options=n;pe("metrics.newrelic")}options;static{i(this,"NewRelicMetricsPlugin")}#e;getTransport(){return this.#e??=new VS(this.options),this.#e}static setContext(n,o){let r=BS.get(n);r||(r=UW);let s=Object.assign({...r},o);BS.set(n,s)}},VS=class{static{i(this,"NewRelicMetricsTransport")}#e;#t;#o;#n;#i;#r=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#o=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#i=e.include??{},this.#n=e.attributes??{service:"zuplo"}}pushMetrics(e,n){this.#r===void 0&&(this.#r=new Be({name:"new-relic-metrics-transport",msDelay:10,dispatchFunction:this.dispatchFunction,systemLogger:de.getLogger(n)}));let o=Math.floor(e.timestamp.getTime()),r={...this.#n,...BS.get(n)?.attributes};if(this.#i.country&&(r.country=e.country),this.#i.httpMethod&&(r.httpMethod=e.method),this.#i.statusCode&&(r.statusCode=e.statusCode.toString()),this.#i.path){let s=e.systemRouteName||e.routePath;r.path=s}this.#o.latency&&this.#r.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:o,attributes:r}),this.#o.requestContentLength&&e.requestContentLength&&this.#r.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:o,attributes:r}),this.#o.responseContentLength&&e.responseContentLength&&this.#r.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:o,attributes:r}),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let n=JSON.stringify([{metrics:e}]),o=await $t({retries:3,retryDelayMs:300,logger:V.console},this.#t,{method:"POST",body:n,headers:{"Content-Type":"application/json","Api-Key":this.#e}});o.ok||await Ve({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${o.status} ${o.statusText}`]},o)}catch(n){await Ve({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct.",`Error: ${n instanceof Error?n.message:String(n)}`]})}},"dispatchFunction")};var JS=new he(Symbol("otel-metrics-context")),qW={attributes:{}},KS=class extends so{constructor(n){super();this.options=n;pe("metrics.otel")}options;static{i(this,"OTelMetricsPlugin")}#e;getTransport(){return this.#e??=new WS(this.options),this.#e}static setContext(n,o){let r=JS.get(n);r||(r=qW);let s=Object.assign({...r},o);JS.set(n,s)}};function DW(t){let e=[];for(let[n,o]of Object.entries(t))o!==void 0&&(typeof o=="string"?e.push({key:n,value:{stringValue:o}}):typeof o=="number"?Number.isInteger(o)?e.push({key:n,value:{intValue:o.toString()}}):e.push({key:n,value:{doubleValue:o}}):typeof o=="boolean"&&e.push({key:n,value:{boolValue:o}}));return e}i(DW,"attributesToOTLP");var WS=class{static{i(this,"OTelMetricsTransport")}#e;#t;#o;#n;#i;#r=void 0;constructor(e){this.#e=e.url,this.#t=e.headers??{},this.#o=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#i=e.include??{},this.#n=e.attributes??{}}pushMetrics(e,n){this.#r===void 0&&(this.#r=new Be({name:"otel-metrics-transport",msDelay:10,dispatchFunction:this.dispatchFunction,systemLogger:de.getLogger(n)}));let o=(e.timestamp.getTime()*1e6).toString(),r={...this.#n},s=JS.get(n)?.attributes??{};if(Object.assign(r,s),this.#i.country&&e.country&&(r["client.geo.country_iso_code"]=e.country),this.#i.httpMethod&&(r["http.request.method"]=e.method),this.#i.statusCode&&(r["http.response.status_code"]=e.statusCode),this.#i.path){let c=e.systemRouteName||e.routePath;r["http.route"]=c}let a=DW(r);this.#o.latency&&this.#r.enqueue({name:"http.server.request.duration",unit:"ms",value:e.durationMs,timeUnixNano:o,attributes:[...a]}),this.#o.requestContentLength&&e.requestContentLength&&this.#r.enqueue({name:"http.server.request.body.size",unit:"By",value:e.requestContentLength,timeUnixNano:o,attributes:[...a]}),this.#o.responseContentLength&&e.responseContentLength&&this.#r.enqueue({name:"http.server.response.body.size",unit:"By",value:e.responseContentLength,timeUnixNano:o,attributes:[...a]}),n.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let n=e.map(a=>({name:a.name,unit:a.unit,gauge:{dataPoints:[{timeUnixNano:a.timeUnixNano,asDouble:a.value,attributes:a.attributes}]}})),r=JSON.stringify({resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:"zuplo",version:"1.0.0"},metrics:n}]}]}),s=await V.fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"application/json",...this.#t}});s.ok||await Ve({level:"error",messages:["Failed to send metrics to OpenTelemetry collector."]},s)}catch{await Ve({level:"error",messages:["Failed to connect to OpenTelemetry metrics service. Check that the URL is correct."]})}},"dispatchFunction")};function _s(t,e,n){let o=t.user,r=He.getId(e)??(typeof o?.configuration?.id=="string"?o.configuration.id:null),s=typeof o?.sub=="string"&&o.sub!==""?o.sub:null,a;try{a=e.route?.path??new URL(t.url).pathname}catch{a=null}return{cacheType:n.cacheType,policyType:n.policyType,policyName:n.policyName,configId:r,consumerSub:s,routePath:a,method:t.method}}i(_s,"buildCacheOperationBase");function K0(t){return{cacheType:t.cacheType,policyType:t.policyType,policyName:t.policyName,outcome:t.outcome,reason:t.reason??null,latencyMs:t.latencyMs??null,similarity:t.similarity??null,configId:t.configId??null,consumerSub:t.consumerSub??null,routePath:t.routePath??null,method:t.method??null,statusCode:t.statusCode??null,savedPromptTokens:t.savedPromptTokens??null,savedCompletionTokens:t.savedCompletionTokens??null}}i(K0,"buildCacheOperationMetadata");function Et(t,e){try{t.analyticsContext.addAnalyticsEvent(1,N.CACHE_OPERATION,K0(e),"count")}catch(n){de.getLogger(t).error(n,"Error emitting cache_operation analytics event")}}i(Et,"emitCacheOperation");function Zo(t,e){try{if(!_.instance.remoteLogURL){de.getLogger(t).debug("Remote log URL is not configured, skipping cache_operation analytics");return}t.analyticsContext.addAnalyticsEvent(1,N.CACHE_OPERATION,K0(e),"count");let n=t.analyticsContext.flushAnalyticsEvents();No()?.pushEvents(n,t)}catch(n){de.getLogger(t).error(n,"Error emitting late cache_operation analytics event")}}i(Zo,"emitCacheOperationLate");var YS=class{static{i(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,pe("audit-logs.datastax")}#e;writeLogBatch=i(async e=>{await Promise.allSettled(e.map(async n=>{await V.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(n)})}))},"writeLogBatch")};var QS=class extends zt{static{i(this,"AuditLogPlugin")}constructor(e,n){super(),this.#e=e,this.#t=n,pe("audit-logs")}#e;#t;async initialize(e){new XS(e,this.#e,this.#t)}},W0=i(t=>{let e={};return t.forEach((n,o)=>{e[o]=n}),e},"serializableHeaders"),$W={requestFilter:i(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},XS=class{static{i(this,"AuditPluginImpl")}constructor(e,n,o){this.#t=n;let r={...$W};o?.requestFilter&&(r.requestFilter=o.requestFilter),o?.include?.request&&Object.assign(r,o.include.request),o?.include?.response&&Object.assign(r,o.include.response),this.#e=r,e.addRequestHook(this.#r),this.#o=new Be({name:"audit-log",msDelay:10,dispatchFunction:this.#n})}#e;#t;#o;#n=i(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#i=i(async(e,n,o,r,s,a)=>{try{let c={timestamp:r,durationMs:s,routePath:o.route.path,requestId:o.requestId,userSub:a,request:{url:n.url,method:n.method,headers:this.#e.include?.request?.headers?W0(n.headers):void 0,body:this.#e.include?.request?.body?await n.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?W0(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#o.enqueue(c),o.waitUntil(this.#o.waitUntilFlushed())}catch(c){o.log.error(c)}},"#asyncPrepLogs");#r=i(async(e,n)=>{try{if(!await this.#e.requestFilter(e,n))return e;let r=new Date,s=Date.now(),a=e.clone();return n.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#i(d,a,n,r,l-s,u.user?.sub).catch(f=>{n.log.error(f)});n.waitUntil(p)}),e}catch(o){return n.log.error(o),e}},"#auditHook")};import{importJWK as zW,SignJWT as jW}from"jose";var Y0="EdDSA",Q0=["EdDSA","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],X0=!1,lp=class t extends zt{static{i(this,"JwtServicePlugin")}#e;static#t=void 0;static#o=void 0;static#n=void 0;static#i=void 0;static#r=Y0;static async signJwt({audience:e,subject:n,expiresIn:o=t.#n,...r}){if(!t.#o){let u=_.instance.authPrivateKey;if(!u)throw new v("JwtServicePlugin - Cannot sign JWT. Private key configured for this Zuplo project.");try{t.#o=await zW(JSON.parse(u),t.#r)}catch(l){throw new v(`JwtServicePlugin - Failed to import private key. Ensure it is a valid JWK format and matches the configured algorithm "${t.#r}".`,{cause:l})}}if(!t.#t)throw new v("JwtServicePlugin - Cannot sign JWT. The issuer URL is not configured. Ensure the plugin is initialized.");if(!t.#n)throw new v("JwtServicePlugin - Cannot sign JWT. The token expiration is not configured. Ensure the plugin is initialized.");let s=o??t.#n,a=typeof s=="number"?new Date(Date.now()+s*1e3):s,c=new jW(r).setProtectedHeader({alg:t.#r}).setIssuer(t.#t).setIssuedAt(new Date).setExpirationTime(a);return e&&c.setAudience(e),n&&c.setSubject(n),await c.sign(t.#o)}constructor(e){if(super(),X0)throw new v("JwtServicePlugin - Only one instance of JwtServicePlugin can be created. Ensure you are not creating multiple instances in your code.");let n=e?.algorithm??Y0;if(!Q0.includes(n))throw new v(`JwtServicePlugin - Unsupported signing algorithm "${n}". Supported algorithms: ${Q0.join(", ")}.`);pe("plugin.jwt-service"),X0=!0,this.#e=e?.basePath??"/__zuplo/issuer",t.#n=e?.expiresIn??"1h",t.#r=n,this.#e.endsWith("/")&&(this.#e=this.#e.slice(0,-1))}registerRoutes({runtimeSettings:e,router:n}){let o=e.api.urls?.defaultUrl;if(!o)throw new v("JwtServicePlugin - Cannot determine issuer URL. Ensure the API is properly configured.");let r=new URL(this.#e,o).toString();t.#t=r,n.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/openid-configuration`,handler:i(async()=>{let s={issuer:r,jwks_uri:`${r}/.well-known/jwks.json`,id_token_signing_alg_values_supported:[t.#r],subject_types_supported:["public"]};return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")}),n.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/jwks.json`,handler:i(async()=>{if(!t.#i)try{let s=_.instance.authPublicKey;if(!s)throw new v("JwtServicePlugin - Public key is not configured for this Zuplo project");let a={keys:[JSON.parse(s)]};t.#i=JSON.stringify(a)}catch(s){throw new v("JwtServicePlugin - Failed to export public key as JWK.",{cause:s})}return new Response(t.#i,{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")})}};var xc=class extends zt{static{i(this,"OAuthProtectedResourceBasePlugin")}createOauthProtectedResourceHandler(){return async(e,n)=>{let o=new URL(e.url),r=e.params.resourcePath,s=r?`${o.origin}/${r}`:o.origin,a;try{a=await this.getMetadataOptions(e,n)}catch(u){return n.log.warn({err:u},"Failed to get metadata options for OAuth protected resource"),new Response("Not Found",{status:404})}let c={resource:s,authorization_servers:a.authorizationServers,resource_name:a.resourceName,scopes_supported:a.scopesSupported};return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}}registerRoutes(e){let{router:n}=e;n.addPluginRoute({methods:["GET"],path:"/.well-known/oauth-protected-resource/:resourcePath*",handler:this.createOauthProtectedResourceHandler(),corsPolicy:"anything-goes",processors:[pa]})}};var dp=class extends xc{static{i(this,"McpGatewayOAuthProtectedResourcePlugin")}authServerBaseUrl;constructor(e){super(),this.authServerBaseUrl=e}async getMetadataOptions(e,n){let r=e.params.resourcePath.split("/").pop();if(!r)throw new Error("Failed to extract resource from path");return{authorizationServers:[`${this.authServerBaseUrl}/${r}`],resource:r,resourceName:"Zuplo MCP Gateway"}}};var HW=/^[\x21\x23-\x5B\x5D-\x7E]+$/,eC="OAuthProtectedResourcePlugin option 'scopesSupported'";function FW(t){if(typeof t=="bigint")return`${t}n`;try{let e=JSON.stringify(t);if(e!==void 0)return e}catch{}return`a value of type ${typeof t}`}i(FW,"describeInvalidScope");function GW(t){if(t!==void 0){if(!Array.isArray(t))throw new v(`${eC} must be an array of scope strings such as ["mcp:access"], received ${typeof t}.`);if(t.length===0)throw new v(`${eC} is an empty array. Omit the option to advertise no scopes, or list at least one scope, for example ["mcp:access"].`);for(let[e,n]of t.entries())if(typeof n!="string"||!HW.test(n))throw new v(`${eC}[${e}] is ${FW(n)}. Each entry must be one OAuth scope token (RFC 6749 \xA73.3): printable ASCII with no spaces, double quotes, or backslashes. Use one entry per scope, for example ["mcp:access", "offline_access"].`);return Object.freeze([...t])}}i(GW,"parseScopesSupported");var pp=class extends xc{static{i(this,"OAuthProtectedResourcePlugin")}options;scopes;constructor(e){super(),this.options=e,this.scopes=GW(e.scopesSupported)}get scopesSupported(){return this.scopes}async getMetadataOptions(e,n){return{authorizationServers:this.options.authorizationServers,resourceName:this.options.resourceName,scopesSupported:this.scopes}}};var tC={None:0,JsonEscape:1},mp=class{constructor(e,n={}){this.stream=e;this.options=n;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}stream;options;static{i(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),n=[];try{for(;;){let{done:c,value:u}=await e.read();if(c)break;n.push(u)}}finally{e.releaseLock()}let o=n.reduce((c,u)=>c+u.length,0),r=new Uint8Array(o),s=0;for(let c of n)r.set(c,s),s+=c.length;let a=new TextDecoder().decode(r);return this.options.base64Encode&&(a=btoa(a)),a}},_g=class{static{i(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,n=>{switch(n){case"\\":return"\\\\";case'"':return'\\"';case`
265
265
  `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return n}})}async toString(){let n=this.getStream().getReader(),o=new TextDecoder,r="";for(;;){let{done:s,value:a}=await n.read();if(s)break;r+=o.decode(a,{stream:!0})}return r+=o.decode(),r}getStream(){let e=this.template,n=this.flags,o=new TextEncoder,r=new Map;for(let h of this.tokens)r.set(h.getSafeToken(),h);let s=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],c=0,u;for(;(u=s.exec(e))!==null;){if(u.index>c&&a.push({type:"literal",value:e.substring(c,u.index)}),u[1]){let h=r.get(u[1]);h?a.push({type:"token",token:h,isQuoted:!0}):a.push({type:"literal",value:u[0]})}else if(u[2]){let h=r.get(u[2]);h?a.push({type:"token",token:h,isQuoted:!1}):a.push({type:"literal",value:u[0]})}c=s.lastIndex}c<e.length&&a.push({type:"literal",value:e.substring(c)});function l(){let h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",y=new Uint8Array(0);return new TransformStream({transform(S,R){let C=new Uint8Array(y.length+S.length);C.set(y),C.set(S,y.length);let T=C.length%3,I=C.length-T;if(I>0){let P=C.subarray(0,I),A="";for(let M=0;M<P.length;M+=3){let z=P[M],$=P[M+1],F=P[M+2],K=z<<16|$<<8|F;A+=h[K>>18&63],A+=h[K>>12&63],A+=h[K>>6&63],A+=h[K&63]}R.enqueue(A)}y=C.subarray(C.length-T)},flush(S){if(y.length>0){let R=y[0],C=y.length>1?y[1]:0,T=R<<16|C<<8,I="";I+=h[T>>18&63],I+=h[T>>12&63],I+=y.length===2?h[T>>6&63]:"=",I+="=",S.enqueue(I)}}})}i(l,"createBase64EncodeTransformStream");function d(){let h=new TextDecoder;return new TransformStream({transform(y,S){let R=new Uint8Array(y.byteLength);R.set(y),S.enqueue(h.decode(R,{stream:!0}))},flush(y){let S=h.decode();S.length>0&&y.enqueue(S)}})}i(d,"createTextDecodeTransformStream");function p(){return new TransformStream({transform(h,y){let S=h.replace(/[\\\"\n\r\t\f\b]/g,R=>{switch(R){case"\\":return"\\\\";case'"':return'\\"';case`
@@ -410,5 +410,5 @@ Signature verification is impossible without access to the original signed mater
410
410
  `);let b=new T("!xml"),E=b,x="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;let L=new I(this.options.processEntities);for(let k=0;k<g.length;k++)if(g[k]==="<")if(g[k+1]==="/"){let W=Sn(g,">",k,"Closing Tag is not closed."),j=g.substring(k+2,W).trim();if(this.options.removeNSPrefix){let Ee=j.indexOf(":");Ee!==-1&&(j=j.substr(Ee+1))}j=Zn(this.options.transformTagName,j,"",this.options).tagName,E&&(x=this.saveTextToParentTag(x,E,this.matcher));let Re=this.matcher.getCurrentTag();if(j&&this.options.unpairedTags.indexOf(j)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${j}>`);Re&&this.options.unpairedTags.indexOf(Re)!==-1&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,E=this.tagsNodeStack.pop(),x="",k=W}else if(g[k+1]==="?"){let W=On(g,k,!1,"?>");if(!W)throw new Error("Pi Tag is not closed.");if(x=this.saveTextToParentTag(x,E,this.matcher),!(this.options.ignoreDeclaration&&W.tagName==="?xml"||this.options.ignorePiTags)){let j=new T(W.tagName);j.add(this.options.textNodeName,""),W.tagName!==W.tagExp&&W.attrExpPresent&&(j[":@"]=this.buildAttributesMap(W.tagExp,this.matcher,W.tagName)),this.addChild(E,j,this.matcher,k)}k=W.closeIndex+1}else if(g.substr(k+1,3)==="!--"){let W=Sn(g,"-->",k+4,"Comment is not closed.");if(this.options.commentPropName){let j=g.substring(k+4,W-2);x=this.saveTextToParentTag(x,E,this.matcher),E.add(this.options.commentPropName,[{[this.options.textNodeName]:j}])}k=W}else if(g.substr(k+1,2)==="!D"){let W=L.readDocType(g,k);this.docTypeEntities=W.entities,k=W.i}else if(g.substr(k+1,2)==="!["){let W=Sn(g,"]]>",k,"CDATA is not closed.")-2,j=g.substring(k+9,W);x=this.saveTextToParentTag(x,E,this.matcher);let Re=this.parseTextData(j,E.tagname,this.matcher,!0,!1,!0,!0);Re==null&&(Re=""),this.options.cdataPropName?E.add(this.options.cdataPropName,[{[this.options.textNodeName]:j}]):E.add(this.options.textNodeName,Re),k=W+2}else{let W=On(g,k,this.options.removeNSPrefix);if(!W){let sn=g.substring(Math.max(0,k-50),Math.min(g.length,k+50));throw new Error(`readTagExp returned undefined at position ${k}. Context: "${sn}"`)}let j=W.tagName,Re=W.rawTagName,Ee=W.tagExp,je=W.attrExpPresent,Rt=W.closeIndex;if({tagName:j,tagExp:Ee}=Zn(this.options.transformTagName,j,Ee,this.options),this.options.strictReservedNames&&(j===this.options.commentPropName||j===this.options.cdataPropName||j===this.options.textNodeName||j===this.options.attributesGroupName))throw new Error(`Invalid tag name: ${j}`);E&&x&&E.tagname!=="!xml"&&(x=this.saveTextToParentTag(x,E,this.matcher,!1));let gn=E;gn&&this.options.unpairedTags.indexOf(gn.tagname)!==-1&&(E=this.tagsNodeStack.pop(),this.matcher.pop());let Br=!1;Ee.length>0&&Ee.lastIndexOf("/")===Ee.length-1&&(Br=!0,j[j.length-1]==="/"?(j=j.substr(0,j.length-1),Ee=j):Ee=Ee.substr(0,Ee.length-1),je=j!==Ee);let wt=null,Ln={},Zr;Zr=ne(Re),j!==b.tagname&&this.matcher.push(j,{},Zr),j!==Ee&&je&&(wt=this.buildAttributesMap(Ee,this.matcher,j),wt&&(Ln=ie(wt,this.options))),j!==b.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode(this.stopNodeExpressions,this.matcher));let vn=k;if(this.isCurrentNodeStopNode){let sn="";if(Br)k=W.closeIndex;else if(this.options.unpairedTags.indexOf(j)!==-1)k=W.closeIndex;else{let Jr=this.readStopNodeData(g,Re,Rt+1);if(!Jr)throw new Error(`Unexpected end of ${Re}`);k=Jr.i,sn=Jr.tagContent}let Vr=new T(j);wt&&(Vr[":@"]=wt),Vr.add(this.options.textNodeName,sn),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(E,Vr,this.matcher,vn)}else{if(Br){({tagName:j,tagExp:Ee}=Zn(this.options.transformTagName,j,Ee,this.options));let sn=new T(j);wt&&(sn[":@"]=wt),this.addChild(E,sn,this.matcher,vn),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(this.options.unpairedTags.indexOf(j)!==-1){let sn=new T(j);wt&&(sn[":@"]=wt),this.addChild(E,sn,this.matcher,vn),this.matcher.pop(),this.isCurrentNodeStopNode=!1,k=W.closeIndex;continue}else{let sn=new T(j);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(E),wt&&(sn[":@"]=wt),this.addChild(E,sn,this.matcher,vn),E=sn}x="",k=Rt}}else x+=g[k];return b.child},"parseXml");function ue(g,b,E,x){this.options.captureMetaData||(x=void 0);let L=this.options.jPath?E.toString():E,k=this.options.updateTag(b.tagname,L,b[":@"]);k===!1||(typeof k=="string"&&(b.tagname=k),g.addChild(b,x))}i(ue,"addChild"),n(ue,"addChild");function le(g,b,E){let x=this.options.processEntities;if(!x||!x.enabled)return g;if(x.allowedTags){let L=this.options.jPath?E.toString():E;if(!(Array.isArray(x.allowedTags)?x.allowedTags.includes(b):x.allowedTags(b,L)))return g}if(x.tagFilter){let L=this.options.jPath?E.toString():E;if(!x.tagFilter(b,L))return g}for(let L of Object.keys(this.docTypeEntities)){let k=this.docTypeEntities[L],ee=g.match(k.regx);if(ee){if(this.entityExpansionCount+=ee.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);let W=g.length;if(g=g.replace(k.regx,k.val),x.maxExpandedLength&&(this.currentExpandedLength+=g.length-W,this.currentExpandedLength>x.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${x.maxExpandedLength}`)}}for(let L of Object.keys(this.lastEntities)){let k=this.lastEntities[L],ee=g.match(k.regex);if(ee&&(this.entityExpansionCount+=ee.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);g=g.replace(k.regex,k.val)}if(g.indexOf("&")===-1)return g;if(this.options.htmlEntities)for(let L of Object.keys(this.htmlEntities)){let k=this.htmlEntities[L],ee=g.match(k.regex);if(ee&&(this.entityExpansionCount+=ee.length,x.maxTotalExpansions&&this.entityExpansionCount>x.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${x.maxTotalExpansions}`);g=g.replace(k.regex,k.val)}return g=g.replace(this.ampEntity.regex,this.ampEntity.val),g}i(le,"replaceEntitiesValue"),n(le,"replaceEntitiesValue");function ke(g,b,E,x){return g&&(x===void 0&&(x=b.child.length===0),g=this.parseTextData(g,b.tagname,E,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,x),g!==void 0&&g!==""&&b.add(this.options.textNodeName,g),g=""),g}i(ke,"saveTextToParentTag"),n(ke,"saveTextToParentTag");function xe(g,b){if(!g||g.length===0)return!1;for(let E=0;E<g.length;E++)if(b.matches(g[E]))return!0;return!1}i(xe,"isItStopNode"),n(xe,"isItStopNode");function q(g,b,E=">"){let x,L="";for(let k=b;k<g.length;k++){let ee=g[k];if(x)ee===x&&(x="");else if(ee==='"'||ee==="'")x=ee;else if(ee===E[0])if(E[1]){if(g[k+1]===E[1])return{data:L,index:k}}else return{data:L,index:k};else ee===" "&&(ee=" ");L+=ee}}i(q,"tagExpWithClosingIndex"),n(q,"tagExpWithClosingIndex");function Sn(g,b,E,x){let L=g.indexOf(b,E);if(L===-1)throw new Error(x);return L+b.length-1}i(Sn,"findClosingIndex"),n(Sn,"findClosingIndex");function On(g,b,E,x=">"){let L=q(g,b+1,x);if(!L)return;let k=L.data,ee=L.index,W=k.search(/\s/),j=k,Re=!0;W!==-1&&(j=k.substring(0,W),k=k.substring(W+1).trimStart());let Ee=j;if(E){let je=j.indexOf(":");je!==-1&&(j=j.substr(je+1),Re=j!==L.data.substr(je+1))}return{tagName:j,tagExp:k,closeIndex:ee,attrExpPresent:Re,rawTagName:Ee}}i(On,"readTagExp"),n(On,"readTagExp");function Po(g,b,E){let x=E,L=1;for(;E<g.length;E++)if(g[E]==="<")if(g[E+1]==="/"){let k=Sn(g,">",E,`${b} is not closed`);if(g.substring(E+2,k).trim()===b&&(L--,L===0))return{tagContent:g.substring(x,E),i:k};E=k}else if(g[E+1]==="?")E=Sn(g,"?>",E+1,"StopNode is not closed.");else if(g.substr(E+1,3)==="!--")E=Sn(g,"-->",E+3,"StopNode is not closed.");else if(g.substr(E+1,2)==="![")E=Sn(g,"]]>",E,"StopNode is not closed.")-2;else{let k=On(g,E,">");k&&((k&&k.tagName)===b&&k.tagExp[k.tagExp.length-1]!=="/"&&L++,E=k.closeIndex)}}i(Po,"readStopNodeData"),n(Po,"readStopNodeData");function no(g,b,E){if(b&&typeof g=="string"){let x=g.trim();return x==="true"?!0:x==="false"?!1:vt(g,E)}else return l(g)?g:""}i(no,"parseValue"),n(no,"parseValue");function tr(g,b,E){let x=Number.parseInt(g,b);return x>=0&&x<=1114111?String.fromCodePoint(x):E+g+";"}i(tr,"fromCodePoint"),n(tr,"fromCodePoint");function Zn(g,b,E,x){if(g){let L=g(b);E===b&&(E=L),b=L}return b=nr(b,x),{tagName:b,tagExp:E}}i(Zn,"transformTagName"),n(Zn,"transformTagName");function nr(g,b){if(p.includes(g))throw new Error(`[SECURITY] Invalid name: "${g}" is a reserved JavaScript keyword that could cause prototype pollution`);return d.includes(g)?b.onDangerousProperty(g):g}i(nr,"sanitizeName"),n(nr,"sanitizeName");var Cn=T.getMetaDataSymbol();function or(g,b){if(!g||typeof g!="object")return{};if(!b)return g;let E={};for(let x in g)if(x.startsWith(b)){let L=x.substring(b.length);E[L]=g[x]}else E[x]=g[x];return E}i(or,"stripAttributePrefix"),n(or,"stripAttributePrefix");function rr(g,b,E){return fo(g,b,E)}i(rr,"prettify"),n(rr,"prettify");function fo(g,b,E){let x,L={};for(let k=0;k<g.length;k++){let ee=g[k],W=Dr(ee);if(W!==void 0&&W!==b.textNodeName){let j=or(ee[":@"]||{},b.attributeNamePrefix);E.push(W,j)}if(W===b.textNodeName)x===void 0?x=ee[W]:x+=""+ee[W];else{if(W===void 0)continue;if(ee[W]){let j=fo(ee[W],b,E),Re=Ao(j,b);if(ee[":@"]?ir(j,ee[":@"],E,b):Object.keys(j).length===1&&j[b.textNodeName]!==void 0&&!b.alwaysCreateTextNode?j=j[b.textNodeName]:Object.keys(j).length===0&&(b.alwaysCreateTextNode?j[b.textNodeName]="":j=""),ee[Cn]!==void 0&&typeof j=="object"&&j!==null&&(j[Cn]=ee[Cn]),L[W]!==void 0&&Object.prototype.hasOwnProperty.call(L,W))Array.isArray(L[W])||(L[W]=[L[W]]),L[W].push(j);else{let Ee=b.jPath?E.toString():E;b.isArray(W,Ee,Re)?L[W]=[j]:L[W]=j}W!==void 0&&W!==b.textNodeName&&E.pop()}}}return typeof x=="string"?x.length>0&&(L[b.textNodeName]=x):x!==void 0&&(L[b.textNodeName]=x),L}i(fo,"compress"),n(fo,"compress");function Dr(g){let b=Object.keys(g);for(let E=0;E<b.length;E++){let x=b[E];if(x!==":@")return x}}i(Dr,"propName"),n(Dr,"propName");function ir(g,b,E,x){if(b){let L=Object.keys(b),k=L.length;for(let ee=0;ee<k;ee++){let W=L[ee],j=W.startsWith(x.attributeNamePrefix)?W.substring(x.attributeNamePrefix.length):W,Re=x.jPath?E.toString()+"."+j:E;x.isArray(W,Re,!0,!0)?g[W]=[b[W]]:g[W]=b[W]}}}i(ir,"assignAttributes"),n(ir,"assignAttributes");function Ao(g,b){let{textNodeName:E}=b,x=Object.keys(g).length;return!!(x===0||x===1&&(g[E]||typeof g[E]=="boolean"||g[E]===0))}i(Ao,"isLeafTag"),n(Ao,"isLeafTag");var $r={allowBooleanAttributes:!1,unpairedTags:[]};function sr(g,b){b=Object.assign({},$r,b);let E=[],x=!1,L=!1;g[0]==="\uFEFF"&&(g=g.substr(1));for(let k=0;k<g.length;k++)if(g[k]==="<"&&g[k+1]==="?"){if(k+=2,k=Yt(g,k),k.err)return k}else if(g[k]==="<"){let ee=k;if(k++,g[k]==="!"){k=ar(g,k);continue}else{let W=!1;g[k]==="/"&&(W=!0,k++);let j="";for(;k<g.length&&g[k]!==">"&&g[k]!==" "&&g[k]!==" "&&g[k]!==`
411
411
  `&&g[k]!=="\r";k++)j+=g[k];if(j=j.trim(),j[j.length-1]==="/"&&(j=j.substring(0,j.length-1),k--),!_i(j)){let je;return j.trim().length===0?je="Invalid space after '<'.":je="Tag '"+j+"' is an invalid name.",ut("InvalidTag",je,Dt(g,k))}let Re=jr(g,k);if(Re===!1)return ut("InvalidAttr","Attributes for '"+j+"' have open quote.",Dt(g,k));let Ee=Re.value;if(k=Re.index,Ee[Ee.length-1]==="/"){let je=k-Ee.length;Ee=Ee.substring(0,Ee.length-1);let Rt=cr(Ee,b);if(Rt===!0)x=!0;else return ut(Rt.err.code,Rt.err.msg,Dt(g,je+Rt.err.line))}else if(W)if(Re.tagClosed){if(Ee.trim().length>0)return ut("InvalidTag","Closing tag '"+j+"' can't have attributes or invalid starting.",Dt(g,ee));if(E.length===0)return ut("InvalidTag","Closing tag '"+j+"' has not been opened.",Dt(g,ee));{let je=E.pop();if(j!==je.tagName){let Rt=Dt(g,je.tagStartPos);return ut("InvalidTag","Expected closing tag '"+je.tagName+"' (opened in line "+Rt.line+", col "+Rt.col+") instead of closing tag '"+j+"'.",Dt(g,ee))}E.length==0&&(L=!0)}}else return ut("InvalidTag","Closing tag '"+j+"' doesn't have proper closing.",Dt(g,k));else{let je=cr(Ee,b);if(je!==!0)return ut(je.err.code,je.err.msg,Dt(g,k-Ee.length+je.err.line));if(L===!0)return ut("InvalidXml","Multiple possible root nodes found.",Dt(g,k));b.unpairedTags.indexOf(j)!==-1||E.push({tagName:j,tagStartPos:ee}),x=!0}for(k++;k<g.length;k++)if(g[k]==="<")if(g[k+1]==="!"){k++,k=ar(g,k);continue}else if(g[k+1]==="?"){if(k=Yt(g,++k),k.err)return k}else break;else if(g[k]==="&"){let je=Fr(g,k);if(je==-1)return ut("InvalidChar","char '&' is not expected.",Dt(g,k));k=je}else if(L===!0&&!ko(g[k]))return ut("InvalidXml","Extra text at the end",Dt(g,k));g[k]==="<"&&k--}}else{if(ko(g[k]))continue;return ut("InvalidChar","char '"+g[k]+"' is not expected.",Dt(g,k))}if(x){if(E.length==1)return ut("InvalidTag","Unclosed tag '"+E[0].tagName+"'.",Dt(g,E[0].tagStartPos));if(E.length>0)return ut("InvalidXml","Invalid '"+JSON.stringify(E.map(k=>k.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return ut("InvalidXml","Start tag expected.",1);return!0}i(sr,"validate"),n(sr,"validate");function ko(g){return g===" "||g===" "||g===`
412
412
  `||g==="\r"}i(ko,"isWhiteSpace"),n(ko,"isWhiteSpace");function Yt(g,b){let E=b;for(;b<g.length;b++)if(g[b]=="?"||g[b]==" "){let x=g.substr(E,b-E);if(b>5&&x==="xml")return ut("InvalidXml","XML declaration allowed only at the start of the document.",Dt(g,b));if(g[b]=="?"&&g[b+1]==">"){b++;break}else continue}return b}i(Yt,"readPI"),n(Yt,"readPI");function ar(g,b){if(g.length>b+5&&g[b+1]==="-"&&g[b+2]==="-"){for(b+=3;b<g.length;b++)if(g[b]==="-"&&g[b+1]==="-"&&g[b+2]===">"){b+=2;break}}else if(g.length>b+8&&g[b+1]==="D"&&g[b+2]==="O"&&g[b+3]==="C"&&g[b+4]==="T"&&g[b+5]==="Y"&&g[b+6]==="P"&&g[b+7]==="E"){let E=1;for(b+=8;b<g.length;b++)if(g[b]==="<")E++;else if(g[b]===">"&&(E--,E===0))break}else if(g.length>b+9&&g[b+1]==="["&&g[b+2]==="C"&&g[b+3]==="D"&&g[b+4]==="A"&&g[b+5]==="T"&&g[b+6]==="A"&&g[b+7]==="["){for(b+=8;b<g.length;b++)if(g[b]==="]"&&g[b+1]==="]"&&g[b+2]===">"){b+=2;break}}return b}i(ar,"readCommentAndCDATA"),n(ar,"readCommentAndCDATA");var Bs='"',zr="'";function jr(g,b){let E="",x="",L=!1;for(;b<g.length;b++){if(g[b]===Bs||g[b]===zr)x===""?x=g[b]:x!==g[b]||(x="");else if(g[b]===">"&&x===""){L=!0;break}E+=g[b]}return x!==""?!1:{value:E,index:b,tagClosed:L}}i(jr,"readAttributeStr"),n(jr,"readAttributeStr");var ki=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function cr(g,b){let E=c(g,ki),x={};for(let L=0;L<E.length;L++){if(E[L][1].length===0)return ut("InvalidAttr","Attribute '"+E[L][2]+"' has no space in starting.",Mn(E[L]));if(E[L][3]!==void 0&&E[L][4]===void 0)return ut("InvalidAttr","Attribute '"+E[L][2]+"' is without value.",Mn(E[L]));if(E[L][3]===void 0&&!b.allowBooleanAttributes)return ut("InvalidAttr","boolean attribute '"+E[L][2]+"' is not allowed.",Mn(E[L]));let k=E[L][2];if(!Gr(k))return ut("InvalidAttr","Attribute '"+k+"' is an invalid name.",Mn(E[L]));if(!Object.prototype.hasOwnProperty.call(x,k))x[k]=1;else return ut("InvalidAttr","Attribute '"+k+"' is repeated.",Mn(E[L]))}return!0}i(cr,"validateAttributeString"),n(cr,"validateAttributeString");function Hr(g,b){let E=/\d/;for(g[b]==="x"&&(b++,E=/[\da-fA-F]/);b<g.length;b++){if(g[b]===";")return b;if(!g[b].match(E))break}return-1}i(Hr,"validateNumberAmpersand"),n(Hr,"validateNumberAmpersand");function Fr(g,b){if(b++,g[b]===";")return-1;if(g[b]==="#")return b++,Hr(g,b);let E=0;for(;b<g.length;b++,E++)if(!(g[b].match(/\w/)&&E<20)){if(g[b]===";")break;return-1}return b}i(Fr,"validateAmpersand"),n(Fr,"validateAmpersand");function ut(g,b,E){return{err:{code:g,msg:b,line:E.line||E,col:E.col}}}i(ut,"getErrorObject"),n(ut,"getErrorObject");function Gr(g){return u(g)}i(Gr,"validateAttrName"),n(Gr,"validateAttrName");function _i(g){return u(g)}i(_i,"validateTagName"),n(_i,"validateTagName");function Dt(g,b){let E=g.substring(0,b).split(/\r?\n/);return{line:E.length,col:E[E.length-1].length+1}}i(Dt,"getLineNumberForPosition"),n(Dt,"getLineNumberForPosition");function Mn(g){return g.startIndex+g[1].length}i(Mn,"getPositionFromMatch"),n(Mn,"getPositionFromMatch");var xi=class{static{i(this,"XMLParser")}static{n(this,"XMLParser")}constructor(g){this.externalEntities={},this.options=R(g)}parse(g,b){if(typeof g!="string"&&g.toString)g=g.toString();else if(typeof g!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(b){b===!0&&(b={});let L=sr(g,b);if(L!==!0)throw Error(`${L.err.msg}:${L.err.line}:${L.err.col}`)}let E=new be(this.options);E.addExternalEntities(this.externalEntities);let x=E.parseXml(g);return this.options.preserveOrder||x===void 0?x:rr(x,this.options,E.matcher)}addEntity(g,b){if(b.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(g.indexOf("&")!==-1||g.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(b==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[g]=b}static getMetaDataSymbol(){return T.getMetaDataSymbol()}};return new xi(t)},"getXmlParser");var QI=class extends ho{static{i(this,"XmlToJsonOutboundPolicy")}static policyType="xml-to-json";parser;parseOnStatusCodes;constructor(e,n){let o=lo(e,["textNodeName"]);super(o,n),Ke(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=o.parseOnStatusCodes?Uo(o.parseOnStatusCodes):void 0,this.parser=iH({removeNSPrefix:o?.removeNSPrefix??!0,ignorePiTags:o?.ignoreProcessingInstructions??!0,ignoreDeclaration:o?.ignoreDeclarations??!0,ignoreAttributes:o?.ignoreAttributes??!0,stopNodes:o?.stopNodes??[],attributeNamePrefix:o?.attributeNamePrefix??"@_",textNodeName:o?.textNodeName??"#text",trimValues:o?.trimValues??!0,processEntities:{enabled:!0,maxTotalExpansions:1/0,maxEntityCount:1e3}})}async handler(e,n,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let r;try{let c=await e.text();r=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(u,c),new H(u)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:s})}};var XI=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,n){if(this.services.get(e))throw new $e(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,n)}getService(e){return this.services.get(e)}};var eE=class{static{i(this,"ApiKeyConsumerClient")}bucketId;cacheDurationSeconds;cacheNamePromise;constructor(e){this.bucketId=e?.bucketId,this.cacheDurationSeconds=e?.cacheDurationSeconds??60}getCacheName(e){return this.cacheNamePromise||(this.cacheNamePromise=Xe("zuplo-get-consumer",{bucketId:e})),this.cacheNamePromise}async get(e){pe("utility.get-consumer");let n=Qi(),o=this.bucketId??et.ZUPLO_SERVICE_BUCKET_ID;if(!o)throw new v("ApiKeyConsumerClient - no bucketId provided and no default bucket is configured for this environment. Pass `bucketId` explicitly (find it in the Zuplo portal under Settings > API Key Buckets).");if(!o.startsWith("bckt_"))throw new v(`ApiKeyConsumerClient - bucketId "${o}" is not a valid bucket id. Bucket ids start with "bckt_" (e.g. "bckt_2HaK3odRyJle6NJSu8mzNKBC30BYxllxL"); a bucket name (e.g. "zprj-...-working-copy") is not accepted here. Find the bucket id in the Zuplo portal under Settings > API Key Buckets.`);if(!e||e.trim()==="")throw new v("ApiKeyConsumerClient.get - consumerId is required and cannot be empty");let r=await this.getCacheName(o),s=new tt(r,n);if(this.cacheDurationSeconds>0){let l=await s.get(e);if(l)return l}let a=`/v2/key-auth/${encodeURIComponent(o)}/consumers/${encodeURIComponent(e)}`,c=await fb(a),u={id:c.id,name:c.name,createdOn:c.createdOn,updatedOn:c.updatedOn};return c.description!==void 0&&(u.description=c.description),c.metadata!==void 0&&(u.metadata=c.metadata),this.cacheDurationSeconds>0&&s.put(e,u,this.cacheDurationSeconds),u}};var sH=10,aH=3e4,fp=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#o;#n;#i;#r;#s={};constructor(e,n){if(typeof n=="number"){let o=n;this.#o=o*1e3,this.#i=aH,this.#n=sH,this.#r=Number.POSITIVE_INFINITY}else{let o=n;this.#o=o.ttlSeconds*1e3,this.#i=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:aH,this.#n=sH,this.#r=o.staleIfErrorSeconds===void 0?Number.POSITIVE_INFINITY:o.staleIfErrorSeconds*1e3}this.#t=e}#a(e){return e.expiry<=new Date}#c(e){let n=this.#s[e];return!(n===void 0||n===0)}#l(e){let n=this.#e.get(e);if(n&&!this.#a(n))return n.data}async get(e){let n=this.#l(e);if(n)return this.#d(e),n;if(this.#c(e))try{await Vee(()=>this.#l(e)!==void 0||!this.#c(e),this.#i+this.#n+1,this.#n);let o=this.#l(e);if(o)return o}catch{}try{return await this.#u(e)}catch(o){let r=this.#e.get(e);if(r&&!this.#p(r))return r.data;throw o}}#p(e){return this.#r===Number.POSITIVE_INFINITY?!1:this.#r<=0?!0:Date.now()>e.expiry.getTime()+this.#r}#d(e){if(!this.#c(e)){let n=this.#u(e);Yr().waitUntil(n)}}async#u(e){try{this.#s[e]===void 0&&(this.#s[e]=0),this.#s[e]++;let n=await Promise.race([this.#t(e),scheduler.wait(this.#i)]);if(n===void 0)throw new v(`BackgroundLoader: Loader timed out after ${this.#i} ms.`);return this.#e.set(e,{data:n,expiry:new Date(Date.now()+this.#o)}),n}finally{this.#s[e]--}}};async function Vee(t,e,n){let o=Date.now();for(;!t();){let r=Date.now()-o;if(r>e)throw new v(`BackgroundLoader: Timeout waiting for an on-going loader after ${r} ms.`);await scheduler.wait(n)}}i(Vee,"waitUntilTrue");import{trace as Jee}from"@opentelemetry/api";var cH,uH=i(()=>(cH??=Jee.getTracer("pipeline"),cH),"tracer"),lH=i(async(t,e,n)=>{let o=ot.instance.routeData.policies,r=fa([t],o);if(r.length===0)throw new H(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let s=r[0],a;try{a=it.getContextExtensions(n)}catch{a=void 0}let c=a?.currentPolicyName;a&&(a.currentPolicyName=s.policyName);try{return await uH().startActiveSpan(`policy:${s.policyName}`,async l=>{try{ma(l,s);let d=await s.handler(e,n);if(d instanceof Request||d instanceof Fe||d instanceof Response)return d instanceof Response||d instanceof Fe?d:new Fe(d);throw new v(`Invalid state - invalid handler on policy '${s.policyName}' invoked via 'invokeInboundPolicy' on route '${n.route.path}'. The result of an inbound policy must be a Response or Request.`)}catch(d){throw Lo(l,d),d}finally{l.end()}})}finally{a&&a.currentPolicyName===s.policyName&&(a.currentPolicyName=c)}},"invokeInboundPolicy"),dH=i(async(t,e,n,o)=>{let r=ot.instance.routeData.policies,s=Pu([t],r);if(s.length===0)throw new H(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=s[0];return await uH().startActiveSpan(`policy:${a.policyName}`,async u=>{try{ma(u,a);let l=await a.handler(e,n,o);if(l instanceof Response)return l;throw new v(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${o.route.path}. The result of an outbound policy must be a Response.`)}catch(l){throw Lo(u,l),l}finally{u.end()}})},"invokeOutboundPolicy");var _t=class{static{i(this,"BaseAnalyticsEvent")}eventId;requestId;timestamp;accountName;projectName;deploymentName;unit;value;constructor(e){this.eventId=e.eventId,this.requestId=e.requestId,this.timestamp=e.timestamp??new Date,this.accountName=e.accountName,this.projectName=e.projectName,this.deploymentName=e.deploymentName,this.unit=e.unit,this.value=e.value}};var zy=class extends _t{static{i(this,"AiGatewayBlockedCountEvent")}eventType=N.AI_GATEWAY_BLOCKED_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var jy=class extends _t{static{i(this,"AiGatewayCostSumEvent")}eventType=N.AI_GATEWAY_COST_SUM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown"),(!this.metadata.costSource||!this.metadata.costSource.trim())&&(this.metadata.costSource="unknown"),(!this.metadata.costAccuracy||!this.metadata.costAccuracy.trim())&&(this.metadata.costAccuracy="unknown")}};var Hy=class extends _t{static{i(this,"AiGatewayFallbackCountEvent")}eventType=N.AI_GATEWAY_FALLBACK_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var Fy=class extends _t{static{i(this,"AiGatewayLatencyHistogramEvent")}eventType=N.AI_GATEWAY_LATENCY_HISTOGRAM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var Gy=class extends _t{static{i(this,"AiGatewayRequestCountEvent")}eventType=N.AI_GATEWAY_REQUEST_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var By=class extends _t{static{i(this,"AiGatewayTokenSumEvent")}eventType=N.AI_GATEWAY_TOKEN_SUM;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.model||!this.metadata.model.trim())&&(this.metadata.model="unknown"),(!this.metadata.provider||!this.metadata.provider.trim())&&(this.metadata.provider="unknown"),(!this.metadata.label||!this.metadata.label.trim())&&(this.metadata.label="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var Zy=class extends _t{static{i(this,"AiGatewayWarningCountEvent")}eventType=N.AI_GATEWAY_WARNING_COUNT;metadata;constructor(e){super(e),this.metadata=e.metadata,(!this.metadata.type||!this.metadata.type.trim())&&(this.metadata.type="unknown"),(!this.metadata.configId||!this.metadata.configId.trim())&&(this.metadata.configId="unknown")}};var Vy=class extends _t{static{i(this,"CacheOperationEvent")}eventType=N.CACHE_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var Jy=class extends _t{static{i(this,"GraphqlOperationEvent")}eventType=N.GRAPHQL_OPERATION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var Ky=class extends _t{static{i(this,"HandlerExecutionEvent")}eventType=N.HANDLER_EXECUTION;metadata;constructor(e){super(e),this.metadata=e.metadata}};var Wy=class extends _t{static{i(this,"McpEvent")}eventType;metadata;constructor(e){super(e),this.eventType=e.eventType,this.metadata=e.metadata}};var yt=i(t=>e=>new Wy({...e,eventType:t}),"buildMcpEvent"),Kee={[N.AI_GATEWAY_COST_SUM]:t=>new jy(t),[N.AI_GATEWAY_REQUEST_COUNT]:t=>new Gy(t),[N.AI_GATEWAY_TOKEN_SUM]:t=>new By(t),[N.AI_GATEWAY_LATENCY_HISTOGRAM]:t=>new Fy(t),[N.AI_GATEWAY_WARNING_COUNT]:t=>new Zy(t),[N.AI_GATEWAY_BLOCKED_COUNT]:t=>new zy(t),[N.AI_GATEWAY_FALLBACK_COUNT]:t=>new Hy(t),[N.MCP_REQUEST_RECEIVED]:yt(N.MCP_REQUEST_RECEIVED),[N.MCP_REQUEST_COMPLETED]:yt(N.MCP_REQUEST_COMPLETED),[N.MCP_REQUEST_REJECTED]:yt(N.MCP_REQUEST_REJECTED),[N.MCP_INITIALIZE_NEGOTIATED]:yt(N.MCP_INITIALIZE_NEGOTIATED),[N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR]:yt(N.MCP_CLIENT_UNSUPPORTED_BEHAVIOR),[N.MCP_CAPABILITY_LISTED]:yt(N.MCP_CAPABILITY_LISTED),[N.MCP_CAPABILITY_INVOKED]:yt(N.MCP_CAPABILITY_INVOKED),[N.MCP_CAPABILITY_COMPLETED]:yt(N.MCP_CAPABILITY_COMPLETED),[N.MCP_CAPABILITY_FAILED]:yt(N.MCP_CAPABILITY_FAILED),[N.MCP_CAPABILITY_CONNECT_REQUIRED]:yt(N.MCP_CAPABILITY_CONNECT_REQUIRED),[N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED]:yt(N.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED),[N.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED]:yt(N.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED),[N.MCP_OAUTH_CLIENT_REGISTERED]:yt(N.MCP_OAUTH_CLIENT_REGISTERED),[N.MCP_OAUTH_AUTHORIZE_STARTED]:yt(N.MCP_OAUTH_AUTHORIZE_STARTED),[N.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP]:yt(N.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP),[N.MCP_OAUTH_TOKEN_ISSUED]:yt(N.MCP_OAUTH_TOKEN_ISSUED),[N.MCP_OAUTH_TOKEN_REFRESH_ROTATED]:yt(N.MCP_OAUTH_TOKEN_REFRESH_ROTATED),[N.MCP_OAUTH_TOKEN_REVOKED]:yt(N.MCP_OAUTH_TOKEN_REVOKED),[N.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED]:yt(N.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED),[N.MCP_AUTH_UPSTREAM_CONNECT_STARTED]:yt(N.MCP_AUTH_UPSTREAM_CONNECT_STARTED),[N.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED]:yt(N.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED),[N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED]:yt(N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED),[N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED]:yt(N.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED),[N.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED]:yt(N.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED),[N.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING]:yt(N.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING),[N.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED]:yt(N.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED),[N.GRAPHQL_OPERATION]:t=>new Jy(t),[N.CACHE_OPERATION]:t=>new Vy(t),[N.HANDLER_EXECUTION]:t=>new Ky(t)};function pH(t,e){let n=Kee[t];return n(e)}i(pH,"createAnalyticsEvent");var Yy=class{static{i(this,"ZuploGatewayAnalyticsContext")}#e;#t;constructor(e){this.#e=[],this.#t=e}addAnalyticsEvent(e,n,o,r,s){let a=this.createAnalyticsEvent(e,n,o,r,s);this.#e.push(a)}flushAnalyticsEvents(){let e=[...this.#e];return this.#e.length=0,e}getAnalyticsEvents(){return[...this.#e]}createAnalyticsEvent(e,n,o,r,s){return pH(n,{eventId:s??crypto.randomUUID(),requestId:this.#t,accountName:_.instance.accountName??"unknown",projectName:_.instance.projectName??"unknown",deploymentName:_.instance.deploymentName??"unknown",metadata:o,unit:r,value:e})}};var Wee="127.0.0.1";function mH(t){let e=_.instance,n=t.get(e.trustedIpHeader)?.trim();return n||(e.isLocalDevelopment?Wee:void 0)}i(mH,"resolveClientIp");function Yee(t){let e={};if(!t)return e;try{let n=t.split(","),o={};return n.forEach(r=>{let[s,a]=r.split("=");s&&a&&(o[s.trim()]=a.trim())}),o.asnum&&(e[um]=o.asnum),o.zip&&(e[lm]=o.zip.split("+")[0]),o.dma&&(e[dm]=o.dma),o.region_code&&(e[pm]=o.region_code),o.timezone&&(e[mm]=o.timezone),o.city&&(e[rm]=o.city),o.continent&&(e[im]=o.continent),o.country_code&&(e[sm]=o.country_code),o.long&&(e[am]=o.long),o.lat&&(e[cm]=o.lat),e}catch{return{}}}i(Yee,"parseEdgeScapeHeader");function fH(t,e){let n=Yee(e);for(let[o,r]of Object.entries(n))t.has(o)||t.set(o,r)}i(fH,"setZpHeadersFromAkamaiEdgeScapeHeader");var Ca=class{static{i(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let n=e.get(OE);if(n){let o=new Headers(e);fH(o,n),this.#e=o}}detachFromRequest(){this.#e=ii(this.#e)}get ip(){return mH(this.#e)}get asn(){try{let e=this.#e.get(um);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(EE)??void 0}get city(){return this.#e.get(aE)??this.#e.get(rm)??void 0}get continent(){return this.#e.get(cE)??this.#e.get(im)??void 0}get country(){return this.#e.get(uE)??this.#e.get(sm)??void 0}get latitude(){return this.#e.get(dE)??this.#e.get(cm)??void 0}get longitude(){return this.#e.get(lE)??this.#e.get(am)??void 0}get colo(){return this.#e.get(PE)??void 0}get postalCode(){return this.#e.get(hE)??this.#e.get(lm)??void 0}get metroCode(){return this.#e.get(fE)??this.#e.get(dm)??void 0}get region(){return this.#e.get(pE)??this.#e.get(AE)??void 0}get regionCode(){return this.#e.get(mE)??this.#e.get(pm)??void 0}get timezone(){return this.#e.get(gE)??this.#e.get(mm)??void 0}get httpProtocol(){return this.#e.get(kE)??void 0}get clientCert(){return this.#e.get(bE)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(RE)??void 0}get clientMtlsVerificationReason(){return this.#e.get(wE)??void 0}get clientCertFingerprintSha256(){return this.#e.get(SE)??void 0}get clientCertNotBefore(){return this.#e.get(CE)??void 0}get clientCertNotAfter(){return this.#e.get(vE)??void 0}get clientCertIssuerDn(){return this.#e.get(TE)??void 0}get clientCertSubjectDn(){return this.#e.get(IE)??void 0}toJSON(){return{ip:this.ip,asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol,clientCert:this.clientCert,clientMtlsVerificationStatus:this.clientMtlsVerificationStatus,clientMtlsVerificationReason:this.clientMtlsVerificationReason,clientCertFingerprintSha256:this.clientCertFingerprintSha256,clientCertNotBefore:this.clientCertNotBefore,clientCertNotAfter:this.clientCertNotAfter,clientCertIssuerDn:this.clientCertIssuerDn,clientCertSubjectDn:this.clientCertSubjectDn}}};function _c(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}i(_c,"createRewriteContext");var yu=class extends Event{static{i(this,"ResponseSendingEvent")}constructor(e,n){super("responseSending"),this.request=e,this.mutableResponse=n}request;mutableResponse},bu=class extends Event{static{i(this,"ResponseSentEvent")}constructor(e,n){super("responseSent"),this.request=e,this.response=n}request;response},Qee=Object.freeze([]),it=class t{static{i(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,n,o=n.url){if(!t.#e.has(e)){let r=new t(n,o);return t.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static findContextExtensions(e){return t.#e.get(e)}static getContextExtensions(e){let n=t.#e.get(e);if(!n)throw new H(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return n}latestRequest;originalRequest;receivedUrl;requestLogProperties=new Map;#t;startDeferringMetrics(){return this.#t?!1:(this.#t=[],!0)}deferMetrics(e){return this.#t?(this.#t.push(e),!0):!1}flushDeferredMetrics(){let e=this.#t??[];this.#t=void 0;let n=[];for(let o of e)try{o()}catch(r){n.push(r)}return n}#o;#n=!1;addPipelineExitHook(e){if(this.#n){try{e(void 0)}catch(n){V.console.error("Error running a late pipeline exit hook",n)}return}this.#o??=[],this.#o.push(e)}runPipelineExitHooks(e){this.#n=!0;let n=this.#o;if(!n)return Qee;this.#o=void 0;let o=[];for(let r of n)try{r(e)}catch(s){o.push(s)}return o}auditLogEventId="";preRequestState;currentPolicyName;preRequestPhase;#i;#r;#s;constructor(e,n){this.latestRequest=e,this.originalRequest=e.originalRequest,this.receivedUrl=n,this.preRequestState=void 0,this.currentPolicyName=void 0,this.preRequestPhase=void 0,this.#i=[],this.#r=[],this.#s=[]}addResponseSendingHook(e){this.#r.push(e)}addResponseSendingFinalHook(e){this.#i.push(e)}addHandlerResponseHook(e){this.#s.push(e)}onResponseSendingFinal=i(async(e,n,o)=>{for(let r of this.#i)await r(e,n,o)},"onResponseSendingFinal");onResponseSending=i(async(e,n,o)=>{let r=e,s=_.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#r)r=await a(s?r:e,n,o);return r},"onResponseSending");onHandlerResponse=i(async(e,n,o)=>{for(let r of this.#s)await r(e,n,o)},"onHandlerResponse")},yf=class extends EventTarget{static{i(this,"SystemZuploContext")}constructor({logger:e,route:n,requestId:o,event:r,custom:s,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=n,this.requestId=o,this.custom=s,this.incomingRequestProperties=a,this.parentContext=c,this.#e=r,this.invokeInboundPolicy=(u,l)=>lH(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>dH(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new Fe(d,l);return ot.instance.handleRequest(p,this,{parentContext:this,routeBinding:Ck(l)})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{it.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{it.getContextExtensions(this).addResponseSendingFinalHook(u)},this.addPreRequestHandler=(u,l)=>{IA(this,it.getContextExtensions(this),u,l)},this.analyticsContext=new Yy(o),Object.freeze(this)}#e;#t=new EventTarget;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addPreRequestHandler;addEventListener(e,n,o){pe("context.addEventListener");let r=i(s=>{try{typeof n=="function"?n(s):n.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");this.#t.addEventListener(e,r,o)}removeEventListener(e,n,o){pe("context.removeEventListener"),this.#t.removeEventListener(e,n,o)}dispatchEvent(e){return this.#t.dispatchEvent(e)}};export{et as a,de as b,ub as c,In as d,Qt as e,lu as f,QH as g,db as h,lt as i,ra as j,XH as k,Hi as l,pb as m,pe as n,fb as o,gb as p,qn as q,lr as r,sa as s,Fi as t,G as u,zt as v,Gi as w,N as x,yb as y,bb as z,Em as A,Be as B,Fn as C,ei as D,fe as E,ho as F,IA as G,Ib as H,_b as I,T1 as J,ni as K,Yy as L,yu as M,bu as N,it as O,ER as P,Jn as Q,H_ as R,Px as S,Ox as T,iV as U,Dx as V,mw as W,fV as X,us as Y,jo as Z,ls as _,Fa as $,yr as aa,br as ba,bi as ca,ds as da,gr as ea,Mt as fa,wh as ga,Ga as ha,Ba as ia,cl as ja,ul as ka,Za as la,fn as ma,Ri as na,Lt as oa,Pn as pa,bn as qa,Va as ra,Nt as sa,Rr as ta,Ja as ua,Ka as va,ps as wa,ms as xa,wi as ya,Sh as za,Wa as Aa,ll as Ba,Ya as Ca,dl as Da,wr as Ea,zo as Fa,wo as Ga,Ch as Ha,vh as Ia,pl as Ja,ml as Ka,Qa as La,Xa as Ma,fl as Na,hl as Oa,gl as Pa,yl as Qa,ec as Ra,bl as Sa,Rl as Ta,tc as Ua,wl as Va,Sr as Wa,Cr as Xa,nc as Ya,oc as Za,rc as _a,vr as $a,Ho as ab,ic as bb,Sl as cb,Cl as db,vl as eb,Tl as fb,Il as gb,fs as hb,El as ib,Pl as jb,Al as kb,kl as lb,_l as mb,xl as nb,Ol as ob,Ml as pb,sc as qb,Ll as rb,Nl as sb,Ul as tb,ql as ub,Dl as vb,$l as wb,zl as xb,jl as yb,Hl as zb,Fl as Ab,Gl as Bb,Bl as Cb,Zl as Db,Vl as Eb,Tr as Fb,Ir as Gb,Er as Hb,Jl as Ib,hs as Jb,gs as Kb,ys as Lb,Kl as Mb,Wl as Nb,Yl as Ob,Ql as Pb,Xl as Qb,ac as Rb,ed as Sb,td as Tb,cc as Ub,Th as Vb,nd as Wb,od as Xb,rd as Yb,gw as Zb,Pr as _b,id as $b,sd as ac,ad as bc,cd as cc,ud as dc,ld as ec,dd as fc,pd as gc,md as hc,yi as ic,fd as jc,hd as kc,gd as lc,yd as mc,bd as nc,uc as oc,bs as pc,Rs as qc,lc as rc,dc as sc,pc as tc,Rd as uc,mc as vc,fc as wc,wd as xc,Sd as yc,hc as zc,ws as Ac,Cd as Bc,vd as Cc,Td as Dc,Id as Ec,Ed as Fc,Pd as Gc,Ad as Hc,kd as Ic,_d as Jc,xd as Kc,Od as Lc,Md as Mc,Ld as Nc,Nd as Oc,Ud as Pc,Ih as Qc,qd as Rc,Ar as Sc,Eh as Tc,Dd as Uc,Ph as Vc,Ah as Wc,kh as Xc,_h as Yc,xh as Zc,Oh as _c,Mh as $c,Lh as ad,Nh as bd,Uh as cd,qh as dd,Dh as ed,$h as fd,zh as gd,jh as hd,Hh as id,$d as jd,zd as kd,Fh as ld,Gh as md,Bh as nd,Zh as od,jd as pd,Hd as qd,Vh as rd,Jh as sd,Kh as td,Is as ud,Xw as vd,dg as wd,Sc as xd,mg as yd,N0 as zd,U0 as Ad,q0 as Bd,D0 as Cd,$0 as Dd,z0 as Ed,pW as Fd,SS as Gd,CW as Hd,CS as Id,TS as Jd,ES as Kd,kS as Ld,xS as Md,MS as Nd,NS as Od,qS as Pd,zS as Qd,FS as Rd,ZS as Sd,KS as Td,_s as Ud,Et as Vd,Zo as Wd,YS as Xd,QS as Yd,lp as Zd,dp as _d,pp as $d,rC as ae,hp as be,aC as ce,cC as de,s3 as ee,uC as fe,lC as ge,vC as he,EC as ie,qg as je,Dg as ke,PN as le,Zg as me,yv as ne,Sv as oe,Xg as pe,Ev as qe,kv as re,dU as se,qv as te,UU as ue,jU as ve,HU as we,Fv as xe,BU as ye,ry as ze,PY as Ae,Gv as Be,kn as Ce,eq as De,Kv as Ee,Wv as Fe,nq as Ge,Xv as He,rq as Ie,mq as Je,fq as Ke,hq as Le,gq as Me,yq as Ne,bq as Oe,sT as Pe,Sq as Qe,Cq as Re,vq as Se,Tq as Te,Iq as Ue,Eq as Ve,Pq as We,Aq as Xe,kq as Ye,hy as Ze,O9 as _e,Mq as $e,Nq as af,mT as bf,Z9 as cf,gT as df,Bq as ef,Pi as ff,Bc as gf,at as hf,kt as if,uHe as jf,Wo as kf,RHe as lf,qp as mf,vHe as nf,THe as of,Xn as pf,PHe as qf,AHe as rf,kHe as sf,_He as tf,xHe as uf,OHe as vf,MHe as wf,LHe as xf,Dp as yf,NHe as zf,Ds as Af,zHe as Bf,wy as Cf,$s as Df,Vc as Ef,wT as Ff,QHe as Gf,ST as Hf,CT as If,vT as Jf,TT as Kf,IT as Lf,ET as Mf,PT as Nf,AT as Of,kT as Pf,_T as Qf,LD as Rf,mo as Sf,eo as Tf,Ht as Uf,DD as Vf,rQ as Wf,iQ as Xf,xT as Yf,fGe as Zf,hGe as _f,gGe as $f,e$ as ag,t$ as bg,zGe as cg,jGe as dg,OT as eg,zp as fg,Ey as gg,HGe as hg,r$ as ig,ZGe as jg,jp as kg,PQ as lg,AQ as mg,LT as ng,tBe as og,c$ as pg,u$ as qg,iBe as rg,sBe as sg,aBe as tg,cBe as ug,l$ as vg,d$ as wg,m$ as xg,Yo as yg,qr as zg,xQ as Ag,OQ as Bg,gBe as Cg,yBe as Dg,bBe as Eg,RBe as Fg,Qo as Gg,UQ as Hg,xBe as Ig,g$ as Jg,jBe as Kg,DT as Lg,DQ as Mg,ZQ as Ng,JQ as Og,R$ as Pg,nZe as Qg,oZe as Rg,rZe as Sg,v$ as Tg,cZe as Ug,uZe as Vg,lZe as Wg,GT as Xg,_y as Yg,BT as Zg,E$ as _g,RZe as $g,wZe as ah,SZe as bh,CZe as ch,Cz as dh,to as eh,WZe as fh,aI as gh,r2e as hh,vz as ih,i2e as jh,C2e as kh,dI as lh,pI as mh,_z as nh,O7 as oh,Lz as ph,bI as qh,Gz as rh,wI as sh,Xz as th,SI as uh,vI as vh,tj as wh,nj as xh,oj as yh,EI as zh,AI as Ah,lj as Bh,dj as Ch,pj as Dh,mj as Eh,fj as Fh,gj as Gh,xI as Hh,eee as Ih,Sj as Jh,NI as Kh,Pj as Lh,Aj as Mh,kj as Nh,mee as Oh,_j as Ph,xj as Qh,Oj as Rh,Mj as Sh,Lj as Th,$I as Uh,Uj as Vh,qj as Wh,zI as Xh,jI as Yh,zj as Zh,Hj as _h,Fj as $h,GI as ai,Bj as bi,Yj as ci,KI as di,WI as ei,Qj as fi,rH as gi,QI as hi,XI as ii,eE as ji,fp as ki};
413
- /*! For license information please see chunk-D4D3WYPP.js.LEGAL.txt */
414
- //# sourceMappingURL=chunk-D4D3WYPP.js.map
413
+ /*! For license information please see chunk-SXGSDVGB.js.LEGAL.txt */
414
+ //# sourceMappingURL=chunk-SXGSDVGB.js.map